repo_name
string
path
string
copies
string
size
string
content
string
license
string
nwjs/blink
Source/core/dom/Range.cpp
5
67384
/* * (C) 1999 Lars Knoll (knoll@kde.org) * (C) 2000 Gunnstein Lye (gunnstein@netcom.no) * (C) 2000 Frederik Holljen (frederik.holljen@hig.no) * (C) 2001 Peter Kelly (pmk@post.com) * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved. * Copyright (C) 2011 Motorola Mobility. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/dom/Range.h" #include "bindings/core/v8/ExceptionState.h" #include "core/dom/ClientRect.h" #include "core/dom/ClientRectList.h" #include "core/dom/DocumentFragment.h" #include "core/dom/ExceptionCode.h" #include "core/dom/Node.h" #include "core/dom/NodeTraversal.h" #include "core/dom/NodeWithIndex.h" #include "core/dom/ProcessingInstruction.h" #include "core/dom/Text.h" #include "core/editing/TextIterator.h" #include "core/editing/VisiblePosition.h" #include "core/editing/VisibleUnits.h" #include "core/editing/markup.h" #include "core/events/ScopedEventQueue.h" #include "core/html/HTMLBodyElement.h" #include "core/html/HTMLElement.h" #include "core/rendering/RenderBoxModelObject.h" #include "core/rendering/RenderText.h" #include "core/svg/SVGSVGElement.h" #include "platform/geometry/FloatQuad.h" #include "wtf/RefCountedLeakCounter.h" #include "wtf/text/CString.h" #include "wtf/text/StringBuilder.h" #ifndef NDEBUG #include <stdio.h> #endif namespace blink { DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, rangeCounter, ("Range")); inline Range::Range(Document& ownerDocument) : m_ownerDocument(&ownerDocument) , m_start(m_ownerDocument) , m_end(m_ownerDocument) { #ifndef NDEBUG rangeCounter.increment(); #endif m_ownerDocument->attachRange(this); } PassRefPtrWillBeRawPtr<Range> Range::create(Document& ownerDocument) { return adoptRefWillBeNoop(new Range(ownerDocument)); } inline Range::Range(Document& ownerDocument, Node* startContainer, int startOffset, Node* endContainer, int endOffset) : m_ownerDocument(&ownerDocument) , m_start(m_ownerDocument) , m_end(m_ownerDocument) { #ifndef NDEBUG rangeCounter.increment(); #endif m_ownerDocument->attachRange(this); // Simply setting the containers and offsets directly would not do any of the checking // that setStart and setEnd do, so we call those functions. setStart(startContainer, startOffset); setEnd(endContainer, endOffset); } PassRefPtrWillBeRawPtr<Range> Range::create(Document& ownerDocument, Node* startContainer, int startOffset, Node* endContainer, int endOffset) { return adoptRefWillBeNoop(new Range(ownerDocument, startContainer, startOffset, endContainer, endOffset)); } PassRefPtrWillBeRawPtr<Range> Range::create(Document& ownerDocument, const Position& start, const Position& end) { return adoptRefWillBeNoop(new Range(ownerDocument, start.containerNode(), start.computeOffsetInContainerNode(), end.containerNode(), end.computeOffsetInContainerNode())); } #if !ENABLE(OILPAN) || !defined(NDEBUG) Range::~Range() { #if !ENABLE(OILPAN) // Always detach (even if we've already detached) to fix https://bugs.webkit.org/show_bug.cgi?id=26044 m_ownerDocument->detachRange(this); #endif #ifndef NDEBUG rangeCounter.decrement(); #endif } #endif void Range::setDocument(Document& document) { ASSERT(m_ownerDocument != document); ASSERT(m_ownerDocument); m_ownerDocument->detachRange(this); m_ownerDocument = &document; m_start.setToStartOfNode(document); m_end.setToStartOfNode(document); m_ownerDocument->attachRange(this); } Node* Range::commonAncestorContainer() const { return commonAncestorContainer(m_start.container(), m_end.container()); } Node* Range::commonAncestorContainer(Node* containerA, Node* containerB) { for (Node* parentA = containerA; parentA; parentA = parentA->parentNode()) { for (Node* parentB = containerB; parentB; parentB = parentB->parentNode()) { if (parentA == parentB) return parentA; } } return 0; } static inline bool checkForDifferentRootContainer(const RangeBoundaryPoint& start, const RangeBoundaryPoint& end) { Node* endRootContainer = end.container(); while (endRootContainer->parentNode()) endRootContainer = endRootContainer->parentNode(); Node* startRootContainer = start.container(); while (startRootContainer->parentNode()) startRootContainer = startRootContainer->parentNode(); return startRootContainer != endRootContainer || (Range::compareBoundaryPoints(start, end, ASSERT_NO_EXCEPTION) > 0); } void Range::setStart(PassRefPtrWillBeRawPtr<Node> refNode, int offset, ExceptionState& exceptionState) { if (!refNode) { exceptionState.throwDOMException(NotFoundError, "The node provided was null."); return; } bool didMoveDocument = false; if (refNode->document() != m_ownerDocument) { setDocument(refNode->document()); didMoveDocument = true; } Node* childNode = checkNodeWOffset(refNode.get(), offset, exceptionState); if (exceptionState.hadException()) return; m_start.set(refNode, offset, childNode); if (didMoveDocument || checkForDifferentRootContainer(m_start, m_end)) collapse(true); } void Range::setEnd(PassRefPtrWillBeRawPtr<Node> refNode, int offset, ExceptionState& exceptionState) { if (!refNode) { exceptionState.throwDOMException(NotFoundError, "The node provided was null."); return; } bool didMoveDocument = false; if (refNode->document() != m_ownerDocument) { setDocument(refNode->document()); didMoveDocument = true; } Node* childNode = checkNodeWOffset(refNode.get(), offset, exceptionState); if (exceptionState.hadException()) return; m_end.set(refNode, offset, childNode); if (didMoveDocument || checkForDifferentRootContainer(m_start, m_end)) collapse(false); } void Range::setStart(const Position& start, ExceptionState& exceptionState) { Position parentAnchored = start.parentAnchoredEquivalent(); setStart(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), exceptionState); } void Range::setEnd(const Position& end, ExceptionState& exceptionState) { Position parentAnchored = end.parentAnchoredEquivalent(); setEnd(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), exceptionState); } void Range::collapse(bool toStart) { if (toStart) m_end = m_start; else m_start = m_end; } bool Range::isPointInRange(Node* refNode, int offset, ExceptionState& exceptionState) { if (!refNode) { exceptionState.throwDOMException(HierarchyRequestError, "The node provided was null."); return false; } if (!refNode->inActiveDocument() || refNode->document() != m_ownerDocument) { return false; } checkNodeWOffset(refNode, offset, exceptionState); if (exceptionState.hadException()) return false; return compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), exceptionState) >= 0 && !exceptionState.hadException() && compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), exceptionState) <= 0 && !exceptionState.hadException(); } short Range::comparePoint(Node* refNode, int offset, ExceptionState& exceptionState) const { // http://developer.mozilla.org/en/docs/DOM:range.comparePoint // This method returns -1, 0 or 1 depending on if the point described by the // refNode node and an offset within the node is before, same as, or after the range respectively. if (!refNode->inActiveDocument()) { exceptionState.throwDOMException(WrongDocumentError, "The node provided is not in an active document."); return 0; } if (refNode->document() != m_ownerDocument) { exceptionState.throwDOMException(WrongDocumentError, "The node provided is not in this Range's Document."); return 0; } checkNodeWOffset(refNode, offset, exceptionState); if (exceptionState.hadException()) return 0; // compare to start, and point comes before if (compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), exceptionState) < 0) return -1; if (exceptionState.hadException()) return 0; // compare to end, and point comes after if (compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), exceptionState) > 0 && !exceptionState.hadException()) return 1; // point is in the middle of this range, or on the boundary points return 0; } Range::CompareResults Range::compareNode(Node* refNode, ExceptionState& exceptionState) const { // http://developer.mozilla.org/en/docs/DOM:range.compareNode // This method returns 0, 1, 2, or 3 based on if the node is before, after, // before and after(surrounds), or inside the range, respectively if (!refNode) { exceptionState.throwDOMException(NotFoundError, "The node provided was null."); return NODE_BEFORE; } if (!refNode->inActiveDocument()) { // Firefox doesn't throw an exception for this case; it returns 0. return NODE_BEFORE; } if (refNode->document() != m_ownerDocument) { // Firefox doesn't throw an exception for this case; it returns 0. return NODE_BEFORE; } ContainerNode* parentNode = refNode->parentNode(); int nodeIndex = refNode->nodeIndex(); if (!parentNode) { // if the node is the top document we should return NODE_BEFORE_AND_AFTER // but we throw to match firefox behavior exceptionState.throwDOMException(NotFoundError, "The provided node has no parent."); return NODE_BEFORE; } if (comparePoint(parentNode, nodeIndex, exceptionState) < 0) { // starts before if (comparePoint(parentNode, nodeIndex + 1, exceptionState) > 0) // ends after the range return NODE_BEFORE_AND_AFTER; return NODE_BEFORE; // ends before or in the range } // starts at or after the range start if (comparePoint(parentNode, nodeIndex + 1, exceptionState) > 0) // ends after the range return NODE_AFTER; return NODE_INSIDE; // ends inside the range } short Range::compareBoundaryPoints(unsigned how, const Range* sourceRange, ExceptionState& exceptionState) const { if (!(how == START_TO_START || how == START_TO_END || how == END_TO_END || how == END_TO_START)) { exceptionState.throwDOMException(NotSupportedError, "The comparison method provided must be one of 'START_TO_START', 'START_TO_END', 'END_TO_END', or 'END_TO_START'."); return 0; } Node* thisCont = commonAncestorContainer(); Node* sourceCont = sourceRange->commonAncestorContainer(); if (thisCont->document() != sourceCont->document()) { exceptionState.throwDOMException(WrongDocumentError, "The source range is in a different document than this range."); return 0; } Node* thisTop = thisCont; Node* sourceTop = sourceCont; while (thisTop->parentNode()) thisTop = thisTop->parentNode(); while (sourceTop->parentNode()) sourceTop = sourceTop->parentNode(); if (thisTop != sourceTop) { // in different DocumentFragments exceptionState.throwDOMException(WrongDocumentError, "The source range is in a different document than this range."); return 0; } switch (how) { case START_TO_START: return compareBoundaryPoints(m_start, sourceRange->m_start, exceptionState); case START_TO_END: return compareBoundaryPoints(m_end, sourceRange->m_start, exceptionState); case END_TO_END: return compareBoundaryPoints(m_end, sourceRange->m_end, exceptionState); case END_TO_START: return compareBoundaryPoints(m_start, sourceRange->m_end, exceptionState); } ASSERT_NOT_REACHED(); return 0; } short Range::compareBoundaryPoints(Node* containerA, int offsetA, Node* containerB, int offsetB, ExceptionState& exceptionState) { ASSERT(containerA); ASSERT(containerB); if (!containerA) return -1; if (!containerB) return 1; // see DOM2 traversal & range section 2.5 // case 1: both points have the same container if (containerA == containerB) { if (offsetA == offsetB) return 0; // A is equal to B if (offsetA < offsetB) return -1; // A is before B else return 1; // A is after B } // case 2: node C (container B or an ancestor) is a child node of A Node* c = containerB; while (c && c->parentNode() != containerA) c = c->parentNode(); if (c) { int offsetC = 0; Node* n = containerA->firstChild(); while (n != c && offsetC < offsetA) { offsetC++; n = n->nextSibling(); } if (offsetA <= offsetC) return -1; // A is before B else return 1; // A is after B } // case 3: node C (container A or an ancestor) is a child node of B c = containerA; while (c && c->parentNode() != containerB) c = c->parentNode(); if (c) { int offsetC = 0; Node* n = containerB->firstChild(); while (n != c && offsetC < offsetB) { offsetC++; n = n->nextSibling(); } if (offsetC < offsetB) return -1; // A is before B else return 1; // A is after B } // case 4: containers A & B are siblings, or children of siblings // ### we need to do a traversal here instead Node* commonAncestor = commonAncestorContainer(containerA, containerB); if (!commonAncestor) { exceptionState.throwDOMException(WrongDocumentError, "The two ranges are in separate documents."); return 0; } Node* childA = containerA; while (childA && childA->parentNode() != commonAncestor) childA = childA->parentNode(); if (!childA) childA = commonAncestor; Node* childB = containerB; while (childB && childB->parentNode() != commonAncestor) childB = childB->parentNode(); if (!childB) childB = commonAncestor; if (childA == childB) return 0; // A is equal to B Node* n = commonAncestor->firstChild(); while (n) { if (n == childA) return -1; // A is before B if (n == childB) return 1; // A is after B n = n->nextSibling(); } // Should never reach this point. ASSERT_NOT_REACHED(); return 0; } short Range::compareBoundaryPoints(const RangeBoundaryPoint& boundaryA, const RangeBoundaryPoint& boundaryB, ExceptionState& exceptionState) { return compareBoundaryPoints(boundaryA.container(), boundaryA.offset(), boundaryB.container(), boundaryB.offset(), exceptionState); } bool Range::boundaryPointsValid() const { TrackExceptionState exceptionState; return compareBoundaryPoints(m_start, m_end, exceptionState) <= 0 && !exceptionState.hadException(); } void Range::deleteContents(ExceptionState& exceptionState) { ASSERT(boundaryPointsValid()); { EventQueueScope eventQueueScope; processContents(DELETE_CONTENTS, exceptionState); } } static bool nodeValidForIntersects(Node* refNode, Document* expectedDocument, ExceptionState& exceptionState) { if (!refNode) { exceptionState.throwDOMException(NotFoundError, "The node provided is null."); return false; } if (!refNode->inActiveDocument() || refNode->document() != expectedDocument) { // Firefox doesn't throw an exception for these cases; it returns false. return false; } return true; } bool Range::intersectsNode(Node* refNode, ExceptionState& exceptionState) { // http://developer.mozilla.org/en/docs/DOM:range.intersectsNode // Returns a bool if the node intersects the range. if (!nodeValidForIntersects(refNode, m_ownerDocument.get(), exceptionState)) return false; ContainerNode* parentNode = refNode->parentNode(); int nodeIndex = refNode->nodeIndex(); if (!parentNode) { // if the node is the top document we should return NODE_BEFORE_AND_AFTER // but we throw to match firefox behavior exceptionState.throwDOMException(NotFoundError, "The node provided has no parent."); return false; } if (comparePoint(parentNode, nodeIndex, exceptionState) < 0 // starts before start && comparePoint(parentNode, nodeIndex + 1, exceptionState) < 0) { // ends before start return false; } if (comparePoint(parentNode, nodeIndex, exceptionState) > 0 // starts after end && comparePoint(parentNode, nodeIndex + 1, exceptionState) > 0) { // ends after end return false; } return true; // all other cases } bool Range::intersectsNode(Node* refNode, const Position& start, const Position& end, ExceptionState& exceptionState) { // http://developer.mozilla.org/en/docs/DOM:range.intersectsNode // Returns a bool if the node intersects the range. if (!nodeValidForIntersects(refNode, start.document(), exceptionState)) return false; ContainerNode* parentNode = refNode->parentNode(); int nodeIndex = refNode->nodeIndex(); if (!parentNode) { // if the node is the top document we should return NODE_BEFORE_AND_AFTER // but we throw to match firefox behavior exceptionState.throwDOMException(NotFoundError, "The node provided has no parent."); return false; } Node* startContainerNode = start.containerNode(); int startOffset = start.computeOffsetInContainerNode(); if (compareBoundaryPoints(parentNode, nodeIndex, startContainerNode, startOffset, exceptionState) < 0 // starts before start && compareBoundaryPoints(parentNode, nodeIndex + 1, startContainerNode, startOffset, exceptionState) < 0) { // ends before start ASSERT(!exceptionState.hadException()); return false; } Node* endContainerNode = end.containerNode(); int endOffset = end.computeOffsetInContainerNode(); if (compareBoundaryPoints(parentNode, nodeIndex, endContainerNode, endOffset, exceptionState) > 0 // starts after end && compareBoundaryPoints(parentNode, nodeIndex + 1, endContainerNode, endOffset, exceptionState) > 0) { // ends after end ASSERT(!exceptionState.hadException()); return false; } return true; // all other cases } static inline Node* highestAncestorUnderCommonRoot(Node* node, Node* commonRoot) { if (node == commonRoot) return 0; ASSERT(commonRoot->contains(node)); while (node->parentNode() != commonRoot) node = node->parentNode(); return node; } static inline Node* childOfCommonRootBeforeOffset(Node* container, unsigned offset, Node* commonRoot) { ASSERT(container); ASSERT(commonRoot); if (!commonRoot->contains(container)) return 0; if (container == commonRoot) { container = container->firstChild(); for (unsigned i = 0; container && i < offset; i++) container = container->nextSibling(); } else { while (container->parentNode() != commonRoot) container = container->parentNode(); } return container; } PassRefPtrWillBeRawPtr<DocumentFragment> Range::processContents(ActionType action, ExceptionState& exceptionState) { typedef WillBeHeapVector<RefPtrWillBeMember<Node>> NodeVector; RefPtrWillBeRawPtr<DocumentFragment> fragment = nullptr; if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) fragment = DocumentFragment::create(*m_ownerDocument.get()); if (collapsed()) return fragment.release(); RefPtrWillBeRawPtr<Node> commonRoot = commonAncestorContainer(); ASSERT(commonRoot); if (m_start.container() == m_end.container()) { processContentsBetweenOffsets(action, fragment, m_start.container(), m_start.offset(), m_end.offset(), exceptionState); return fragment; } // Since mutation observers can modify the range during the process, the boundary points need to be saved. RangeBoundaryPoint originalStart(m_start); RangeBoundaryPoint originalEnd(m_end); // what is the highest node that partially selects the start / end of the range? RefPtrWillBeRawPtr<Node> partialStart = highestAncestorUnderCommonRoot(originalStart.container(), commonRoot.get()); RefPtrWillBeRawPtr<Node> partialEnd = highestAncestorUnderCommonRoot(originalEnd.container(), commonRoot.get()); // Start and end containers are different. // There are three possibilities here: // 1. Start container == commonRoot (End container must be a descendant) // 2. End container == commonRoot (Start container must be a descendant) // 3. Neither is commonRoot, they are both descendants // // In case 3, we grab everything after the start (up until a direct child // of commonRoot) into leftContents, and everything before the end (up until // a direct child of commonRoot) into rightContents. Then we process all // commonRoot children between leftContents and rightContents // // In case 1 or 2, we skip either processing of leftContents or rightContents, // in which case the last lot of nodes either goes from the first or last // child of commonRoot. // // These are deleted, cloned, or extracted (i.e. both) depending on action. // Note that we are verifying that our common root hierarchy is still intact // after any DOM mutation event, at various stages below. See webkit bug 60350. RefPtrWillBeRawPtr<Node> leftContents = nullptr; if (originalStart.container() != commonRoot && commonRoot->contains(originalStart.container())) { leftContents = processContentsBetweenOffsets(action, nullptr, originalStart.container(), originalStart.offset(), originalStart.container()->lengthOfContents(), exceptionState); leftContents = processAncestorsAndTheirSiblings(action, originalStart.container(), ProcessContentsForward, leftContents, commonRoot.get(), exceptionState); } RefPtrWillBeRawPtr<Node> rightContents = nullptr; if (m_end.container() != commonRoot && commonRoot->contains(originalEnd.container())) { rightContents = processContentsBetweenOffsets(action, nullptr, originalEnd.container(), 0, originalEnd.offset(), exceptionState); rightContents = processAncestorsAndTheirSiblings(action, originalEnd.container(), ProcessContentsBackward, rightContents, commonRoot.get(), exceptionState); } // delete all children of commonRoot between the start and end container RefPtrWillBeRawPtr<Node> processStart = childOfCommonRootBeforeOffset(originalStart.container(), originalStart.offset(), commonRoot.get()); if (processStart && originalStart.container() != commonRoot) // processStart contains nodes before m_start. processStart = processStart->nextSibling(); RefPtrWillBeRawPtr<Node> processEnd = childOfCommonRootBeforeOffset(originalEnd.container(), originalEnd.offset(), commonRoot.get()); // Collapse the range, making sure that the result is not within a node that was partially selected. if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) { if (partialStart && commonRoot->contains(partialStart.get())) { // FIXME: We should not continue if we have an earlier error. exceptionState.clearException(); setStart(partialStart->parentNode(), partialStart->nodeIndex() + 1, exceptionState); } else if (partialEnd && commonRoot->contains(partialEnd.get())) { // FIXME: We should not continue if we have an earlier error. exceptionState.clearException(); setStart(partialEnd->parentNode(), partialEnd->nodeIndex(), exceptionState); } if (exceptionState.hadException()) return nullptr; m_end = m_start; } originalStart.clear(); originalEnd.clear(); // Now add leftContents, stuff in between, and rightContents to the fragment // (or just delete the stuff in between) if ((action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) && leftContents) fragment->appendChild(leftContents, exceptionState); if (processStart) { NodeVector nodes; for (Node* n = processStart.get(); n && n != processEnd; n = n->nextSibling()) nodes.append(n); processNodes(action, nodes, commonRoot, fragment, exceptionState); } if ((action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) && rightContents) fragment->appendChild(rightContents, exceptionState); return fragment.release(); } static inline void deleteCharacterData(PassRefPtrWillBeRawPtr<CharacterData> data, unsigned startOffset, unsigned endOffset, ExceptionState& exceptionState) { if (data->length() - endOffset) data->deleteData(endOffset, data->length() - endOffset, exceptionState); if (startOffset) data->deleteData(0, startOffset, exceptionState); } PassRefPtrWillBeRawPtr<Node> Range::processContentsBetweenOffsets(ActionType action, PassRefPtrWillBeRawPtr<DocumentFragment> fragment, Node* container, unsigned startOffset, unsigned endOffset, ExceptionState& exceptionState) { ASSERT(container); ASSERT(startOffset <= endOffset); // This switch statement must be consistent with that of Node::lengthOfContents. RefPtrWillBeRawPtr<Node> result = nullptr; switch (container->nodeType()) { case Node::TEXT_NODE: case Node::CDATA_SECTION_NODE: case Node::COMMENT_NODE: endOffset = std::min(endOffset, toCharacterData(container)->length()); if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) { RefPtrWillBeRawPtr<CharacterData> c = static_pointer_cast<CharacterData>(container->cloneNode(true)); deleteCharacterData(c, startOffset, endOffset, exceptionState); if (fragment) { result = fragment; result->appendChild(c.release(), exceptionState); } else result = c.release(); } if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) toCharacterData(container)->deleteData(startOffset, endOffset - startOffset, exceptionState); break; case Node::PROCESSING_INSTRUCTION_NODE: endOffset = std::min(endOffset, toProcessingInstruction(container)->data().length()); if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) { RefPtrWillBeRawPtr<ProcessingInstruction> c = static_pointer_cast<ProcessingInstruction>(container->cloneNode(true)); c->setData(c->data().substring(startOffset, endOffset - startOffset)); if (fragment) { result = fragment; result->appendChild(c.release(), exceptionState); } else result = c.release(); } if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) { ProcessingInstruction* pi = toProcessingInstruction(container); String data(pi->data()); data.remove(startOffset, endOffset - startOffset); pi->setData(data); } break; case Node::ELEMENT_NODE: case Node::ATTRIBUTE_NODE: case Node::DOCUMENT_NODE: case Node::DOCUMENT_TYPE_NODE: case Node::DOCUMENT_FRAGMENT_NODE: // FIXME: Should we assert that some nodes never appear here? if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) { if (fragment) result = fragment; else result = container->cloneNode(false); } Node* n = container->firstChild(); WillBeHeapVector<RefPtrWillBeMember<Node>> nodes; for (unsigned i = startOffset; n && i; i--) n = n->nextSibling(); for (unsigned i = startOffset; n && i < endOffset; i++, n = n->nextSibling()) nodes.append(n); processNodes(action, nodes, container, result, exceptionState); break; } return result.release(); } void Range::processNodes(ActionType action, WillBeHeapVector<RefPtrWillBeMember<Node>>& nodes, PassRefPtrWillBeRawPtr<Node> oldContainer, PassRefPtrWillBeRawPtr<Node> newContainer, ExceptionState& exceptionState) { for (auto& node : nodes) { switch (action) { case DELETE_CONTENTS: oldContainer->removeChild(node.get(), exceptionState); break; case EXTRACT_CONTENTS: newContainer->appendChild(node.release(), exceptionState); // Will remove n from its parent. break; case CLONE_CONTENTS: newContainer->appendChild(node->cloneNode(true), exceptionState); break; } } } PassRefPtrWillBeRawPtr<Node> Range::processAncestorsAndTheirSiblings(ActionType action, Node* container, ContentsProcessDirection direction, PassRefPtrWillBeRawPtr<Node> passedClonedContainer, Node* commonRoot, ExceptionState& exceptionState) { typedef WillBeHeapVector<RefPtrWillBeMember<Node>> NodeVector; RefPtrWillBeRawPtr<Node> clonedContainer = passedClonedContainer; NodeVector ancestors; for (ContainerNode* n = container->parentNode(); n && n != commonRoot; n = n->parentNode()) ancestors.append(n); RefPtrWillBeRawPtr<Node> firstChildInAncestorToProcess = direction == ProcessContentsForward ? container->nextSibling() : container->previousSibling(); for (const RefPtrWillBeRawPtr<Node>& ancestor : ancestors) { if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) { if (RefPtrWillBeRawPtr<Node> clonedAncestor = ancestor->cloneNode(false)) { // Might have been removed already during mutation event. clonedAncestor->appendChild(clonedContainer, exceptionState); clonedContainer = clonedAncestor; } } // Copy siblings of an ancestor of start/end containers // FIXME: This assertion may fail if DOM is modified during mutation event // FIXME: Share code with Range::processNodes ASSERT(!firstChildInAncestorToProcess || firstChildInAncestorToProcess->parentNode() == ancestor); NodeVector nodes; for (Node* child = firstChildInAncestorToProcess.get(); child; child = (direction == ProcessContentsForward) ? child->nextSibling() : child->previousSibling()) nodes.append(child); for (const RefPtrWillBeRawPtr<Node>& node : nodes) { Node* child = node.get(); switch (action) { case DELETE_CONTENTS: // Prior call of ancestor->removeChild() may cause a tree change due to DOMSubtreeModified event. // Therefore, we need to make sure |ancestor| is still |child|'s parent. if (ancestor == child->parentNode()) ancestor->removeChild(child, exceptionState); break; case EXTRACT_CONTENTS: // will remove child from ancestor if (direction == ProcessContentsForward) clonedContainer->appendChild(child, exceptionState); else clonedContainer->insertBefore(child, clonedContainer->firstChild(), exceptionState); break; case CLONE_CONTENTS: if (direction == ProcessContentsForward) clonedContainer->appendChild(child->cloneNode(true), exceptionState); else clonedContainer->insertBefore(child->cloneNode(true), clonedContainer->firstChild(), exceptionState); break; } } firstChildInAncestorToProcess = direction == ProcessContentsForward ? ancestor->nextSibling() : ancestor->previousSibling(); } return clonedContainer.release(); } PassRefPtrWillBeRawPtr<DocumentFragment> Range::extractContents(ExceptionState& exceptionState) { checkExtractPrecondition(exceptionState); if (exceptionState.hadException()) return nullptr; return processContents(EXTRACT_CONTENTS, exceptionState); } PassRefPtrWillBeRawPtr<DocumentFragment> Range::cloneContents(ExceptionState& exceptionState) { return processContents(CLONE_CONTENTS, exceptionState); } void Range::insertNode(PassRefPtrWillBeRawPtr<Node> prpNewNode, ExceptionState& exceptionState) { RefPtrWillBeRawPtr<Node> newNode = prpNewNode; if (!newNode) { exceptionState.throwDOMException(NotFoundError, "The node provided is null."); return; } // HierarchyRequestError: Raised if the container of the start of the Range is of a type that // does not allow children of the type of newNode or if newNode is an ancestor of the container. // an extra one here - if a text node is going to split, it must have a parent to insert into bool startIsText = m_start.container()->isTextNode(); if (startIsText && !m_start.container()->parentNode()) { exceptionState.throwDOMException(HierarchyRequestError, "This operation would split a text node, but there's no parent into which to insert."); return; } // In the case where the container is a text node, we check against the container's parent, because // text nodes get split up upon insertion. Node* checkAgainst; if (startIsText) checkAgainst = m_start.container()->parentNode(); else checkAgainst = m_start.container(); Node::NodeType newNodeType = newNode->nodeType(); int numNewChildren; if (newNodeType == Node::DOCUMENT_FRAGMENT_NODE && !newNode->isShadowRoot()) { // check each child node, not the DocumentFragment itself numNewChildren = 0; for (Node* c = toDocumentFragment(newNode)->firstChild(); c; c = c->nextSibling()) { if (!checkAgainst->childTypeAllowed(c->nodeType())) { exceptionState.throwDOMException(HierarchyRequestError, "The node to be inserted contains a '" + c->nodeName() + "' node, which may not be inserted here."); return; } ++numNewChildren; } } else { numNewChildren = 1; if (!checkAgainst->childTypeAllowed(newNodeType)) { exceptionState.throwDOMException(HierarchyRequestError, "The node to be inserted is a '" + newNode->nodeName() + "' node, which may not be inserted here."); return; } } for (Node* n = m_start.container(); n; n = n->parentNode()) { if (n == newNode) { exceptionState.throwDOMException(HierarchyRequestError, "The node to be inserted contains the insertion point; it may not be inserted into itself."); return; } } // InvalidNodeTypeError: Raised if newNode is an Attr, Entity, Notation, ShadowRoot or Document node. switch (newNodeType) { case Node::ATTRIBUTE_NODE: case Node::DOCUMENT_NODE: exceptionState.throwDOMException(InvalidNodeTypeError, "The node to be inserted is a '" + newNode->nodeName() + "' node, which may not be inserted here."); return; default: if (newNode->isShadowRoot()) { exceptionState.throwDOMException(InvalidNodeTypeError, "The node to be inserted is a shadow root, which may not be inserted here."); return; } break; } EventQueueScope scope; bool collapsed = m_start == m_end; RefPtrWillBeRawPtr<Node> container = nullptr; if (startIsText) { container = m_start.container(); RefPtrWillBeRawPtr<Text> newText = toText(container)->splitText(m_start.offset(), exceptionState); if (exceptionState.hadException()) return; container = m_start.container(); container->parentNode()->insertBefore(newNode.release(), newText.get(), exceptionState); if (exceptionState.hadException()) return; if (collapsed) { // The load event would be fired regardless of EventQueueScope; // e.g. by ContainerNode::updateTreeAfterInsertion // Given circumstance may mutate the tree so newText->parentNode() may become null if (!newText->parentNode()) { exceptionState.throwDOMException(HierarchyRequestError, "This operation would set range's end to parent with new offset, but there's no parent into which to continue."); return; } m_end.setToBeforeChild(*newText); } } else { RefPtrWillBeRawPtr<Node> lastChild = (newNodeType == Node::DOCUMENT_FRAGMENT_NODE) ? toDocumentFragment(newNode)->lastChild() : newNode.get(); if (lastChild && lastChild == m_start.childBefore()) { // The insertion will do nothing, but we need to extend the range to include // the inserted nodes. Node* firstChild = (newNodeType == Node::DOCUMENT_FRAGMENT_NODE) ? toDocumentFragment(newNode)->firstChild() : newNode.get(); ASSERT(firstChild); m_start.setToBeforeChild(*firstChild); return; } container = m_start.container(); container->insertBefore(newNode.release(), NodeTraversal::childAt(*container, m_start.offset()), exceptionState); if (exceptionState.hadException()) return; // Note that m_start.offset() may have changed as a result of container->insertBefore, // when the node we are inserting comes before the range in the same container. if (collapsed && numNewChildren) m_end.set(m_start.container(), m_start.offset() + numNewChildren, lastChild.get()); } } String Range::toString() const { StringBuilder builder; Node* pastLast = pastLastNode(); for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(*n)) { Node::NodeType type = n->nodeType(); if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) { String data = toCharacterData(n)->data(); int length = data.length(); int start = (n == m_start.container()) ? std::min(std::max(0, m_start.offset()), length) : 0; int end = (n == m_end.container()) ? std::min(std::max(start, m_end.offset()), length) : length; builder.append(data, start, end - start); } } return builder.toString(); } String Range::text() const { return plainText(this, TextIteratorEmitsObjectReplacementCharacter); } PassRefPtrWillBeRawPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionState& exceptionState) { // Algorithm: http://domparsing.spec.whatwg.org/#extensions-to-the-range-interface Node* node = m_start.container(); // Step 1. RefPtrWillBeRawPtr<Element> element; if (!m_start.offset() && (node->isDocumentNode() || node->isDocumentFragment())) element = nullptr; else if (node->isElementNode()) element = toElement(node); else element = node->parentElement(); // Step 2. if (!element || isHTMLHtmlElement(element)) { Document& document = node->document(); if (document.isHTMLDocument() || document.isXHTMLDocument()) { // Optimization over spec: try to reuse the existing <body> element, if it is available. element = document.body(); if (!element) element = HTMLBodyElement::create(document); } else if (document.isSVGDocument()) { element = document.documentElement(); if (!element) element = SVGSVGElement::create(document); } } if (!element || (!element->isHTMLElement() && !element->isSVGElement())) { exceptionState.throwDOMException(NotSupportedError, "The range's container must be an HTML or SVG Element, Document, or DocumentFragment."); return nullptr; } // Steps 3, 4, 5. RefPtrWillBeRawPtr<DocumentFragment> fragment = blink::createContextualFragment(markup, element.get(), AllowScriptingContentAndDoNotMarkAlreadyStarted, exceptionState); if (!fragment) return nullptr; return fragment.release(); } void Range::detach() { // This is now a no-op as per the DOM specification. } Node* Range::checkNodeWOffset(Node* n, int offset, ExceptionState& exceptionState) const { switch (n->nodeType()) { case Node::DOCUMENT_TYPE_NODE: exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + n->nodeName() + "'."); return nullptr; case Node::CDATA_SECTION_NODE: case Node::COMMENT_NODE: case Node::TEXT_NODE: if (static_cast<unsigned>(offset) > toCharacterData(n)->length()) exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is larger than or equal to the node's length (" + String::number(toCharacterData(n)->length()) + ")."); return nullptr; case Node::PROCESSING_INSTRUCTION_NODE: if (static_cast<unsigned>(offset) > toProcessingInstruction(n)->data().length()) exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is larger than or equal to than the node's length (" + String::number(toProcessingInstruction(n)->data().length()) + ")."); return nullptr; case Node::ATTRIBUTE_NODE: case Node::DOCUMENT_FRAGMENT_NODE: case Node::DOCUMENT_NODE: case Node::ELEMENT_NODE: { if (!offset) return nullptr; Node* childBefore = NodeTraversal::childAt(*n, offset - 1); if (!childBefore) exceptionState.throwDOMException(IndexSizeError, "There is no child at offset " + String::number(offset) + "."); return childBefore; } } ASSERT_NOT_REACHED(); return nullptr; } void Range::checkNodeBA(Node* n, ExceptionState& exceptionState) const { if (!n) { exceptionState.throwDOMException(NotFoundError, "The node provided is null."); return; } // InvalidNodeTypeError: Raised if the root container of refNode is not an // Attr, Document, DocumentFragment or ShadowRoot node, or part of a SVG shadow DOM tree, // or if refNode is a Document, DocumentFragment, ShadowRoot, Attr, Entity, or Notation node. if (!n->parentNode()) { exceptionState.throwDOMException(InvalidNodeTypeError, "the given Node has no parent."); return; } switch (n->nodeType()) { case Node::ATTRIBUTE_NODE: case Node::DOCUMENT_FRAGMENT_NODE: case Node::DOCUMENT_NODE: exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + n->nodeName() + "'."); return; case Node::CDATA_SECTION_NODE: case Node::COMMENT_NODE: case Node::DOCUMENT_TYPE_NODE: case Node::ELEMENT_NODE: case Node::PROCESSING_INSTRUCTION_NODE: case Node::TEXT_NODE: break; } Node* root = n; while (ContainerNode* parent = root->parentNode()) root = parent; switch (root->nodeType()) { case Node::ATTRIBUTE_NODE: case Node::DOCUMENT_NODE: case Node::DOCUMENT_FRAGMENT_NODE: case Node::ELEMENT_NODE: break; case Node::CDATA_SECTION_NODE: case Node::COMMENT_NODE: case Node::DOCUMENT_TYPE_NODE: case Node::PROCESSING_INSTRUCTION_NODE: case Node::TEXT_NODE: exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + n->nodeName() + "'."); return; } } PassRefPtrWillBeRawPtr<Range> Range::cloneRange() const { return Range::create(*m_ownerDocument.get(), m_start.container(), m_start.offset(), m_end.container(), m_end.offset()); } void Range::setStartAfter(Node* refNode, ExceptionState& exceptionState) { checkNodeBA(refNode, exceptionState); if (exceptionState.hadException()) return; setStart(refNode->parentNode(), refNode->nodeIndex() + 1, exceptionState); } void Range::setEndBefore(Node* refNode, ExceptionState& exceptionState) { checkNodeBA(refNode, exceptionState); if (exceptionState.hadException()) return; setEnd(refNode->parentNode(), refNode->nodeIndex(), exceptionState); } void Range::setEndAfter(Node* refNode, ExceptionState& exceptionState) { checkNodeBA(refNode, exceptionState); if (exceptionState.hadException()) return; setEnd(refNode->parentNode(), refNode->nodeIndex() + 1, exceptionState); } void Range::selectNode(Node* refNode, ExceptionState& exceptionState) { if (!refNode) { exceptionState.throwDOMException(NotFoundError, "The node provided is null."); return; } if (!refNode->parentNode()) { exceptionState.throwDOMException(InvalidNodeTypeError, "the given Node has no parent."); return; } // InvalidNodeTypeError: Raised if an ancestor of refNode is an Entity, Notation or // DocumentType node or if refNode is a Document, DocumentFragment, ShadowRoot, Attr, Entity, or Notation // node. for (ContainerNode* anc = refNode->parentNode(); anc; anc = anc->parentNode()) { switch (anc->nodeType()) { case Node::ATTRIBUTE_NODE: case Node::CDATA_SECTION_NODE: case Node::COMMENT_NODE: case Node::DOCUMENT_FRAGMENT_NODE: case Node::DOCUMENT_NODE: case Node::ELEMENT_NODE: case Node::PROCESSING_INSTRUCTION_NODE: case Node::TEXT_NODE: break; case Node::DOCUMENT_TYPE_NODE: exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided has an ancestor of type '" + anc->nodeName() + "'."); return; } } switch (refNode->nodeType()) { case Node::CDATA_SECTION_NODE: case Node::COMMENT_NODE: case Node::DOCUMENT_TYPE_NODE: case Node::ELEMENT_NODE: case Node::PROCESSING_INSTRUCTION_NODE: case Node::TEXT_NODE: break; case Node::ATTRIBUTE_NODE: case Node::DOCUMENT_FRAGMENT_NODE: case Node::DOCUMENT_NODE: exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + refNode->nodeName() + "'."); return; } if (m_ownerDocument != refNode->document()) setDocument(refNode->document()); setStartBefore(refNode); setEndAfter(refNode); } void Range::selectNodeContents(Node* refNode, ExceptionState& exceptionState) { if (!refNode) { exceptionState.throwDOMException(NotFoundError, "The node provided is null."); return; } // InvalidNodeTypeError: Raised if refNode or an ancestor of refNode is an Entity, Notation // or DocumentType node. for (Node* n = refNode; n; n = n->parentNode()) { switch (n->nodeType()) { case Node::ATTRIBUTE_NODE: case Node::CDATA_SECTION_NODE: case Node::COMMENT_NODE: case Node::DOCUMENT_FRAGMENT_NODE: case Node::DOCUMENT_NODE: case Node::ELEMENT_NODE: case Node::PROCESSING_INSTRUCTION_NODE: case Node::TEXT_NODE: break; case Node::DOCUMENT_TYPE_NODE: exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + refNode->nodeName() + "'."); return; } } if (m_ownerDocument != refNode->document()) setDocument(refNode->document()); m_start.setToStartOfNode(*refNode); m_end.setToEndOfNode(*refNode); } bool Range::selectNodeContents(Node* refNode, Position& start, Position& end) { if (!refNode) { return false; } for (Node* n = refNode; n; n = n->parentNode()) { switch (n->nodeType()) { case Node::ATTRIBUTE_NODE: case Node::CDATA_SECTION_NODE: case Node::COMMENT_NODE: case Node::DOCUMENT_FRAGMENT_NODE: case Node::DOCUMENT_NODE: case Node::ELEMENT_NODE: case Node::PROCESSING_INSTRUCTION_NODE: case Node::TEXT_NODE: break; case Node::DOCUMENT_TYPE_NODE: return false; } } RangeBoundaryPoint startBoundaryPoint(refNode); startBoundaryPoint.setToStartOfNode(*refNode); start = startBoundaryPoint.toPosition(); RangeBoundaryPoint endBoundaryPoint(refNode); endBoundaryPoint.setToEndOfNode(*refNode); end = endBoundaryPoint.toPosition(); return true; } void Range::surroundContents(PassRefPtrWillBeRawPtr<Node> passNewParent, ExceptionState& exceptionState) { RefPtrWillBeRawPtr<Node> newParent = passNewParent; if (!newParent) { exceptionState.throwDOMException(NotFoundError, "The node provided is null."); return; } // InvalidStateError: Raised if the Range partially selects a non-Text node. Node* startNonTextContainer = m_start.container(); if (startNonTextContainer->nodeType() == Node::TEXT_NODE) startNonTextContainer = startNonTextContainer->parentNode(); Node* endNonTextContainer = m_end.container(); if (endNonTextContainer->nodeType() == Node::TEXT_NODE) endNonTextContainer = endNonTextContainer->parentNode(); if (startNonTextContainer != endNonTextContainer) { exceptionState.throwDOMException(InvalidStateError, "The Range has partially selected a non-Text node."); return; } // InvalidNodeTypeError: Raised if node is an Attr, Entity, DocumentType, Notation, // Document, or DocumentFragment node. switch (newParent->nodeType()) { case Node::ATTRIBUTE_NODE: case Node::DOCUMENT_FRAGMENT_NODE: case Node::DOCUMENT_NODE: case Node::DOCUMENT_TYPE_NODE: exceptionState.throwDOMException(InvalidNodeTypeError, "The node provided is of type '" + newParent->nodeName() + "'."); return; case Node::CDATA_SECTION_NODE: case Node::COMMENT_NODE: case Node::ELEMENT_NODE: case Node::PROCESSING_INSTRUCTION_NODE: case Node::TEXT_NODE: break; } // Raise a HierarchyRequestError if m_start.container() doesn't accept children like newParent. Node* parentOfNewParent = m_start.container(); // If m_start.container() is a character data node, it will be split and it will be its parent that will // need to accept newParent (or in the case of a comment, it logically "would" be inserted into the parent, // although this will fail below for another reason). if (parentOfNewParent->isCharacterDataNode()) parentOfNewParent = parentOfNewParent->parentNode(); if (!parentOfNewParent) { exceptionState.throwDOMException(HierarchyRequestError, "The container node is a detached character data node; no parent node is available for insertion."); return; } if (!parentOfNewParent->childTypeAllowed(newParent->nodeType())) { exceptionState.throwDOMException(HierarchyRequestError, "The node provided is of type '" + newParent->nodeName() + "', which may not be inserted here."); return; } if (newParent->contains(m_start.container())) { exceptionState.throwDOMException(HierarchyRequestError, "The node provided contains the insertion point; it may not be inserted into itself."); return; } // FIXME: Do we need a check if the node would end up with a child node of a type not // allowed by the type of node? while (Node* n = newParent->firstChild()) { toContainerNode(newParent)->removeChild(n, exceptionState); if (exceptionState.hadException()) return; } RefPtrWillBeRawPtr<DocumentFragment> fragment = extractContents(exceptionState); if (exceptionState.hadException()) return; insertNode(newParent, exceptionState); if (exceptionState.hadException()) return; newParent->appendChild(fragment.release(), exceptionState); if (exceptionState.hadException()) return; selectNode(newParent.get(), exceptionState); } void Range::setStartBefore(Node* refNode, ExceptionState& exceptionState) { checkNodeBA(refNode, exceptionState); if (exceptionState.hadException()) return; setStart(refNode->parentNode(), refNode->nodeIndex(), exceptionState); } void Range::checkExtractPrecondition(ExceptionState& exceptionState) { ASSERT(boundaryPointsValid()); if (!commonAncestorContainer()) return; Node* pastLast = pastLastNode(); for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(*n)) { if (n->isDocumentTypeNode()) { exceptionState.throwDOMException(HierarchyRequestError, "The Range contains a doctype node."); return; } } } Node* Range::firstNode() const { if (m_start.container()->offsetInCharacters()) return m_start.container(); if (Node* child = NodeTraversal::childAt(*m_start.container(), m_start.offset())) return child; if (!m_start.offset()) return m_start.container(); return NodeTraversal::nextSkippingChildren(*m_start.container()); } ShadowRoot* Range::shadowRoot() const { return startContainer() ? startContainer()->containingShadowRoot() : nullptr; } Node* Range::pastLastNode() const { if (m_end.container()->offsetInCharacters()) return NodeTraversal::nextSkippingChildren(*m_end.container()); if (Node* child = NodeTraversal::childAt(*m_end.container(), m_end.offset())) return child; return NodeTraversal::nextSkippingChildren(*m_end.container()); } IntRect Range::boundingBox() const { IntRect result; Vector<IntRect> rects; textRects(rects); for (const IntRect& rect : rects) result.unite(rect); return result; } void Range::textRects(Vector<IntRect>& rects, bool useSelectionHeight, RangeInFixedPosition* inFixed) const { Node* startContainer = m_start.container(); ASSERT(startContainer); Node* endContainer = m_end.container(); ASSERT(endContainer); bool allFixed = true; bool someFixed = false; Node* stopNode = pastLastNode(); for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) { RenderObject* r = node->renderer(); if (!r || !r->isText()) continue; RenderText* renderText = toRenderText(r); int startOffset = node == startContainer ? m_start.offset() : 0; int endOffset = node == endContainer ? m_end.offset() : std::numeric_limits<int>::max(); bool isFixed = false; renderText->absoluteRectsForRange(rects, startOffset, endOffset, useSelectionHeight, &isFixed); allFixed &= isFixed; someFixed |= isFixed; } if (inFixed) *inFixed = allFixed ? EntirelyFixedPosition : (someFixed ? PartiallyFixedPosition : NotFixedPosition); } void Range::textQuads(Vector<FloatQuad>& quads, bool useSelectionHeight, RangeInFixedPosition* inFixed) const { Node* startContainer = m_start.container(); ASSERT(startContainer); Node* endContainer = m_end.container(); ASSERT(endContainer); bool allFixed = true; bool someFixed = false; Node* stopNode = pastLastNode(); for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) { RenderObject* r = node->renderer(); if (!r || !r->isText()) continue; RenderText* renderText = toRenderText(r); int startOffset = node == startContainer ? m_start.offset() : 0; int endOffset = node == endContainer ? m_end.offset() : std::numeric_limits<int>::max(); bool isFixed = false; renderText->absoluteQuadsForRange(quads, startOffset, endOffset, useSelectionHeight, &isFixed); allFixed &= isFixed; someFixed |= isFixed; } if (inFixed) *inFixed = allFixed ? EntirelyFixedPosition : (someFixed ? PartiallyFixedPosition : NotFixedPosition); } #ifndef NDEBUG void Range::formatForDebugger(char* buffer, unsigned length) const { StringBuilder result; const int FormatBufferSize = 1024; char s[FormatBufferSize]; result.appendLiteral("from offset "); result.appendNumber(m_start.offset()); result.appendLiteral(" of "); m_start.container()->formatForDebugger(s, FormatBufferSize); result.append(s); result.appendLiteral(" to offset "); result.appendNumber(m_end.offset()); result.appendLiteral(" of "); m_end.container()->formatForDebugger(s, FormatBufferSize); result.append(s); strncpy(buffer, result.toString().utf8().data(), length - 1); } #endif bool areRangesEqual(const Range* a, const Range* b) { if (a == b) return true; if (!a || !b) return false; return a->startPosition() == b->startPosition() && a->endPosition() == b->endPosition(); } PassRefPtrWillBeRawPtr<Range> rangeOfContents(Node* node) { ASSERT(node); RefPtrWillBeRawPtr<Range> range = Range::create(node->document()); range->selectNodeContents(node, IGNORE_EXCEPTION); return range.release(); } static inline void boundaryNodeChildrenChanged(RangeBoundaryPoint& boundary, ContainerNode* container) { if (!boundary.childBefore()) return; if (boundary.container() != container) return; boundary.invalidateOffset(); } void Range::nodeChildrenChanged(ContainerNode* container) { ASSERT(container); ASSERT(container->document() == m_ownerDocument); boundaryNodeChildrenChanged(m_start, container); boundaryNodeChildrenChanged(m_end, container); } static inline void boundaryNodeChildrenWillBeRemoved(RangeBoundaryPoint& boundary, ContainerNode& container) { for (Node* nodeToBeRemoved = container.firstChild(); nodeToBeRemoved; nodeToBeRemoved = nodeToBeRemoved->nextSibling()) { if (boundary.childBefore() == nodeToBeRemoved) { boundary.setToStartOfNode(container); return; } for (Node* n = boundary.container(); n; n = n->parentNode()) { if (n == nodeToBeRemoved) { boundary.setToStartOfNode(container); return; } } } } void Range::nodeChildrenWillBeRemoved(ContainerNode& container) { ASSERT(container.document() == m_ownerDocument); boundaryNodeChildrenWillBeRemoved(m_start, container); boundaryNodeChildrenWillBeRemoved(m_end, container); } static inline void boundaryNodeWillBeRemoved(RangeBoundaryPoint& boundary, Node& nodeToBeRemoved) { if (boundary.childBefore() == nodeToBeRemoved) { boundary.childBeforeWillBeRemoved(); return; } for (Node* n = boundary.container(); n; n = n->parentNode()) { if (n == nodeToBeRemoved) { boundary.setToBeforeChild(nodeToBeRemoved); return; } } } void Range::nodeWillBeRemoved(Node& node) { ASSERT(node.document() == m_ownerDocument); ASSERT(node != m_ownerDocument.get()); // FIXME: Once DOMNodeRemovedFromDocument mutation event removed, we // should change following if-statement to ASSERT(!node->parentNode). if (!node.parentNode()) return; boundaryNodeWillBeRemoved(m_start, node); boundaryNodeWillBeRemoved(m_end, node); } static inline void boundaryTextInserted(RangeBoundaryPoint& boundary, Node* text, unsigned offset, unsigned length) { if (boundary.container() != text) return; unsigned boundaryOffset = boundary.offset(); if (offset >= boundaryOffset) return; boundary.setOffset(boundaryOffset + length); } void Range::didInsertText(Node* text, unsigned offset, unsigned length) { ASSERT(text); ASSERT(text->document() == m_ownerDocument); boundaryTextInserted(m_start, text, offset, length); boundaryTextInserted(m_end, text, offset, length); } static inline void boundaryTextRemoved(RangeBoundaryPoint& boundary, Node* text, unsigned offset, unsigned length) { if (boundary.container() != text) return; unsigned boundaryOffset = boundary.offset(); if (offset >= boundaryOffset) return; if (offset + length >= boundaryOffset) boundary.setOffset(offset); else boundary.setOffset(boundaryOffset - length); } void Range::didRemoveText(Node* text, unsigned offset, unsigned length) { ASSERT(text); ASSERT(text->document() == m_ownerDocument); boundaryTextRemoved(m_start, text, offset, length); boundaryTextRemoved(m_end, text, offset, length); } static inline void boundaryTextNodesMerged(RangeBoundaryPoint& boundary, const NodeWithIndex& oldNode, unsigned offset) { if (boundary.container() == oldNode.node()) boundary.set(oldNode.node().previousSibling(), boundary.offset() + offset, 0); else if (boundary.container() == oldNode.node().parentNode() && boundary.offset() == oldNode.index()) boundary.set(oldNode.node().previousSibling(), offset, 0); } void Range::didMergeTextNodes(const NodeWithIndex& oldNode, unsigned offset) { ASSERT(oldNode.node().document() == m_ownerDocument); ASSERT(oldNode.node().parentNode()); ASSERT(oldNode.node().isTextNode()); ASSERT(oldNode.node().previousSibling()); ASSERT(oldNode.node().previousSibling()->isTextNode()); boundaryTextNodesMerged(m_start, oldNode, offset); boundaryTextNodesMerged(m_end, oldNode, offset); } void Range::updateOwnerDocumentIfNeeded() { ASSERT(m_start.container()); ASSERT(m_end.container()); Document& newDocument = m_start.container()->document(); ASSERT(newDocument == m_end.container()->document()); if (newDocument == m_ownerDocument) return; m_ownerDocument->detachRange(this); m_ownerDocument = &newDocument; m_ownerDocument->attachRange(this); } static inline void boundaryTextNodeSplit(RangeBoundaryPoint& boundary, Text& oldNode) { Node* boundaryContainer = boundary.container(); unsigned boundaryOffset = boundary.offset(); if (boundary.childBefore() == &oldNode) boundary.set(boundaryContainer, boundaryOffset + 1, oldNode.nextSibling()); else if (boundary.container() == &oldNode && boundaryOffset > oldNode.length()) boundary.set(oldNode.nextSibling(), boundaryOffset - oldNode.length(), 0); } void Range::didSplitTextNode(Text& oldNode) { ASSERT(oldNode.document() == m_ownerDocument); ASSERT(oldNode.parentNode()); ASSERT(oldNode.nextSibling()); ASSERT(oldNode.nextSibling()->isTextNode()); boundaryTextNodeSplit(m_start, oldNode); boundaryTextNodeSplit(m_end, oldNode); ASSERT(boundaryPointsValid()); } void Range::expand(const String& unit, ExceptionState& exceptionState) { VisiblePosition start(startPosition()); VisiblePosition end(endPosition()); if (unit == "word") { start = startOfWord(start); end = endOfWord(end); } else if (unit == "sentence") { start = startOfSentence(start); end = endOfSentence(end); } else if (unit == "block") { start = startOfParagraph(start); end = endOfParagraph(end); } else if (unit == "document") { start = startOfDocument(start); end = endOfDocument(end); } else return; setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), exceptionState); setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), exceptionState); } PassRefPtrWillBeRawPtr<ClientRectList> Range::getClientRects() const { m_ownerDocument->updateLayoutIgnorePendingStylesheets(); Vector<FloatQuad> quads; getBorderAndTextQuads(quads); return ClientRectList::create(quads); } PassRefPtrWillBeRawPtr<ClientRect> Range::getBoundingClientRect() const { return ClientRect::create(boundingRect()); } void Range::getBorderAndTextQuads(Vector<FloatQuad>& quads) const { Node* startContainer = m_start.container(); Node* endContainer = m_end.container(); Node* stopNode = pastLastNode(); WillBeHeapHashSet<RawPtrWillBeMember<Node>> nodeSet; for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) { if (node->isElementNode()) nodeSet.add(node); } for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) { if (node->isElementNode()) { if (!nodeSet.contains(node->parentNode())) { if (RenderBoxModelObject* renderBoxModelObject = toElement(node)->renderBoxModelObject()) { Vector<FloatQuad> elementQuads; renderBoxModelObject->absoluteQuads(elementQuads); m_ownerDocument->adjustFloatQuadsForScrollAndAbsoluteZoom(elementQuads, *renderBoxModelObject); quads.appendVector(elementQuads); } } } else if (node->isTextNode()) { if (RenderText* renderText = toText(node)->renderer()) { int startOffset = (node == startContainer) ? m_start.offset() : 0; int endOffset = (node == endContainer) ? m_end.offset() : INT_MAX; Vector<FloatQuad> textQuads; renderText->absoluteQuadsForRange(textQuads, startOffset, endOffset); m_ownerDocument->adjustFloatQuadsForScrollAndAbsoluteZoom(textQuads, *renderText); quads.appendVector(textQuads); } } } } FloatRect Range::boundingRect() const { m_ownerDocument->updateLayoutIgnorePendingStylesheets(); Vector<FloatQuad> quads; getBorderAndTextQuads(quads); FloatRect result; for (const FloatQuad& quad : quads) result.unite(quad.boundingBox()); return result; } void Range::trace(Visitor* visitor) { visitor->trace(m_ownerDocument); visitor->trace(m_start); visitor->trace(m_end); } } // namespace blink #ifndef NDEBUG void showTree(const blink::Range* range) { if (range && range->boundaryPointsValid()) { range->startContainer()->showTreeAndMark(range->startContainer(), "S", range->endContainer(), "E"); fprintf(stderr, "start offset: %d, end offset: %d\n", range->startOffset(), range->endOffset()); } } #endif
bsd-3-clause
buaasun/grappa
applications/NPB/MPI/LU/exchange_6.f
5
2409
c--------------------------------------------------------------------- c--------------------------------------------------------------------- subroutine exchange_6(g,jbeg,jfin1) c--------------------------------------------------------------------- c--------------------------------------------------------------------- c--------------------------------------------------------------------- c compute the right hand side based on exact solution c--------------------------------------------------------------------- implicit none include 'mpinpb.h' include 'applu.incl' c--------------------------------------------------------------------- c input parameters c--------------------------------------------------------------------- double precision g(0:isiz2+1,0:isiz3+1) integer jbeg, jfin1 c--------------------------------------------------------------------- c local parameters c--------------------------------------------------------------------- integer k double precision dum(1024) integer msgid3 integer STATUS(MPI_STATUS_SIZE) integer IERROR c--------------------------------------------------------------------- c communicate in the east and west directions c--------------------------------------------------------------------- c--------------------------------------------------------------------- c receive from east c--------------------------------------------------------------------- if (jfin1.eq.ny) then call MPI_IRECV( dum, > nz, > dp_type, > east, > from_e, > MPI_COMM_WORLD, > msgid3, > IERROR ) call MPI_WAIT( msgid3, STATUS, IERROR ) do k = 1,nz g(ny+1,k) = dum(k) end do end if c--------------------------------------------------------------------- c send west c--------------------------------------------------------------------- if (jbeg.eq.1) then do k = 1,nz dum(k) = g(1,k) end do call MPI_SEND( dum, > nz, > dp_type, > west, > from_e, > MPI_COMM_WORLD, > IERROR ) end if return end
bsd-3-clause
ylow/SFrame
oss_src/fault/query_object_server_replica.cpp
5
7125
/** * Copyright (C) 2016 Turi * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #include <poll.h> #include <unistd.h> #include <fault/query_object_server_replica.hpp> #include <fault/query_object_server_internal_signals.hpp> #include <fault/query_object_client.hpp> namespace libfault{ query_object_server_replica::query_object_server_replica(void* zmq_ctx, graphlab::zookeeper_util::key_value* zk_keyval, std::string _objectkey, query_object* _qobj, size_t _replicaid) { z_ctx = zmq_ctx; keyval = zk_keyval; objectkey = _objectkey; replicaid = _replicaid; qobj = _qobj; localpipes[0] = 0; localpipes[1] = 0; pipe(localpipes); repsock = new reply_socket(zmq_ctx, keyval, boost::bind(&query_object_server_replica::replica_reply_callback, this, _1, _2)); subsock = new subscribe_socket(zmq_ctx, keyval, boost::bind(&query_object_server_replica::subscribe_callback, this, _1)); waiting_for_snapshot = true; assert(repsock->reserve_key(get_zk_objectkey_name(objectkey, replicaid))); subsock->subscribe(""); subsock->connect(get_publish_key(objectkey)); subsock->add_to_pollset(&pollset); pollset.start_poll_thread(); } query_object_server_replica::~query_object_server_replica() { subsock->remove_from_pollset(); repsock->remove_from_pollset(); close(localpipes[0]); close(localpipes[1]); delete subsock; delete repsock; } int query_object_server_replica::start() { // spawn a client to request for a serialization of the server query_object_client client(z_ctx, keyval, 0); void* handle = client.get_object_handle(objectkey); assert(handle != NULL); query_object_client::query_result res = client.query_update_general(handle, NULL, 0, QO_MESSAGE_FLAG_GET_SERIALIZED_CONTENTS | QO_MESSAGE_FLAG_QUERY); res.wait(); if (res.get_status() != 0) { std::cout << "Unable to acquire serialized object from master.\n"; return -1; } else { waiting_for_snapshot = false; qobj->deserialize(res.get_reply().c_str(), res.get_reply().length()); qobj->version = res.reply_header_version(); playback_recorded_messages(); } repsock->add_to_pollset(&pollset); assert(repsock->register_key(get_zk_objectkey_name(objectkey, replicaid))); // ok. now watch for changes. if the server goes down... etc zk_kv_callback_id = keyval->add_callback( boost::bind(&query_object_server_replica::keyval_change, this, _1, _2, _3, _4)); int ret; pollfd pfd[2]; pfd[0].fd = STDIN_FILENO; pfd[0].revents = 0; pfd[0].events = POLLIN; pfd[1].fd = localpipes[0]; pfd[1].revents = 0; pfd[1].events = POLLIN; while(1) { pfd[0].revents = 0; pfd[1].revents = 0; poll(pfd, 2, -1); char buf[64] = {0}; ssize_t buflen = 0; if (pfd[0].revents) { buflen = read(pfd[0].fd, buf, 63); } else if (pfd[1].revents) { buflen = read(pfd[1].fd, buf, 63); } if (buflen > 0) { // null terminate if necessary buf[buflen] = 0; ret = atoi(buf); } if (ret == QO_SERVER_FAIL || ret == QO_SERVER_STOP || ret == QO_SERVER_PROMOTE) { break; } else if (ret == QO_SERVER_PRINT) { std::cout << "\t" << objectkey << ":" << replicaid << "\n"; } } keyval->remove_callback(zk_kv_callback_id); pollset.stop_poll_thread(); repsock->unregister_all_keys(); return ret; } void query_object_server_replica::playback_recorded_messages(){ for (size_t i = 0;i < buffered_messages.size(); ++i) { uint64_t version = (*(size_t*)zmq_msg_data(buffered_messages[i].front())); if (version >= qobj->version) { buffered_messages[i].pop_front(); zmq_msg_vector ignored_reply; bool hasreply = false; qobj->message_wrapper(buffered_messages[i], ignored_reply, &hasreply, QO_MESSAGE_FLAG_NOREPLY); } } buffered_messages.clear(); } bool query_object_server_replica::replica_reply_callback(zmq_msg_vector& recv, zmq_msg_vector& reply) { bool hasreply = false; reply.clear(); bool is_shared_lock = false; query_object_message qrecv; qobj->parse_message(recv, qrecv); // acquire lock if (qrecv.header.flags & QO_MESSAGE_FLAG_QUERY) { query_obj_rwlock.lock_shared(); is_shared_lock = true; } else { query_obj_rwlock.lock(); is_shared_lock = false; } qobj->process_message(qrecv, reply, &hasreply); // release the lock if (is_shared_lock) { query_obj_rwlock.unlock_shared(); } else { query_obj_rwlock.unlock(); } return hasreply; } bool query_object_server_replica::subscribe_callback(zmq_msg_vector& recv) { if (waiting_for_snapshot) { buffered_messages.push_back(recv); return false; } else { assert(zmq_msg_size(recv.front()) == sizeof(uint64_t)); uint64_t version = (*(size_t*)zmq_msg_data(recv.front())); if (version != qobj->version) { std::cout << "Slave master version divergence\n"; } recv.pop_front(); bool hasreply = false; zmq_msg_vector ignored_reply; // parse the message to determine if it a query or an update // (thus read lock, or write lock) query_object_message qrecv; qobj->parse_message(recv, qrecv); bool is_shared_lock = false; if (qrecv.header.flags & QO_MESSAGE_FLAG_QUERY) { query_obj_rwlock.lock_shared(); is_shared_lock = true; } else { query_obj_rwlock.lock(); is_shared_lock = false; } // set the no reply flag qrecv.header.flags |= QO_MESSAGE_FLAG_NOREPLY; qobj->process_message(qrecv, ignored_reply, &hasreply); // release the lcok if (is_shared_lock) { query_obj_rwlock.unlock_shared(); } else { query_obj_rwlock.unlock(); } return false; } } void query_object_server_replica::keyval_change(graphlab::zookeeper_util::key_value* unused, const std::vector<std::string>& newkeys, const std::vector<std::string>& deletedkeys, const std::vector<std::string>& modifiedkeys) { // if the master for this key was deleted if (std::find(deletedkeys.begin(), deletedkeys.end(), objectkey) != deletedkeys.end()) { if (master_election(keyval, objectkey)) { // halt and promote const char* promote = QO_SERVER_PROMOTE_STR; write(localpipes[1], promote, strlen(promote)); } } } } // namespace
bsd-3-clause
mirror/libtorrent
src/receive_buffer.cpp
5
12278
/* Copyright (c) 2014, Arvid Norberg, Steven Siloti All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <libtorrent/receive_buffer.hpp> namespace libtorrent { int round_up8(int v) { return ((v & 7) == 0) ? v : v + (8 - (v & 7)); } int receive_buffer::max_receive() { int max = packet_bytes_remaining(); if (m_recv_pos >= m_soft_packet_size) m_soft_packet_size = 0; if (m_soft_packet_size && max > m_soft_packet_size - m_recv_pos) max = m_soft_packet_size - m_recv_pos; return max; } boost::asio::mutable_buffer receive_buffer::reserve(int size) { TORRENT_ASSERT(size > 0); TORRENT_ASSERT(!m_disk_recv_buffer); m_recv_buffer.resize(m_recv_pos + size); return boost::asio::buffer(&m_recv_buffer[m_recv_pos], size); } int receive_buffer::reserve(boost::array<boost::asio::mutable_buffer, 2>& vec, int size) { TORRENT_ASSERT(size > 0); TORRENT_ASSERT(m_recv_pos >= 0); TORRENT_ASSERT(m_packet_size > 0); int num_bufs; int regular_buf_size = regular_buffer_size(); if (int(m_recv_buffer.size()) < regular_buf_size) m_recv_buffer.resize(round_up8(regular_buf_size)); if (!m_disk_recv_buffer || regular_buf_size >= m_recv_pos + size) { // only receive into regular buffer TORRENT_ASSERT(m_recv_pos + size <= int(m_recv_buffer.size())); vec[0] = boost::asio::buffer(&m_recv_buffer[m_recv_pos], size); TORRENT_ASSERT(boost::asio::buffer_size(vec[0]) > 0); num_bufs = 1; } else if (m_recv_pos >= regular_buf_size) { // only receive into disk buffer TORRENT_ASSERT(m_recv_pos - regular_buf_size >= 0); TORRENT_ASSERT(m_recv_pos - regular_buf_size + size <= m_disk_recv_buffer_size); vec[0] = boost::asio::buffer(m_disk_recv_buffer.get() + m_recv_pos - regular_buf_size, size); TORRENT_ASSERT(boost::asio::buffer_size(vec[0]) > 0); num_bufs = 1; } else { // receive into both regular and disk buffer TORRENT_ASSERT(size + m_recv_pos > regular_buf_size); TORRENT_ASSERT(m_recv_pos < regular_buf_size); TORRENT_ASSERT(size - regular_buf_size + m_recv_pos <= m_disk_recv_buffer_size); vec[0] = boost::asio::buffer(&m_recv_buffer[m_recv_pos] , regular_buf_size - m_recv_pos); vec[1] = boost::asio::buffer(m_disk_recv_buffer.get() , size - regular_buf_size + m_recv_pos); TORRENT_ASSERT(boost::asio::buffer_size(vec[0]) + boost::asio::buffer_size(vec[1])> 0); num_bufs = 2; } return num_bufs; } int receive_buffer::advance_pos(int bytes) { int packet_size = m_soft_packet_size ? m_soft_packet_size : m_packet_size; int limit = packet_size > m_recv_pos ? packet_size - m_recv_pos : packet_size; int sub_transferred = (std::min)(bytes, limit); m_recv_pos += sub_transferred; if (m_recv_pos >= m_soft_packet_size) m_soft_packet_size = 0; return sub_transferred; } void receive_buffer::clamp_size() { if (m_recv_pos == 0 && (m_recv_buffer.capacity() - m_packet_size) > 128) { // round up to an even 8 bytes since that's the RC4 blocksize buffer(round_up8(m_packet_size)).swap(m_recv_buffer); } } // size = the packet size to remove from the receive buffer // packet_size = the next packet size to receive in the buffer // offset = the offset into the receive buffer where to remove `size` bytes void receive_buffer::cut(int size, int packet_size, int offset) { TORRENT_ASSERT(packet_size > 0); TORRENT_ASSERT(int(m_recv_buffer.size()) >= size); TORRENT_ASSERT(int(m_recv_buffer.size()) >= m_recv_pos); TORRENT_ASSERT(m_recv_pos >= size + offset); TORRENT_ASSERT(offset >= 0); TORRENT_ASSERT(m_recv_buffer.size() >= m_recv_end); TORRENT_ASSERT(m_recv_start <= m_recv_end); TORRENT_ASSERT(size >= 0); if (offset > 0) { TORRENT_ASSERT(m_recv_start - size <= m_recv_end); if (size > 0) std::memmove(&m_recv_buffer[0] + m_recv_start + offset , &m_recv_buffer[0] + m_recv_start + offset + size , m_recv_end - m_recv_start - size - offset); m_recv_pos -= size; m_recv_end -= size; #ifdef TORRENT_DEBUG std::fill(m_recv_buffer.begin() + m_recv_end, m_recv_buffer.end(), 0xcc); #endif } else { TORRENT_ASSERT(m_recv_start + size <= m_recv_end); m_recv_start += size; m_recv_pos -= size; } m_packet_size = packet_size; } buffer::const_interval receive_buffer::get() const { if (m_recv_buffer.empty()) { TORRENT_ASSERT(m_recv_pos == 0); return buffer::interval(0,0); } int rcv_pos = (std::min)(m_recv_pos, int(m_recv_buffer.size())); return buffer::const_interval(&m_recv_buffer[0] + m_recv_start , &m_recv_buffer[0] + m_recv_start + rcv_pos); } #if !defined(TORRENT_DISABLE_ENCRYPTION) && !defined(TORRENT_DISABLE_EXTENSIONS) buffer::interval receive_buffer::mutable_buffer() { if (m_recv_buffer.empty()) { TORRENT_ASSERT(m_recv_pos == 0); return buffer::interval(0,0); } TORRENT_ASSERT(!m_disk_recv_buffer); TORRENT_ASSERT(m_disk_recv_buffer_size == 0); int rcv_pos = (std::min)(m_recv_pos, int(m_recv_buffer.size())); return buffer::interval(&m_recv_buffer[0] + m_recv_start , &m_recv_buffer[0] + m_recv_start + rcv_pos); } void receive_buffer::mutable_buffers(std::vector<boost::asio::mutable_buffer>& vec, int bytes) { using namespace boost; TORRENT_ASSERT(bytes <= m_recv_pos); int regular_buf_size = regular_buffer_size(); TORRENT_ASSERT(regular_buf_size >= 0); if (!m_disk_recv_buffer || regular_buf_size >= m_recv_pos) { vec.push_back(asio::mutable_buffer(&m_recv_buffer[0] + m_recv_start + m_recv_pos - bytes, bytes)); } else if (m_recv_pos - bytes >= regular_buf_size) { vec.push_back(asio::mutable_buffer(m_disk_recv_buffer.get() + m_recv_pos - regular_buf_size - bytes, bytes)); } else { TORRENT_ASSERT(m_recv_pos - bytes < regular_buf_size); TORRENT_ASSERT(m_recv_pos > regular_buf_size); vec.push_back(asio::mutable_buffer(&m_recv_buffer[0] + m_recv_start + m_recv_pos - bytes , regular_buf_size - (m_recv_start + m_recv_pos - bytes))); vec.push_back(asio::mutable_buffer(m_disk_recv_buffer.get() , m_recv_pos - regular_buf_size)); } #if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS int vec_bytes = 0; for (std::vector<asio::mutable_buffer>::iterator i = vec.begin(); i != vec.end(); ++i) vec_bytes += boost::asio::buffer_size(*i); TORRENT_ASSERT(vec_bytes == bytes); #endif } #endif void receive_buffer::assign_disk_buffer(char* buffer, int size) { TORRENT_ASSERT(m_packet_size > 0); assert_no_disk_buffer(); m_disk_recv_buffer.reset(buffer); if (m_disk_recv_buffer) m_disk_recv_buffer_size = size; } char* receive_buffer::release_disk_buffer() { if (!m_disk_recv_buffer) return 0; TORRENT_ASSERT(m_disk_recv_buffer_size <= m_recv_end); TORRENT_ASSERT(m_recv_start <= m_recv_end - m_disk_recv_buffer_size); m_recv_end -= m_disk_recv_buffer_size; m_disk_recv_buffer_size = 0; return m_disk_recv_buffer.release(); } // the purpose of this function is to free up and cut off all messages // in the receive buffer that have been parsed and processed. void receive_buffer::normalize() { TORRENT_ASSERT(m_recv_end >= m_recv_start); if (m_recv_start == 0) return; if (m_recv_end > m_recv_start) std::memmove(&m_recv_buffer[0], &m_recv_buffer[0] + m_recv_start, m_recv_end - m_recv_start); m_recv_end -= m_recv_start; m_recv_start = 0; #ifdef TORRENT_DEBUG std::fill(m_recv_buffer.begin() + m_recv_end, m_recv_buffer.end(), 0xcc); #endif } void receive_buffer::reset(int packet_size) { TORRENT_ASSERT(m_recv_buffer.size() >= m_recv_end); TORRENT_ASSERT(packet_size > 0); if (m_recv_end > m_packet_size) { cut(m_packet_size, packet_size); return; } m_recv_pos = 0; m_recv_start = 0; m_recv_end = 0; m_packet_size = packet_size; } #if !defined(TORRENT_DISABLE_ENCRYPTION) && !defined(TORRENT_DISABLE_EXTENSIONS) bool crypto_receive_buffer::packet_finished() const { if (m_recv_pos == INT_MAX) return m_connection_buffer.packet_finished(); else return m_packet_size <= m_recv_pos; } int crypto_receive_buffer::packet_size() const { if (m_recv_pos == INT_MAX) return m_connection_buffer.packet_size(); else return m_packet_size; } int crypto_receive_buffer::pos() const { if (m_recv_pos == INT_MAX) return m_connection_buffer.pos(); else return m_recv_pos; } void crypto_receive_buffer::cut(int size, int packet_size, int offset) { if (m_recv_pos != INT_MAX) { TORRENT_ASSERT(size <= m_recv_pos); m_packet_size = packet_size; packet_size = m_connection_buffer.packet_size() - size; m_recv_pos -= size; } m_connection_buffer.cut(size, packet_size, offset); } void crypto_receive_buffer::reset(int packet_size) { if (m_recv_pos != INT_MAX) { if (m_connection_buffer.m_recv_end > m_packet_size) { cut(m_packet_size, packet_size); return; } m_packet_size = packet_size; packet_size = m_connection_buffer.packet_size() - m_recv_pos; m_recv_pos = 0; } m_connection_buffer.reset(packet_size); } void crypto_receive_buffer::crypto_reset(int packet_size) { TORRENT_ASSERT(packet_finished()); TORRENT_ASSERT(crypto_packet_finished()); TORRENT_ASSERT(m_recv_pos == INT_MAX || m_recv_pos == m_connection_buffer.pos()); TORRENT_ASSERT(m_recv_pos == INT_MAX || m_connection_buffer.pos_at_end()); TORRENT_ASSERT(!m_connection_buffer.has_disk_buffer()); if (packet_size == 0) { if (m_recv_pos != INT_MAX) m_connection_buffer.cut(0, m_packet_size); m_recv_pos = INT_MAX; } else { if (m_recv_pos == INT_MAX) m_packet_size = m_connection_buffer.packet_size(); m_recv_pos = m_connection_buffer.pos(); TORRENT_ASSERT(m_recv_pos >= 0); m_connection_buffer.cut(0, m_recv_pos + packet_size); } } void crypto_receive_buffer::set_soft_packet_size(int size) { if (m_recv_pos == INT_MAX) m_connection_buffer.set_soft_packet_size(size); else m_soft_packet_size = size; } int crypto_receive_buffer::advance_pos(int bytes) { if (m_recv_pos == INT_MAX) return bytes; int packet_size = m_soft_packet_size ? m_soft_packet_size : m_packet_size; int limit = packet_size > m_recv_pos ? packet_size - m_recv_pos : packet_size; int sub_transferred = (std::min)(bytes, limit); m_recv_pos += sub_transferred; m_connection_buffer.cut(0, m_connection_buffer.packet_size() + sub_transferred); if (m_recv_pos >= m_soft_packet_size) m_soft_packet_size = 0; return sub_transferred; } buffer::const_interval crypto_receive_buffer::get() const { buffer::const_interval recv_buffer = m_connection_buffer.get(); if (m_recv_pos < m_connection_buffer.pos()) recv_buffer.end = recv_buffer.begin + m_recv_pos; return recv_buffer; } void crypto_receive_buffer::mutable_buffers( std::vector<boost::asio::mutable_buffer>& vec , std::size_t bytes_transfered) { int pending_decryption = bytes_transfered; if (m_recv_pos != INT_MAX) { pending_decryption = m_connection_buffer.packet_size() - m_recv_pos; } m_connection_buffer.mutable_buffers(vec, pending_decryption); } #endif // TORRENT_DISABLE_ENCRYPTION } // namespace libtorrent
bsd-3-clause
ehein6/stinger
src/clients/tools/json_rpc_server/src/get_data_array_set.cpp
6
2568
#include "json_rpc_server.h" #include "json_rpc.h" #include "rapidjson/document.h" #define LOG_AT_W /* warning only */ #include "stinger_core/stinger_error.h" using namespace gt::stinger; int64_t JSON_RPC_get_data_array_set::operator()(rapidjson::Value * params, rapidjson::Value & result, rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator> & allocator) { char * algorithm_name; char * data_array_name; params_array_t set_array; params_array_t vtype_array; bool strings; rpc_params_t p[] = { {"name", TYPE_STRING, &algorithm_name, false, 0}, {"data", TYPE_STRING, &data_array_name, false, 0}, {"set", TYPE_ARRAY, &set_array, false, 0}, {"strings", TYPE_BOOL, &strings, true, 0}, {"vtypes", TYPE_ARRAY, &vtype_array, true, 0}, {NULL, TYPE_NONE, NULL, false, 0} }; rapidjson::Value max_time_seen; max_time_seen.SetInt64(server_state->get_max_time()); if (contains_params(p, params)) { StingerAlgState * alg_state = server_state->get_alg(algorithm_name); if (!alg_state) { if(0 != strcmp("stinger", algorithm_name)) { LOG_E ("Algorithm is not running"); return json_rpc_error(-32003, result, allocator); } else { LOG_D_A ("Checking Stinger Algorithm: %s", algorithm_name); result.AddMember("time", max_time_seen, allocator); stinger_t * S = server_state->get_stinger(); char * data_description = stinger_local_state_get_data_description(S); int64_t rtn = array_to_json_monolithic ( SET, S, result, allocator, data_description, // alg_state->data_description.c_str(), stinger_mapping_nv(S), NULL, // (uint8_t *) alg_state->data, strings, data_array_name, vtype_array.arr, vtype_array.len, 1, false, 0, 0, NULL, set_array.arr, set_array.len ); return rtn; } } result.AddMember("time", max_time_seen, allocator); return array_to_json_monolithic ( SET, server_state->get_stinger(), result, allocator, alg_state->data_description.c_str(), stinger_mapping_nv(server_state->get_stinger()), (uint8_t *) alg_state->data, strings, data_array_name, vtype_array.arr, vtype_array.len, 1, false, 0, 0, NULL, set_array.arr, set_array.len ); } else { LOG_W ("didn't have the right params"); return json_rpc_error(-32602, result, allocator); } }
bsd-3-clause
MohamedSeliem/contiki
platform/srf06-cc26xx/common/board-spi.c
7
5385
/* * Copyright (c) 2014, Texas Instruments Incorporated - http://www.ti.com/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /*---------------------------------------------------------------------------*/ /** * \addtogroup sensortag-cc26xx-spi * @{ * * \file * Board-specific SPI driver common to the Sensortag and LaunchPad */ /*---------------------------------------------------------------------------*/ #include "contiki.h" #include "ti-lib.h" #include "board-spi.h" #include "board.h" #include <stdbool.h> /*---------------------------------------------------------------------------*/ static bool accessible(void) { /* First, check the PD */ if(ti_lib_prcm_power_domain_status(PRCM_DOMAIN_SERIAL) != PRCM_DOMAIN_POWER_ON) { return false; } /* Then check the 'run mode' clock gate */ if(!(HWREG(PRCM_BASE + PRCM_O_SSICLKGR) & PRCM_SSICLKGR_CLK_EN_SSI0)) { return false; } return true; } /*---------------------------------------------------------------------------*/ bool board_spi_write(const uint8_t *buf, size_t len) { if(accessible() == false) { return false; } while(len > 0) { uint32_t ul; ti_lib_ssi_data_put(SSI0_BASE, *buf); ti_lib_rom_ssi_data_get(SSI0_BASE, &ul); len--; buf++; } return true; } /*---------------------------------------------------------------------------*/ bool board_spi_read(uint8_t *buf, size_t len) { if(accessible() == false) { return false; } while(len > 0) { uint32_t ul; if(!ti_lib_rom_ssi_data_put_non_blocking(SSI0_BASE, 0)) { /* Error */ return false; } ti_lib_rom_ssi_data_get(SSI0_BASE, &ul); *buf = (uint8_t)ul; len--; buf++; } return true; } /*---------------------------------------------------------------------------*/ void board_spi_flush() { if(accessible() == false) { return; } uint32_t ul; while(ti_lib_rom_ssi_data_get_non_blocking(SSI0_BASE, &ul)); } /*---------------------------------------------------------------------------*/ void board_spi_open(uint32_t bit_rate, uint32_t clk_pin) { uint32_t buf; /* First, make sure the SERIAL PD is on */ ti_lib_prcm_power_domain_on(PRCM_DOMAIN_SERIAL); while((ti_lib_prcm_power_domain_status(PRCM_DOMAIN_SERIAL) != PRCM_DOMAIN_POWER_ON)); /* Enable clock in active mode */ ti_lib_rom_prcm_peripheral_run_enable(PRCM_PERIPH_SSI0); ti_lib_prcm_load_set(); while(!ti_lib_prcm_load_get()); /* SPI configuration */ ti_lib_ssi_int_disable(SSI0_BASE, SSI_RXOR | SSI_RXFF | SSI_RXTO | SSI_TXFF); ti_lib_ssi_int_clear(SSI0_BASE, SSI_RXOR | SSI_RXTO); ti_lib_rom_ssi_config_set_exp_clk(SSI0_BASE, ti_lib_sys_ctrl_clock_get(), SSI_FRF_MOTO_MODE_0, SSI_MODE_MASTER, bit_rate, 8); ti_lib_rom_ioc_pin_type_ssi_master(SSI0_BASE, BOARD_IOID_SPI_MISO, BOARD_IOID_SPI_MOSI, IOID_UNUSED, clk_pin); ti_lib_ssi_enable(SSI0_BASE); /* Get rid of residual data from SSI port */ while(ti_lib_ssi_data_get_non_blocking(SSI0_BASE, &buf)); } /*---------------------------------------------------------------------------*/ void board_spi_close() { /* Power down SSI0 */ ti_lib_rom_prcm_peripheral_run_disable(PRCM_PERIPH_SSI0); ti_lib_prcm_load_set(); while(!ti_lib_prcm_load_get()); /* Restore pins to a low-consumption state */ ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SPI_MISO); ti_lib_ioc_io_port_pull_set(BOARD_IOID_SPI_MISO, IOC_IOPULL_DOWN); ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SPI_MOSI); ti_lib_ioc_io_port_pull_set(BOARD_IOID_SPI_MOSI, IOC_IOPULL_DOWN); ti_lib_ioc_pin_type_gpio_input(BOARD_IOID_SPI_CLK_FLASH); ti_lib_ioc_io_port_pull_set(BOARD_IOID_SPI_CLK_FLASH, IOC_IOPULL_DOWN); } /*---------------------------------------------------------------------------*/ /** @} */
bsd-3-clause
holtgrewe/seqan
extras/demos/tutorial/data_journaling/example_journal_string_basic.cpp
8
1438
// FRAGMENT(main) #include <iostream> #include <seqan/file.h> #include <seqan/sequence_journaled.h> using namespace seqan; int main() { // FRAGMENT(typedef) typedef String<char, Journaled<Alloc<>, SortedArray, Alloc<> > > TJournaledString; typedef Host<TJournaledString>::Type THost; // FRAGMENT(init) String<char> hostStr = "thisisahostsequence"; TJournaledString journalStr; setHost(journalStr, hostStr); std::cout << "After creating the Journaled String:" << std::endl; std::cout << "Host: " << host(journalStr) << std::endl; std::cout << "Journal: "<< journalStr << std::endl; std::cout << "Nodes: " << journalStr._journalEntries << std::endl; std::cout << std::endl; // FRAGMENT(modification) insert(journalStr, 7, "modified"); erase(journalStr, 19,27); std::cout << "After modifying the Journaled String:" << std::endl; std::cout << "Host: " << host(journalStr) << std::endl; std::cout << "Journal: " << journalStr << std::endl; std::cout << "Nodes: " << journalStr._journalEntries << std::endl; std::cout << std::endl; // FRAGMENT(flatten) flatten(journalStr); std::cout << "After flatten the Journaled String:" << std::endl; std::cout << "Host: " << host(journalStr) << std::endl; std::cout << "Journal: " << journalStr << std::endl; std::cout << "Nodes: " << journalStr._journalEntries << std::endl; return 0; }
bsd-3-clause
yoannd/mtcp
dpdk-2.2.0/lib/share/dpdk/examples/ip_pipeline/pipeline/pipeline_firewall.c
8
46457
/*- * BSD LICENSE * * Copyright(c) 2010-2015 Intel Corporation. All rights reserved. * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <string.h> #include <sys/queue.h> #include <netinet/in.h> #include <rte_common.h> #include <rte_hexdump.h> #include <rte_malloc.h> #include <cmdline_rdline.h> #include <cmdline_parse.h> #include <cmdline_parse_num.h> #include <cmdline_parse_string.h> #include <cmdline_parse_ipaddr.h> #include <cmdline_parse_etheraddr.h> #include <cmdline_socket.h> #include "app.h" #include "pipeline_common_fe.h" #include "pipeline_firewall.h" #define BUF_SIZE 1024 struct app_pipeline_firewall_rule { struct pipeline_firewall_key key; int32_t priority; uint32_t port_id; void *entry_ptr; TAILQ_ENTRY(app_pipeline_firewall_rule) node; }; struct app_pipeline_firewall { /* parameters */ uint32_t n_ports_in; uint32_t n_ports_out; /* rules */ TAILQ_HEAD(, app_pipeline_firewall_rule) rules; uint32_t n_rules; uint32_t default_rule_present; uint32_t default_rule_port_id; void *default_rule_entry_ptr; }; struct app_pipeline_add_bulk_params { struct pipeline_firewall_key *keys; uint32_t n_keys; uint32_t *priorities; uint32_t *port_ids; }; struct app_pipeline_del_bulk_params { struct pipeline_firewall_key *keys; uint32_t n_keys; }; static void print_firewall_ipv4_rule(struct app_pipeline_firewall_rule *rule) { printf("Prio = %" PRId32 " (SA = %" PRIu32 ".%" PRIu32 ".%" PRIu32 ".%" PRIu32 "/%" PRIu32 ", " "DA = %" PRIu32 ".%" PRIu32 ".%"PRIu32 ".%" PRIu32 "/%" PRIu32 ", " "SP = %" PRIu32 "-%" PRIu32 ", " "DP = %" PRIu32 "-%" PRIu32 ", " "Proto = %" PRIu32 " / 0x%" PRIx32 ") => " "Port = %" PRIu32 " (entry ptr = %p)\n", rule->priority, (rule->key.key.ipv4_5tuple.src_ip >> 24) & 0xFF, (rule->key.key.ipv4_5tuple.src_ip >> 16) & 0xFF, (rule->key.key.ipv4_5tuple.src_ip >> 8) & 0xFF, rule->key.key.ipv4_5tuple.src_ip & 0xFF, rule->key.key.ipv4_5tuple.src_ip_mask, (rule->key.key.ipv4_5tuple.dst_ip >> 24) & 0xFF, (rule->key.key.ipv4_5tuple.dst_ip >> 16) & 0xFF, (rule->key.key.ipv4_5tuple.dst_ip >> 8) & 0xFF, rule->key.key.ipv4_5tuple.dst_ip & 0xFF, rule->key.key.ipv4_5tuple.dst_ip_mask, rule->key.key.ipv4_5tuple.src_port_from, rule->key.key.ipv4_5tuple.src_port_to, rule->key.key.ipv4_5tuple.dst_port_from, rule->key.key.ipv4_5tuple.dst_port_to, rule->key.key.ipv4_5tuple.proto, rule->key.key.ipv4_5tuple.proto_mask, rule->port_id, rule->entry_ptr); } static struct app_pipeline_firewall_rule * app_pipeline_firewall_rule_find(struct app_pipeline_firewall *p, struct pipeline_firewall_key *key) { struct app_pipeline_firewall_rule *r; TAILQ_FOREACH(r, &p->rules, node) if (memcmp(key, &r->key, sizeof(struct pipeline_firewall_key)) == 0) return r; return NULL; } static int app_pipeline_firewall_ls( struct app_params *app, uint32_t pipeline_id) { struct app_pipeline_firewall *p; struct app_pipeline_firewall_rule *rule; uint32_t n_rules; int priority; /* Check input arguments */ if (app == NULL) return -1; p = app_pipeline_data_fe(app, pipeline_id, &pipeline_firewall); if (p == NULL) return -1; n_rules = p->n_rules; for (priority = 0; n_rules; priority++) TAILQ_FOREACH(rule, &p->rules, node) if (rule->priority == priority) { print_firewall_ipv4_rule(rule); n_rules--; } if (p->default_rule_present) printf("Default rule: port %" PRIu32 " (entry ptr = %p)\n", p->default_rule_port_id, p->default_rule_entry_ptr); else printf("Default rule: DROP\n"); printf("\n"); return 0; } static void* app_pipeline_firewall_init(struct pipeline_params *params, __rte_unused void *arg) { struct app_pipeline_firewall *p; uint32_t size; /* Check input arguments */ if ((params == NULL) || (params->n_ports_in == 0) || (params->n_ports_out == 0)) return NULL; /* Memory allocation */ size = RTE_CACHE_LINE_ROUNDUP(sizeof(struct app_pipeline_firewall)); p = rte_zmalloc(NULL, size, RTE_CACHE_LINE_SIZE); if (p == NULL) return NULL; /* Initialization */ p->n_ports_in = params->n_ports_in; p->n_ports_out = params->n_ports_out; TAILQ_INIT(&p->rules); p->n_rules = 0; p->default_rule_present = 0; p->default_rule_port_id = 0; p->default_rule_entry_ptr = NULL; return (void *) p; } static int app_pipeline_firewall_free(void *pipeline) { struct app_pipeline_firewall *p = pipeline; /* Check input arguments */ if (p == NULL) return -1; /* Free resources */ while (!TAILQ_EMPTY(&p->rules)) { struct app_pipeline_firewall_rule *rule; rule = TAILQ_FIRST(&p->rules); TAILQ_REMOVE(&p->rules, rule, node); rte_free(rule); } rte_free(p); return 0; } static int app_pipeline_firewall_key_check_and_normalize(struct pipeline_firewall_key *key) { switch (key->type) { case PIPELINE_FIREWALL_IPV4_5TUPLE: { uint32_t src_ip_depth = key->key.ipv4_5tuple.src_ip_mask; uint32_t dst_ip_depth = key->key.ipv4_5tuple.dst_ip_mask; uint16_t src_port_from = key->key.ipv4_5tuple.src_port_from; uint16_t src_port_to = key->key.ipv4_5tuple.src_port_to; uint16_t dst_port_from = key->key.ipv4_5tuple.dst_port_from; uint16_t dst_port_to = key->key.ipv4_5tuple.dst_port_to; uint32_t src_ip_netmask = 0; uint32_t dst_ip_netmask = 0; if ((src_ip_depth > 32) || (dst_ip_depth > 32) || (src_port_from > src_port_to) || (dst_port_from > dst_port_to)) return -1; if (src_ip_depth) src_ip_netmask = (~0) << (32 - src_ip_depth); if (dst_ip_depth) dst_ip_netmask = ((~0) << (32 - dst_ip_depth)); key->key.ipv4_5tuple.src_ip &= src_ip_netmask; key->key.ipv4_5tuple.dst_ip &= dst_ip_netmask; return 0; } default: return -1; } } static int app_pipeline_add_bulk_parse_file(char *filename, struct app_pipeline_add_bulk_params *params) { FILE *f; char file_buf[BUF_SIZE]; uint32_t i; int status = 0; f = fopen(filename, "r"); if (f == NULL) return -1; params->n_keys = 0; while (fgets(file_buf, BUF_SIZE, f) != NULL) params->n_keys++; rewind(f); if (params->n_keys == 0) { status = -1; goto end; } params->keys = rte_malloc(NULL, params->n_keys * sizeof(struct pipeline_firewall_key), RTE_CACHE_LINE_SIZE); if (params->keys == NULL) { status = -1; goto end; } params->priorities = rte_malloc(NULL, params->n_keys * sizeof(uint32_t), RTE_CACHE_LINE_SIZE); if (params->priorities == NULL) { status = -1; goto end; } params->port_ids = rte_malloc(NULL, params->n_keys * sizeof(uint32_t), RTE_CACHE_LINE_SIZE); if (params->port_ids == NULL) { status = -1; goto end; } i = 0; while (fgets(file_buf, BUF_SIZE, f) != NULL) { char *str; str = strtok(file_buf, " "); if (str == NULL) { status = -1; goto end; } params->priorities[i] = atoi(str); str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_ip = atoi(str)<<24; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_ip |= atoi(str)<<16; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_ip |= atoi(str)<<8; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_ip |= atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_ip_mask = atoi(str); str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_ip = atoi(str)<<24; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_ip |= atoi(str)<<16; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_ip |= atoi(str)<<8; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_ip |= atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_ip_mask = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_port_from = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_port_to = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_port_from = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_port_to = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.proto = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } /* Need to add 2 to str to skip leading 0x */ params->keys[i].key.ipv4_5tuple.proto_mask = strtol(str+2, NULL, 16); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->port_ids[i] = atoi(str); params->keys[i].type = PIPELINE_FIREWALL_IPV4_5TUPLE; i++; } end: fclose(f); return status; } static int app_pipeline_del_bulk_parse_file(char *filename, struct app_pipeline_del_bulk_params *params) { FILE *f; char file_buf[BUF_SIZE]; uint32_t i; int status = 0; f = fopen(filename, "r"); if (f == NULL) return -1; params->n_keys = 0; while (fgets(file_buf, BUF_SIZE, f) != NULL) params->n_keys++; rewind(f); if (params->n_keys == 0) { status = -1; goto end; } params->keys = rte_malloc(NULL, params->n_keys * sizeof(struct pipeline_firewall_key), RTE_CACHE_LINE_SIZE); if (params->keys == NULL) { status = -1; goto end; } i = 0; while (fgets(file_buf, BUF_SIZE, f) != NULL) { char *str; str = strtok(file_buf, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_ip = atoi(str)<<24; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_ip |= atoi(str)<<16; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_ip |= atoi(str)<<8; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_ip |= atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_ip_mask = atoi(str); str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_ip = atoi(str)<<24; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_ip |= atoi(str)<<16; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_ip |= atoi(str)<<8; str = strtok(NULL, " ."); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_ip |= atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_ip_mask = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_port_from = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.src_port_to = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_port_from = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.dst_port_to = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } params->keys[i].key.ipv4_5tuple.proto = atoi(str); str = strtok(NULL, " "); if (str == NULL) { status = -1; goto end; } /* Need to add 2 to str to skip leading 0x */ params->keys[i].key.ipv4_5tuple.proto_mask = strtol(str+2, NULL, 16); params->keys[i].type = PIPELINE_FIREWALL_IPV4_5TUPLE; i++; } for (i = 0; i < params->n_keys; i++) { if (app_pipeline_firewall_key_check_and_normalize(&params->keys[i]) != 0) { status = -1; goto end; } } end: fclose(f); return status; } int app_pipeline_firewall_add_rule(struct app_params *app, uint32_t pipeline_id, struct pipeline_firewall_key *key, uint32_t priority, uint32_t port_id) { struct app_pipeline_firewall *p; struct app_pipeline_firewall_rule *rule; struct pipeline_firewall_add_msg_req *req; struct pipeline_firewall_add_msg_rsp *rsp; int new_rule; /* Check input arguments */ if ((app == NULL) || (key == NULL) || (key->type != PIPELINE_FIREWALL_IPV4_5TUPLE)) return -1; p = app_pipeline_data_fe(app, pipeline_id, &pipeline_firewall); if (p == NULL) return -1; if (port_id >= p->n_ports_out) return -1; if (app_pipeline_firewall_key_check_and_normalize(key) != 0) return -1; /* Find existing rule or allocate new rule */ rule = app_pipeline_firewall_rule_find(p, key); new_rule = (rule == NULL); if (rule == NULL) { rule = rte_malloc(NULL, sizeof(*rule), RTE_CACHE_LINE_SIZE); if (rule == NULL) return -1; } /* Allocate and write request */ req = app_msg_alloc(app); if (req == NULL) { if (new_rule) rte_free(rule); return -1; } req->type = PIPELINE_MSG_REQ_CUSTOM; req->subtype = PIPELINE_FIREWALL_MSG_REQ_ADD; memcpy(&req->key, key, sizeof(*key)); req->priority = priority; req->port_id = port_id; /* Send request and wait for response */ rsp = app_msg_send_recv(app, pipeline_id, req, MSG_TIMEOUT_DEFAULT); if (rsp == NULL) { if (new_rule) rte_free(rule); return -1; } /* Read response and write rule */ if (rsp->status || (rsp->entry_ptr == NULL) || ((new_rule == 0) && (rsp->key_found == 0)) || ((new_rule == 1) && (rsp->key_found == 1))) { app_msg_free(app, rsp); if (new_rule) rte_free(rule); return -1; } memcpy(&rule->key, key, sizeof(*key)); rule->priority = priority; rule->port_id = port_id; rule->entry_ptr = rsp->entry_ptr; /* Commit rule */ if (new_rule) { TAILQ_INSERT_TAIL(&p->rules, rule, node); p->n_rules++; } print_firewall_ipv4_rule(rule); /* Free response */ app_msg_free(app, rsp); return 0; } int app_pipeline_firewall_delete_rule(struct app_params *app, uint32_t pipeline_id, struct pipeline_firewall_key *key) { struct app_pipeline_firewall *p; struct app_pipeline_firewall_rule *rule; struct pipeline_firewall_del_msg_req *req; struct pipeline_firewall_del_msg_rsp *rsp; /* Check input arguments */ if ((app == NULL) || (key == NULL) || (key->type != PIPELINE_FIREWALL_IPV4_5TUPLE)) return -1; p = app_pipeline_data_fe(app, pipeline_id, &pipeline_firewall); if (p == NULL) return -1; if (app_pipeline_firewall_key_check_and_normalize(key) != 0) return -1; /* Find rule */ rule = app_pipeline_firewall_rule_find(p, key); if (rule == NULL) return 0; /* Allocate and write request */ req = app_msg_alloc(app); if (req == NULL) return -1; req->type = PIPELINE_MSG_REQ_CUSTOM; req->subtype = PIPELINE_FIREWALL_MSG_REQ_DEL; memcpy(&req->key, key, sizeof(*key)); /* Send request and wait for response */ rsp = app_msg_send_recv(app, pipeline_id, req, MSG_TIMEOUT_DEFAULT); if (rsp == NULL) return -1; /* Read response */ if (rsp->status || !rsp->key_found) { app_msg_free(app, rsp); return -1; } /* Remove rule */ TAILQ_REMOVE(&p->rules, rule, node); p->n_rules--; rte_free(rule); /* Free response */ app_msg_free(app, rsp); return 0; } int app_pipeline_firewall_add_bulk(struct app_params *app, uint32_t pipeline_id, struct pipeline_firewall_key *keys, uint32_t n_keys, uint32_t *priorities, uint32_t *port_ids) { struct app_pipeline_firewall *p; struct pipeline_firewall_add_bulk_msg_req *req; struct pipeline_firewall_add_bulk_msg_rsp *rsp; struct app_pipeline_firewall_rule **rules; int *new_rules; int *keys_found; void **entries_ptr; uint32_t i; int status = 0; /* Check input arguments */ if (app == NULL) return -1; p = app_pipeline_data_fe(app, pipeline_id, &pipeline_firewall); if (p == NULL) return -1; rules = rte_malloc(NULL, n_keys * sizeof(struct app_pipeline_firewall_rule *), RTE_CACHE_LINE_SIZE); if (rules == NULL) return -1; new_rules = rte_malloc(NULL, n_keys * sizeof(int), RTE_CACHE_LINE_SIZE); if (new_rules == NULL) { rte_free(rules); return -1; } /* check data integrity and add to rule list */ for (i = 0; i < n_keys; i++) { if (port_ids[i] >= p->n_ports_out) { rte_free(rules); rte_free(new_rules); return -1; } if (app_pipeline_firewall_key_check_and_normalize(&keys[i]) != 0) { rte_free(rules); rte_free(new_rules); return -1; } rules[i] = app_pipeline_firewall_rule_find(p, &keys[i]); new_rules[i] = (rules[i] == NULL); if (rules[i] == NULL) { rules[i] = rte_malloc(NULL, sizeof(rules[i]), RTE_CACHE_LINE_SIZE); if (rules[i] == NULL) { uint32_t j; for (j = 0; j <= i; j++) if (new_rules[j]) rte_free(rules[j]); rte_free(rules); rte_free(new_rules); return -1; } } } keys_found = rte_malloc(NULL, n_keys * sizeof(int), RTE_CACHE_LINE_SIZE); if (keys_found == NULL) { uint32_t j; for (j = 0; j < n_keys; j++) if (new_rules[j]) rte_free(rules[j]); rte_free(rules); rte_free(new_rules); return -1; } entries_ptr = rte_malloc(NULL, n_keys * sizeof(struct rte_pipeline_table_entry *), RTE_CACHE_LINE_SIZE); if (entries_ptr == NULL) { uint32_t j; for (j = 0; j < n_keys; j++) if (new_rules[j]) rte_free(rules[j]); rte_free(rules); rte_free(new_rules); rte_free(keys_found); return -1; } for (i = 0; i < n_keys; i++) { entries_ptr[i] = rte_malloc(NULL, sizeof(struct rte_pipeline_table_entry), RTE_CACHE_LINE_SIZE); if (entries_ptr[i] == NULL) { uint32_t j; for (j = 0; j < n_keys; j++) if (new_rules[j]) rte_free(rules[j]); for (j = 0; j <= i; j++) rte_free(entries_ptr[j]); rte_free(rules); rte_free(new_rules); rte_free(keys_found); rte_free(entries_ptr); return -1; } } /* Allocate and write request */ req = app_msg_alloc(app); if (req == NULL) { uint32_t j; for (j = 0; j < n_keys; j++) if (new_rules[j]) rte_free(rules[j]); for (j = 0; j < n_keys; j++) rte_free(entries_ptr[j]); rte_free(rules); rte_free(new_rules); rte_free(keys_found); rte_free(entries_ptr); return -1; } req->type = PIPELINE_MSG_REQ_CUSTOM; req->subtype = PIPELINE_FIREWALL_MSG_REQ_ADD_BULK; req->keys = keys; req->n_keys = n_keys; req->port_ids = port_ids; req->priorities = priorities; req->keys_found = keys_found; req->entries_ptr = entries_ptr; /* Send request and wait for response */ rsp = app_msg_send_recv(app, pipeline_id, req, MSG_TIMEOUT_DEFAULT); if (rsp == NULL) { uint32_t j; for (j = 0; j < n_keys; j++) if (new_rules[j]) rte_free(rules[j]); for (j = 0; j < n_keys; j++) rte_free(entries_ptr[j]); rte_free(rules); rte_free(new_rules); rte_free(keys_found); rte_free(entries_ptr); return -1; } if (rsp->status) { for (i = 0; i < n_keys; i++) if (new_rules[i]) rte_free(rules[i]); for (i = 0; i < n_keys; i++) rte_free(entries_ptr[i]); status = -1; goto cleanup; } for (i = 0; i < n_keys; i++) { if (entries_ptr[i] == NULL || ((new_rules[i] == 0) && (keys_found[i] == 0)) || ((new_rules[i] == 1) && (keys_found[i] == 1))) { for (i = 0; i < n_keys; i++) if (new_rules[i]) rte_free(rules[i]); for (i = 0; i < n_keys; i++) rte_free(entries_ptr[i]); status = -1; goto cleanup; } } for (i = 0; i < n_keys; i++) { memcpy(&rules[i]->key, &keys[i], sizeof(keys[i])); rules[i]->priority = priorities[i]; rules[i]->port_id = port_ids[i]; rules[i]->entry_ptr = entries_ptr[i]; /* Commit rule */ if (new_rules[i]) { TAILQ_INSERT_TAIL(&p->rules, rules[i], node); p->n_rules++; } print_firewall_ipv4_rule(rules[i]); } cleanup: app_msg_free(app, rsp); rte_free(rules); rte_free(new_rules); rte_free(keys_found); rte_free(entries_ptr); return status; } int app_pipeline_firewall_delete_bulk(struct app_params *app, uint32_t pipeline_id, struct pipeline_firewall_key *keys, uint32_t n_keys) { struct app_pipeline_firewall *p; struct pipeline_firewall_del_bulk_msg_req *req; struct pipeline_firewall_del_bulk_msg_rsp *rsp; struct app_pipeline_firewall_rule **rules; int *keys_found; uint32_t i; int status = 0; /* Check input arguments */ if (app == NULL) return -1; p = app_pipeline_data_fe(app, pipeline_id, &pipeline_firewall); if (p == NULL) return -1; rules = rte_malloc(NULL, n_keys * sizeof(struct app_pipeline_firewall_rule *), RTE_CACHE_LINE_SIZE); if (rules == NULL) return -1; for (i = 0; i < n_keys; i++) { if (app_pipeline_firewall_key_check_and_normalize(&keys[i]) != 0) { return -1; } rules[i] = app_pipeline_firewall_rule_find(p, &keys[i]); } keys_found = rte_malloc(NULL, n_keys * sizeof(int), RTE_CACHE_LINE_SIZE); if (keys_found == NULL) { rte_free(rules); return -1; } /* Allocate and write request */ req = app_msg_alloc(app); if (req == NULL) { rte_free(rules); rte_free(keys_found); return -1; } req->type = PIPELINE_MSG_REQ_CUSTOM; req->subtype = PIPELINE_FIREWALL_MSG_REQ_DEL_BULK; req->keys = keys; req->n_keys = n_keys; req->keys_found = keys_found; /* Send request and wait for response */ rsp = app_msg_send_recv(app, pipeline_id, req, MSG_TIMEOUT_DEFAULT); if (rsp == NULL) { rte_free(rules); rte_free(keys_found); return -1; } if (rsp->status) { status = -1; goto cleanup; } for (i = 0; i < n_keys; i++) { if (keys_found[i] == 0) { status = -1; goto cleanup; } } for (i = 0; i < n_keys; i++) { TAILQ_REMOVE(&p->rules, rules[i], node); p->n_rules--; rte_free(rules[i]); } cleanup: app_msg_free(app, rsp); rte_free(rules); rte_free(keys_found); return status; } int app_pipeline_firewall_add_default_rule(struct app_params *app, uint32_t pipeline_id, uint32_t port_id) { struct app_pipeline_firewall *p; struct pipeline_firewall_add_default_msg_req *req; struct pipeline_firewall_add_default_msg_rsp *rsp; /* Check input arguments */ if (app == NULL) return -1; p = app_pipeline_data_fe(app, pipeline_id, &pipeline_firewall); if (p == NULL) return -1; if (port_id >= p->n_ports_out) return -1; /* Allocate and write request */ req = app_msg_alloc(app); if (req == NULL) return -1; req->type = PIPELINE_MSG_REQ_CUSTOM; req->subtype = PIPELINE_FIREWALL_MSG_REQ_ADD_DEFAULT; req->port_id = port_id; /* Send request and wait for response */ rsp = app_msg_send_recv(app, pipeline_id, req, MSG_TIMEOUT_DEFAULT); if (rsp == NULL) return -1; /* Read response and write rule */ if (rsp->status || (rsp->entry_ptr == NULL)) { app_msg_free(app, rsp); return -1; } p->default_rule_port_id = port_id; p->default_rule_entry_ptr = rsp->entry_ptr; /* Commit rule */ p->default_rule_present = 1; /* Free response */ app_msg_free(app, rsp); return 0; } int app_pipeline_firewall_delete_default_rule(struct app_params *app, uint32_t pipeline_id) { struct app_pipeline_firewall *p; struct pipeline_firewall_del_default_msg_req *req; struct pipeline_firewall_del_default_msg_rsp *rsp; /* Check input arguments */ if (app == NULL) return -1; p = app_pipeline_data_fe(app, pipeline_id, &pipeline_firewall); if (p == NULL) return -1; /* Allocate and write request */ req = app_msg_alloc(app); if (req == NULL) return -1; req->type = PIPELINE_MSG_REQ_CUSTOM; req->subtype = PIPELINE_FIREWALL_MSG_REQ_DEL_DEFAULT; /* Send request and wait for response */ rsp = app_msg_send_recv(app, pipeline_id, req, MSG_TIMEOUT_DEFAULT); if (rsp == NULL) return -1; /* Read response and write rule */ if (rsp->status) { app_msg_free(app, rsp); return -1; } /* Commit rule */ p->default_rule_present = 0; /* Free response */ app_msg_free(app, rsp); return 0; } /* * p firewall add ipv4 */ struct cmd_firewall_add_ipv4_result { cmdline_fixed_string_t p_string; uint32_t pipeline_id; cmdline_fixed_string_t firewall_string; cmdline_fixed_string_t add_string; cmdline_fixed_string_t ipv4_string; int32_t priority; cmdline_ipaddr_t src_ip; uint32_t src_ip_mask; cmdline_ipaddr_t dst_ip; uint32_t dst_ip_mask; uint16_t src_port_from; uint16_t src_port_to; uint16_t dst_port_from; uint16_t dst_port_to; uint8_t proto; uint8_t proto_mask; uint8_t port_id; }; static void cmd_firewall_add_ipv4_parsed( void *parsed_result, __attribute__((unused)) struct cmdline *cl, void *data) { struct cmd_firewall_add_ipv4_result *params = parsed_result; struct app_params *app = data; struct pipeline_firewall_key key; int status; key.type = PIPELINE_FIREWALL_IPV4_5TUPLE; key.key.ipv4_5tuple.src_ip = rte_bswap32( (uint32_t) params->src_ip.addr.ipv4.s_addr); key.key.ipv4_5tuple.src_ip_mask = params->src_ip_mask; key.key.ipv4_5tuple.dst_ip = rte_bswap32( (uint32_t) params->dst_ip.addr.ipv4.s_addr); key.key.ipv4_5tuple.dst_ip_mask = params->dst_ip_mask; key.key.ipv4_5tuple.src_port_from = params->src_port_from; key.key.ipv4_5tuple.src_port_to = params->src_port_to; key.key.ipv4_5tuple.dst_port_from = params->dst_port_from; key.key.ipv4_5tuple.dst_port_to = params->dst_port_to; key.key.ipv4_5tuple.proto = params->proto; key.key.ipv4_5tuple.proto_mask = params->proto_mask; status = app_pipeline_firewall_add_rule(app, params->pipeline_id, &key, params->priority, params->port_id); if (status != 0) { printf("Command failed\n"); return; } } cmdline_parse_token_string_t cmd_firewall_add_ipv4_p_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_ipv4_result, p_string, "p"); cmdline_parse_token_num_t cmd_firewall_add_ipv4_pipeline_id = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, pipeline_id, UINT32); cmdline_parse_token_string_t cmd_firewall_add_ipv4_firewall_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_ipv4_result, firewall_string, "firewall"); cmdline_parse_token_string_t cmd_firewall_add_ipv4_add_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_ipv4_result, add_string, "add"); cmdline_parse_token_string_t cmd_firewall_add_ipv4_ipv4_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_ipv4_result, ipv4_string, "ipv4"); cmdline_parse_token_num_t cmd_firewall_add_ipv4_priority = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, priority, INT32); cmdline_parse_token_ipaddr_t cmd_firewall_add_ipv4_src_ip = TOKEN_IPV4_INITIALIZER(struct cmd_firewall_add_ipv4_result, src_ip); cmdline_parse_token_num_t cmd_firewall_add_ipv4_src_ip_mask = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, src_ip_mask, UINT32); cmdline_parse_token_ipaddr_t cmd_firewall_add_ipv4_dst_ip = TOKEN_IPV4_INITIALIZER(struct cmd_firewall_add_ipv4_result, dst_ip); cmdline_parse_token_num_t cmd_firewall_add_ipv4_dst_ip_mask = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, dst_ip_mask, UINT32); cmdline_parse_token_num_t cmd_firewall_add_ipv4_src_port_from = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, src_port_from, UINT16); cmdline_parse_token_num_t cmd_firewall_add_ipv4_src_port_to = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, src_port_to, UINT16); cmdline_parse_token_num_t cmd_firewall_add_ipv4_dst_port_from = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, dst_port_from, UINT16); cmdline_parse_token_num_t cmd_firewall_add_ipv4_dst_port_to = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, dst_port_to, UINT16); cmdline_parse_token_num_t cmd_firewall_add_ipv4_proto = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, proto, UINT8); cmdline_parse_token_num_t cmd_firewall_add_ipv4_proto_mask = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, proto_mask, UINT8); cmdline_parse_token_num_t cmd_firewall_add_ipv4_port_id = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_ipv4_result, port_id, UINT8); cmdline_parse_inst_t cmd_firewall_add_ipv4 = { .f = cmd_firewall_add_ipv4_parsed, .data = NULL, .help_str = "Firewall rule add", .tokens = { (void *) &cmd_firewall_add_ipv4_p_string, (void *) &cmd_firewall_add_ipv4_pipeline_id, (void *) &cmd_firewall_add_ipv4_firewall_string, (void *) &cmd_firewall_add_ipv4_add_string, (void *) &cmd_firewall_add_ipv4_ipv4_string, (void *) &cmd_firewall_add_ipv4_priority, (void *) &cmd_firewall_add_ipv4_src_ip, (void *) &cmd_firewall_add_ipv4_src_ip_mask, (void *) &cmd_firewall_add_ipv4_dst_ip, (void *) &cmd_firewall_add_ipv4_dst_ip_mask, (void *) &cmd_firewall_add_ipv4_src_port_from, (void *) &cmd_firewall_add_ipv4_src_port_to, (void *) &cmd_firewall_add_ipv4_dst_port_from, (void *) &cmd_firewall_add_ipv4_dst_port_to, (void *) &cmd_firewall_add_ipv4_proto, (void *) &cmd_firewall_add_ipv4_proto_mask, (void *) &cmd_firewall_add_ipv4_port_id, NULL, }, }; /* * p firewall del ipv4 */ struct cmd_firewall_del_ipv4_result { cmdline_fixed_string_t p_string; uint32_t pipeline_id; cmdline_fixed_string_t firewall_string; cmdline_fixed_string_t del_string; cmdline_fixed_string_t ipv4_string; cmdline_ipaddr_t src_ip; uint32_t src_ip_mask; cmdline_ipaddr_t dst_ip; uint32_t dst_ip_mask; uint16_t src_port_from; uint16_t src_port_to; uint16_t dst_port_from; uint16_t dst_port_to; uint8_t proto; uint8_t proto_mask; }; static void cmd_firewall_del_ipv4_parsed( void *parsed_result, __attribute__((unused)) struct cmdline *cl, void *data) { struct cmd_firewall_del_ipv4_result *params = parsed_result; struct app_params *app = data; struct pipeline_firewall_key key; int status; key.type = PIPELINE_FIREWALL_IPV4_5TUPLE; key.key.ipv4_5tuple.src_ip = rte_bswap32( (uint32_t) params->src_ip.addr.ipv4.s_addr); key.key.ipv4_5tuple.src_ip_mask = params->src_ip_mask; key.key.ipv4_5tuple.dst_ip = rte_bswap32( (uint32_t) params->dst_ip.addr.ipv4.s_addr); key.key.ipv4_5tuple.dst_ip_mask = params->dst_ip_mask; key.key.ipv4_5tuple.src_port_from = params->src_port_from; key.key.ipv4_5tuple.src_port_to = params->src_port_to; key.key.ipv4_5tuple.dst_port_from = params->dst_port_from; key.key.ipv4_5tuple.dst_port_to = params->dst_port_to; key.key.ipv4_5tuple.proto = params->proto; key.key.ipv4_5tuple.proto_mask = params->proto_mask; status = app_pipeline_firewall_delete_rule(app, params->pipeline_id, &key); if (status != 0) { printf("Command failed\n"); return; } } cmdline_parse_token_string_t cmd_firewall_del_ipv4_p_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_ipv4_result, p_string, "p"); cmdline_parse_token_num_t cmd_firewall_del_ipv4_pipeline_id = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_ipv4_result, pipeline_id, UINT32); cmdline_parse_token_string_t cmd_firewall_del_ipv4_firewall_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_ipv4_result, firewall_string, "firewall"); cmdline_parse_token_string_t cmd_firewall_del_ipv4_del_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_ipv4_result, del_string, "del"); cmdline_parse_token_string_t cmd_firewall_del_ipv4_ipv4_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_ipv4_result, ipv4_string, "ipv4"); cmdline_parse_token_ipaddr_t cmd_firewall_del_ipv4_src_ip = TOKEN_IPV4_INITIALIZER(struct cmd_firewall_del_ipv4_result, src_ip); cmdline_parse_token_num_t cmd_firewall_del_ipv4_src_ip_mask = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_ipv4_result, src_ip_mask, UINT32); cmdline_parse_token_ipaddr_t cmd_firewall_del_ipv4_dst_ip = TOKEN_IPV4_INITIALIZER(struct cmd_firewall_del_ipv4_result, dst_ip); cmdline_parse_token_num_t cmd_firewall_del_ipv4_dst_ip_mask = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_ipv4_result, dst_ip_mask, UINT32); cmdline_parse_token_num_t cmd_firewall_del_ipv4_src_port_from = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_ipv4_result, src_port_from, UINT16); cmdline_parse_token_num_t cmd_firewall_del_ipv4_src_port_to = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_ipv4_result, src_port_to, UINT16); cmdline_parse_token_num_t cmd_firewall_del_ipv4_dst_port_from = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_ipv4_result, dst_port_from, UINT16); cmdline_parse_token_num_t cmd_firewall_del_ipv4_dst_port_to = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_ipv4_result, dst_port_to, UINT16); cmdline_parse_token_num_t cmd_firewall_del_ipv4_proto = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_ipv4_result, proto, UINT8); cmdline_parse_token_num_t cmd_firewall_del_ipv4_proto_mask = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_ipv4_result, proto_mask, UINT8); cmdline_parse_inst_t cmd_firewall_del_ipv4 = { .f = cmd_firewall_del_ipv4_parsed, .data = NULL, .help_str = "Firewall rule delete", .tokens = { (void *) &cmd_firewall_del_ipv4_p_string, (void *) &cmd_firewall_del_ipv4_pipeline_id, (void *) &cmd_firewall_del_ipv4_firewall_string, (void *) &cmd_firewall_del_ipv4_del_string, (void *) &cmd_firewall_del_ipv4_ipv4_string, (void *) &cmd_firewall_del_ipv4_src_ip, (void *) &cmd_firewall_del_ipv4_src_ip_mask, (void *) &cmd_firewall_del_ipv4_dst_ip, (void *) &cmd_firewall_del_ipv4_dst_ip_mask, (void *) &cmd_firewall_del_ipv4_src_port_from, (void *) &cmd_firewall_del_ipv4_src_port_to, (void *) &cmd_firewall_del_ipv4_dst_port_from, (void *) &cmd_firewall_del_ipv4_dst_port_to, (void *) &cmd_firewall_del_ipv4_proto, (void *) &cmd_firewall_del_ipv4_proto_mask, NULL, }, }; /* * p firewall add bulk */ struct cmd_firewall_add_bulk_result { cmdline_fixed_string_t p_string; uint32_t pipeline_id; cmdline_fixed_string_t firewall_string; cmdline_fixed_string_t add_string; cmdline_fixed_string_t bulk_string; cmdline_fixed_string_t file_path; }; static void cmd_firewall_add_bulk_parsed( void *parsed_result, __attribute__((unused)) struct cmdline *cl, void *data) { struct cmd_firewall_add_bulk_result *params = parsed_result; struct app_params *app = data; int status; struct app_pipeline_add_bulk_params add_bulk_params; status = app_pipeline_add_bulk_parse_file(params->file_path, &add_bulk_params); if (status != 0) { printf("Command failed\n"); goto end; } status = app_pipeline_firewall_add_bulk(app, params->pipeline_id, add_bulk_params.keys, add_bulk_params.n_keys, add_bulk_params.priorities, add_bulk_params.port_ids); if (status != 0) { printf("Command failed\n"); goto end; } end: rte_free(add_bulk_params.keys); rte_free(add_bulk_params.priorities); rte_free(add_bulk_params.port_ids); } cmdline_parse_token_string_t cmd_firewall_add_bulk_p_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_bulk_result, p_string, "p"); cmdline_parse_token_num_t cmd_firewall_add_bulk_pipeline_id = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_bulk_result, pipeline_id, UINT32); cmdline_parse_token_string_t cmd_firewall_add_bulk_firewall_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_bulk_result, firewall_string, "firewall"); cmdline_parse_token_string_t cmd_firewall_add_bulk_add_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_bulk_result, add_string, "add"); cmdline_parse_token_string_t cmd_firewall_add_bulk_bulk_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_bulk_result, bulk_string, "bulk"); cmdline_parse_token_string_t cmd_firewall_add_bulk_file_path_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_bulk_result, file_path, NULL); cmdline_parse_inst_t cmd_firewall_add_bulk = { .f = cmd_firewall_add_bulk_parsed, .data = NULL, .help_str = "Firewall rule add bulk", .tokens = { (void *) &cmd_firewall_add_bulk_p_string, (void *) &cmd_firewall_add_bulk_pipeline_id, (void *) &cmd_firewall_add_bulk_firewall_string, (void *) &cmd_firewall_add_bulk_add_string, (void *) &cmd_firewall_add_bulk_bulk_string, (void *) &cmd_firewall_add_bulk_file_path_string, NULL, }, }; /* * p firewall del bulk */ struct cmd_firewall_del_bulk_result { cmdline_fixed_string_t p_string; uint32_t pipeline_id; cmdline_fixed_string_t firewall_string; cmdline_fixed_string_t del_string; cmdline_fixed_string_t bulk_string; cmdline_fixed_string_t file_path; }; static void cmd_firewall_del_bulk_parsed( void *parsed_result, __attribute__((unused)) struct cmdline *cl, void *data) { struct cmd_firewall_del_bulk_result *params = parsed_result; struct app_params *app = data; int status; struct app_pipeline_del_bulk_params del_bulk_params; status = app_pipeline_del_bulk_parse_file(params->file_path, &del_bulk_params); if (status != 0) { printf("Command failed\n"); goto end; } status = app_pipeline_firewall_delete_bulk(app, params->pipeline_id, del_bulk_params.keys, del_bulk_params.n_keys); if (status != 0) { printf("Command failed\n"); goto end; } end: rte_free(del_bulk_params.keys); } cmdline_parse_token_string_t cmd_firewall_del_bulk_p_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_bulk_result, p_string, "p"); cmdline_parse_token_num_t cmd_firewall_del_bulk_pipeline_id = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_bulk_result, pipeline_id, UINT32); cmdline_parse_token_string_t cmd_firewall_del_bulk_firewall_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_bulk_result, firewall_string, "firewall"); cmdline_parse_token_string_t cmd_firewall_del_bulk_add_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_bulk_result, del_string, "del"); cmdline_parse_token_string_t cmd_firewall_del_bulk_bulk_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_bulk_result, bulk_string, "bulk"); cmdline_parse_token_string_t cmd_firewall_del_bulk_file_path_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_bulk_result, file_path, NULL); cmdline_parse_inst_t cmd_firewall_del_bulk = { .f = cmd_firewall_del_bulk_parsed, .data = NULL, .help_str = "Firewall rule del bulk", .tokens = { (void *) &cmd_firewall_del_bulk_p_string, (void *) &cmd_firewall_del_bulk_pipeline_id, (void *) &cmd_firewall_del_bulk_firewall_string, (void *) &cmd_firewall_del_bulk_add_string, (void *) &cmd_firewall_del_bulk_bulk_string, (void *) &cmd_firewall_del_bulk_file_path_string, NULL, }, }; /* * p firewall add default */ struct cmd_firewall_add_default_result { cmdline_fixed_string_t p_string; uint32_t pipeline_id; cmdline_fixed_string_t firewall_string; cmdline_fixed_string_t add_string; cmdline_fixed_string_t default_string; uint8_t port_id; }; static void cmd_firewall_add_default_parsed( void *parsed_result, __attribute__((unused)) struct cmdline *cl, void *data) { struct cmd_firewall_add_default_result *params = parsed_result; struct app_params *app = data; int status; status = app_pipeline_firewall_add_default_rule(app, params->pipeline_id, params->port_id); if (status != 0) { printf("Command failed\n"); return; } } cmdline_parse_token_string_t cmd_firewall_add_default_p_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_default_result, p_string, "p"); cmdline_parse_token_num_t cmd_firewall_add_default_pipeline_id = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_default_result, pipeline_id, UINT32); cmdline_parse_token_string_t cmd_firewall_add_default_firewall_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_default_result, firewall_string, "firewall"); cmdline_parse_token_string_t cmd_firewall_add_default_add_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_default_result, add_string, "add"); cmdline_parse_token_string_t cmd_firewall_add_default_default_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_add_default_result, default_string, "default"); cmdline_parse_token_num_t cmd_firewall_add_default_port_id = TOKEN_NUM_INITIALIZER(struct cmd_firewall_add_default_result, port_id, UINT8); cmdline_parse_inst_t cmd_firewall_add_default = { .f = cmd_firewall_add_default_parsed, .data = NULL, .help_str = "Firewall default rule add", .tokens = { (void *) &cmd_firewall_add_default_p_string, (void *) &cmd_firewall_add_default_pipeline_id, (void *) &cmd_firewall_add_default_firewall_string, (void *) &cmd_firewall_add_default_add_string, (void *) &cmd_firewall_add_default_default_string, (void *) &cmd_firewall_add_default_port_id, NULL, }, }; /* * p firewall del default */ struct cmd_firewall_del_default_result { cmdline_fixed_string_t p_string; uint32_t pipeline_id; cmdline_fixed_string_t firewall_string; cmdline_fixed_string_t del_string; cmdline_fixed_string_t default_string; }; static void cmd_firewall_del_default_parsed( void *parsed_result, __attribute__((unused)) struct cmdline *cl, void *data) { struct cmd_firewall_del_default_result *params = parsed_result; struct app_params *app = data; int status; status = app_pipeline_firewall_delete_default_rule(app, params->pipeline_id); if (status != 0) { printf("Command failed\n"); return; } } cmdline_parse_token_string_t cmd_firewall_del_default_p_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_default_result, p_string, "p"); cmdline_parse_token_num_t cmd_firewall_del_default_pipeline_id = TOKEN_NUM_INITIALIZER(struct cmd_firewall_del_default_result, pipeline_id, UINT32); cmdline_parse_token_string_t cmd_firewall_del_default_firewall_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_default_result, firewall_string, "firewall"); cmdline_parse_token_string_t cmd_firewall_del_default_del_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_default_result, del_string, "del"); cmdline_parse_token_string_t cmd_firewall_del_default_default_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_del_default_result, default_string, "default"); cmdline_parse_inst_t cmd_firewall_del_default = { .f = cmd_firewall_del_default_parsed, .data = NULL, .help_str = "Firewall default rule delete", .tokens = { (void *) &cmd_firewall_del_default_p_string, (void *) &cmd_firewall_del_default_pipeline_id, (void *) &cmd_firewall_del_default_firewall_string, (void *) &cmd_firewall_del_default_del_string, (void *) &cmd_firewall_del_default_default_string, NULL, }, }; /* * p firewall ls */ struct cmd_firewall_ls_result { cmdline_fixed_string_t p_string; uint32_t pipeline_id; cmdline_fixed_string_t firewall_string; cmdline_fixed_string_t ls_string; }; static void cmd_firewall_ls_parsed( void *parsed_result, __attribute__((unused)) struct cmdline *cl, void *data) { struct cmd_firewall_ls_result *params = parsed_result; struct app_params *app = data; int status; status = app_pipeline_firewall_ls(app, params->pipeline_id); if (status != 0) { printf("Command failed\n"); return; } } cmdline_parse_token_string_t cmd_firewall_ls_p_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_ls_result, p_string, "p"); cmdline_parse_token_num_t cmd_firewall_ls_pipeline_id = TOKEN_NUM_INITIALIZER(struct cmd_firewall_ls_result, pipeline_id, UINT32); cmdline_parse_token_string_t cmd_firewall_ls_firewall_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_ls_result, firewall_string, "firewall"); cmdline_parse_token_string_t cmd_firewall_ls_ls_string = TOKEN_STRING_INITIALIZER(struct cmd_firewall_ls_result, ls_string, "ls"); cmdline_parse_inst_t cmd_firewall_ls = { .f = cmd_firewall_ls_parsed, .data = NULL, .help_str = "Firewall rule list", .tokens = { (void *) &cmd_firewall_ls_p_string, (void *) &cmd_firewall_ls_pipeline_id, (void *) &cmd_firewall_ls_firewall_string, (void *) &cmd_firewall_ls_ls_string, NULL, }, }; static cmdline_parse_ctx_t pipeline_cmds[] = { (cmdline_parse_inst_t *) &cmd_firewall_add_ipv4, (cmdline_parse_inst_t *) &cmd_firewall_del_ipv4, (cmdline_parse_inst_t *) &cmd_firewall_add_bulk, (cmdline_parse_inst_t *) &cmd_firewall_del_bulk, (cmdline_parse_inst_t *) &cmd_firewall_add_default, (cmdline_parse_inst_t *) &cmd_firewall_del_default, (cmdline_parse_inst_t *) &cmd_firewall_ls, NULL, }; static struct pipeline_fe_ops pipeline_firewall_fe_ops = { .f_init = app_pipeline_firewall_init, .f_free = app_pipeline_firewall_free, .cmds = pipeline_cmds, }; struct pipeline_type pipeline_firewall = { .name = "FIREWALL", .be_ops = &pipeline_firewall_be_ops, .fe_ops = &pipeline_firewall_fe_ops, };
bsd-3-clause
swcho/strace_4.8_hack
quota.c
12
18413
/* * Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl> * Copyright (c) 1993 Branko Lankester <branko@hacktic.nl> * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com> * Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl> * Copyright (c) 2005, 2006 Dmitry V. Levin <ldv@altlinux.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "defs.h" #define SUBCMDMASK 0x00ff #define SUBCMDSHIFT 8 #define QCMD_CMD(cmd) ((u_int32_t)(cmd) >> SUBCMDSHIFT) #define QCMD_TYPE(cmd) ((u_int32_t)(cmd) & SUBCMDMASK) #define OLD_CMD(cmd) ((u_int32_t)(cmd) << 8) #define NEW_CMD(cmd) ((u_int32_t)(cmd) | 0x800000) #define XQM_CMD(cmd) ((u_int32_t)(cmd) | ('X'<<8)) #define Q_V1_QUOTAON OLD_CMD(0x1) #define Q_V1_QUOTAOFF OLD_CMD(0x2) #define Q_V1_GETQUOTA OLD_CMD(0x3) #define Q_V1_SETQUOTA OLD_CMD(0x4) #define Q_V1_SETUSE OLD_CMD(0x5) #define Q_V1_SYNC OLD_CMD(0x6) #define Q_SETQLIM OLD_CMD(0x7) #define Q_V1_GETSTATS OLD_CMD(0x8) #define Q_V1_RSQUASH OLD_CMD(0x10) #define Q_V2_GETQUOTA OLD_CMD(0xD) #define Q_V2_SETQUOTA OLD_CMD(0xE) #define Q_V2_SETUSE OLD_CMD(0xF) #define Q_V2_GETINFO OLD_CMD(0x9) #define Q_V2_SETINFO OLD_CMD(0xA) #define Q_V2_SETGRACE OLD_CMD(0xB) #define Q_V2_SETFLAGS OLD_CMD(0xC) #define Q_V2_GETSTATS OLD_CMD(0x11) #define Q_SYNC NEW_CMD(0x1) #define Q_QUOTAON NEW_CMD(0x2) #define Q_QUOTAOFF NEW_CMD(0x3) #define Q_GETFMT NEW_CMD(0x4) #define Q_GETINFO NEW_CMD(0x5) #define Q_SETINFO NEW_CMD(0x6) #define Q_GETQUOTA NEW_CMD(0x7) #define Q_SETQUOTA NEW_CMD(0x8) #define Q_XQUOTAON XQM_CMD(0x1) #define Q_XQUOTAOFF XQM_CMD(0x2) #define Q_XGETQUOTA XQM_CMD(0x3) #define Q_XSETQLIM XQM_CMD(0x4) #define Q_XGETQSTAT XQM_CMD(0x5) #define Q_XQUOTARM XQM_CMD(0x6) #define Q_XQUOTASYNC XQM_CMD(0x7) static const struct xlat quotacmds[] = { {Q_V1_QUOTAON, "Q_V1_QUOTAON"}, {Q_V1_QUOTAOFF, "Q_V1_QUOTAOFF"}, {Q_V1_GETQUOTA, "Q_V1_GETQUOTA"}, {Q_V1_SETQUOTA, "Q_V1_SETQUOTA"}, {Q_V1_SETUSE, "Q_V1_SETUSE"}, {Q_V1_SYNC, "Q_V1_SYNC"}, {Q_SETQLIM, "Q_SETQLIM"}, {Q_V1_GETSTATS, "Q_V1_GETSTATS"}, {Q_V1_RSQUASH, "Q_V1_RSQUASH"}, {Q_V2_GETQUOTA, "Q_V2_GETQUOTA"}, {Q_V2_SETQUOTA, "Q_V2_SETQUOTA"}, {Q_V2_SETUSE, "Q_V2_SETUSE"}, {Q_V2_GETINFO, "Q_V2_GETINFO"}, {Q_V2_SETINFO, "Q_V2_SETINFO"}, {Q_V2_SETGRACE, "Q_V2_SETGRACE"}, {Q_V2_SETFLAGS, "Q_V2_SETFLAGS"}, {Q_V2_GETSTATS, "Q_V2_GETSTATS"}, {Q_SYNC, "Q_SYNC"}, {Q_QUOTAON, "Q_QUOTAON"}, {Q_QUOTAOFF, "Q_QUOTAOFF"}, {Q_GETFMT, "Q_GETFMT"}, {Q_GETINFO, "Q_GETINFO"}, {Q_SETINFO, "Q_SETINFO"}, {Q_GETQUOTA, "Q_GETQUOTA"}, {Q_SETQUOTA, "Q_SETQUOTA"}, {Q_XQUOTAON, "Q_XQUOTAON"}, {Q_XQUOTAOFF, "Q_XQUOTAOFF"}, {Q_XGETQUOTA, "Q_XGETQUOTA"}, {Q_XSETQLIM, "Q_XSETQLIM"}, {Q_XGETQSTAT, "Q_XGETQSTAT"}, {Q_XQUOTARM, "Q_XQUOTARM"}, {Q_XQUOTASYNC, "Q_XQUOTASYNC"}, {0, NULL}, }; #define USRQUOTA 0 #define GRPQUOTA 1 static const struct xlat quotatypes[] = { {USRQUOTA, "USRQUOTA"}, {GRPQUOTA, "GRPQUOTA"}, {0, NULL}, }; /* Quota format identifiers */ #define QFMT_VFS_OLD 1 #define QFMT_VFS_V0 2 static const struct xlat quota_formats[] = { {QFMT_VFS_OLD, "QFMT_VFS_OLD"}, {QFMT_VFS_V0, "QFMT_VFS_V0"}, {0, NULL}, }; #define XFS_QUOTA_UDQ_ACCT (1<<0) /* user quota accounting */ #define XFS_QUOTA_UDQ_ENFD (1<<1) /* user quota limits enforcement */ #define XFS_QUOTA_GDQ_ACCT (1<<2) /* group quota accounting */ #define XFS_QUOTA_GDQ_ENFD (1<<3) /* group quota limits enforcement */ #define XFS_USER_QUOTA (1<<0) /* user quota type */ #define XFS_PROJ_QUOTA (1<<1) /* (IRIX) project quota type */ #define XFS_GROUP_QUOTA (1<<2) /* group quota type */ static const struct xlat xfs_quota_flags[] = { {XFS_QUOTA_UDQ_ACCT, "XFS_QUOTA_UDQ_ACCT"}, {XFS_QUOTA_UDQ_ENFD, "XFS_QUOTA_UDQ_ENFD"}, {XFS_QUOTA_GDQ_ACCT, "XFS_QUOTA_GDQ_ACCT"}, {XFS_QUOTA_GDQ_ENFD, "XFS_QUOTA_GDQ_ENFD"}, {0, NULL} }; static const struct xlat xfs_dqblk_flags[] = { {XFS_USER_QUOTA, "XFS_USER_QUOTA"}, {XFS_PROJ_QUOTA, "XFS_PROJ_QUOTA"}, {XFS_GROUP_QUOTA, "XFS_GROUP_QUOTA"}, {0, NULL} }; /* * Following flags are used to specify which fields are valid */ #define QIF_BLIMITS 1 #define QIF_SPACE 2 #define QIF_ILIMITS 4 #define QIF_INODES 8 #define QIF_BTIME 16 #define QIF_ITIME 32 static const struct xlat if_dqblk_valid[] = { {QIF_BLIMITS, "QIF_BLIMITS"}, {QIF_SPACE, "QIF_SPACE"}, {QIF_ILIMITS, "QIF_ILIMITS"}, {QIF_INODES, "QIF_INODES"}, {QIF_BTIME, "QIF_BTIME"}, {QIF_ITIME, "QIF_ITIME"}, {0, NULL} }; struct if_dqblk { u_int64_t dqb_bhardlimit; u_int64_t dqb_bsoftlimit; u_int64_t dqb_curspace; u_int64_t dqb_ihardlimit; u_int64_t dqb_isoftlimit; u_int64_t dqb_curinodes; u_int64_t dqb_btime; u_int64_t dqb_itime; u_int32_t dqb_valid; }; struct v1_dqblk { u_int32_t dqb_bhardlimit; /* absolute limit on disk blks alloc */ u_int32_t dqb_bsoftlimit; /* preferred limit on disk blks */ u_int32_t dqb_curblocks; /* current block count */ u_int32_t dqb_ihardlimit; /* maximum # allocated inodes */ u_int32_t dqb_isoftlimit; /* preferred inode limit */ u_int32_t dqb_curinodes; /* current # allocated inodes */ time_t dqb_btime; /* time limit for excessive disk use */ time_t dqb_itime; /* time limit for excessive files */ }; struct v2_dqblk { unsigned int dqb_ihardlimit; unsigned int dqb_isoftlimit; unsigned int dqb_curinodes; unsigned int dqb_bhardlimit; unsigned int dqb_bsoftlimit; u_int64_t dqb_curspace; time_t dqb_btime; time_t dqb_itime; }; struct xfs_dqblk { int8_t d_version; /* version of this structure */ int8_t d_flags; /* XFS_{USER,PROJ,GROUP}_QUOTA */ u_int16_t d_fieldmask; /* field specifier */ u_int32_t d_id; /* user, project, or group ID */ u_int64_t d_blk_hardlimit; /* absolute limit on disk blks */ u_int64_t d_blk_softlimit; /* preferred limit on disk blks */ u_int64_t d_ino_hardlimit; /* maximum # allocated inodes */ u_int64_t d_ino_softlimit; /* preferred inode limit */ u_int64_t d_bcount; /* # disk blocks owned by the user */ u_int64_t d_icount; /* # inodes owned by the user */ int32_t d_itimer; /* zero if within inode limits */ int32_t d_btimer; /* similar to above; for disk blocks */ u_int16_t d_iwarns; /* # warnings issued wrt num inodes */ u_int16_t d_bwarns; /* # warnings issued wrt disk blocks */ int32_t d_padding2; /* padding2 - for future use */ u_int64_t d_rtb_hardlimit; /* absolute limit on realtime blks */ u_int64_t d_rtb_softlimit; /* preferred limit on RT disk blks */ u_int64_t d_rtbcount; /* # realtime blocks owned */ int32_t d_rtbtimer; /* similar to above; for RT disk blks */ u_int16_t d_rtbwarns; /* # warnings issued wrt RT disk blks */ int16_t d_padding3; /* padding3 - for future use */ char d_padding4[8]; /* yet more padding */ }; /* * Following flags are used to specify which fields are valid */ #define IIF_BGRACE 1 #define IIF_IGRACE 2 #define IIF_FLAGS 4 static const struct xlat if_dqinfo_valid[] = { {IIF_BGRACE, "IIF_BGRACE"}, {IIF_IGRACE, "IIF_IGRACE"}, {IIF_FLAGS, "IIF_FLAGS"}, {0, NULL} }; struct if_dqinfo { u_int64_t dqi_bgrace; u_int64_t dqi_igrace; u_int32_t dqi_flags; u_int32_t dqi_valid; }; struct v2_dqinfo { unsigned int dqi_bgrace; unsigned int dqi_igrace; unsigned int dqi_flags; unsigned int dqi_blocks; unsigned int dqi_free_blk; unsigned int dqi_free_entry; }; struct v1_dqstats { u_int32_t lookups; u_int32_t drops; u_int32_t reads; u_int32_t writes; u_int32_t cache_hits; u_int32_t allocated_dquots; u_int32_t free_dquots; u_int32_t syncs; }; struct v2_dqstats { u_int32_t lookups; u_int32_t drops; u_int32_t reads; u_int32_t writes; u_int32_t cache_hits; u_int32_t allocated_dquots; u_int32_t free_dquots; u_int32_t syncs; u_int32_t version; }; typedef struct fs_qfilestat { u_int64_t qfs_ino; /* inode number */ u_int64_t qfs_nblks; /* number of BBs 512-byte-blks */ u_int32_t qfs_nextents; /* number of extents */ } fs_qfilestat_t; struct xfs_dqstats { int8_t qs_version; /* version number for future changes */ u_int16_t qs_flags; /* XFS_QUOTA_{U,P,G}DQ_{ACCT,ENFD} */ int8_t qs_pad; /* unused */ fs_qfilestat_t qs_uquota; /* user quota storage information */ fs_qfilestat_t qs_gquota; /* group quota storage information */ u_int32_t qs_incoredqs; /* number of dquots incore */ int32_t qs_btimelimit; /* limit for blks timer */ int32_t qs_itimelimit; /* limit for inodes timer */ int32_t qs_rtbtimelimit; /* limit for rt blks timer */ u_int16_t qs_bwarnlimit; /* limit for num warnings */ u_int16_t qs_iwarnlimit; /* limit for num warnings */ }; static void decode_cmd_data(struct tcb *tcp, u_int32_t cmd, unsigned long data) { switch (cmd) { case Q_GETQUOTA: case Q_SETQUOTA: { struct if_dqblk dq; if (cmd == Q_GETQUOTA && syserror(tcp)) { tprintf("%#lx", data); break; } if (umove(tcp, data, &dq) < 0) { tprintf("{???} %#lx", data); break; } tprintf("{bhardlimit=%" PRIu64 ", ", dq.dqb_bhardlimit); tprintf("bsoftlimit=%" PRIu64 ", ", dq.dqb_bsoftlimit); tprintf("curspace=%" PRIu64 ", ", dq.dqb_curspace); tprintf("ihardlimit=%" PRIu64 ", ", dq.dqb_ihardlimit); tprintf("isoftlimit=%" PRIu64 ", ", dq.dqb_isoftlimit); tprintf("curinodes=%" PRIu64 ", ", dq.dqb_curinodes); if (!abbrev(tcp)) { tprintf("btime=%" PRIu64 ", ", dq.dqb_btime); tprintf("itime=%" PRIu64 ", ", dq.dqb_itime); tprints("valid="); printflags(if_dqblk_valid, dq.dqb_valid, "QIF_???"); tprints("}"); } else tprints("...}"); break; } case Q_V1_GETQUOTA: case Q_V1_SETQUOTA: { struct v1_dqblk dq; if (cmd == Q_V1_GETQUOTA && syserror(tcp)) { tprintf("%#lx", data); break; } if (umove(tcp, data, &dq) < 0) { tprintf("{???} %#lx", data); break; } tprintf("{bhardlimit=%u, ", dq.dqb_bhardlimit); tprintf("bsoftlimit=%u, ", dq.dqb_bsoftlimit); tprintf("curblocks=%u, ", dq.dqb_curblocks); tprintf("ihardlimit=%u, ", dq.dqb_ihardlimit); tprintf("isoftlimit=%u, ", dq.dqb_isoftlimit); tprintf("curinodes=%u, ", dq.dqb_curinodes); tprintf("btime=%lu, ", (long) dq.dqb_btime); tprintf("itime=%lu}", (long) dq.dqb_itime); break; } case Q_V2_GETQUOTA: case Q_V2_SETQUOTA: { struct v2_dqblk dq; if (cmd == Q_V2_GETQUOTA && syserror(tcp)) { tprintf("%#lx", data); break; } if (umove(tcp, data, &dq) < 0) { tprintf("{???} %#lx", data); break; } tprintf("{ihardlimit=%u, ", dq.dqb_ihardlimit); tprintf("isoftlimit=%u, ", dq.dqb_isoftlimit); tprintf("curinodes=%u, ", dq.dqb_curinodes); tprintf("bhardlimit=%u, ", dq.dqb_bhardlimit); tprintf("bsoftlimit=%u, ", dq.dqb_bsoftlimit); tprintf("curspace=%" PRIu64 ", ", dq.dqb_curspace); tprintf("btime=%lu, ", (long) dq.dqb_btime); tprintf("itime=%lu}", (long) dq.dqb_itime); break; } case Q_XGETQUOTA: case Q_XSETQLIM: { struct xfs_dqblk dq; if (cmd == Q_XGETQUOTA && syserror(tcp)) { tprintf("%#lx", data); break; } if (umove(tcp, data, &dq) < 0) { tprintf("{???} %#lx", data); break; } tprintf("{version=%d, ", dq.d_version); tprints("flags="); printflags(xfs_dqblk_flags, dq.d_flags, "XFS_???_QUOTA"); tprintf(", fieldmask=%#x, ", dq.d_fieldmask); tprintf("id=%u, ", dq.d_id); tprintf("blk_hardlimit=%" PRIu64 ", ", dq.d_blk_hardlimit); tprintf("blk_softlimit=%" PRIu64 ", ", dq.d_blk_softlimit); tprintf("ino_hardlimit=%" PRIu64 ", ", dq.d_ino_hardlimit); tprintf("ino_softlimit=%" PRIu64 ", ", dq.d_ino_softlimit); tprintf("bcount=%" PRIu64 ", ", dq.d_bcount); tprintf("icount=%" PRIu64 ", ", dq.d_icount); if (!abbrev(tcp)) { tprintf("itimer=%d, ", dq.d_itimer); tprintf("btimer=%d, ", dq.d_btimer); tprintf("iwarns=%u, ", dq.d_iwarns); tprintf("bwarns=%u, ", dq.d_bwarns); tprintf("rtbcount=%" PRIu64 ", ", dq.d_rtbcount); tprintf("rtbtimer=%d, ", dq.d_rtbtimer); tprintf("rtbwarns=%u}", dq.d_rtbwarns); } else tprints("...}"); break; } case Q_GETFMT: { u_int32_t fmt; if (syserror(tcp)) { tprintf("%#lx", data); break; } if (umove(tcp, data, &fmt) < 0) { tprintf("{???} %#lx", data); break; } tprints("{"); printxval(quota_formats, fmt, "QFMT_VFS_???"); tprints("}"); break; } case Q_GETINFO: case Q_SETINFO: { struct if_dqinfo dq; if (cmd == Q_GETINFO && syserror(tcp)) { tprintf("%#lx", data); break; } if (umove(tcp, data, &dq) < 0) { tprintf("{???} %#lx", data); break; } tprintf("{bgrace=%" PRIu64 ", ", dq.dqi_bgrace); tprintf("igrace=%" PRIu64 ", ", dq.dqi_igrace); tprintf("flags=%#x, ", dq.dqi_flags); tprints("valid="); printflags(if_dqinfo_valid, dq.dqi_valid, "IIF_???"); tprints("}"); break; } case Q_V2_GETINFO: case Q_V2_SETINFO: { struct v2_dqinfo dq; if (cmd == Q_V2_GETINFO && syserror(tcp)) { tprintf("%#lx", data); break; } if (umove(tcp, data, &dq) < 0) { tprintf("{???} %#lx", data); break; } tprintf("{bgrace=%u, ", dq.dqi_bgrace); tprintf("igrace=%u, ", dq.dqi_igrace); tprintf("flags=%#x, ", dq.dqi_flags); tprintf("blocks=%u, ", dq.dqi_blocks); tprintf("free_blk=%u, ", dq.dqi_free_blk); tprintf("free_entry=%u}", dq.dqi_free_entry); break; } case Q_V1_GETSTATS: { struct v1_dqstats dq; if (syserror(tcp)) { tprintf("%#lx", data); break; } if (umove(tcp, data, &dq) < 0) { tprintf("{???} %#lx", data); break; } tprintf("{lookups=%u, ", dq.lookups); tprintf("drops=%u, ", dq.drops); tprintf("reads=%u, ", dq.reads); tprintf("writes=%u, ", dq.writes); tprintf("cache_hits=%u, ", dq.cache_hits); tprintf("allocated_dquots=%u, ", dq.allocated_dquots); tprintf("free_dquots=%u, ", dq.free_dquots); tprintf("syncs=%u}", dq.syncs); break; } case Q_V2_GETSTATS: { struct v2_dqstats dq; if (syserror(tcp)) { tprintf("%#lx", data); break; } if (umove(tcp, data, &dq) < 0) { tprintf("{???} %#lx", data); break; } tprintf("{lookups=%u, ", dq.lookups); tprintf("drops=%u, ", dq.drops); tprintf("reads=%u, ", dq.reads); tprintf("writes=%u, ", dq.writes); tprintf("cache_hits=%u, ", dq.cache_hits); tprintf("allocated_dquots=%u, ", dq.allocated_dquots); tprintf("free_dquots=%u, ", dq.free_dquots); tprintf("syncs=%u, ", dq.syncs); tprintf("version=%u}", dq.version); break; } case Q_XGETQSTAT: { struct xfs_dqstats dq; if (syserror(tcp)) { tprintf("%#lx", data); break; } if (umove(tcp, data, &dq) < 0) { tprintf("{???} %#lx", data); break; } tprintf("{version=%d, ", dq.qs_version); if (abbrev(tcp)) { tprints("...}"); break; } tprints("flags="); printflags(xfs_quota_flags, dq.qs_flags, "XFS_QUOTA_???"); tprintf(", incoredqs=%u, ", dq.qs_incoredqs); tprintf("u_ino=%" PRIu64 ", ", dq.qs_uquota.qfs_ino); tprintf("u_nblks=%" PRIu64 ", ", dq.qs_uquota.qfs_nblks); tprintf("u_nextents=%u, ", dq.qs_uquota.qfs_nextents); tprintf("g_ino=%" PRIu64 ", ", dq.qs_gquota.qfs_ino); tprintf("g_nblks=%" PRIu64 ", ", dq.qs_gquota.qfs_nblks); tprintf("g_nextents=%u, ", dq.qs_gquota.qfs_nextents); tprintf("btimelimit=%d, ", dq.qs_btimelimit); tprintf("itimelimit=%d, ", dq.qs_itimelimit); tprintf("rtbtimelimit=%d, ", dq.qs_rtbtimelimit); tprintf("bwarnlimit=%u, ", dq.qs_bwarnlimit); tprintf("iwarnlimit=%u}", dq.qs_iwarnlimit); break; } case Q_XQUOTAON: { u_int32_t flag; if (umove(tcp, data, &flag) < 0) { tprintf("{???} %#lx", data); break; } tprints("{"); printflags(xfs_quota_flags, flag, "XFS_QUOTA_???"); tprints("}"); break; } default: tprintf("%#lx", data); break; } } int sys_quotactl(struct tcb *tcp) { /* * The Linux kernel only looks at the low 32 bits of command and id * arguments, but on some 64-bit architectures (s390x) this word * will have been sign-extended when we see it. The high 1 bits * don't mean anything, so don't confuse the output with them. */ u_int32_t qcmd = tcp->u_arg[0]; u_int32_t cmd = QCMD_CMD(qcmd); u_int32_t type = QCMD_TYPE(qcmd); u_int32_t id = tcp->u_arg[2]; if (!verbose(tcp)) return printargs(tcp); if (entering(tcp)) { printxval(quotacmds, cmd, "Q_???"); tprints("|"); printxval(quotatypes, type, "???QUOTA"); tprints(", "); printpath(tcp, tcp->u_arg[1]); tprints(", "); switch (cmd) { case Q_V1_QUOTAON: case Q_QUOTAON: printxval(quota_formats, id, "QFMT_VFS_???"); break; case Q_V1_GETQUOTA: case Q_V2_GETQUOTA: case Q_GETQUOTA: case Q_V1_SETQUOTA: case Q_V2_SETQUOTA: case Q_V1_SETUSE: case Q_V2_SETUSE: case Q_SETQLIM: case Q_SETQUOTA: case Q_XGETQUOTA: case Q_XSETQLIM: tprintf("%u", id); break; default: tprintf("%#lx", tcp->u_arg[2]); break; } tprints(", "); } else { if (!tcp->u_arg[3]) tprints("NULL"); else decode_cmd_data(tcp, cmd, tcp->u_arg[3]); } return 0; }
bsd-3-clause
geekboxzone/lollipop_external_chromium_org_third_party_WebKit
Source/core/svg/graphics/SVGImageChromeClient.cpp
14
3779
/* * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/svg/graphics/SVGImageChromeClient.h" #include "core/frame/FrameView.h" #include "core/svg/graphics/SVGImage.h" #include "platform/ScriptForbiddenScope.h" #include "platform/graphics/ImageObserver.h" #include "wtf/CurrentTime.h" namespace blink { static const double animationFrameDelay = 0.025; SVGImageChromeClient::SVGImageChromeClient(SVGImage* image) : m_image(image) , m_animationTimer(this, &SVGImageChromeClient::animationTimerFired) { } bool SVGImageChromeClient::isSVGImageChromeClient() const { return true; } void SVGImageChromeClient::chromeDestroyed() { m_image = 0; } void SVGImageChromeClient::invalidateContentsAndRootView(const IntRect& r) { // If m_image->m_page is null, we're being destructed, don't fire changedInRect() in that case. if (m_image && m_image->imageObserver() && m_image->m_page) m_image->imageObserver()->changedInRect(m_image, r); } void SVGImageChromeClient::scheduleAnimation() { // Because a single SVGImage can be shared by multiple pages, we can't key // our svg image layout on the page's real animation frame. Therefore, we // run this fake animation timer to trigger layout in SVGImages. The name, // "animationTimer", is to match the new requestAnimationFrame-based layout // approach. if (m_animationTimer.isActive()) return; // Schedule the 'animation' ASAP if the image does not contain any // animations, but prefer a fixed, jittery, frame-delay if there're any // animations. Checking for pending/active animations could be more // stringent. double fireTime = m_image->hasAnimations() ? animationFrameDelay : 0; m_animationTimer.startOneShot(fireTime, FROM_HERE); } void SVGImageChromeClient::animationTimerFired(Timer<SVGImageChromeClient>*) { if (!m_image) return; // serviceScriptedAnimations runs requestAnimationFrame callbacks, but SVG // images can't have any so we assert there's no script. ScriptForbiddenScope forbidScript; m_image->frameView()->page()->animator().serviceScriptedAnimations(monotonicallyIncreasingTime()); m_image->frameView()->updateLayoutAndStyleForPainting(); } }
bsd-3-clause
leecade/coturn
src/apps/relay/dbdrivers/dbd_pgsql.c
14
28252
/* * Copyright (C) 2011, 2012, 2013 Citrix Systems * Copyright (C) 2014 Vivocha S.p.A. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "../mainrelay.h" #include "dbd_pgsql.h" #if !defined(TURN_NO_PQ) #include <libpq-fe.h> /////////////////////////////////////////////////////////////////////////////////////////////////////////// static int donot_print_connection_success = 0; static PGconn *get_pqdb_connection(void) { persistent_users_db_t *pud = get_persistent_users_db(); PGconn *pqdbconnection = (PGconn*)pthread_getspecific(connection_key); if(pqdbconnection) { ConnStatusType status = PQstatus(pqdbconnection); if(status != CONNECTION_OK) { PQfinish(pqdbconnection); pqdbconnection = NULL; (void) pthread_setspecific(connection_key, pqdbconnection); } } if(!pqdbconnection) { char *errmsg=NULL; PQconninfoOption *co = PQconninfoParse(pud->userdb, &errmsg); if(!co) { if(errmsg) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot open PostgreSQL DB connection <%s>, connection string format error: %s\n",pud->userdb,errmsg); turn_free(errmsg,strlen(errmsg)+1); } else { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot open PostgreSQL DB connection: <%s>, unknown connection string format error\n",pud->userdb); } } else { PQconninfoFree(co); if(errmsg) turn_free(errmsg,strlen(errmsg)+1); pqdbconnection = PQconnectdb(pud->userdb); if(!pqdbconnection) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot open PostgreSQL DB connection: <%s>, runtime error\n",pud->userdb); } else { ConnStatusType status = PQstatus(pqdbconnection); if(status != CONNECTION_OK) { PQfinish(pqdbconnection); pqdbconnection = NULL; TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot open PostgreSQL DB connection: <%s>, runtime error\n",pud->userdb); } else if(!donot_print_connection_success){ TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "PostgreSQL DB connection success: %s\n",pud->userdb); donot_print_connection_success = 1; } } } if(pqdbconnection) { (void) pthread_setspecific(connection_key, pqdbconnection); } } return pqdbconnection; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// static int pgsql_get_auth_secrets(secrets_list_t *sl, u08bits *realm) { int ret = -1; PGconn * pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; snprintf(statement,sizeof(statement)-1,"select value from turn_secret where realm='%s'",realm); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { char *kval = PQgetvalue(res,i,0); if(kval) { add_to_secrets_list(sl,kval); } } ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_get_user_key(u08bits *usname, u08bits *realm, hmackey_t key) { int ret = -1; PGconn * pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; snprintf(statement,sizeof(statement),"select hmackey from turnusers_lt where name='%s' and realm='%s'",usname,realm); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK) || (PQntuples(res)!=1)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { char *kval = PQgetvalue(res,0,0); int len = PQgetlength(res,0,0); if(kval) { size_t sz = get_hmackey_size(SHATYPE_DEFAULT); if(((size_t)len<sz*2)||(strlen(kval)<sz*2)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Wrong key format: %s, user %s\n",kval,usname); } else if(convert_string_key_to_binary(kval, key, sz)<0) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Wrong key: %s, user %s\n",kval,usname); } else { ret = 0; } } else { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Wrong hmackey data for user %s: NULL\n",usname); } } if(res) PQclear(res); } return ret; } static int pgsql_get_oauth_key(const u08bits *kid, oauth_key_data_raw *key) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; snprintf(statement,sizeof(statement),"select ikm_key,timestamp,lifetime,as_rs_alg from oauth_key where kid='%s'",(const char*)kid); PGconn * pqc = get_pqdb_connection(); if(pqc) { PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK) || (PQntuples(res)!=1)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { STRCPY(key->ikm_key,PQgetvalue(res,0,0)); key->timestamp = (u64bits)strtoll(PQgetvalue(res,0,1),NULL,10); key->lifetime = (u32bits)strtol(PQgetvalue(res,0,2),NULL,10); STRCPY(key->as_rs_alg,PQgetvalue(res,0,3)); STRCPY(key->kid,kid); ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_list_oauth_keys(secrets_list_t *kids,secrets_list_t *teas,secrets_list_t *tss,secrets_list_t *lts) { oauth_key_data_raw key_; oauth_key_data_raw *key=&key_; int ret = -1; char statement[TURN_LONG_STRING_SIZE]; snprintf(statement,sizeof(statement),"select ikm_key,timestamp,lifetime,as_rs_alg,kid from oauth_key order by kid"); PGconn * pqc = get_pqdb_connection(); if(pqc) { PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { STRCPY(key->ikm_key,PQgetvalue(res,i,0)); key->timestamp = (u64bits)strtoll(PQgetvalue(res,i,1),NULL,10); key->lifetime = (u32bits)strtol(PQgetvalue(res,i,2),NULL,10); STRCPY(key->as_rs_alg,PQgetvalue(res,i,3)); STRCPY(key->kid,PQgetvalue(res,i,4)); if(kids) { add_to_secrets_list(kids,key->kid); add_to_secrets_list(teas,key->as_rs_alg); { char ts[256]; snprintf(ts,sizeof(ts)-1,"%llu",(unsigned long long)key->timestamp); add_to_secrets_list(tss,ts); } { char lt[256]; snprintf(lt,sizeof(lt)-1,"%lu",(unsigned long)key->lifetime); add_to_secrets_list(lts,lt); } } else { printf(" kid=%s, ikm_key=%s, timestamp=%llu, lifetime=%lu, as_rs_alg=%s\n", key->kid, key->ikm_key, (unsigned long long)key->timestamp, (unsigned long)key->lifetime, key->as_rs_alg); } ret = 0; } } if(res) { PQclear(res); } } return ret; } static int pgsql_set_user_key(u08bits *usname, u08bits *realm, const char *key) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"insert into turnusers_lt (realm,name,hmackey) values('%s','%s','%s')",realm,usname,key); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { if(res) { PQclear(res); } snprintf(statement,sizeof(statement),"update turnusers_lt set hmackey='%s' where name='%s' and realm='%s'",key,usname,realm); res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting/updating user information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } } if(res) { PQclear(res); } } return ret; } static int pgsql_set_oauth_key(oauth_key_data_raw *key) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"insert into oauth_key (kid,ikm_key,timestamp,lifetime,as_rs_alg) values('%s','%s',%llu,%lu,'%s')", key->kid,key->ikm_key,(unsigned long long)key->timestamp,(unsigned long)key->lifetime, key->as_rs_alg); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { if(res) { PQclear(res); } snprintf(statement,sizeof(statement),"update oauth_key set ikm_key='%s',timestamp=%lu,lifetime=%lu, as_rs_alg='%s' where kid='%s'",key->ikm_key,(unsigned long)key->timestamp,(unsigned long)key->lifetime, key->as_rs_alg,key->kid); res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting/updating oauth_key information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } } else { ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_del_user(u08bits *usname, u08bits *realm) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"delete from turnusers_lt where name='%s' and realm='%s'",usname,realm); PGresult *res = PQexec(pqc, statement); if(res) { PQclear(res); ret = 0; } } return ret; } static int pgsql_del_oauth_key(const u08bits *kid) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"delete from oauth_key where kid = '%s'",(const char*)kid); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error deleting oauth_key information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_list_users(u08bits *realm, secrets_list_t *users, secrets_list_t *realms) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; u08bits realm0[STUN_MAX_REALM_SIZE+1] = "\0"; if(!realm) realm=realm0; PGconn *pqc = get_pqdb_connection(); if(pqc) { if(realm[0]) { snprintf(statement,sizeof(statement),"select name,realm from turnusers_lt where realm='%s' order by name",realm); } else { snprintf(statement,sizeof(statement),"select name,realm from turnusers_lt order by realm,name"); } PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { char *kval = PQgetvalue(res,i,0); if(kval) { char *rval = PQgetvalue(res,i,1); if(rval) { if(users) { add_to_secrets_list(users,kval); if(realms) { if(rval && *rval) { add_to_secrets_list(realms,rval); } else { add_to_secrets_list(realms,(char*)realm); } } } else { printf("%s[%s]\n", kval, rval); } } } } ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_list_secrets(u08bits *realm, secrets_list_t *secrets, secrets_list_t *realms) { int ret = -1; u08bits realm0[STUN_MAX_REALM_SIZE+1] = "\0"; if(!realm) realm=realm0; char statement[TURN_LONG_STRING_SIZE]; if (realm[0]) { snprintf(statement, sizeof(statement), "select value,realm from turn_secret where realm='%s' order by value", realm); } else { snprintf(statement, sizeof(statement), "select value,realm from turn_secret order by realm,value"); } donot_print_connection_success=1; PGconn *pqc = get_pqdb_connection(); if(pqc) { PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { char *kval = PQgetvalue(res,i,0); if(kval) { char* rval = PQgetvalue(res,i,1); if(secrets) { add_to_secrets_list(secrets,kval); if(realms) { if(rval && *rval) { add_to_secrets_list(realms,rval); } else { add_to_secrets_list(realms,(char*)realm); } } } else { printf("%s[%s]\n",kval,rval); } } } ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_del_secret(u08bits *secret, u08bits *realm) { int ret = -1; donot_print_connection_success=1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if (pqc) { if(!secret || (secret[0]==0)) snprintf(statement,sizeof(statement),"delete from turn_secret where realm='%s'",realm); else snprintf(statement,sizeof(statement),"delete from turn_secret where value='%s' and realm='%s'",secret,realm); PGresult *res = PQexec(pqc, statement); if (res) { PQclear(res); ret = 0; } } return ret; } static int pgsql_set_secret(u08bits *secret, u08bits *realm) { int ret = -1; donot_print_connection_success = 1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if (pqc) { snprintf(statement,sizeof(statement),"insert into turn_secret (realm,value) values('%s','%s')",realm,secret); PGresult *res = PQexec(pqc, statement); if (!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC( TURN_LOG_LEVEL_ERROR, "Error inserting/updating secret key information: %s\n", PQerrorMessage(pqc)); } else { ret = 0; } if (res) { PQclear(res); } } return ret; } static int pgsql_set_permission_ip(const char *kind, u08bits *realm, const char* ip, int del) { int ret = -1; u08bits realm0[STUN_MAX_REALM_SIZE+1] = "\0"; if(!realm) realm=realm0; donot_print_connection_success = 1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if (pqc) { if(del) { snprintf(statement, sizeof(statement), "delete from %s_peer_ip where realm = '%s' and ip_range = '%s'", kind, (char*)realm, ip); } else { snprintf(statement, sizeof(statement), "insert into %s_peer_ip (realm,ip_range) values('%s','%s')", kind, (char*)realm, ip); } PGresult *res = PQexec(pqc, statement); if (!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC( TURN_LOG_LEVEL_ERROR, "Error inserting ip permission information: %s\n", PQerrorMessage(pqc)); } else { ret = 0; } if (res) { PQclear(res); } } return ret; } static int pgsql_add_origin(u08bits *origin, u08bits *realm) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"insert into turn_origin_to_realm (origin,realm) values('%s','%s')",origin,realm); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting origin information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_del_origin(u08bits *origin) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"delete from turn_origin_to_realm where origin='%s'",origin); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error deleting origin information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_list_origins(u08bits *realm, secrets_list_t *origins, secrets_list_t *realms) { int ret = -1; u08bits realm0[STUN_MAX_REALM_SIZE+1] = "\0"; if(!realm) realm=realm0; donot_print_connection_success = 1; PGconn *pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; if(realm && realm[0]) { snprintf(statement,sizeof(statement),"select origin,realm from turn_origin_to_realm where realm='%s' order by origin",realm); } else { snprintf(statement,sizeof(statement),"select origin,realm from turn_origin_to_realm order by realm,origin"); } PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { char *kval = PQgetvalue(res,i,0); if(kval) { char *rval = PQgetvalue(res,i,1); if(rval) { if(origins) { add_to_secrets_list(origins,kval); if(realms) { if(rval && *rval) { add_to_secrets_list(realms,rval); } else { add_to_secrets_list(realms,(char*)realm); } } } else { printf("%s ==>> %s\n",kval,rval); } } } } ret = 0; } if(res) { PQclear(res); } } return ret; } static int pgsql_set_realm_option_one(u08bits *realm, unsigned long value, const char* opt) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { { snprintf(statement,sizeof(statement),"delete from turn_realm_option where realm='%s' and opt='%s'",realm,opt); PGresult *res = PQexec(pqc, statement); if(res) { PQclear(res); } } if(value>0) { snprintf(statement,sizeof(statement),"insert into turn_realm_option (realm,opt,value) values('%s','%s','%lu')",realm,opt,(unsigned long)value); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting realm option information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } if(res) { PQclear(res); } } } return ret; } static int pgsql_list_realm_options(u08bits *realm) { int ret = -1; donot_print_connection_success = 1; char statement[TURN_LONG_STRING_SIZE]; PGconn *pqc = get_pqdb_connection(); if(pqc) { if(realm && realm[0]) { snprintf(statement,sizeof(statement),"select realm,opt,value from turn_realm_option where realm='%s' order by realm,opt",realm); } else { snprintf(statement,sizeof(statement),"select realm,opt,value from turn_realm_option order by realm,opt"); } PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; for(i=0;i<PQntuples(res);i++) { char *rval = PQgetvalue(res,i,0); if(rval) { char *oval = PQgetvalue(res,i,1); if(oval) { char *vval = PQgetvalue(res,i,2); if(vval) { printf("%s[%s]=%s\n",oval,rval,vval); } } } } ret = 0; } if(res) { PQclear(res); } } return ret; } static void pgsql_auth_ping(void * rch) { UNUSED_ARG(rch); PGconn * pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; STRCPY(statement,"select value from turn_secret"); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } if(res) { PQclear(res); } } } static int pgsql_get_ip_list(const char *kind, ip_range_list_t * list) { int ret = -1; PGconn * pqc = get_pqdb_connection(); if (pqc) { char statement[TURN_LONG_STRING_SIZE]; snprintf(statement, sizeof(statement), "select ip_range,realm from %s_peer_ip", kind); PGresult *res = PQexec(pqc, statement); if (!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { static int wrong_table_reported = 0; if(!wrong_table_reported) { wrong_table_reported = 1; TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s; probably, the tables 'allowed_peer_ip' and/or 'denied_peer_ip' have to be upgraded to include the realm column.\n",PQerrorMessage(pqc)); } snprintf(statement, sizeof(statement), "select ip_range,'' from %s_peer_ip", kind); res = PQexec(pqc, statement); } if (res && (PQresultStatus(res) == PGRES_TUPLES_OK)) { int i = 0; for (i = 0; i < PQntuples(res); i++) { char *kval = PQgetvalue(res, i, 0); char *rval = PQgetvalue(res, i, 1); if (kval) { add_ip_list_range(kval, rval, list); } } ret = 0; } if (res) { PQclear(res); } } return ret; } static void pgsql_reread_realms(secrets_list_t * realms_list) { PGconn * pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; { snprintf(statement,sizeof(statement),"select origin,realm from turn_origin_to_realm"); PGresult *res = PQexec(pqc, statement); if(res && (PQresultStatus(res) == PGRES_TUPLES_OK)) { ur_string_map *o_to_realm_new = ur_string_map_create(turn_free_simple); int i = 0; for(i=0;i<PQntuples(res);i++) { char *oval = PQgetvalue(res,i,0); if(oval) { char *rval = PQgetvalue(res,i,1); if(rval) { get_realm(rval); ur_string_map_value_type value = turn_strdup(rval); ur_string_map_put(o_to_realm_new, (const ur_string_map_key_type) oval, value); } } } update_o_to_realm(o_to_realm_new); } if(res) { PQclear(res); } } { { size_t i = 0; size_t rlsz = 0; lock_realms(); rlsz = realms_list->sz; unlock_realms(); for (i = 0; i<rlsz; ++i) { char *realm = realms_list->secrets[i]; realm_params_t* rp = get_realm(realm); lock_realms(); rp->options.perf_options.max_bps = turn_params.max_bps; unlock_realms(); lock_realms(); rp->options.perf_options.total_quota = turn_params.total_quota; unlock_realms(); lock_realms(); rp->options.perf_options.user_quota = turn_params.user_quota; unlock_realms(); } } snprintf(statement,sizeof(statement),"select realm,opt,value from turn_realm_option"); PGresult *res = PQexec(pqc, statement); if(res && (PQresultStatus(res) == PGRES_TUPLES_OK)) { int i = 0; for(i=0;i<PQntuples(res);i++) { char *rval = PQgetvalue(res,i,0); char *oval = PQgetvalue(res,i,1); char *vval = PQgetvalue(res,i,2); if(rval && oval && vval) { realm_params_t* rp = get_realm(rval); if(!strcmp(oval,"max-bps")) rp->options.perf_options.max_bps = (band_limit_t)strtoul(vval,NULL,10); else if(!strcmp(oval,"total-quota")) rp->options.perf_options.total_quota = (vint)atoi(vval); else if(!strcmp(oval,"user-quota")) rp->options.perf_options.user_quota = (vint)atoi(vval); else { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown realm option: %s\n", oval); } } } } if(res) { PQclear(res); } } } } ////////////////////////////////////////////// static int pgsql_get_admin_user(const u08bits *usname, u08bits *realm, password_t pwd) { int ret = -1; realm[0]=0; pwd[0]=0; PGconn * pqc = get_pqdb_connection(); if(pqc) { char statement[TURN_LONG_STRING_SIZE]; snprintf(statement,sizeof(statement),"select realm,password from admin_user where name='%s'",usname); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK) || (PQntuples(res)!=1)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { const char *kval = PQgetvalue(res,0,0); if(kval) { strncpy((char*)realm,kval,STUN_MAX_REALM_SIZE); } kval = (const char*) PQgetvalue(res,0,1); if(kval) { strncpy((char*)pwd,kval,STUN_MAX_PWD_SIZE); } ret = 0; } if(res) PQclear(res); } return ret; } static int pgsql_set_admin_user(const u08bits *usname, const u08bits *realm, const password_t pwd) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; donot_print_connection_success=1; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"insert into admin_user (realm,name,password) values('%s','%s','%s')",realm,usname,pwd); PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { if(res) { PQclear(res); } snprintf(statement,sizeof(statement),"update admin_user set password='%s',realm='%s' where name='%s'",pwd,realm,usname); res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_COMMAND_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error inserting/updating user information: %s\n",PQerrorMessage(pqc)); } else { ret = 0; } } if(res) { PQclear(res); } } return ret; } static int pgsql_del_admin_user(const u08bits *usname) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; donot_print_connection_success=1; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"delete from admin_user where name='%s'",usname); PGresult *res = PQexec(pqc, statement); if(res) { PQclear(res); ret = 0; } } return ret; } static int pgsql_list_admin_users(int no_print) { int ret = -1; char statement[TURN_LONG_STRING_SIZE]; donot_print_connection_success=1; PGconn *pqc = get_pqdb_connection(); if(pqc) { snprintf(statement,sizeof(statement),"select name,realm,password from admin_user order by realm,name"); } PGresult *res = PQexec(pqc, statement); if(!res || (PQresultStatus(res) != PGRES_TUPLES_OK)) { TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error retrieving PostgreSQL DB information: %s\n",PQerrorMessage(pqc)); } else { int i = 0; ret = 0; for(i=0;i<PQntuples(res);i++) { char *kval = PQgetvalue(res,i,0); ++ret; if(kval && !no_print) { char *rval = PQgetvalue(res,i,1); if(rval && *rval) { printf("%s[%s]\n",kval,rval); } else { printf("%s\n",kval); } } } } if(res) { PQclear(res); } return ret; } ///////////////////////////////////////////////////////////// static const turn_dbdriver_t driver = { &pgsql_get_auth_secrets, &pgsql_get_user_key, &pgsql_set_user_key, &pgsql_del_user, &pgsql_list_users, &pgsql_list_secrets, &pgsql_del_secret, &pgsql_set_secret, &pgsql_add_origin, &pgsql_del_origin, &pgsql_list_origins, &pgsql_set_realm_option_one, &pgsql_list_realm_options, &pgsql_auth_ping, &pgsql_get_ip_list, &pgsql_set_permission_ip, &pgsql_reread_realms, &pgsql_set_oauth_key, &pgsql_get_oauth_key, &pgsql_del_oauth_key, &pgsql_list_oauth_keys, &pgsql_get_admin_user, &pgsql_set_admin_user, &pgsql_del_admin_user, &pgsql_list_admin_users }; const turn_dbdriver_t * get_pgsql_dbdriver(void) { return &driver; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// #else const turn_dbdriver_t * get_pgsql_dbdriver(void) { return NULL; } #endif
bsd-3-clause
premake/premake-core
contrib/mbedtls/library/nist_kw.c
15
24226
/* * Implementation of NIST SP 800-38F key wrapping, supporting KW and KWP modes * only * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * 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. */ /* * Definition of Key Wrapping: * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf * RFC 3394 "Advanced Encryption Standard (AES) Key Wrap Algorithm" * RFC 5649 "Advanced Encryption Standard (AES) Key Wrap with Padding Algorithm" * * Note: RFC 3394 defines different methodology for intermediate operations for * the wrapping and unwrapping operation than the definition in NIST SP 800-38F. */ #include "common.h" #if defined(MBEDTLS_NIST_KW_C) #include "mbedtls/nist_kw.h" #include "mbedtls/platform_util.h" #include "mbedtls/error.h" #include <stdint.h> #include <string.h> #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #define mbedtls_printf printf #endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ #if !defined(MBEDTLS_NIST_KW_ALT) #define KW_SEMIBLOCK_LENGTH 8 #define MIN_SEMIBLOCKS_COUNT 3 /* constant-time buffer comparison */ static inline unsigned char mbedtls_nist_kw_safer_memcmp( const void *a, const void *b, size_t n ) { size_t i; volatile const unsigned char *A = (volatile const unsigned char *) a; volatile const unsigned char *B = (volatile const unsigned char *) b; volatile unsigned char diff = 0; for( i = 0; i < n; i++ ) { /* Read volatile data in order before computing diff. * This avoids IAR compiler warning: * 'the order of volatile accesses is undefined ..' */ unsigned char x = A[i], y = B[i]; diff |= x ^ y; } return( diff ); } /*! The 64-bit default integrity check value (ICV) for KW mode. */ static const unsigned char NIST_KW_ICV1[] = {0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6}; /*! The 32-bit default integrity check value (ICV) for KWP mode. */ static const unsigned char NIST_KW_ICV2[] = {0xA6, 0x59, 0x59, 0xA6}; #ifndef GET_UINT32_BE #define GET_UINT32_BE(n,b,i) \ do { \ (n) = ( (uint32_t) (b)[(i) ] << 24 ) \ | ( (uint32_t) (b)[(i) + 1] << 16 ) \ | ( (uint32_t) (b)[(i) + 2] << 8 ) \ | ( (uint32_t) (b)[(i) + 3] ); \ } while( 0 ) #endif #ifndef PUT_UINT32_BE #define PUT_UINT32_BE(n,b,i) \ do { \ (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ (b)[(i) + 3] = (unsigned char) ( (n) ); \ } while( 0 ) #endif /* * Initialize context */ void mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx ) { memset( ctx, 0, sizeof( mbedtls_nist_kw_context ) ); } int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx, mbedtls_cipher_id_t cipher, const unsigned char *key, unsigned int keybits, const int is_wrap ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const mbedtls_cipher_info_t *cipher_info; cipher_info = mbedtls_cipher_info_from_values( cipher, keybits, MBEDTLS_MODE_ECB ); if( cipher_info == NULL ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); if( cipher_info->block_size != 16 ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); /* * SP 800-38F currently defines AES cipher as the only block cipher allowed: * "For KW and KWP, the underlying block cipher shall be approved, and the * block size shall be 128 bits. Currently, the AES block cipher, with key * lengths of 128, 192, or 256 bits, is the only block cipher that fits * this profile." * Currently we don't support other 128 bit block ciphers for key wrapping, * such as Camellia and Aria. */ if( cipher != MBEDTLS_CIPHER_ID_AES ) return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); mbedtls_cipher_free( &ctx->cipher_ctx ); if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 ) return( ret ); if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits, is_wrap ? MBEDTLS_ENCRYPT : MBEDTLS_DECRYPT ) ) != 0 ) { return( ret ); } return( 0 ); } /* * Free context */ void mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx ) { mbedtls_cipher_free( &ctx->cipher_ctx ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_nist_kw_context ) ); } /* * Helper function for Xoring the uint64_t "t" with the encrypted A. * Defined in NIST SP 800-38F section 6.1 */ static void calc_a_xor_t( unsigned char A[KW_SEMIBLOCK_LENGTH], uint64_t t ) { size_t i = 0; for( i = 0; i < sizeof( t ); i++ ) { A[i] ^= ( t >> ( ( sizeof( t ) - 1 - i ) * 8 ) ) & 0xff; } } /* * KW-AE as defined in SP 800-38F section 6.2 * KWP-AE as defined in SP 800-38F section 6.3 */ int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode, const unsigned char *input, size_t in_len, unsigned char *output, size_t *out_len, size_t out_size ) { int ret = 0; size_t semiblocks = 0; size_t s; size_t olen, padlen = 0; uint64_t t = 0; unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2]; unsigned char inbuff[KW_SEMIBLOCK_LENGTH * 2]; unsigned char *R2 = output + KW_SEMIBLOCK_LENGTH; unsigned char *A = output; *out_len = 0; /* * Generate the String to work on */ if( mode == MBEDTLS_KW_MODE_KW ) { if( out_size < in_len + KW_SEMIBLOCK_LENGTH ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } /* * According to SP 800-38F Table 1, the plaintext length for KW * must be between 2 to 2^54-1 semiblocks inclusive. */ if( in_len < 16 || #if SIZE_MAX > 0x1FFFFFFFFFFFFF8 in_len > 0x1FFFFFFFFFFFFF8 || #endif in_len % KW_SEMIBLOCK_LENGTH != 0 ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } memcpy( output, NIST_KW_ICV1, KW_SEMIBLOCK_LENGTH ); memmove( output + KW_SEMIBLOCK_LENGTH, input, in_len ); } else { if( in_len % 8 != 0 ) { padlen = ( 8 - ( in_len % 8 ) ); } if( out_size < in_len + KW_SEMIBLOCK_LENGTH + padlen ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } /* * According to SP 800-38F Table 1, the plaintext length for KWP * must be between 1 and 2^32-1 octets inclusive. */ if( in_len < 1 #if SIZE_MAX > 0xFFFFFFFF || in_len > 0xFFFFFFFF #endif ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } memcpy( output, NIST_KW_ICV2, KW_SEMIBLOCK_LENGTH / 2 ); PUT_UINT32_BE( ( in_len & 0xffffffff ), output, KW_SEMIBLOCK_LENGTH / 2 ); memcpy( output + KW_SEMIBLOCK_LENGTH, input, in_len ); memset( output + KW_SEMIBLOCK_LENGTH + in_len, 0, padlen ); } semiblocks = ( ( in_len + padlen ) / KW_SEMIBLOCK_LENGTH ) + 1; s = 6 * ( semiblocks - 1 ); if( mode == MBEDTLS_KW_MODE_KWP && in_len <= KW_SEMIBLOCK_LENGTH ) { memcpy( inbuff, output, 16 ); ret = mbedtls_cipher_update( &ctx->cipher_ctx, inbuff, 16, output, &olen ); if( ret != 0 ) goto cleanup; } else { /* * Do the wrapping function W, as defined in RFC 3394 section 2.2.1 */ if( semiblocks < MIN_SEMIBLOCKS_COUNT ) { ret = MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA; goto cleanup; } /* Calculate intermediate values */ for( t = 1; t <= s; t++ ) { memcpy( inbuff, A, KW_SEMIBLOCK_LENGTH ); memcpy( inbuff + KW_SEMIBLOCK_LENGTH, R2, KW_SEMIBLOCK_LENGTH ); ret = mbedtls_cipher_update( &ctx->cipher_ctx, inbuff, 16, outbuff, &olen ); if( ret != 0 ) goto cleanup; memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH ); calc_a_xor_t( A, t ); memcpy( R2, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH ); R2 += KW_SEMIBLOCK_LENGTH; if( R2 >= output + ( semiblocks * KW_SEMIBLOCK_LENGTH ) ) R2 = output + KW_SEMIBLOCK_LENGTH; } } *out_len = semiblocks * KW_SEMIBLOCK_LENGTH; cleanup: if( ret != 0) { memset( output, 0, semiblocks * KW_SEMIBLOCK_LENGTH ); } mbedtls_platform_zeroize( inbuff, KW_SEMIBLOCK_LENGTH * 2 ); mbedtls_platform_zeroize( outbuff, KW_SEMIBLOCK_LENGTH * 2 ); return( ret ); } /* * W-1 function as defined in RFC 3394 section 2.2.2 * This function assumes the following: * 1. Output buffer is at least of size ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH. * 2. The input buffer is of size semiblocks * KW_SEMIBLOCK_LENGTH. * 3. Minimal number of semiblocks is 3. * 4. A is a buffer to hold the first semiblock of the input buffer. */ static int unwrap( mbedtls_nist_kw_context *ctx, const unsigned char *input, size_t semiblocks, unsigned char A[KW_SEMIBLOCK_LENGTH], unsigned char *output, size_t* out_len ) { int ret = 0; const size_t s = 6 * ( semiblocks - 1 ); size_t olen; uint64_t t = 0; unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2]; unsigned char inbuff[KW_SEMIBLOCK_LENGTH * 2]; unsigned char *R = output + ( semiblocks - 2 ) * KW_SEMIBLOCK_LENGTH; *out_len = 0; if( semiblocks < MIN_SEMIBLOCKS_COUNT ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } memcpy( A, input, KW_SEMIBLOCK_LENGTH ); memmove( output, input + KW_SEMIBLOCK_LENGTH, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH ); /* Calculate intermediate values */ for( t = s; t >= 1; t-- ) { calc_a_xor_t( A, t ); memcpy( inbuff, A, KW_SEMIBLOCK_LENGTH ); memcpy( inbuff + KW_SEMIBLOCK_LENGTH, R, KW_SEMIBLOCK_LENGTH ); ret = mbedtls_cipher_update( &ctx->cipher_ctx, inbuff, 16, outbuff, &olen ); if( ret != 0 ) goto cleanup; memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH ); /* Set R as LSB64 of outbuff */ memcpy( R, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH ); if( R == output ) R = output + ( semiblocks - 2 ) * KW_SEMIBLOCK_LENGTH; else R -= KW_SEMIBLOCK_LENGTH; } *out_len = ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH; cleanup: if( ret != 0) memset( output, 0, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH ); mbedtls_platform_zeroize( inbuff, sizeof( inbuff ) ); mbedtls_platform_zeroize( outbuff, sizeof( outbuff ) ); return( ret ); } /* * KW-AD as defined in SP 800-38F section 6.2 * KWP-AD as defined in SP 800-38F section 6.3 */ int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode, const unsigned char *input, size_t in_len, unsigned char *output, size_t *out_len, size_t out_size ) { int ret = 0; size_t i, olen; unsigned char A[KW_SEMIBLOCK_LENGTH]; unsigned char diff, bad_padding = 0; *out_len = 0; if( out_size < in_len - KW_SEMIBLOCK_LENGTH ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } if( mode == MBEDTLS_KW_MODE_KW ) { /* * According to SP 800-38F Table 1, the ciphertext length for KW * must be between 3 to 2^54 semiblocks inclusive. */ if( in_len < 24 || #if SIZE_MAX > 0x200000000000000 in_len > 0x200000000000000 || #endif in_len % KW_SEMIBLOCK_LENGTH != 0 ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } ret = unwrap( ctx, input, in_len / KW_SEMIBLOCK_LENGTH, A, output, out_len ); if( ret != 0 ) goto cleanup; /* Check ICV in "constant-time" */ diff = mbedtls_nist_kw_safer_memcmp( NIST_KW_ICV1, A, KW_SEMIBLOCK_LENGTH ); if( diff != 0 ) { ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED; goto cleanup; } } else if( mode == MBEDTLS_KW_MODE_KWP ) { size_t padlen = 0; uint32_t Plen; /* * According to SP 800-38F Table 1, the ciphertext length for KWP * must be between 2 to 2^29 semiblocks inclusive. */ if( in_len < KW_SEMIBLOCK_LENGTH * 2 || #if SIZE_MAX > 0x100000000 in_len > 0x100000000 || #endif in_len % KW_SEMIBLOCK_LENGTH != 0 ) { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } if( in_len == KW_SEMIBLOCK_LENGTH * 2 ) { unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2]; ret = mbedtls_cipher_update( &ctx->cipher_ctx, input, 16, outbuff, &olen ); if( ret != 0 ) goto cleanup; memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH ); memcpy( output, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH ); mbedtls_platform_zeroize( outbuff, sizeof( outbuff ) ); *out_len = KW_SEMIBLOCK_LENGTH; } else { /* in_len >= KW_SEMIBLOCK_LENGTH * 3 */ ret = unwrap( ctx, input, in_len / KW_SEMIBLOCK_LENGTH, A, output, out_len ); if( ret != 0 ) goto cleanup; } /* Check ICV in "constant-time" */ diff = mbedtls_nist_kw_safer_memcmp( NIST_KW_ICV2, A, KW_SEMIBLOCK_LENGTH / 2 ); if( diff != 0 ) { ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED; } GET_UINT32_BE( Plen, A, KW_SEMIBLOCK_LENGTH / 2 ); /* * Plen is the length of the plaintext, when the input is valid. * If Plen is larger than the plaintext and padding, padlen will be * larger than 8, because of the type wrap around. */ padlen = in_len - KW_SEMIBLOCK_LENGTH - Plen; if ( padlen > 7 ) { padlen &= 7; ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED; } /* Check padding in "constant-time" */ for( diff = 0, i = 0; i < KW_SEMIBLOCK_LENGTH; i++ ) { if( i >= KW_SEMIBLOCK_LENGTH - padlen ) diff |= output[*out_len - KW_SEMIBLOCK_LENGTH + i]; else bad_padding |= output[*out_len - KW_SEMIBLOCK_LENGTH + i]; } if( diff != 0 ) { ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED; } if( ret != 0 ) { goto cleanup; } memset( output + Plen, 0, padlen ); *out_len = Plen; } else { ret = MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE; goto cleanup; } cleanup: if( ret != 0 ) { memset( output, 0, *out_len ); *out_len = 0; } mbedtls_platform_zeroize( &bad_padding, sizeof( bad_padding) ); mbedtls_platform_zeroize( &diff, sizeof( diff ) ); mbedtls_platform_zeroize( A, sizeof( A ) ); return( ret ); } #endif /* !MBEDTLS_NIST_KW_ALT */ #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) #define KW_TESTS 3 /* * Test vectors taken from NIST * https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/CAVP-TESTING-BLOCK-CIPHER-MODES#KW */ static const unsigned int key_len[KW_TESTS] = { 16, 24, 32 }; static const unsigned char kw_key[KW_TESTS][32] = { { 0x75, 0x75, 0xda, 0x3a, 0x93, 0x60, 0x7c, 0xc2, 0xbf, 0xd8, 0xce, 0xc7, 0xaa, 0xdf, 0xd9, 0xa6 }, { 0x2d, 0x85, 0x26, 0x08, 0x1d, 0x02, 0xfb, 0x5b, 0x85, 0xf6, 0x9a, 0xc2, 0x86, 0xec, 0xd5, 0x7d, 0x40, 0xdf, 0x5d, 0xf3, 0x49, 0x47, 0x44, 0xd3 }, { 0x11, 0x2a, 0xd4, 0x1b, 0x48, 0x56, 0xc7, 0x25, 0x4a, 0x98, 0x48, 0xd3, 0x0f, 0xdd, 0x78, 0x33, 0x5b, 0x03, 0x9a, 0x48, 0xa8, 0x96, 0x2c, 0x4d, 0x1c, 0xb7, 0x8e, 0xab, 0xd5, 0xda, 0xd7, 0x88 } }; static const unsigned char kw_msg[KW_TESTS][40] = { { 0x42, 0x13, 0x6d, 0x3c, 0x38, 0x4a, 0x3e, 0xea, 0xc9, 0x5a, 0x06, 0x6f, 0xd2, 0x8f, 0xed, 0x3f }, { 0x95, 0xc1, 0x1b, 0xf5, 0x35, 0x3a, 0xfe, 0xdb, 0x98, 0xfd, 0xd6, 0xc8, 0xca, 0x6f, 0xdb, 0x6d, 0xa5, 0x4b, 0x74, 0xb4, 0x99, 0x0f, 0xdc, 0x45, 0xc0, 0x9d, 0x15, 0x8f, 0x51, 0xce, 0x62, 0x9d, 0xe2, 0xaf, 0x26, 0xe3, 0x25, 0x0e, 0x6b, 0x4c }, { 0x1b, 0x20, 0xbf, 0x19, 0x90, 0xb0, 0x65, 0xd7, 0x98, 0xe1, 0xb3, 0x22, 0x64, 0xad, 0x50, 0xa8, 0x74, 0x74, 0x92, 0xba, 0x09, 0xa0, 0x4d, 0xd1 } }; static const size_t kw_msg_len[KW_TESTS] = { 16, 40, 24 }; static const size_t kw_out_len[KW_TESTS] = { 24, 48, 32 }; static const unsigned char kw_res[KW_TESTS][48] = { { 0x03, 0x1f, 0x6b, 0xd7, 0xe6, 0x1e, 0x64, 0x3d, 0xf6, 0x85, 0x94, 0x81, 0x6f, 0x64, 0xca, 0xa3, 0xf5, 0x6f, 0xab, 0xea, 0x25, 0x48, 0xf5, 0xfb }, { 0x44, 0x3c, 0x6f, 0x15, 0x09, 0x83, 0x71, 0x91, 0x3e, 0x5c, 0x81, 0x4c, 0xa1, 0xa0, 0x42, 0xec, 0x68, 0x2f, 0x7b, 0x13, 0x6d, 0x24, 0x3a, 0x4d, 0x6c, 0x42, 0x6f, 0xc6, 0x97, 0x15, 0x63, 0xe8, 0xa1, 0x4a, 0x55, 0x8e, 0x09, 0x64, 0x16, 0x19, 0xbf, 0x03, 0xfc, 0xaf, 0x90, 0xb1, 0xfc, 0x2d }, { 0xba, 0x8a, 0x25, 0x9a, 0x47, 0x1b, 0x78, 0x7d, 0xd5, 0xd5, 0x40, 0xec, 0x25, 0xd4, 0x3d, 0x87, 0x20, 0x0f, 0xda, 0xdc, 0x6d, 0x1f, 0x05, 0xd9, 0x16, 0x58, 0x4f, 0xa9, 0xf6, 0xcb, 0xf5, 0x12 } }; static const unsigned char kwp_key[KW_TESTS][32] = { { 0x78, 0x65, 0xe2, 0x0f, 0x3c, 0x21, 0x65, 0x9a, 0xb4, 0x69, 0x0b, 0x62, 0x9c, 0xdf, 0x3c, 0xc4 }, { 0xf5, 0xf8, 0x96, 0xa3, 0xbd, 0x2f, 0x4a, 0x98, 0x23, 0xef, 0x16, 0x2b, 0x00, 0xb8, 0x05, 0xd7, 0xde, 0x1e, 0xa4, 0x66, 0x26, 0x96, 0xa2, 0x58 }, { 0x95, 0xda, 0x27, 0x00, 0xca, 0x6f, 0xd9, 0xa5, 0x25, 0x54, 0xee, 0x2a, 0x8d, 0xf1, 0x38, 0x6f, 0x5b, 0x94, 0xa1, 0xa6, 0x0e, 0xd8, 0xa4, 0xae, 0xf6, 0x0a, 0x8d, 0x61, 0xab, 0x5f, 0x22, 0x5a } }; static const unsigned char kwp_msg[KW_TESTS][31] = { { 0xbd, 0x68, 0x43, 0xd4, 0x20, 0x37, 0x8d, 0xc8, 0x96 }, { 0x6c, 0xcd, 0xd5, 0x85, 0x18, 0x40, 0x97, 0xeb, 0xd5, 0xc3, 0xaf, 0x3e, 0x47, 0xd0, 0x2c, 0x19, 0x14, 0x7b, 0x4d, 0x99, 0x5f, 0x96, 0x43, 0x66, 0x91, 0x56, 0x75, 0x8c, 0x13, 0x16, 0x8f }, { 0xd1 } }; static const size_t kwp_msg_len[KW_TESTS] = { 9, 31, 1 }; static const unsigned char kwp_res[KW_TESTS][48] = { { 0x41, 0xec, 0xa9, 0x56, 0xd4, 0xaa, 0x04, 0x7e, 0xb5, 0xcf, 0x4e, 0xfe, 0x65, 0x96, 0x61, 0xe7, 0x4d, 0xb6, 0xf8, 0xc5, 0x64, 0xe2, 0x35, 0x00 }, { 0x4e, 0x9b, 0xc2, 0xbc, 0xbc, 0x6c, 0x1e, 0x13, 0xd3, 0x35, 0xbc, 0xc0, 0xf7, 0x73, 0x6a, 0x88, 0xfa, 0x87, 0x53, 0x66, 0x15, 0xbb, 0x8e, 0x63, 0x8b, 0xcc, 0x81, 0x66, 0x84, 0x68, 0x17, 0x90, 0x67, 0xcf, 0xa9, 0x8a, 0x9d, 0x0e, 0x33, 0x26 }, { 0x06, 0xba, 0x7a, 0xe6, 0xf3, 0x24, 0x8c, 0xfd, 0xcf, 0x26, 0x75, 0x07, 0xfa, 0x00, 0x1b, 0xc4 } }; static const size_t kwp_out_len[KW_TESTS] = { 24, 40, 16 }; int mbedtls_nist_kw_self_test( int verbose ) { mbedtls_nist_kw_context ctx; unsigned char out[48]; size_t olen; int i; int ret = 0; mbedtls_nist_kw_init( &ctx ); for( i = 0; i < KW_TESTS; i++ ) { if( verbose != 0 ) mbedtls_printf( " KW-AES-%u ", (unsigned int) key_len[i] * 8 ); ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, kw_key[i], key_len[i] * 8, 1 ); if( ret != 0 ) { if( verbose != 0 ) mbedtls_printf( " KW: setup failed " ); goto end; } ret = mbedtls_nist_kw_wrap( &ctx, MBEDTLS_KW_MODE_KW, kw_msg[i], kw_msg_len[i], out, &olen, sizeof( out ) ); if( ret != 0 || kw_out_len[i] != olen || memcmp( out, kw_res[i], kw_out_len[i] ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed. "); ret = 1; goto end; } if( ( ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, kw_key[i], key_len[i] * 8, 0 ) ) != 0 ) { if( verbose != 0 ) mbedtls_printf( " KW: setup failed "); goto end; } ret = mbedtls_nist_kw_unwrap( &ctx, MBEDTLS_KW_MODE_KW, out, olen, out, &olen, sizeof( out ) ); if( ret != 0 || olen != kw_msg_len[i] || memcmp( out, kw_msg[i], kw_msg_len[i] ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed\n" ); ret = 1; goto end; } if( verbose != 0 ) mbedtls_printf( " passed\n" ); } for( i = 0; i < KW_TESTS; i++ ) { olen = sizeof( out ); if( verbose != 0 ) mbedtls_printf( " KWP-AES-%u ", (unsigned int) key_len[i] * 8 ); ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, kwp_key[i], key_len[i] * 8, 1 ); if( ret != 0 ) { if( verbose != 0 ) mbedtls_printf( " KWP: setup failed " ); goto end; } ret = mbedtls_nist_kw_wrap( &ctx, MBEDTLS_KW_MODE_KWP, kwp_msg[i], kwp_msg_len[i], out, &olen, sizeof( out ) ); if( ret != 0 || kwp_out_len[i] != olen || memcmp( out, kwp_res[i], kwp_out_len[i] ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed. "); ret = 1; goto end; } if( ( ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, kwp_key[i], key_len[i] * 8, 0 ) ) != 0 ) { if( verbose != 0 ) mbedtls_printf( " KWP: setup failed "); goto end; } ret = mbedtls_nist_kw_unwrap( &ctx, MBEDTLS_KW_MODE_KWP, out, olen, out, &olen, sizeof( out ) ); if( ret != 0 || olen != kwp_msg_len[i] || memcmp( out, kwp_msg[i], kwp_msg_len[i] ) != 0 ) { if( verbose != 0 ) mbedtls_printf( "failed. "); ret = 1; goto end; } if( verbose != 0 ) mbedtls_printf( " passed\n" ); } end: mbedtls_nist_kw_free( &ctx ); if( verbose != 0 ) mbedtls_printf( "\n" ); return( ret ); } #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ #endif /* MBEDTLS_NIST_KW_C */
bsd-3-clause
endlessm/chromium-browser
third_party/llvm/libcxx/test/std/numerics/rand/rand.dis/rand.dist.samp/rand.dist.samp.plinear/eval_param.pass.cpp
15
2703
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // REQUIRES: long_tests // <random> // template<class RealType = double> // class piecewise_linear_distribution // template<class _URNG> result_type operator()(_URNG& g, const param_type& parm); #include <random> #include <vector> #include <iterator> #include <numeric> #include <algorithm> // for sort #include <cassert> #include <limits> #include "test_macros.h" template <class T> inline T sqr(T x) { return x*x; } double f(double x, double a, double m, double b, double c) { return a + m*(sqr(x) - sqr(b))/2 + c*(x-b); } int main(int, char**) { { typedef std::piecewise_linear_distribution<> D; typedef D::param_type P; typedef std::mt19937_64 G; G g; double b[] = {10, 14, 16, 17}; double p[] = {25, 62.5, 12.5, 0}; const size_t Np = sizeof(p) / sizeof(p[0]) - 1; D d; P pa(b, b+Np+1, p); const size_t N = 1000000; std::vector<D::result_type> u; for (size_t i = 0; i < N; ++i) { D::result_type v = d(g, pa); assert(10 <= v && v < 17); u.push_back(v); } std::sort(u.begin(), u.end()); int kp = -1; double a = std::numeric_limits<double>::quiet_NaN(); double m = std::numeric_limits<double>::quiet_NaN(); double bk = std::numeric_limits<double>::quiet_NaN(); double c = std::numeric_limits<double>::quiet_NaN(); std::vector<double> areas(Np); double S = 0; for (size_t i = 0; i < areas.size(); ++i) { areas[i] = (p[i]+p[i+1])*(b[i+1]-b[i])/2; S += areas[i]; } for (size_t i = 0; i < areas.size(); ++i) areas[i] /= S; for (size_t i = 0; i < Np+1; ++i) p[i] /= S; for (size_t i = 0; i < N; ++i) { int k = std::lower_bound(b, b+Np+1, u[i]) - b - 1; if (k != kp) { a = 0; for (int j = 0; j < k; ++j) a += areas[j]; m = (p[k+1] - p[k]) / (b[k+1] - b[k]); bk = b[k]; c = (b[k+1]*p[k] - b[k]*p[k+1]) / (b[k+1] - b[k]); kp = k; } assert(std::abs(f(u[i], a, m, bk, c) - double(i)/N) < .001); } } return 0; }
bsd-3-clause
mxOBS/deb-pkg_trusty_phantomjs
src/qt/src/corelib/thread/qthread_symbian.cpp
17
21835
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qthread.h" #include "qplatformdefs.h" #include <private/qcoreapplication_p.h> #include <private/qeventdispatcher_symbian_p.h> #include "qthreadstorage.h" #include "qthread_p.h" #include <private/qsystemerror_p.h> #include <private/qcore_symbian_p.h> #include <sched.h> #include <hal.h> #include <hal_data.h> #include <e32math.h> #include <QRegExp> // This can be manually enabled if debugging thread problems #ifdef QT_USE_RTTI_IN_THREAD_CLASSNAME #include <typeinfo> #endif // You only find these enumerations on Symbian^3 onwards, so we need to provide our own // to remain compatible with older releases. They won't be called by pre-Sym^3 SDKs. // HALData::ENumCpus #define QT_HALData_ENumCpus 119 QT_BEGIN_NAMESPACE #ifndef QT_NO_THREAD enum { ThreadPriorityResetFlag = 0x80000000 }; // Utility functions for getting, setting and clearing thread specific data. static QThreadData *get_thread_data() { return reinterpret_cast<QThreadData *>(Dll::Tls()); } static void set_thread_data(QThreadData *data) { qt_symbian_throwIfError(Dll::SetTls(data)); } static void clear_thread_data() { Dll::FreeTls(); } static void init_symbian_thread_handle(RThread &thread) { thread = RThread(); TThreadId threadId = thread.Id(); qt_symbian_throwIfError(thread.Open(threadId, EOwnerProcess)); } QThreadData *QThreadData::current() { QThreadData *data = get_thread_data(); if (!data) { void *a; if (QInternal::activateCallbacks(QInternal::AdoptCurrentThread, &a)) { QThread *adopted = static_cast<QThread*>(a); Q_ASSERT(adopted); data = QThreadData::get2(adopted); set_thread_data(data); adopted->d_func()->running = true; adopted->d_func()->finished = false; static_cast<QAdoptedThread *>(adopted)->init(); } else { data = new QThreadData; QT_TRY { set_thread_data(data); data->thread = new QAdoptedThread(data); } QT_CATCH(...) { clear_thread_data(); data->deref(); data = 0; QT_RETHROW; } data->deref(); } data->isAdopted = true; data->threadId = QThread::currentThreadId(); if (!QCoreApplicationPrivate::theMainThread) QCoreApplicationPrivate::theMainThread = data->thread; } return data; } class QCAdoptedThreadMonitor : public CActive { public: QCAdoptedThreadMonitor(QThread *thread) : CActive(EPriorityStandard), data(QThreadData::get2(thread)) { CActiveScheduler::Add(this); data->symbian_thread_handle.Logon(iStatus); SetActive(); } ~QCAdoptedThreadMonitor() { Cancel(); } void DoCancel() { data->symbian_thread_handle.LogonCancel(iStatus); } void RunL(); private: QThreadData* data; }; class QCAddAdoptedThread : public CActive { public: QCAddAdoptedThread() : CActive(EPriorityStandard) { CActiveScheduler::Add(this); } void ConstructL() { User::LeaveIfError(monitorThread.Open(RThread().Id())); start(); } ~QCAddAdoptedThread() { Cancel(); monitorThread.Close(); } void DoCancel() { User::RequestComplete(stat, KErrCancel); } void start() { iStatus = KRequestPending; SetActive(); stat = &iStatus; } void RunL() { if (iStatus.Int() != KErrNone) return; QMutexLocker adoptedThreadMonitorMutexlock(&adoptedThreadMonitorMutex); for (int i=threadsToAdd.size()-1; i>=0; i--) { // Create an active object to monitor the thread new (ELeave) QCAdoptedThreadMonitor(threadsToAdd[i]); count++; threadsToAdd.pop_back(); } start(); } static void add(QThread *thread) { QMutexLocker adoptedThreadMonitorMutexlock(&adoptedThreadMonitorMutex); if (!adoptedThreadAdder) { RThread monitorThread; qt_symbian_throwIfError(monitorThread.Create(KNullDesC(), &monitorThreadFunc, 1024, &User::Allocator(), 0)); TRequestStatus started; monitorThread.Rendezvous(started); monitorThread.Resume(); User::WaitForRequest(started); monitorThread.Close(); } if (RThread().Id() == adoptedThreadAdder->monitorThread.Id()) return; adoptedThreadAdder->threadsToAdd.push_back(thread); if (adoptedThreadAdder->stat) { adoptedThreadAdder->monitorThread.RequestComplete(adoptedThreadAdder->stat, KErrNone); } } static void monitorThreadFuncL() { CActiveScheduler* scheduler = new (ELeave) CActiveScheduler(); CleanupStack::PushL(scheduler); CActiveScheduler::Install(scheduler); adoptedThreadAdder = new(ELeave) QCAddAdoptedThread(); CleanupStack::PushL(adoptedThreadAdder); adoptedThreadAdder->ConstructL(); QCAddAdoptedThread *adder = adoptedThreadAdder; RThread::Rendezvous(KErrNone); CActiveScheduler::Start(); CleanupStack::PopAndDestroy(adder); CleanupStack::PopAndDestroy(scheduler); } static int monitorThreadFunc(void *) { _LIT(KMonitorThreadName, "adoptedMonitorThread"); RThread::RenameMe(KMonitorThreadName()); CTrapCleanup* cleanup = CTrapCleanup::New(); TRAPD(ret, monitorThreadFuncL()); delete cleanup; return ret; } static void threadDied() { QMutexLocker adoptedThreadMonitorMutexlock(&adoptedThreadMonitorMutex); if (adoptedThreadAdder) { adoptedThreadAdder->count--; if (adoptedThreadAdder->count <= 0 && adoptedThreadAdder->threadsToAdd.size() == 0) { CActiveScheduler::Stop(); adoptedThreadAdder = 0; } } } private: QVector<QThread*> threadsToAdd; RThread monitorThread; static QMutex adoptedThreadMonitorMutex; static QCAddAdoptedThread *adoptedThreadAdder; int count; TRequestStatus *stat; }; QMutex QCAddAdoptedThread::adoptedThreadMonitorMutex; QCAddAdoptedThread* QCAddAdoptedThread::adoptedThreadAdder = 0; static void finishAdoptedThread(QThreadData* data, bool closeNativeHandle) { if (data->isAdopted) { QThread *thread = data->thread; Q_ASSERT(thread); QThreadPrivate *thread_p = static_cast<QThreadPrivate *>(QObjectPrivate::get(thread)); if (!thread_p->finished) thread_p->finish(thread, true, closeNativeHandle); else if (closeNativeHandle && data->symbian_thread_handle.Handle()) data->symbian_thread_handle.Close(); } } void QCAdoptedThreadMonitor::RunL() { // clean up the thread, or close the handle if that's all that's left finishAdoptedThread(data, true); data->deref(); QCAddAdoptedThread::threadDied(); delete this; } static pthread_once_t current_thread_data_once = PTHREAD_ONCE_INIT; static pthread_key_t current_thread_data_key; static void pthread_in_thread_cleanup(void *p) { QThreadData *data = static_cast<QThreadData *>(p); // clean up the thread, but leave the handle for adoptedThreadMonitor finishAdoptedThread(data, false); } static void create_current_thread_data_key() { pthread_key_create(&current_thread_data_key, pthread_in_thread_cleanup); } static void destroy_current_thread_data_key() { pthread_once(&current_thread_data_once, create_current_thread_data_key); pthread_key_delete(current_thread_data_key); } Q_DESTRUCTOR_FUNCTION(destroy_current_thread_data_key) void QAdoptedThread::init() { Q_D(QThread); d->thread_id = RThread().Id(); // type operator to TUint init_symbian_thread_handle(d->data->symbian_thread_handle); QCAddAdoptedThread::add(this); pthread_once(&current_thread_data_once, create_current_thread_data_key); pthread_setspecific(current_thread_data_key, get_thread_data()); } /* QThreadPrivate */ #if defined(Q_C_CALLBACKS) extern "C" { #endif typedef void*(*QtThreadCallback)(void*); #if defined(Q_C_CALLBACKS) } #endif #endif // QT_NO_THREAD void QThreadPrivate::createEventDispatcher(QThreadData *data) { data->eventDispatcher = new QEventDispatcherSymbian; data->eventDispatcher->startingUp(); } #ifndef QT_NO_THREAD void *QThreadPrivate::start(void *arg) { QThread *thr = reinterpret_cast<QThread *>(arg); QThreadData *data = QThreadData::get2(thr); // do we need to reset the thread priority? if (int(thr->d_func()->priority) & ThreadPriorityResetFlag) { thr->setPriority(QThread::Priority(thr->d_func()->priority & ~ThreadPriorityResetFlag)); } // On symbian, threads other than the main thread are non critical by default // This means a worker thread can crash without crashing the application - to // use this feature, we would need to use RThread::Logon in the main thread // to catch abnormal thread exit and emit the finished signal. // For the sake of cross platform consistency, we set the thread as process critical // - advanced users who want the symbian behaviour can change the critical // attribute of the thread again once the app gains control in run() User::SetCritical(User::EProcessCritical); data->threadId = QThread::currentThreadId(); set_thread_data(data); CTrapCleanup *cleanup = CTrapCleanup::New(); q_check_ptr(cleanup); { QMutexLocker locker(&thr->d_func()->mutex); data->quitNow = thr->d_func()->exited; } // ### TODO: allow the user to create a custom event dispatcher createEventDispatcher(data); TRAPD(err, { try { emit thr->started(); thr->run(); } catch (const std::exception& ex) { qWarning("QThreadPrivate::start: Thread exited on exception %s", ex.what()); User::Leave(KErrGeneral); // leave to force cleanup stack cleanup } }); if (err) qWarning("QThreadPrivate::start: Thread exited on leave %d", err); // finish emits signals which should be wrapped in a trap for Symbian code, but otherwise ignore leaves and exceptions. TRAP(err, { try { QThreadPrivate::finish(arg); } catch (const std::exception& ex) { User::Leave(KErrGeneral); // leave to force cleanup stack cleanup } }); delete cleanup; return 0; } void QThreadPrivate::finish(void *arg, bool lockAnyway, bool closeNativeHandle) { QThread *thr = reinterpret_cast<QThread *>(arg); QThreadPrivate *d = thr->d_func(); QMutexLocker locker(lockAnyway ? &d->mutex : 0); d->isInFinish = true; d->priority = QThread::InheritPriority; bool terminated = d->terminated; void *data = &d->data->tls; locker.unlock(); if (terminated) emit thr->terminated(); emit thr->finished(); QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete); QThreadStorageData::finish((void **)data); locker.relock(); d->terminated = false; QAbstractEventDispatcher *eventDispatcher = d->data->eventDispatcher; if (eventDispatcher) { d->data->eventDispatcher = 0; locker.unlock(); eventDispatcher->closingDown(); delete eventDispatcher; locker.relock(); } d->thread_id = 0; if (closeNativeHandle) d->data->symbian_thread_handle.Close(); d->running = false; d->finished = true; d->isInFinish = false; d->thread_done.wakeAll(); } /************************************************************************** ** QThread *************************************************************************/ Qt::HANDLE QThread::currentThreadId() { return (Qt::HANDLE) (TUint) RThread().Id(); } int QThread::idealThreadCount() { int cores = 1; if (QSysInfo::symbianVersion() >= QSysInfo::SV_SF_3) { TInt inumcpus; TInt err; err = HAL::Get((HALData::TAttribute)QT_HALData_ENumCpus, inumcpus); if (err == KErrNone) { cores = qMax(inumcpus, 1); } } return cores; } void QThread::yieldCurrentThread() { sched_yield(); } /* \internal helper function to do thread sleeps */ static void thread_sleep(unsigned long remaining, unsigned long scale) { // maximum Symbian wait is 2^31 microseconds unsigned long maxWait = KMaxTInt / scale; do { unsigned long waitTime = qMin(maxWait, remaining); remaining -= waitTime; User::AfterHighRes(waitTime * scale); } while (remaining); } void QThread::sleep(unsigned long secs) { thread_sleep(secs, 1000000ul); } void QThread::msleep(unsigned long msecs) { thread_sleep(msecs, 1000ul); } void QThread::usleep(unsigned long usecs) { thread_sleep(usecs, 1ul); } TThreadPriority calculateSymbianPriority(QThread::Priority priority) { // Both Qt & Symbian use limited enums; this matches the mapping previously done through conversion to Posix granularity TThreadPriority symPriority; switch (priority) { case QThread::IdlePriority: symPriority = EPriorityMuchLess; break; case QThread::LowestPriority: case QThread::LowPriority: symPriority = EPriorityLess; break; case QThread::NormalPriority: symPriority = EPriorityNormal; break; case QThread::HighPriority: symPriority = EPriorityMore; break; case QThread::HighestPriority: case QThread::TimeCriticalPriority: symPriority = EPriorityMuchMore; break; case QThread::InheritPriority: default: symPriority = RThread().Priority(); break; } return symPriority; } void QThread::start(Priority priority) { Q_D(QThread); QMutexLocker locker(&d->mutex); if (d->isInFinish) d->thread_done.wait(locker.mutex()); if (d->running) return; d->running = true; d->finished = false; d->terminated = false; d->returnCode = 0; d->exited = false; d->priority = priority; if (d->stackSize == 0) // The default stack size on Symbian is very small, making even basic // operations like file I/O fail, so we increase it by default. d->stackSize = 0x14000; // Maximum stack size on Symbian. int code = KErrAlreadyExists; QString className(QLatin1String(metaObject()->className())); #ifdef QT_USE_RTTI_IN_THREAD_CLASSNAME // use RTTI, if enabled, to get a more accurate className. This must be manually enabled. const char* rttiName = typeid(*this).name(); if (rttiName) className = QLatin1String(rttiName); #endif QString threadNameBase = QString(QLatin1String("%1_%2_v=0x%3_")).arg(objectName()).arg(className).arg(*(uint*)this,8,16,QLatin1Char('0')); // Thread name can contain only characters allowed by User::ValidateName() otherwise RThread::Create fails. // Not allowed characters are: // - any character outside range 0x20 - 0x7e // - or asterisk, question mark or colon const QRegExp notAllowedChars(QLatin1String("[^\\x20-\\x7e]|\\*|\\?|\\:")); threadNameBase.replace(notAllowedChars, QLatin1String("_")); TPtrC threadNameBasePtr(qt_QString2TPtrC(threadNameBase)); // max thread name length is KMaxKernelName TBuf<KMaxKernelName> name; threadNameBasePtr.Set(threadNameBasePtr.Left(qMin(threadNameBasePtr.Length(), name.MaxLength() - 8))); const int MaxRetries = 10; for (int i=0; i<MaxRetries && code == KErrAlreadyExists; i++) { // generate a thread name with a random component to avoid and resolve name collisions // a named thread can be opened from another process name.Zero(); name.Append(threadNameBasePtr); name.AppendNumFixedWidth(Math::Random(), EHex, 8); code = d->data->symbian_thread_handle.Create(name, (TThreadFunction) QThreadPrivate::start, d->stackSize, NULL, this); } if (code == KErrNone) { d->thread_id = d->data->symbian_thread_handle.Id(); TThreadPriority symPriority = calculateSymbianPriority(priority); d->data->symbian_thread_handle.SetPriority(symPriority); d->data->symbian_thread_handle.Resume(); } else { qWarning("QThread::start: Thread creation error: %s", qPrintable(QSystemError(code, QSystemError::NativeError).toString())); d->running = false; d->finished = false; d->thread_id = 0; d->data->symbian_thread_handle.Close(); } } void QThread::terminate() { Q_D(QThread); QMutexLocker locker(&d->mutex); if (!d->thread_id) return; if (!d->running) return; if (!d->terminationEnabled) { d->terminatePending = true; return; } d->terminated = true; // "false, false" meaning: // 1. lockAnyway = false. Don't lock the mutex because it's already locked // (see above). // 2. closeNativeSymbianHandle = false. We don't want to close the thread handle, // because we need it here to terminate the thread. QThreadPrivate::finish(this, false, false); d->data->symbian_thread_handle.Terminate(KErrNone); d->data->symbian_thread_handle.Close(); } bool QThread::wait(unsigned long time) { Q_D(QThread); QMutexLocker locker(&d->mutex); if (d->thread_id == (TUint) RThread().Id()) { qWarning("QThread::wait: Thread tried to wait on itself"); return false; } if (d->finished || !d->running) return true; while (d->running) { // Check if thread still exists. Needed because kernel will kill it without notification // before global statics are deleted at application exit. if (d->data->symbian_thread_handle.Handle() && d->data->symbian_thread_handle.ExitType() != EExitPending) { // Cannot call finish here as wait is typically called from another thread. // It won't be necessary anyway, as we should never get here under normal operations; // all QThreads are EProcessCritical and therefore cannot normally exit // undetected (i.e. panic) as long as all thread control is via QThread. return true; } if (!d->thread_done.wait(locker.mutex(), time)) return false; } return true; } void QThread::setTerminationEnabled(bool enabled) { QThread *thr = currentThread(); Q_ASSERT_X(thr != 0, "QThread::setTerminationEnabled()", "Current thread was not started with QThread."); QThreadPrivate *d = thr->d_func(); QMutexLocker locker(&d->mutex); d->terminationEnabled = enabled; if (enabled && d->terminatePending) { d->terminated = true; // "false" meaning: // - lockAnyway = false. Don't lock the mutex because it's already locked // (see above). QThreadPrivate::finish(thr, false); locker.unlock(); // don't leave the mutex locked! User::Exit(0); // may be some other cleanup required? what if AS or cleanup stack? } } void QThread::setPriority(Priority priority) { Q_D(QThread); QMutexLocker locker(&d->mutex); if (!d->running) { qWarning("QThread::setPriority: Cannot set priority, thread is not running"); return; } d->priority = priority; // copied from start() with a few modifications: TThreadPriority symPriority = calculateSymbianPriority(priority); d->data->symbian_thread_handle.SetPriority(symPriority); } #endif // QT_NO_THREAD QT_END_NAMESPACE
bsd-3-clause
UCSantaCruzComputationalGenomicsLab/clapack
TESTING/LIN/dtrt02.c
21
6572
/* dtrt02.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" #include "blaswrap.h" /* Table of constant values */ static integer c__1 = 1; static doublereal c_b10 = -1.; /* Subroutine */ int dtrt02_(char *uplo, char *trans, char *diag, integer *n, integer *nrhs, doublereal *a, integer *lda, doublereal *x, integer * ldx, doublereal *b, integer *ldb, doublereal *work, doublereal *resid) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, x_dim1, x_offset, i__1; doublereal d__1, d__2; /* Local variables */ integer j; doublereal eps; extern logical lsame_(char *, char *); extern doublereal dasum_(integer *, doublereal *, integer *); doublereal anorm, bnorm; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), daxpy_(integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dtrmv_(char *, char *, char *, integer *, doublereal *, integer *, doublereal *, integer *); doublereal xnorm; extern doublereal dlamch_(char *), dlantr_(char *, char *, char *, integer *, integer *, doublereal *, integer *, doublereal *); /* -- LAPACK test routine (version 3.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DTRT02 computes the residual for the computed solution to a */ /* triangular system of linear equations A*x = b or A'*x = b. */ /* Here A is a triangular matrix, A' is the transpose of A, and x and b */ /* are N by NRHS matrices. The test ratio is the maximum over the */ /* number of right hand sides of */ /* norm(b - op(A)*x) / ( norm(op(A)) * norm(x) * EPS ), */ /* where op(A) denotes A or A' and EPS is the machine epsilon. */ /* Arguments */ /* ========= */ /* UPLO (input) CHARACTER*1 */ /* Specifies whether the matrix A is upper or lower triangular. */ /* = 'U': Upper triangular */ /* = 'L': Lower triangular */ /* TRANS (input) CHARACTER*1 */ /* Specifies the operation applied to A. */ /* = 'N': A *x = b (No transpose) */ /* = 'T': A'*x = b (Transpose) */ /* = 'C': A'*x = b (Conjugate transpose = Transpose) */ /* DIAG (input) CHARACTER*1 */ /* Specifies whether or not the matrix A is unit triangular. */ /* = 'N': Non-unit triangular */ /* = 'U': Unit triangular */ /* N (input) INTEGER */ /* The order of the matrix A. N >= 0. */ /* NRHS (input) INTEGER */ /* The number of right hand sides, i.e., the number of columns */ /* of the matrices X and B. NRHS >= 0. */ /* A (input) DOUBLE PRECISION array, dimension (LDA,N) */ /* The triangular matrix A. If UPLO = 'U', the leading n by n */ /* upper triangular part of the array A contains the upper */ /* triangular matrix, and the strictly lower triangular part of */ /* A is not referenced. If UPLO = 'L', the leading n by n lower */ /* triangular part of the array A contains the lower triangular */ /* matrix, and the strictly upper triangular part of A is not */ /* referenced. If DIAG = 'U', the diagonal elements of A are */ /* also not referenced and are assumed to be 1. */ /* LDA (input) INTEGER */ /* The leading dimension of the array A. LDA >= max(1,N). */ /* X (input) DOUBLE PRECISION array, dimension (LDX,NRHS) */ /* The computed solution vectors for the system of linear */ /* equations. */ /* LDX (input) INTEGER */ /* The leading dimension of the array X. LDX >= max(1,N). */ /* B (input) DOUBLE PRECISION array, dimension (LDB,NRHS) */ /* The right hand side vectors for the system of linear */ /* equations. */ /* LDB (input) INTEGER */ /* The leading dimension of the array B. LDB >= max(1,N). */ /* WORK (workspace) DOUBLE PRECISION array, dimension (N) */ /* RESID (output) DOUBLE PRECISION */ /* The maximum over the number of right hand sides of */ /* norm(op(A)*x - b) / ( norm(op(A)) * norm(x) * EPS ). */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Quick exit if N = 0 or NRHS = 0 */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; x_dim1 = *ldx; x_offset = 1 + x_dim1; x -= x_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; --work; /* Function Body */ if (*n <= 0 || *nrhs <= 0) { *resid = 0.; return 0; } /* Compute the 1-norm of A or A'. */ if (lsame_(trans, "N")) { anorm = dlantr_("1", uplo, diag, n, n, &a[a_offset], lda, &work[1]); } else { anorm = dlantr_("I", uplo, diag, n, n, &a[a_offset], lda, &work[1]); } /* Exit with RESID = 1/EPS if ANORM = 0. */ eps = dlamch_("Epsilon"); if (anorm <= 0.) { *resid = 1. / eps; return 0; } /* Compute the maximum over the number of right hand sides of */ /* norm(op(A)*x - b) / ( norm(op(A)) * norm(x) * EPS ) */ *resid = 0.; i__1 = *nrhs; for (j = 1; j <= i__1; ++j) { dcopy_(n, &x[j * x_dim1 + 1], &c__1, &work[1], &c__1); dtrmv_(uplo, trans, diag, n, &a[a_offset], lda, &work[1], &c__1); daxpy_(n, &c_b10, &b[j * b_dim1 + 1], &c__1, &work[1], &c__1); bnorm = dasum_(n, &work[1], &c__1); xnorm = dasum_(n, &x[j * x_dim1 + 1], &c__1); if (xnorm <= 0.) { *resid = 1. / eps; } else { /* Computing MAX */ d__1 = *resid, d__2 = bnorm / anorm / xnorm / eps; *resid = max(d__1,d__2); } /* L10: */ } return 0; /* End of DTRT02 */ } /* dtrt02_ */
bsd-3-clause
SuperNexus/android_external_skia
src/core/SkString.cpp
21
17792
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkString.h" #include "SkFixed.h" #include "SkThread.h" #include "SkUtils.h" #include <stdarg.h> #include <stdio.h> // number of bytes (on the stack) to receive the printf result static const size_t kBufferSize = 1024; #ifdef SK_BUILD_FOR_WIN #define VSNPRINTF(buffer, size, format, args) \ _vsnprintf_s(buffer, size, _TRUNCATE, format, args) #define SNPRINTF _snprintf #else #define VSNPRINTF vsnprintf #define SNPRINTF snprintf #endif #define ARGS_TO_BUFFER(format, buffer, size) \ do { \ va_list args; \ va_start(args, format); \ VSNPRINTF(buffer, size, format, args); \ va_end(args); \ } while (0) /////////////////////////////////////////////////////////////////////////////// bool SkStrEndsWith(const char string[], const char suffixStr[]) { SkASSERT(string); SkASSERT(suffixStr); size_t strLen = strlen(string); size_t suffixLen = strlen(suffixStr); return strLen >= suffixLen && !strncmp(string + strLen - suffixLen, suffixStr, suffixLen); } bool SkStrEndsWith(const char string[], const char suffixChar) { SkASSERT(string); size_t strLen = strlen(string); if (0 == strLen) { return false; } else { return (suffixChar == string[strLen-1]); } } int SkStrStartsWithOneOf(const char string[], const char prefixes[]) { int index = 0; do { const char* limit = strchr(prefixes, '\0'); if (!strncmp(string, prefixes, limit - prefixes)) { return index; } prefixes = limit + 1; index++; } while (prefixes[0]); return -1; } char* SkStrAppendU32(char string[], uint32_t dec) { SkDEBUGCODE(char* start = string;) char buffer[SkStrAppendU32_MaxSize]; char* p = buffer + sizeof(buffer); do { *--p = SkToU8('0' + dec % 10); dec /= 10; } while (dec != 0); SkASSERT(p >= buffer); char* stop = buffer + sizeof(buffer); while (p < stop) { *string++ = *p++; } SkASSERT(string - start <= SkStrAppendU32_MaxSize); return string; } char* SkStrAppendS32(char string[], int32_t dec) { if (dec < 0) { *string++ = '-'; dec = -dec; } return SkStrAppendU32(string, static_cast<uint32_t>(dec)); } char* SkStrAppendU64(char string[], uint64_t dec, int minDigits) { SkDEBUGCODE(char* start = string;) char buffer[SkStrAppendU64_MaxSize]; char* p = buffer + sizeof(buffer); do { *--p = SkToU8('0' + (int32_t) (dec % 10)); dec /= 10; minDigits--; } while (dec != 0); while (minDigits > 0) { *--p = '0'; minDigits--; } SkASSERT(p >= buffer); size_t cp_len = buffer + sizeof(buffer) - p; memcpy(string, p, cp_len); string += cp_len; SkASSERT(string - start <= SkStrAppendU64_MaxSize); return string; } char* SkStrAppendS64(char string[], int64_t dec, int minDigits) { if (dec < 0) { *string++ = '-'; dec = -dec; } return SkStrAppendU64(string, static_cast<uint64_t>(dec), minDigits); } char* SkStrAppendFloat(char string[], float value) { // since floats have at most 8 significant digits, we limit our %g to that. static const char gFormat[] = "%.8g"; // make it 1 larger for the terminating 0 char buffer[SkStrAppendScalar_MaxSize + 1]; int len = SNPRINTF(buffer, sizeof(buffer), gFormat, value); memcpy(string, buffer, len); SkASSERT(len <= SkStrAppendScalar_MaxSize); return string + len; } char* SkStrAppendFixed(char string[], SkFixed x) { SkDEBUGCODE(char* start = string;) if (x < 0) { *string++ = '-'; x = -x; } unsigned frac = x & 0xFFFF; x >>= 16; if (frac == 0xFFFF) { // need to do this to "round up", since 65535/65536 is closer to 1 than to .9999 x += 1; frac = 0; } string = SkStrAppendS32(string, x); // now handle the fractional part (if any) if (frac) { static const uint16_t gTens[] = { 1000, 100, 10, 1 }; const uint16_t* tens = gTens; x = SkFixedRound(frac * 10000); SkASSERT(x <= 10000); if (x == 10000) { x -= 1; } *string++ = '.'; do { unsigned powerOfTen = *tens++; *string++ = SkToU8('0' + x / powerOfTen); x %= powerOfTen; } while (x != 0); } SkASSERT(string - start <= SkStrAppendScalar_MaxSize); return string; } /////////////////////////////////////////////////////////////////////////////// // the 3 values are [length] [refcnt] [terminating zero data] const SkString::Rec SkString::gEmptyRec = { 0, 0, 0 }; #define SizeOfRec() (gEmptyRec.data() - (const char*)&gEmptyRec) static uint32_t trim_size_t_to_u32(size_t value) { if (sizeof(size_t) > sizeof(uint32_t)) { if (value > SK_MaxU32) { value = SK_MaxU32; } } return (uint32_t)value; } static size_t check_add32(size_t base, size_t extra) { SkASSERT(base <= SK_MaxU32); if (sizeof(size_t) > sizeof(uint32_t)) { if (base + extra > SK_MaxU32) { extra = SK_MaxU32 - base; } } return extra; } SkString::Rec* SkString::AllocRec(const char text[], size_t len) { Rec* rec; if (0 == len) { rec = const_cast<Rec*>(&gEmptyRec); } else { len = trim_size_t_to_u32(len); // add 1 for terminating 0, then align4 so we can have some slop when growing the string rec = (Rec*)sk_malloc_throw(SizeOfRec() + SkAlign4(len + 1)); rec->fLength = SkToU32(len); rec->fRefCnt = 1; if (text) { memcpy(rec->data(), text, len); } rec->data()[len] = 0; } return rec; } SkString::Rec* SkString::RefRec(Rec* src) { if (src != &gEmptyRec) { sk_atomic_inc(&src->fRefCnt); } return src; } #ifdef SK_DEBUG void SkString::validate() const { // make sure know one has written over our global SkASSERT(0 == gEmptyRec.fLength); SkASSERT(0 == gEmptyRec.fRefCnt); SkASSERT(0 == gEmptyRec.data()[0]); if (fRec != &gEmptyRec) { SkASSERT(fRec->fLength > 0); SkASSERT(fRec->fRefCnt > 0); SkASSERT(0 == fRec->data()[fRec->fLength]); } SkASSERT(fStr == c_str()); } #endif /////////////////////////////////////////////////////////////////////////////// SkString::SkString() : fRec(const_cast<Rec*>(&gEmptyRec)) { #ifdef SK_DEBUG fStr = fRec->data(); #endif } SkString::SkString(size_t len) { fRec = AllocRec(NULL, len); #ifdef SK_DEBUG fStr = fRec->data(); #endif } SkString::SkString(const char text[]) { size_t len = text ? strlen(text) : 0; fRec = AllocRec(text, len); #ifdef SK_DEBUG fStr = fRec->data(); #endif } SkString::SkString(const char text[], size_t len) { fRec = AllocRec(text, len); #ifdef SK_DEBUG fStr = fRec->data(); #endif } SkString::SkString(const SkString& src) { src.validate(); fRec = RefRec(src.fRec); #ifdef SK_DEBUG fStr = fRec->data(); #endif } SkString::~SkString() { this->validate(); if (fRec->fLength) { SkASSERT(fRec->fRefCnt > 0); if (sk_atomic_dec(&fRec->fRefCnt) == 1) { sk_free(fRec); } } } bool SkString::equals(const SkString& src) const { return fRec == src.fRec || this->equals(src.c_str(), src.size()); } bool SkString::equals(const char text[]) const { return this->equals(text, text ? strlen(text) : 0); } bool SkString::equals(const char text[], size_t len) const { SkASSERT(len == 0 || text != NULL); return fRec->fLength == len && !memcmp(fRec->data(), text, len); } SkString& SkString::operator=(const SkString& src) { this->validate(); if (fRec != src.fRec) { SkString tmp(src); this->swap(tmp); } return *this; } SkString& SkString::operator=(const char text[]) { this->validate(); SkString tmp(text); this->swap(tmp); return *this; } void SkString::reset() { this->validate(); if (fRec->fLength) { SkASSERT(fRec->fRefCnt > 0); if (sk_atomic_dec(&fRec->fRefCnt) == 1) { sk_free(fRec); } } fRec = const_cast<Rec*>(&gEmptyRec); #ifdef SK_DEBUG fStr = fRec->data(); #endif } char* SkString::writable_str() { this->validate(); if (fRec->fLength) { if (fRec->fRefCnt > 1) { Rec* rec = AllocRec(fRec->data(), fRec->fLength); if (sk_atomic_dec(&fRec->fRefCnt) == 1) { // In this case after our check of fRecCnt > 1, we suddenly // did become the only owner, so now we have two copies of the // data (fRec and rec), so we need to delete one of them. sk_free(fRec); } fRec = rec; #ifdef SK_DEBUG fStr = fRec->data(); #endif } } return fRec->data(); } void SkString::set(const char text[]) { this->set(text, text ? strlen(text) : 0); } void SkString::set(const char text[], size_t len) { len = trim_size_t_to_u32(len); if (0 == len) { this->reset(); } else if (1 == fRec->fRefCnt && len <= fRec->fLength) { // should we resize if len <<<< fLength, to save RAM? (e.g. len < (fLength>>1))? // just use less of the buffer without allocating a smaller one char* p = this->writable_str(); if (text) { memcpy(p, text, len); } p[len] = 0; fRec->fLength = SkToU32(len); } else if (1 == fRec->fRefCnt && (fRec->fLength >> 2) == (len >> 2)) { // we have spare room in the current allocation, so don't alloc a larger one char* p = this->writable_str(); if (text) { memcpy(p, text, len); } p[len] = 0; fRec->fLength = SkToU32(len); } else { SkString tmp(text, len); this->swap(tmp); } } void SkString::setUTF16(const uint16_t src[]) { int count = 0; while (src[count]) { count += 1; } this->setUTF16(src, count); } void SkString::setUTF16(const uint16_t src[], size_t count) { count = trim_size_t_to_u32(count); if (0 == count) { this->reset(); } else if (count <= fRec->fLength) { // should we resize if len <<<< fLength, to save RAM? (e.g. len < (fLength>>1)) if (count < fRec->fLength) { this->resize(count); } char* p = this->writable_str(); for (size_t i = 0; i < count; i++) { p[i] = SkToU8(src[i]); } p[count] = 0; } else { SkString tmp(count); // puts a null terminator at the end of the string char* p = tmp.writable_str(); for (size_t i = 0; i < count; i++) { p[i] = SkToU8(src[i]); } this->swap(tmp); } } void SkString::insert(size_t offset, const char text[]) { this->insert(offset, text, text ? strlen(text) : 0); } void SkString::insert(size_t offset, const char text[], size_t len) { if (len) { size_t length = fRec->fLength; if (offset > length) { offset = length; } // Check if length + len exceeds 32bits, we trim len len = check_add32(length, len); if (0 == len) { return; } /* If we're the only owner, and we have room in our allocation for the insert, do it in place, rather than allocating a new buffer. To know we have room, compare the allocated sizes beforeAlloc = SkAlign4(length + 1) afterAlloc = SkAligh4(length + 1 + len) but SkAlign4(x) is (x + 3) >> 2 << 2 which is equivalent for testing to (length + 1 + 3) >> 2 == (length + 1 + 3 + len) >> 2 and we can then eliminate the +1+3 since that doesn't affec the answer */ if (1 == fRec->fRefCnt && (length >> 2) == ((length + len) >> 2)) { char* dst = this->writable_str(); if (offset < length) { memmove(dst + offset + len, dst + offset, length - offset); } memcpy(dst + offset, text, len); dst[length + len] = 0; fRec->fLength = SkToU32(length + len); } else { /* Seems we should use realloc here, since that is safe if it fails (we have the original data), and might be faster than alloc/copy/free. */ SkString tmp(fRec->fLength + len); char* dst = tmp.writable_str(); if (offset > 0) { memcpy(dst, fRec->data(), offset); } memcpy(dst + offset, text, len); if (offset < fRec->fLength) { memcpy(dst + offset + len, fRec->data() + offset, fRec->fLength - offset); } this->swap(tmp); } } } void SkString::insertUnichar(size_t offset, SkUnichar uni) { char buffer[kMaxBytesInUTF8Sequence]; size_t len = SkUTF8_FromUnichar(uni, buffer); if (len) { this->insert(offset, buffer, len); } } void SkString::insertS32(size_t offset, int32_t dec) { char buffer[SkStrAppendS32_MaxSize]; char* stop = SkStrAppendS32(buffer, dec); this->insert(offset, buffer, stop - buffer); } void SkString::insertS64(size_t offset, int64_t dec, int minDigits) { char buffer[SkStrAppendS64_MaxSize]; char* stop = SkStrAppendS64(buffer, dec, minDigits); this->insert(offset, buffer, stop - buffer); } void SkString::insertU32(size_t offset, uint32_t dec) { char buffer[SkStrAppendU32_MaxSize]; char* stop = SkStrAppendU32(buffer, dec); this->insert(offset, buffer, stop - buffer); } void SkString::insertU64(size_t offset, uint64_t dec, int minDigits) { char buffer[SkStrAppendU64_MaxSize]; char* stop = SkStrAppendU64(buffer, dec, minDigits); this->insert(offset, buffer, stop - buffer); } void SkString::insertHex(size_t offset, uint32_t hex, int minDigits) { minDigits = SkPin32(minDigits, 0, 8); static const char gHex[] = "0123456789ABCDEF"; char buffer[8]; char* p = buffer + sizeof(buffer); do { *--p = gHex[hex & 0xF]; hex >>= 4; minDigits -= 1; } while (hex != 0); while (--minDigits >= 0) { *--p = '0'; } SkASSERT(p >= buffer); this->insert(offset, p, buffer + sizeof(buffer) - p); } void SkString::insertScalar(size_t offset, SkScalar value) { char buffer[SkStrAppendScalar_MaxSize]; char* stop = SkStrAppendScalar(buffer, value); this->insert(offset, buffer, stop - buffer); } void SkString::printf(const char format[], ...) { char buffer[kBufferSize]; ARGS_TO_BUFFER(format, buffer, kBufferSize); this->set(buffer, strlen(buffer)); } void SkString::appendf(const char format[], ...) { char buffer[kBufferSize]; ARGS_TO_BUFFER(format, buffer, kBufferSize); this->append(buffer, strlen(buffer)); } void SkString::appendf(const char format[], va_list args) { char buffer[kBufferSize]; VSNPRINTF(buffer, kBufferSize, format, args); this->append(buffer, strlen(buffer)); } void SkString::prependf(const char format[], ...) { char buffer[kBufferSize]; ARGS_TO_BUFFER(format, buffer, kBufferSize); this->prepend(buffer, strlen(buffer)); } /////////////////////////////////////////////////////////////////////////////// void SkString::remove(size_t offset, size_t length) { size_t size = this->size(); if (offset < size) { if (offset + length > size) { length = size - offset; } if (length > 0) { SkASSERT(size > length); SkString tmp(size - length); char* dst = tmp.writable_str(); const char* src = this->c_str(); if (offset) { SkASSERT(offset <= tmp.size()); memcpy(dst, src, offset); } size_t tail = size - offset - length; SkASSERT((int32_t)tail >= 0); if (tail) { // SkASSERT(offset + length <= tmp.size()); memcpy(dst + offset, src + offset + length, tail); } SkASSERT(dst[tmp.size()] == 0); this->swap(tmp); } } } void SkString::swap(SkString& other) { this->validate(); other.validate(); SkTSwap<Rec*>(fRec, other.fRec); #ifdef SK_DEBUG SkTSwap<const char*>(fStr, other.fStr); #endif } /////////////////////////////////////////////////////////////////////////////// SkAutoUCS2::SkAutoUCS2(const char utf8[]) { size_t len = strlen(utf8); fUCS2 = (uint16_t*)sk_malloc_throw((len + 1) * sizeof(uint16_t)); uint16_t* dst = fUCS2; for (;;) { SkUnichar uni = SkUTF8_NextUnichar(&utf8); *dst++ = SkToU16(uni); if (uni == 0) { break; } } fCount = (int)(dst - fUCS2); } SkAutoUCS2::~SkAutoUCS2() { sk_free(fUCS2); } /////////////////////////////////////////////////////////////////////////////// SkString SkStringPrintf(const char* format, ...) { SkString formattedOutput; char buffer[kBufferSize]; ARGS_TO_BUFFER(format, buffer, kBufferSize); formattedOutput.set(buffer); return formattedOutput; } #undef VSNPRINTF #undef SNPRINTF
bsd-3-clause
MonkeyZZZZ/platform_external_skia
gm/fontscaler.cpp
31
2740
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkTypeface.h" namespace skiagm { class FontScalerGM : public GM { public: FontScalerGM() { this->setBGColor(0xFFFFFFFF); } virtual ~FontScalerGM() { } protected: SkString onShortName() override { return SkString("fontscaler"); } SkISize onISize() override { return SkISize::Make(1450, 750); } static void rotate_about(SkCanvas* canvas, SkScalar degrees, SkScalar px, SkScalar py) { canvas->translate(px, py); canvas->rotate(degrees); canvas->translate(-px, -py); } void onDraw(SkCanvas* canvas) override { SkPaint paint; paint.setAntiAlias(true); paint.setLCDRenderText(true); //With freetype the default (normal hinting) can be really ugly. //Most distros now set slight (vertical hinting only) in any event. paint.setHinting(SkPaint::kSlight_Hinting); sk_tool_utils::set_portable_typeface(&paint, "Times Roman", SkTypeface::kNormal); const char* text = "Hamburgefons ooo mmm"; const size_t textLen = strlen(text); for (int j = 0; j < 2; ++j) { // This used to do 6 iterations but it causes the N4 to crash in the MSAA4 config. for (int i = 0; i < 5; ++i) { SkScalar x = SkIntToScalar(10); SkScalar y = SkIntToScalar(20); SkAutoCanvasRestore acr(canvas, true); canvas->translate(SkIntToScalar(50 + i * 230), SkIntToScalar(20)); rotate_about(canvas, SkIntToScalar(i * 5), x, y * 10); { SkPaint p; p.setAntiAlias(true); SkRect r; r.set(x - SkIntToScalar(3), SkIntToScalar(15), x - SkIntToScalar(1), SkIntToScalar(280)); canvas->drawRect(r, p); } for (int ps = 6; ps <= 22; ps++) { paint.setTextSize(SkIntToScalar(ps)); canvas->drawText(text, textLen, x, y, paint); y += paint.getFontMetrics(NULL); } } canvas->translate(0, SkIntToScalar(360)); paint.setSubpixelText(true); } } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new FontScalerGM; } static GMRegistry reg(MyFactory); }
bsd-3-clause
gavinp/chromium
third_party/mesa/MesaLib/src/mesa/state_tracker/st_atom_sampler.c
32
7971
/************************************************************************** * * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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. * **************************************************************************/ /* * Authors: * Keith Whitwell <keith@tungstengraphics.com> * Brian Paul */ #include "main/macros.h" #include "st_context.h" #include "st_cb_texture.h" #include "st_atom.h" #include "pipe/p_context.h" #include "pipe/p_defines.h" #include "cso_cache/cso_context.h" /** * Convert GLenum texcoord wrap tokens to pipe tokens. */ static GLuint gl_wrap_xlate(GLenum wrap) { switch (wrap) { case GL_REPEAT: return PIPE_TEX_WRAP_REPEAT; case GL_CLAMP: return PIPE_TEX_WRAP_CLAMP; case GL_CLAMP_TO_EDGE: return PIPE_TEX_WRAP_CLAMP_TO_EDGE; case GL_CLAMP_TO_BORDER: return PIPE_TEX_WRAP_CLAMP_TO_BORDER; case GL_MIRRORED_REPEAT: return PIPE_TEX_WRAP_MIRROR_REPEAT; case GL_MIRROR_CLAMP_EXT: return PIPE_TEX_WRAP_MIRROR_CLAMP; case GL_MIRROR_CLAMP_TO_EDGE_EXT: return PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE; case GL_MIRROR_CLAMP_TO_BORDER_EXT: return PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER; default: assert(0); return 0; } } static GLuint gl_filter_to_mip_filter(GLenum filter) { switch (filter) { case GL_NEAREST: case GL_LINEAR: return PIPE_TEX_MIPFILTER_NONE; case GL_NEAREST_MIPMAP_NEAREST: case GL_LINEAR_MIPMAP_NEAREST: return PIPE_TEX_MIPFILTER_NEAREST; case GL_NEAREST_MIPMAP_LINEAR: case GL_LINEAR_MIPMAP_LINEAR: return PIPE_TEX_MIPFILTER_LINEAR; default: assert(0); return PIPE_TEX_MIPFILTER_NONE; } } static GLuint gl_filter_to_img_filter(GLenum filter) { switch (filter) { case GL_NEAREST: case GL_NEAREST_MIPMAP_NEAREST: case GL_NEAREST_MIPMAP_LINEAR: return PIPE_TEX_FILTER_NEAREST; case GL_LINEAR: case GL_LINEAR_MIPMAP_NEAREST: case GL_LINEAR_MIPMAP_LINEAR: return PIPE_TEX_FILTER_LINEAR; default: assert(0); return PIPE_TEX_FILTER_NEAREST; } } static void xlate_border_color(const GLfloat *colorIn, GLenum baseFormat, GLfloat *colorOut) { switch (baseFormat) { case GL_RGB: colorOut[0] = colorIn[0]; colorOut[1] = colorIn[1]; colorOut[2] = colorIn[2]; colorOut[3] = 1.0F; break; case GL_ALPHA: colorOut[0] = colorOut[1] = colorOut[2] = 0.0; colorOut[3] = colorIn[3]; break; case GL_LUMINANCE: colorOut[0] = colorOut[1] = colorOut[2] = colorIn[0]; colorOut[3] = 1.0; break; case GL_LUMINANCE_ALPHA: colorOut[0] = colorOut[1] = colorOut[2] = colorIn[0]; colorOut[3] = colorIn[3]; break; case GL_INTENSITY: colorOut[0] = colorOut[1] = colorOut[2] = colorOut[3] = colorIn[0]; break; default: COPY_4V(colorOut, colorIn); } } static void update_samplers(struct st_context *st) { struct gl_vertex_program *vprog = st->ctx->VertexProgram._Current; struct gl_fragment_program *fprog = st->ctx->FragmentProgram._Current; const GLbitfield samplersUsed = (vprog->Base.SamplersUsed | fprog->Base.SamplersUsed); GLuint su; st->state.num_samplers = 0; /* loop over sampler units (aka tex image units) */ for (su = 0; su < st->ctx->Const.MaxTextureImageUnits; su++) { struct pipe_sampler_state *sampler = st->state.samplers + su; memset(sampler, 0, sizeof(*sampler)); if (samplersUsed & (1 << su)) { struct gl_texture_object *texobj; struct gl_texture_image *teximg; GLuint texUnit; if (fprog->Base.SamplersUsed & (1 << su)) texUnit = fprog->Base.SamplerUnits[su]; else texUnit = vprog->Base.SamplerUnits[su]; texobj = st->ctx->Texture.Unit[texUnit]._Current; if (!texobj) { texobj = st_get_default_texture(st); } teximg = texobj->Image[0][texobj->BaseLevel]; sampler->wrap_s = gl_wrap_xlate(texobj->WrapS); sampler->wrap_t = gl_wrap_xlate(texobj->WrapT); sampler->wrap_r = gl_wrap_xlate(texobj->WrapR); sampler->min_img_filter = gl_filter_to_img_filter(texobj->MinFilter); sampler->min_mip_filter = gl_filter_to_mip_filter(texobj->MinFilter); sampler->mag_img_filter = gl_filter_to_img_filter(texobj->MagFilter); if (texobj->Target != GL_TEXTURE_RECTANGLE_ARB) sampler->normalized_coords = 1; sampler->lod_bias = st->ctx->Texture.Unit[su].LodBias; sampler->min_lod = texobj->BaseLevel + texobj->MinLod; if (sampler->min_lod < texobj->BaseLevel) sampler->min_lod = texobj->BaseLevel; sampler->max_lod = MIN2((GLfloat) texobj->MaxLevel, (texobj->MaxLod + texobj->BaseLevel)); if (sampler->max_lod < sampler->min_lod) { /* The GL spec doesn't seem to specify what to do in this case. * Swap the values. */ float tmp = sampler->max_lod; sampler->max_lod = sampler->min_lod; sampler->min_lod = tmp; assert(sampler->min_lod <= sampler->max_lod); } xlate_border_color(texobj->BorderColor.f, teximg ? teximg->_BaseFormat : GL_RGBA, sampler->border_color); sampler->max_anisotropy = (texobj->MaxAnisotropy == 1.0 ? 0 : (GLuint)texobj->MaxAnisotropy); /* only care about ARB_shadow, not SGI shadow */ if (texobj->CompareMode == GL_COMPARE_R_TO_TEXTURE) { sampler->compare_mode = PIPE_TEX_COMPARE_R_TO_TEXTURE; sampler->compare_func = st_compare_func_to_pipe(texobj->CompareFunc); } st->state.num_samplers = su + 1; /*printf("%s su=%u non-null\n", __FUNCTION__, su);*/ cso_single_sampler(st->cso_context, su, sampler); if (su < st->ctx->Const.MaxVertexTextureImageUnits) { cso_single_vertex_sampler(st->cso_context, su, sampler); } } else { /*printf("%s su=%u null\n", __FUNCTION__, su);*/ cso_single_sampler(st->cso_context, su, NULL); if (su < st->ctx->Const.MaxVertexTextureImageUnits) { cso_single_vertex_sampler(st->cso_context, su, NULL); } } } cso_single_sampler_done(st->cso_context); if (st->ctx->Const.MaxVertexTextureImageUnits > 0) { cso_single_vertex_sampler_done(st->cso_context); } } const struct st_tracked_state st_update_sampler = { "st_update_sampler", /* name */ { /* dirty */ _NEW_TEXTURE, /* mesa */ 0, /* st */ }, update_samplers /* update */ };
bsd-3-clause
mwiebe/numpy
numpy/core/src/multiarray/arrayobject.c
32
57133
/* Provide multidimensional arrays as a basic object type in python. Based on Original Numeric implementation Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu with contributions from many Numeric Python developers 1995-2004 Heavily modified in 2005 with inspiration from Numarray by Travis Oliphant, oliphant@ee.byu.edu Brigham Young Univeristy maintainer email: oliphant.travis@ieee.org Numarray design (which provided guidance) by Space Science Telescope Institute (J. Todd Miller, Perry Greenfield, Rick White) */ #define PY_SSIZE_T_CLEAN #include <Python.h> #include "structmember.h" /*#include <stdio.h>*/ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "number.h" #include "usertypes.h" #include "arraytypes.h" #include "scalartypes.h" #include "arrayobject.h" #include "ctors.h" #include "methods.h" #include "descriptor.h" #include "iterators.h" #include "mapping.h" #include "getset.h" #include "sequence.h" #include "buffer.h" #include "array_assign.h" #include "alloc.h" #include "mem_overlap.h" /*NUMPY_API Compute the size of an array (in number of items) */ NPY_NO_EXPORT npy_intp PyArray_Size(PyObject *op) { if (PyArray_Check(op)) { return PyArray_SIZE((PyArrayObject *)op); } else { return 0; } } /*NUMPY_API * * Precondition: 'arr' is a copy of 'base' (though possibly with different * strides, ordering, etc.). This function sets the UPDATEIFCOPY flag and the * ->base pointer on 'arr', so that when 'arr' is destructed, it will copy any * changes back to 'base'. * * Steals a reference to 'base'. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_SetUpdateIfCopyBase(PyArrayObject *arr, PyArrayObject *base) { if (base == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot UPDATEIFCOPY to NULL array"); return -1; } if (PyArray_BASE(arr) != NULL) { PyErr_SetString(PyExc_ValueError, "Cannot set array with existing base to UPDATEIFCOPY"); goto fail; } if (PyArray_FailUnlessWriteable(base, "UPDATEIFCOPY base") < 0) { goto fail; } /* * Any writes to 'arr' will magicaly turn into writes to 'base', so we * should warn if necessary. */ if (PyArray_FLAGS(base) & NPY_ARRAY_WARN_ON_WRITE) { PyArray_ENABLEFLAGS(arr, NPY_ARRAY_WARN_ON_WRITE); } /* * Unlike PyArray_SetBaseObject, we do not compress the chain of base * references. */ ((PyArrayObject_fields *)arr)->base = (PyObject *)base; PyArray_ENABLEFLAGS(arr, NPY_ARRAY_UPDATEIFCOPY); PyArray_CLEARFLAGS(base, NPY_ARRAY_WRITEABLE); return 0; fail: Py_DECREF(base); return -1; } /*NUMPY_API * Sets the 'base' attribute of the array. This steals a reference * to 'obj'. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_SetBaseObject(PyArrayObject *arr, PyObject *obj) { if (obj == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot set the NumPy array 'base' " "dependency to NULL after initialization"); return -1; } /* * Allow the base to be set only once. Once the object which * owns the data is set, it doesn't make sense to change it. */ if (PyArray_BASE(arr) != NULL) { Py_DECREF(obj); PyErr_SetString(PyExc_ValueError, "Cannot set the NumPy array 'base' " "dependency more than once"); return -1; } /* * Don't allow infinite chains of views, always set the base * to the first owner of the data. * That is, either the first object which isn't an array, * or the first object which owns its own data. */ while (PyArray_Check(obj) && (PyObject *)arr != obj) { PyArrayObject *obj_arr = (PyArrayObject *)obj; PyObject *tmp; /* Propagate WARN_ON_WRITE through views. */ if (PyArray_FLAGS(obj_arr) & NPY_ARRAY_WARN_ON_WRITE) { PyArray_ENABLEFLAGS(arr, NPY_ARRAY_WARN_ON_WRITE); } /* If this array owns its own data, stop collapsing */ if (PyArray_CHKFLAGS(obj_arr, NPY_ARRAY_OWNDATA)) { break; } tmp = PyArray_BASE(obj_arr); /* If there's no base, stop collapsing */ if (tmp == NULL) { break; } /* Stop the collapse new base when the would not be of the same * type (i.e. different subclass). */ if (Py_TYPE(tmp) != Py_TYPE(arr)) { break; } Py_INCREF(tmp); Py_DECREF(obj); obj = tmp; } /* Disallow circular references */ if ((PyObject *)arr == obj) { Py_DECREF(obj); PyErr_SetString(PyExc_ValueError, "Cannot create a circular NumPy array 'base' dependency"); return -1; } ((PyArrayObject_fields *)arr)->base = obj; return 0; } /*NUMPY_API*/ NPY_NO_EXPORT int PyArray_CopyObject(PyArrayObject *dest, PyObject *src_object) { int ret = 0; PyArrayObject *src; PyArray_Descr *dtype = NULL; int ndim = 0; npy_intp dims[NPY_MAXDIMS]; Py_INCREF(src_object); /* * Special code to mimic Numeric behavior for * character arrays. */ if (PyArray_DESCR(dest)->type == NPY_CHARLTR && PyArray_NDIM(dest) > 0 && PyString_Check(src_object)) { npy_intp n_new, n_old; char *new_string; PyObject *tmp; n_new = PyArray_DIMS(dest)[PyArray_NDIM(dest)-1]; n_old = PyString_Size(src_object); if (n_new > n_old) { new_string = malloc(n_new); if (new_string == NULL) { Py_DECREF(src_object); PyErr_NoMemory(); return -1; } memcpy(new_string, PyString_AS_STRING(src_object), n_old); memset(new_string + n_old, ' ', n_new - n_old); tmp = PyString_FromStringAndSize(new_string, n_new); free(new_string); Py_DECREF(src_object); src_object = tmp; } } /* * Get either an array object we can copy from, or its parameters * if there isn't a convenient array available. */ if (PyArray_GetArrayParamsFromObject(src_object, PyArray_DESCR(dest), 0, &dtype, &ndim, dims, &src, NULL) < 0) { Py_DECREF(src_object); return -1; } /* If it's not an array, either assign from a sequence or as a scalar */ if (src == NULL) { /* If the input is scalar */ if (ndim == 0) { /* If there's one dest element and src is a Python scalar */ if (PyArray_IsScalar(src_object, Generic)) { char *value; int retcode; value = scalar_value(src_object, dtype); if (value == NULL) { Py_DECREF(dtype); Py_DECREF(src_object); return -1; } /* TODO: switch to SAME_KIND casting */ retcode = PyArray_AssignRawScalar(dest, dtype, value, NULL, NPY_UNSAFE_CASTING); Py_DECREF(dtype); Py_DECREF(src_object); return retcode; } /* Otherwise use the dtype's setitem function */ else { if (PyArray_SIZE(dest) == 1) { Py_DECREF(dtype); Py_DECREF(src_object); ret = PyArray_DESCR(dest)->f->setitem(src_object, PyArray_DATA(dest), dest); return ret; } else { src = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 0, NULL, NULL, NULL, 0, NULL); if (src == NULL) { Py_DECREF(src_object); return -1; } if (PyArray_DESCR(src)->f->setitem(src_object, PyArray_DATA(src), src) < 0) { Py_DECREF(src_object); Py_DECREF(src); return -1; } } } } else { /* * If there are more than enough dims, use AssignFromSequence * because it can handle this style of broadcasting. */ if (ndim >= PyArray_NDIM(dest)) { int res; Py_DECREF(dtype); res = PyArray_AssignFromSequence(dest, src_object); Py_DECREF(src_object); return res; } /* Otherwise convert to an array and do an array-based copy */ src = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, dims, NULL, NULL, PyArray_ISFORTRAN(dest), NULL); if (src == NULL) { Py_DECREF(src_object); return -1; } if (PyArray_AssignFromSequence(src, src_object) < 0) { Py_DECREF(src); Py_DECREF(src_object); return -1; } } } /* If it's an array, do a move (handling possible overlapping data) */ ret = PyArray_MoveInto(dest, src); Py_DECREF(src); Py_DECREF(src_object); return ret; } /* returns an Array-Scalar Object of the type of arr from the given pointer to memory -- main Scalar creation function default new method calls this. */ /* Ideally, here the descriptor would contain all the information needed. So, that we simply need the data and the descriptor, and perhaps a flag */ /* Given a string return the type-number for the data-type with that string as the type-object name. Returns NPY_NOTYPE without setting an error if no type can be found. Only works for user-defined data-types. */ /*NUMPY_API */ NPY_NO_EXPORT int PyArray_TypeNumFromName(char *str) { int i; PyArray_Descr *descr; for (i = 0; i < NPY_NUMUSERTYPES; i++) { descr = userdescrs[i]; if (strcmp(descr->typeobj->tp_name, str) == 0) { return descr->type_num; } } return NPY_NOTYPE; } /*********************** end C-API functions **********************/ /* array object functions */ static void array_dealloc(PyArrayObject *self) { PyArrayObject_fields *fa = (PyArrayObject_fields *)self; _array_dealloc_buffer_info(self); if (fa->weakreflist != NULL) { PyObject_ClearWeakRefs((PyObject *)self); } if (fa->base) { /* * UPDATEIFCOPY means that base points to an * array that should be updated with the contents * of this array upon destruction. * fa->base->flags must have been WRITEABLE * (checked previously) and it was locked here * thus, unlock it. */ if (fa->flags & NPY_ARRAY_UPDATEIFCOPY) { PyArray_ENABLEFLAGS(((PyArrayObject *)fa->base), NPY_ARRAY_WRITEABLE); Py_INCREF(self); /* hold on to self in next call */ if (PyArray_CopyAnyInto((PyArrayObject *)fa->base, self) < 0) { PyErr_Print(); PyErr_Clear(); } /* * Don't need to DECREF -- because we are deleting *self already... */ } /* * In any case base is pointing to something that we need * to DECREF -- either a view or a buffer object */ Py_DECREF(fa->base); } if ((fa->flags & NPY_ARRAY_OWNDATA) && fa->data) { /* Free internal references if an Object array */ if (PyDataType_FLAGCHK(fa->descr, NPY_ITEM_REFCOUNT)) { Py_INCREF(self); /*hold on to self */ PyArray_XDECREF(self); /* * Don't need to DECREF -- because we are deleting * self already... */ } npy_free_cache(fa->data, PyArray_NBYTES(self)); } /* must match allocation in PyArray_NewFromDescr */ npy_free_cache_dim(fa->dimensions, 2 * fa->nd); Py_DECREF(fa->descr); Py_TYPE(self)->tp_free((PyObject *)self); } /* * Extend string. On failure, returns NULL and leaves *strp alone. * XXX we do this in multiple places; time for a string library? */ static char * extend(char **strp, Py_ssize_t n, Py_ssize_t *maxp) { char *str = *strp; Py_ssize_t new_cap; if (n >= *maxp - 16) { new_cap = *maxp * 2; if (new_cap <= *maxp) { /* overflow */ return NULL; } str = PyArray_realloc(*strp, new_cap); if (str != NULL) { *strp = str; *maxp = new_cap; } } return str; } static int dump_data(char **string, Py_ssize_t *n, Py_ssize_t *max_n, char *data, int nd, npy_intp *dimensions, npy_intp *strides, PyArrayObject* self) { PyArray_Descr *descr=PyArray_DESCR(self); PyObject *op = NULL, *sp = NULL; char *ostring; npy_intp i, N, ret = 0; #define CHECK_MEMORY do { \ if (extend(string, *n, max_n) == NULL) { \ ret = -1; \ goto end; \ } \ } while (0) if (nd == 0) { if ((op = descr->f->getitem(data, self)) == NULL) { return -1; } sp = PyObject_Repr(op); if (sp == NULL) { ret = -1; goto end; } ostring = PyString_AsString(sp); N = PyString_Size(sp)*sizeof(char); *n += N; CHECK_MEMORY; memmove(*string + (*n - N), ostring, N); } else { CHECK_MEMORY; (*string)[*n] = '['; *n += 1; for (i = 0; i < dimensions[0]; i++) { if (dump_data(string, n, max_n, data + (*strides)*i, nd - 1, dimensions + 1, strides + 1, self) < 0) { return -1; } CHECK_MEMORY; if (i < dimensions[0] - 1) { (*string)[*n] = ','; (*string)[*n+1] = ' '; *n += 2; } } CHECK_MEMORY; (*string)[*n] = ']'; *n += 1; } #undef CHECK_MEMORY end: Py_XDECREF(op); Py_XDECREF(sp); return ret; } /*NUMPY_API * Prints the raw data of the ndarray in a form useful for debugging * low-level C issues. */ NPY_NO_EXPORT void PyArray_DebugPrint(PyArrayObject *obj) { int i; PyArrayObject_fields *fobj = (PyArrayObject_fields *)obj; printf("-------------------------------------------------------\n"); printf(" Dump of NumPy ndarray at address %p\n", obj); if (obj == NULL) { printf(" It's NULL!\n"); printf("-------------------------------------------------------\n"); fflush(stdout); return; } printf(" ndim : %d\n", fobj->nd); printf(" shape :"); for (i = 0; i < fobj->nd; ++i) { printf(" %d", (int)fobj->dimensions[i]); } printf("\n"); printf(" dtype : "); PyObject_Print((PyObject *)fobj->descr, stdout, 0); printf("\n"); printf(" data : %p\n", fobj->data); printf(" strides:"); for (i = 0; i < fobj->nd; ++i) { printf(" %d", (int)fobj->strides[i]); } printf("\n"); printf(" base : %p\n", fobj->base); printf(" flags :"); if (fobj->flags & NPY_ARRAY_C_CONTIGUOUS) printf(" NPY_C_CONTIGUOUS"); if (fobj->flags & NPY_ARRAY_F_CONTIGUOUS) printf(" NPY_F_CONTIGUOUS"); if (fobj->flags & NPY_ARRAY_OWNDATA) printf(" NPY_OWNDATA"); if (fobj->flags & NPY_ARRAY_ALIGNED) printf(" NPY_ALIGNED"); if (fobj->flags & NPY_ARRAY_WRITEABLE) printf(" NPY_WRITEABLE"); if (fobj->flags & NPY_ARRAY_UPDATEIFCOPY) printf(" NPY_UPDATEIFCOPY"); printf("\n"); if (fobj->base != NULL && PyArray_Check(fobj->base)) { printf("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n"); printf("Dump of array's BASE:\n"); PyArray_DebugPrint((PyArrayObject *)fobj->base); printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); } printf("-------------------------------------------------------\n"); fflush(stdout); } static PyObject * array_repr_builtin(PyArrayObject *self, int repr) { PyObject *ret; char *string; /* max_n initial value is arbitrary, dump_data will extend it */ Py_ssize_t n = 0, max_n = PyArray_NBYTES(self) * 4 + 7; if ((string = PyArray_malloc(max_n)) == NULL) { return PyErr_NoMemory(); } if (dump_data(&string, &n, &max_n, PyArray_DATA(self), PyArray_NDIM(self), PyArray_DIMS(self), PyArray_STRIDES(self), self) < 0) { PyArray_free(string); return NULL; } if (repr) { if (PyArray_ISEXTENDED(self)) { ret = PyUString_FromFormat("array(%s, '%c%d')", string, PyArray_DESCR(self)->type, PyArray_DESCR(self)->elsize); } else { ret = PyUString_FromFormat("array(%s, '%c')", string, PyArray_DESCR(self)->type); } } else { ret = PyUString_FromStringAndSize(string, n); } PyArray_free(string); return ret; } static PyObject *PyArray_StrFunction = NULL; static PyObject *PyArray_ReprFunction = NULL; /*NUMPY_API * Set the array print function to be a Python function. */ NPY_NO_EXPORT void PyArray_SetStringFunction(PyObject *op, int repr) { if (repr) { /* Dispose of previous callback */ Py_XDECREF(PyArray_ReprFunction); /* Add a reference to new callback */ Py_XINCREF(op); /* Remember new callback */ PyArray_ReprFunction = op; } else { /* Dispose of previous callback */ Py_XDECREF(PyArray_StrFunction); /* Add a reference to new callback */ Py_XINCREF(op); /* Remember new callback */ PyArray_StrFunction = op; } } /*NUMPY_API * This function is scheduled to be removed * * TO BE REMOVED - NOT USED INTERNALLY. */ NPY_NO_EXPORT void PyArray_SetDatetimeParseFunction(PyObject *op) { } static PyObject * array_repr(PyArrayObject *self) { PyObject *s, *arglist; if (PyArray_ReprFunction == NULL) { s = array_repr_builtin(self, 1); } else { arglist = Py_BuildValue("(O)", self); s = PyEval_CallObject(PyArray_ReprFunction, arglist); Py_DECREF(arglist); } return s; } static PyObject * array_str(PyArrayObject *self) { PyObject *s, *arglist; if (PyArray_StrFunction == NULL) { s = array_repr_builtin(self, 0); } else { arglist = Py_BuildValue("(O)", self); s = PyEval_CallObject(PyArray_StrFunction, arglist); Py_DECREF(arglist); } return s; } /*NUMPY_API */ NPY_NO_EXPORT int PyArray_CompareUCS4(npy_ucs4 *s1, npy_ucs4 *s2, size_t len) { npy_ucs4 c1, c2; while(len-- > 0) { c1 = *s1++; c2 = *s2++; if (c1 != c2) { return (c1 < c2) ? -1 : 1; } } return 0; } /*NUMPY_API */ NPY_NO_EXPORT int PyArray_CompareString(char *s1, char *s2, size_t len) { const unsigned char *c1 = (unsigned char *)s1; const unsigned char *c2 = (unsigned char *)s2; size_t i; for(i = 0; i < len; ++i) { if (c1[i] != c2[i]) { return (c1[i] > c2[i]) ? 1 : -1; } } return 0; } /* Call this from contexts where an array might be written to, but we have no * way to tell. (E.g., when converting to a read-write buffer.) */ NPY_NO_EXPORT int array_might_be_written(PyArrayObject *obj) { const char *msg = "Numpy has detected that you (may be) writing to an array returned\n" "by numpy.diagonal or by selecting multiple fields in a structured\n" "array. This code will likely break in a future numpy release --\n" "see numpy.diagonal or arrays.indexing reference docs for details.\n" "The quick fix is to make an explicit copy (e.g., do\n" "arr.diagonal().copy() or arr[['f0','f1']].copy())."; if (PyArray_FLAGS(obj) & NPY_ARRAY_WARN_ON_WRITE) { /* 2012-07-17, 1.7 */ if (DEPRECATE_FUTUREWARNING(msg) < 0) { return -1; } /* Only warn once per array */ while (1) { PyArray_CLEARFLAGS(obj, NPY_ARRAY_WARN_ON_WRITE); if (!PyArray_BASE(obj) || !PyArray_Check(PyArray_BASE(obj))) { break; } obj = (PyArrayObject *)PyArray_BASE(obj); } } return 0; } /*NUMPY_API * * This function does nothing if obj is writeable, and raises an exception * (and returns -1) if obj is not writeable. It may also do other * house-keeping, such as issuing warnings on arrays which are transitioning * to become views. Always call this function at some point before writing to * an array. * * 'name' is a name for the array, used to give better error * messages. Something like "assignment destination", "output array", or even * just "array". */ NPY_NO_EXPORT int PyArray_FailUnlessWriteable(PyArrayObject *obj, const char *name) { if (!PyArray_ISWRITEABLE(obj)) { PyErr_Format(PyExc_ValueError, "%s is read-only", name); return -1; } if (array_might_be_written(obj) < 0) { return -1; } return 0; } /* This also handles possibly mis-aligned data */ /* Compare s1 and s2 which are not necessarily NULL-terminated. s1 is of length len1 s2 is of length len2 If they are NULL terminated, then stop comparison. */ static int _myunincmp(npy_ucs4 *s1, npy_ucs4 *s2, int len1, int len2) { npy_ucs4 *sptr; npy_ucs4 *s1t=s1, *s2t=s2; int val; npy_intp size; int diff; if ((npy_intp)s1 % sizeof(npy_ucs4) != 0) { size = len1*sizeof(npy_ucs4); s1t = malloc(size); memcpy(s1t, s1, size); } if ((npy_intp)s2 % sizeof(npy_ucs4) != 0) { size = len2*sizeof(npy_ucs4); s2t = malloc(size); memcpy(s2t, s2, size); } val = PyArray_CompareUCS4(s1t, s2t, PyArray_MIN(len1,len2)); if ((val != 0) || (len1 == len2)) { goto finish; } if (len2 > len1) { sptr = s2t+len1; val = -1; diff = len2-len1; } else { sptr = s1t+len2; val = 1; diff=len1-len2; } while (diff--) { if (*sptr != 0) { goto finish; } sptr++; } val = 0; finish: if (s1t != s1) { free(s1t); } if (s2t != s2) { free(s2t); } return val; } /* * Compare s1 and s2 which are not necessarily NULL-terminated. * s1 is of length len1 * s2 is of length len2 * If they are NULL terminated, then stop comparison. */ static int _mystrncmp(char *s1, char *s2, int len1, int len2) { char *sptr; int val; int diff; val = memcmp(s1, s2, PyArray_MIN(len1, len2)); if ((val != 0) || (len1 == len2)) { return val; } if (len2 > len1) { sptr = s2 + len1; val = -1; diff = len2 - len1; } else { sptr = s1 + len2; val = 1; diff = len1 - len2; } while (diff--) { if (*sptr != 0) { return val; } sptr++; } return 0; /* Only happens if NULLs are everywhere */ } /* Borrowed from Numarray */ #define SMALL_STRING 2048 #if defined(isspace) #undef isspace #define isspace(c) ((c==' ')||(c=='\t')||(c=='\n')||(c=='\r')||(c=='\v')||(c=='\f')) #endif static void _rstripw(char *s, int n) { int i; for (i = n - 1; i >= 1; i--) { /* Never strip to length 0. */ int c = s[i]; if (!c || isspace(c)) { s[i] = 0; } else { break; } } } static void _unistripw(npy_ucs4 *s, int n) { int i; for (i = n - 1; i >= 1; i--) { /* Never strip to length 0. */ npy_ucs4 c = s[i]; if (!c || isspace(c)) { s[i] = 0; } else { break; } } } static char * _char_copy_n_strip(char *original, char *temp, int nc) { if (nc > SMALL_STRING) { temp = malloc(nc); if (!temp) { PyErr_NoMemory(); return NULL; } } memcpy(temp, original, nc); _rstripw(temp, nc); return temp; } static void _char_release(char *ptr, int nc) { if (nc > SMALL_STRING) { free(ptr); } } static char * _uni_copy_n_strip(char *original, char *temp, int nc) { if (nc*sizeof(npy_ucs4) > SMALL_STRING) { temp = malloc(nc*sizeof(npy_ucs4)); if (!temp) { PyErr_NoMemory(); return NULL; } } memcpy(temp, original, nc*sizeof(npy_ucs4)); _unistripw((npy_ucs4 *)temp, nc); return temp; } static void _uni_release(char *ptr, int nc) { if (nc*sizeof(npy_ucs4) > SMALL_STRING) { free(ptr); } } /* End borrowed from numarray */ #define _rstrip_loop(CMP) { \ void *aptr, *bptr; \ char atemp[SMALL_STRING], btemp[SMALL_STRING]; \ while(size--) { \ aptr = stripfunc(iself->dataptr, atemp, N1); \ if (!aptr) return -1; \ bptr = stripfunc(iother->dataptr, btemp, N2); \ if (!bptr) { \ relfunc(aptr, N1); \ return -1; \ } \ val = compfunc(aptr, bptr, N1, N2); \ *dptr = (val CMP 0); \ PyArray_ITER_NEXT(iself); \ PyArray_ITER_NEXT(iother); \ dptr += 1; \ relfunc(aptr, N1); \ relfunc(bptr, N2); \ } \ } #define _reg_loop(CMP) { \ while(size--) { \ val = compfunc((void *)iself->dataptr, \ (void *)iother->dataptr, \ N1, N2); \ *dptr = (val CMP 0); \ PyArray_ITER_NEXT(iself); \ PyArray_ITER_NEXT(iother); \ dptr += 1; \ } \ } static int _compare_strings(PyArrayObject *result, PyArrayMultiIterObject *multi, int cmp_op, void *func, int rstrip) { PyArrayIterObject *iself, *iother; npy_bool *dptr; npy_intp size; int val; int N1, N2; int (*compfunc)(void *, void *, int, int); void (*relfunc)(char *, int); char* (*stripfunc)(char *, char *, int); compfunc = func; dptr = (npy_bool *)PyArray_DATA(result); iself = multi->iters[0]; iother = multi->iters[1]; size = multi->size; N1 = PyArray_DESCR(iself->ao)->elsize; N2 = PyArray_DESCR(iother->ao)->elsize; if ((void *)compfunc == (void *)_myunincmp) { N1 >>= 2; N2 >>= 2; stripfunc = _uni_copy_n_strip; relfunc = _uni_release; } else { stripfunc = _char_copy_n_strip; relfunc = _char_release; } switch (cmp_op) { case Py_EQ: if (rstrip) { _rstrip_loop(==); } else { _reg_loop(==); } break; case Py_NE: if (rstrip) { _rstrip_loop(!=); } else { _reg_loop(!=); } break; case Py_LT: if (rstrip) { _rstrip_loop(<); } else { _reg_loop(<); } break; case Py_LE: if (rstrip) { _rstrip_loop(<=); } else { _reg_loop(<=); } break; case Py_GT: if (rstrip) { _rstrip_loop(>); } else { _reg_loop(>); } break; case Py_GE: if (rstrip) { _rstrip_loop(>=); } else { _reg_loop(>=); } break; default: PyErr_SetString(PyExc_RuntimeError, "bad comparison operator"); return -1; } return 0; } #undef _reg_loop #undef _rstrip_loop #undef SMALL_STRING NPY_NO_EXPORT PyObject * _strings_richcompare(PyArrayObject *self, PyArrayObject *other, int cmp_op, int rstrip) { PyArrayObject *result; PyArrayMultiIterObject *mit; int val; /* Cast arrays to a common type */ if (PyArray_TYPE(self) != PyArray_DESCR(other)->type_num) { #if defined(NPY_PY3K) /* * Comparison between Bytes and Unicode is not defined in Py3K; * we follow. */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; #else PyObject *new; if (PyArray_TYPE(self) == NPY_STRING && PyArray_DESCR(other)->type_num == NPY_UNICODE) { PyArray_Descr* unicode = PyArray_DescrNew(PyArray_DESCR(other)); unicode->elsize = PyArray_DESCR(self)->elsize << 2; new = PyArray_FromAny((PyObject *)self, unicode, 0, 0, 0, NULL); if (new == NULL) { return NULL; } Py_INCREF(other); self = (PyArrayObject *)new; } else if (PyArray_TYPE(self) == NPY_UNICODE && PyArray_DESCR(other)->type_num == NPY_STRING) { PyArray_Descr* unicode = PyArray_DescrNew(PyArray_DESCR(self)); unicode->elsize = PyArray_DESCR(other)->elsize << 2; new = PyArray_FromAny((PyObject *)other, unicode, 0, 0, 0, NULL); if (new == NULL) { return NULL; } Py_INCREF(self); other = (PyArrayObject *)new; } else { PyErr_SetString(PyExc_TypeError, "invalid string data-types " "in comparison"); return NULL; } #endif } else { Py_INCREF(self); Py_INCREF(other); } /* Broad-cast the arrays to a common shape */ mit = (PyArrayMultiIterObject *)PyArray_MultiIterNew(2, self, other); Py_DECREF(self); Py_DECREF(other); if (mit == NULL) { return NULL; } result = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, PyArray_DescrFromType(NPY_BOOL), mit->nd, mit->dimensions, NULL, NULL, 0, NULL); if (result == NULL) { goto finish; } if (PyArray_TYPE(self) == NPY_UNICODE) { val = _compare_strings(result, mit, cmp_op, _myunincmp, rstrip); } else { val = _compare_strings(result, mit, cmp_op, _mystrncmp, rstrip); } if (val < 0) { Py_DECREF(result); result = NULL; } finish: Py_DECREF(mit); return (PyObject *)result; } /* * VOID-type arrays can only be compared equal and not-equal * in which case the fields are all compared by extracting the fields * and testing one at a time... * equality testing is performed using logical_ands on all the fields. * in-equality testing is performed using logical_ors on all the fields. * * VOID-type arrays without fields are compared for equality by comparing their * memory at each location directly (using string-code). */ static PyObject * _void_compare(PyArrayObject *self, PyArrayObject *other, int cmp_op) { if (!(cmp_op == Py_EQ || cmp_op == Py_NE)) { PyErr_SetString(PyExc_ValueError, "Void-arrays can only be compared for equality."); return NULL; } if (PyArray_HASFIELDS(self)) { PyObject *res = NULL, *temp, *a, *b; PyObject *key, *value, *temp2; PyObject *op; Py_ssize_t pos = 0; npy_intp result_ndim = PyArray_NDIM(self) > PyArray_NDIM(other) ? PyArray_NDIM(self) : PyArray_NDIM(other); op = (cmp_op == Py_EQ ? n_ops.logical_and : n_ops.logical_or); while (PyDict_Next(PyArray_DESCR(self)->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } a = array_subscript_asarray(self, key); if (a == NULL) { Py_XDECREF(res); return NULL; } b = array_subscript_asarray(other, key); if (b == NULL) { Py_XDECREF(res); Py_DECREF(a); return NULL; } temp = array_richcompare((PyArrayObject *)a,b,cmp_op); Py_DECREF(a); Py_DECREF(b); if (temp == NULL) { Py_XDECREF(res); return NULL; } /* * If the field type has a non-trivial shape, additional * dimensions will have been appended to `a` and `b`. * In that case, reduce them using `op`. */ if (PyArray_Check(temp) && PyArray_NDIM((PyArrayObject *)temp) > result_ndim) { /* If the type was multidimensional, collapse that part to 1-D */ if (PyArray_NDIM((PyArrayObject *)temp) != result_ndim+1) { npy_intp dimensions[NPY_MAXDIMS]; PyArray_Dims newdims; newdims.ptr = dimensions; newdims.len = result_ndim+1; memcpy(dimensions, PyArray_DIMS((PyArrayObject *)temp), sizeof(npy_intp)*result_ndim); dimensions[result_ndim] = -1; temp2 = PyArray_Newshape((PyArrayObject *)temp, &newdims, NPY_ANYORDER); if (temp2 == NULL) { Py_DECREF(temp); Py_XDECREF(res); return NULL; } Py_DECREF(temp); temp = temp2; } /* Reduce the extra dimension of `temp` using `op` */ temp2 = PyArray_GenericReduceFunction((PyArrayObject *)temp, op, result_ndim, NPY_BOOL, NULL); if (temp2 == NULL) { Py_DECREF(temp); Py_XDECREF(res); return NULL; } Py_DECREF(temp); temp = temp2; } if (res == NULL) { res = temp; } else { temp2 = PyObject_CallFunction(op, "OO", res, temp); Py_DECREF(temp); Py_DECREF(res); if (temp2 == NULL) { return NULL; } res = temp2; } } if (res == NULL && !PyErr_Occurred()) { PyErr_SetString(PyExc_ValueError, "No fields found."); } return res; } else { /* * compare as a string. Assumes self and * other have same descr->type */ return _strings_richcompare(self, other, cmp_op, 0); } } NPY_NO_EXPORT PyObject * array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) { PyArrayObject *array_other; PyObject *obj_self = (PyObject *)self; PyObject *result = NULL; /* Special case for string arrays (which don't and currently can't have * ufunc loops defined, so there's no point in trying). */ if (PyArray_ISSTRING(self)) { array_other = (PyArrayObject *)PyArray_FromObject(other, NPY_NOTYPE, 0, 0); if (array_other == NULL) { PyErr_Clear(); /* Never mind, carry on, see what happens */ } else if (!PyArray_ISSTRING(array_other)) { Py_DECREF(array_other); /* Never mind, carry on, see what happens */ } else { result = _strings_richcompare(self, array_other, cmp_op, 0); Py_DECREF(array_other); return result; } /* If we reach this point, it means that we are not comparing * string-to-string. It's possible that this will still work out, * e.g. if the other array is an object array, then both will be cast * to object or something? I don't know how that works actually, but * it does, b/c this works: * l = ["a", "b"] * assert np.array(l, dtype="S1") == np.array(l, dtype="O") * So we fall through and see what happens. */ } switch (cmp_op) { case Py_LT: if (needs_right_binop_forward(obj_self, other, "__gt__", 0) && Py_TYPE(obj_self)->tp_richcompare != Py_TYPE(other)->tp_richcompare) { /* See discussion in number.c */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } result = PyArray_GenericBinaryFunction(self, other, n_ops.less); break; case Py_LE: if (needs_right_binop_forward(obj_self, other, "__ge__", 0) && Py_TYPE(obj_self)->tp_richcompare != Py_TYPE(other)->tp_richcompare) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } result = PyArray_GenericBinaryFunction(self, other, n_ops.less_equal); break; case Py_EQ: if (other == Py_None) { /* 2013-07-25, 1.7 */ if (DEPRECATE_FUTUREWARNING("comparison to `None` will result in " "an elementwise object comparison in the future.") < 0) { return NULL; } Py_INCREF(Py_False); return Py_False; } /* * The ufunc does not support void/structured types, so these * need to be handled specifically. Only a few cases are supported. */ if (PyArray_TYPE(self) == NPY_VOID) { int _res; array_other = (PyArrayObject *)PyArray_FromAny(other, NULL, 0, 0, 0, NULL); /* * If not successful, indicate that the items cannot be compared * this way. */ if (array_other == NULL) { /* 2015-05-07, 1.10 */ PyErr_Clear(); if (DEPRECATE( "elementwise == comparison failed and returning scalar " "instead; this will raise an error in the future.") < 0) { return NULL; } Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } _res = PyArray_CanCastTypeTo(PyArray_DESCR(self), PyArray_DESCR(array_other), NPY_EQUIV_CASTING); if (_res == 0) { /* 2015-05-07, 1.10 */ Py_DECREF(array_other); if (DEPRECATE_FUTUREWARNING( "elementwise == comparison failed and returning scalar " "instead; this will raise an error or perform " "elementwise comparison in the future.") < 0) { return NULL; } Py_INCREF(Py_False); return Py_False; } else { result = _void_compare(self, array_other, cmp_op); } Py_DECREF(array_other); return result; } if (needs_right_binop_forward(obj_self, other, "__eq__", 0) && Py_TYPE(obj_self)->tp_richcompare != Py_TYPE(other)->tp_richcompare) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } result = PyArray_GenericBinaryFunction(self, (PyObject *)other, n_ops.equal); /* * If the comparison results in NULL, then the * two array objects can not be compared together; * indicate that */ if (result == NULL) { /* * Comparisons should raise errors when element-wise comparison * is not possible. */ /* 2015-05-14, 1.10 */ PyErr_Clear(); if (DEPRECATE("elementwise == comparison failed; " "this will raise an error in the future.") < 0) { return NULL; } Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } break; case Py_NE: if (other == Py_None) { /* 2013-07-25, 1.8 */ if (DEPRECATE_FUTUREWARNING("comparison to `None` will result in " "an elementwise object comparison in the future.") < 0) { return NULL; } Py_INCREF(Py_True); return Py_True; } /* * The ufunc does not support void/structured types, so these * need to be handled specifically. Only a few cases are supported. */ if (PyArray_TYPE(self) == NPY_VOID) { int _res; array_other = (PyArrayObject *)PyArray_FromAny(other, NULL, 0, 0, 0, NULL); /* * If not successful, indicate that the items cannot be compared * this way. */ if (array_other == NULL) { /* 2015-05-07, 1.10 */ PyErr_Clear(); if (DEPRECATE( "elementwise != comparison failed and returning scalar " "instead; this will raise an error in the future.") < 0) { return NULL; } Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } _res = PyArray_CanCastTypeTo(PyArray_DESCR(self), PyArray_DESCR(array_other), NPY_EQUIV_CASTING); if (_res == 0) { /* 2015-05-07, 1.10 */ Py_DECREF(array_other); if (DEPRECATE_FUTUREWARNING( "elementwise != comparison failed and returning scalar " "instead; this will raise an error or perform " "elementwise comparison in the future.") < 0) { return NULL; } Py_INCREF(Py_True); return Py_True; } else { result = _void_compare(self, array_other, cmp_op); Py_DECREF(array_other); } return result; } if (needs_right_binop_forward(obj_self, other, "__ne__", 0) && Py_TYPE(obj_self)->tp_richcompare != Py_TYPE(other)->tp_richcompare) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } result = PyArray_GenericBinaryFunction(self, (PyObject *)other, n_ops.not_equal); if (result == NULL) { /* * Comparisons should raise errors when element-wise comparison * is not possible. */ /* 2015-05-14, 1.10 */ PyErr_Clear(); if (DEPRECATE("elementwise != comparison failed; " "this will raise an error in the future.") < 0) { return NULL; } Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } break; case Py_GT: if (needs_right_binop_forward(obj_self, other, "__lt__", 0) && Py_TYPE(obj_self)->tp_richcompare != Py_TYPE(other)->tp_richcompare) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } result = PyArray_GenericBinaryFunction(self, other, n_ops.greater); break; case Py_GE: if (needs_right_binop_forward(obj_self, other, "__le__", 0) && Py_TYPE(obj_self)->tp_richcompare != Py_TYPE(other)->tp_richcompare) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } result = PyArray_GenericBinaryFunction(self, other, n_ops.greater_equal); break; default: result = Py_NotImplemented; Py_INCREF(result); } return result; } /*NUMPY_API */ NPY_NO_EXPORT int PyArray_ElementStrides(PyObject *obj) { PyArrayObject *arr; int itemsize; int i, ndim; npy_intp *strides; if (!PyArray_Check(obj)) { return 0; } arr = (PyArrayObject *)obj; itemsize = PyArray_ITEMSIZE(arr); ndim = PyArray_NDIM(arr); strides = PyArray_STRIDES(arr); for (i = 0; i < ndim; i++) { if ((strides[i] % itemsize) != 0) { return 0; } } return 1; } /* * This routine checks to see if newstrides (of length nd) will not * ever be able to walk outside of the memory implied numbytes and offset. * * The available memory is assumed to start at -offset and proceed * to numbytes-offset. The strides are checked to ensure * that accessing memory using striding will not try to reach beyond * this memory for any of the axes. * * If numbytes is 0 it will be calculated using the dimensions and * element-size. * * This function checks for walking beyond the beginning and right-end * of the buffer and therefore works for any integer stride (positive * or negative). */ /*NUMPY_API*/ NPY_NO_EXPORT npy_bool PyArray_CheckStrides(int elsize, int nd, npy_intp numbytes, npy_intp offset, npy_intp *dims, npy_intp *newstrides) { npy_intp begin, end; npy_intp lower_offset; npy_intp upper_offset; if (numbytes == 0) { numbytes = PyArray_MultiplyList(dims, nd) * elsize; } begin = -offset; end = numbytes - offset; offset_bounds_from_strides(elsize, nd, dims, newstrides, &lower_offset, &upper_offset); if ((upper_offset > end) || (lower_offset < begin)) { return NPY_FALSE; } return NPY_TRUE; } static PyObject * array_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"shape", "dtype", "buffer", "offset", "strides", "order", NULL}; PyArray_Descr *descr = NULL; int itemsize; PyArray_Dims dims = {NULL, 0}; PyArray_Dims strides = {NULL, 0}; PyArray_Chunk buffer; npy_longlong offset = 0; NPY_ORDER order = NPY_CORDER; int is_f_order = 0; PyArrayObject *ret; buffer.ptr = NULL; /* * Usually called with shape and type but can also be called with buffer, * strides, and swapped info For now, let's just use this to create an * empty, contiguous array of a specific type and shape. */ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&LO&O&", kwlist, PyArray_IntpConverter, &dims, PyArray_DescrConverter, &descr, PyArray_BufferConverter, &buffer, &offset, &PyArray_IntpConverter, &strides, &PyArray_OrderConverter, &order)) { goto fail; } if (order == NPY_FORTRANORDER) { is_f_order = 1; } if (descr == NULL) { descr = PyArray_DescrFromType(NPY_DEFAULT_TYPE); } itemsize = descr->elsize; if (itemsize == 0) { PyErr_SetString(PyExc_ValueError, "data-type with unspecified variable length"); goto fail; } if (strides.ptr != NULL) { npy_intp nb, off; if (strides.len != dims.len) { PyErr_SetString(PyExc_ValueError, "strides, if given, must be " \ "the same length as shape"); goto fail; } if (buffer.ptr == NULL) { nb = 0; off = 0; } else { nb = buffer.len; off = (npy_intp) offset; } if (!PyArray_CheckStrides(itemsize, dims.len, nb, off, dims.ptr, strides.ptr)) { PyErr_SetString(PyExc_ValueError, "strides is incompatible " \ "with shape of requested " \ "array and size of buffer"); goto fail; } } if (buffer.ptr == NULL) { ret = (PyArrayObject *) PyArray_NewFromDescr(subtype, descr, (int)dims.len, dims.ptr, strides.ptr, NULL, is_f_order, NULL); if (ret == NULL) { descr = NULL; goto fail; } if (PyDataType_FLAGCHK(descr, NPY_ITEM_HASOBJECT)) { /* place Py_None in object positions */ PyArray_FillObjectArray(ret, Py_None); if (PyErr_Occurred()) { descr = NULL; goto fail; } } } else { /* buffer given -- use it */ if (dims.len == 1 && dims.ptr[0] == -1) { dims.ptr[0] = (buffer.len-(npy_intp)offset) / itemsize; } else if ((strides.ptr == NULL) && (buffer.len < (offset + (((npy_intp)itemsize)* PyArray_MultiplyList(dims.ptr, dims.len))))) { PyErr_SetString(PyExc_TypeError, "buffer is too small for " \ "requested array"); goto fail; } /* get writeable and aligned */ if (is_f_order) { buffer.flags |= NPY_ARRAY_F_CONTIGUOUS; } ret = (PyArrayObject *)\ PyArray_NewFromDescr(subtype, descr, dims.len, dims.ptr, strides.ptr, offset + (char *)buffer.ptr, buffer.flags, NULL); if (ret == NULL) { descr = NULL; goto fail; } PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL); Py_INCREF(buffer.base); if (PyArray_SetBaseObject(ret, buffer.base) < 0) { Py_DECREF(ret); ret = NULL; goto fail; } } PyDimMem_FREE(dims.ptr); PyDimMem_FREE(strides.ptr); return (PyObject *)ret; fail: Py_XDECREF(descr); PyDimMem_FREE(dims.ptr); PyDimMem_FREE(strides.ptr); return NULL; } static PyObject * array_iter(PyArrayObject *arr) { if (PyArray_NDIM(arr) == 0) { PyErr_SetString(PyExc_TypeError, "iteration over a 0-d array"); return NULL; } return PySeqIter_New((PyObject *)arr); } static PyObject * array_alloc(PyTypeObject *type, Py_ssize_t NPY_UNUSED(nitems)) { /* nitems will always be 0 */ PyObject *obj = PyObject_Malloc(type->tp_basicsize); PyObject_Init(obj, type); return obj; } static void array_free(PyObject * v) { /* avoid same deallocator as PyBaseObject, see gentype_free */ PyObject_Free(v); } NPY_NO_EXPORT PyTypeObject PyArray_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.ndarray", /* tp_name */ NPY_SIZEOF_PYARRAYOBJECT, /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)array_dealloc, /* tp_dealloc */ (printfunc)NULL, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif (reprfunc)array_repr, /* tp_repr */ &array_as_number, /* tp_as_number */ &array_as_sequence, /* tp_as_sequence */ &array_as_mapping, /* tp_as_mapping */ /* * The tp_hash slot will be set PyObject_HashNotImplemented when the * module is loaded. */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)array_str, /* tp_str */ (getattrofunc)0, /* tp_getattro */ (setattrofunc)0, /* tp_setattro */ &array_as_buffer, /* tp_as_buffer */ (Py_TPFLAGS_DEFAULT #if !defined(NPY_PY3K) | Py_TPFLAGS_CHECKTYPES | Py_TPFLAGS_HAVE_NEWBUFFER #endif | Py_TPFLAGS_BASETYPE), /* tp_flags */ 0, /* tp_doc */ (traverseproc)0, /* tp_traverse */ (inquiry)0, /* tp_clear */ (richcmpfunc)array_richcompare, /* tp_richcompare */ offsetof(PyArrayObject_fields, weakreflist), /* tp_weaklistoffset */ (getiterfunc)array_iter, /* tp_iter */ (iternextfunc)0, /* tp_iternext */ array_methods, /* tp_methods */ 0, /* tp_members */ array_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)0, /* tp_init */ (allocfunc)array_alloc, /* tp_alloc */ (newfunc)array_new, /* tp_new */ (freefunc)array_free, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ };
bsd-3-clause
yury-s/v8-inspector
Source/wtf/DataLog.cpp
42
3293
/* * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "DataLog.h" #if OS(POSIX) #include <pthread.h> #include <unistd.h> #endif #define DATA_LOG_TO_FILE 0 // Uncomment to force logging to the given file regardless of what the environment variable says. Note that // we will append ".<pid>.txt" where <pid> is the PID. // This path won't work on Windows, make sure to change to something like C:\\Users\\<more path>\\log.txt. #define DATA_LOG_FILENAME "/tmp/WTFLog" namespace WTF { #if USE(PTHREADS) static pthread_once_t initializeLogFileOnceKey = PTHREAD_ONCE_INIT; #endif static FilePrintStream* file; static void initializeLogFileOnce() { #if DATA_LOG_TO_FILE #ifdef DATA_LOG_FILENAME const char* filename = DATA_LOG_FILENAME; #else const char* filename = getenv("WTF_DATA_LOG_FILENAME"); #endif char actualFilename[1024]; snprintf(actualFilename, sizeof(actualFilename), "%s.%d.txt", filename, getpid()); if (filename) { file = FilePrintStream::open(actualFilename, "w").leakPtr(); if (!file) fprintf(stderr, "Warning: Could not open log file %s for writing.\n", actualFilename); } #endif // DATA_LOG_TO_FILE if (!file) file = new FilePrintStream(stderr, FilePrintStream::Borrow); setvbuf(file->file(), 0, _IONBF, 0); // Prefer unbuffered output, so that we get a full log upon crash or deadlock. } static void initializeLogFile() { #if USE(PTHREADS) pthread_once(&initializeLogFileOnceKey, initializeLogFileOnce); #else if (!file) initializeLogFileOnce(); #endif } FilePrintStream& dataFile() { initializeLogFile(); return *file; } void dataLogFV(const char* format, va_list argList) { dataFile().vprintf(format, argList); } void dataLogF(const char* format, ...) { va_list argList; va_start(argList, format); dataLogFV(format, argList); va_end(argList); } void dataLogFString(const char* str) { dataFile().printf("%s", str); } } // namespace WTF
bsd-3-clause
jeanleflambeur/silkopter
bullet/LinearMath/btQuickprof.cpp
53
22797
/* *************************************************************************************************** ** ** profile.cpp ** ** Real-Time Hierarchical Profiling for Game Programming Gems 3 ** ** by Greg Hjelstrom & Byon Garrabrant ** ***************************************************************************************************/ // Credits: The Clock class was inspired by the Timer classes in // Ogre (www.ogre3d.org). #include "btQuickprof.h" #include "btThreads.h" #ifdef __CELLOS_LV2__ #include <sys/sys_time.h> #include <sys/time_util.h> #include <stdio.h> #endif #if defined (SUNOS) || defined (__SUNOS__) #include <stdio.h> #endif #ifdef __APPLE__ #include <mach/mach_time.h> #include <TargetConditionals.h> #endif #if defined(WIN32) || defined(_WIN32) #define BT_USE_WINDOWS_TIMERS #define WIN32_LEAN_AND_MEAN #define NOWINRES #define NOMCX #define NOIME #ifdef _XBOX #include <Xtl.h> #else //_XBOX #include <windows.h> #if WINVER <0x0602 #define GetTickCount64 GetTickCount #endif #endif //_XBOX #include <time.h> #else //_WIN32 #include <sys/time.h> #ifdef BT_LINUX_REALTIME //required linking against rt (librt) #include <time.h> #endif //BT_LINUX_REALTIME #endif //_WIN32 #define mymin(a,b) (a > b ? a : b) struct btClockData { #ifdef BT_USE_WINDOWS_TIMERS LARGE_INTEGER mClockFrequency; LONGLONG mStartTick; LARGE_INTEGER mStartTime; #else #ifdef __CELLOS_LV2__ uint64_t mStartTime; #else #ifdef __APPLE__ uint64_t mStartTimeNano; #endif struct timeval mStartTime; #endif #endif //__CELLOS_LV2__ }; ///The btClock is a portable basic clock that measures accurate time in seconds, use for profiling. btClock::btClock() { m_data = new btClockData; #ifdef BT_USE_WINDOWS_TIMERS QueryPerformanceFrequency(&m_data->mClockFrequency); #endif reset(); } btClock::~btClock() { delete m_data; } btClock::btClock(const btClock& other) { m_data = new btClockData; *m_data = *other.m_data; } btClock& btClock::operator=(const btClock& other) { *m_data = *other.m_data; return *this; } /// Resets the initial reference time. void btClock::reset() { #ifdef BT_USE_WINDOWS_TIMERS QueryPerformanceCounter(&m_data->mStartTime); m_data->mStartTick = GetTickCount64(); #else #ifdef __CELLOS_LV2__ typedef uint64_t ClockSize; ClockSize newTime; //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory"); SYS_TIMEBASE_GET( newTime ); m_data->mStartTime = newTime; #else #ifdef __APPLE__ m_data->mStartTimeNano = mach_absolute_time(); #endif gettimeofday(&m_data->mStartTime, 0); #endif #endif } /// Returns the time in ms since the last call to reset or since /// the btClock was created. unsigned long long int btClock::getTimeMilliseconds() { #ifdef BT_USE_WINDOWS_TIMERS LARGE_INTEGER currentTime; QueryPerformanceCounter(&currentTime); LONGLONG elapsedTime = currentTime.QuadPart - m_data->mStartTime.QuadPart; // Compute the number of millisecond ticks elapsed. unsigned long msecTicks = (unsigned long)(1000 * elapsedTime / m_data->mClockFrequency.QuadPart); return msecTicks; #else #ifdef __CELLOS_LV2__ uint64_t freq=sys_time_get_timebase_frequency(); double dFreq=((double) freq) / 1000.0; typedef uint64_t ClockSize; ClockSize newTime; SYS_TIMEBASE_GET( newTime ); //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory"); return (unsigned long int)((double(newTime-m_data->mStartTime)) / dFreq); #else struct timeval currentTime; gettimeofday(&currentTime, 0); return (currentTime.tv_sec - m_data->mStartTime.tv_sec) * 1000 + (currentTime.tv_usec - m_data->mStartTime.tv_usec) / 1000; #endif //__CELLOS_LV2__ #endif } /// Returns the time in us since the last call to reset or since /// the Clock was created. unsigned long long int btClock::getTimeMicroseconds() { #ifdef BT_USE_WINDOWS_TIMERS //see https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx LARGE_INTEGER currentTime, elapsedTime; QueryPerformanceCounter(&currentTime); elapsedTime.QuadPart = currentTime.QuadPart - m_data->mStartTime.QuadPart; elapsedTime.QuadPart *= 1000000; elapsedTime.QuadPart /= m_data->mClockFrequency.QuadPart; return (unsigned long long) elapsedTime.QuadPart; #else #ifdef __CELLOS_LV2__ uint64_t freq=sys_time_get_timebase_frequency(); double dFreq=((double) freq)/ 1000000.0; typedef uint64_t ClockSize; ClockSize newTime; //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory"); SYS_TIMEBASE_GET( newTime ); return (unsigned long int)((double(newTime-m_data->mStartTime)) / dFreq); #else struct timeval currentTime; gettimeofday(&currentTime, 0); return (currentTime.tv_sec - m_data->mStartTime.tv_sec) * 1000000 + (currentTime.tv_usec - m_data->mStartTime.tv_usec); #endif//__CELLOS_LV2__ #endif } unsigned long long int btClock::getTimeNanoseconds() { #ifdef BT_USE_WINDOWS_TIMERS //see https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx LARGE_INTEGER currentTime, elapsedTime; QueryPerformanceCounter(&currentTime); elapsedTime.QuadPart = currentTime.QuadPart - m_data->mStartTime.QuadPart; elapsedTime.QuadPart *= 1000000000; elapsedTime.QuadPart /= m_data->mClockFrequency.QuadPart; return (unsigned long long) elapsedTime.QuadPart; #else #ifdef __CELLOS_LV2__ uint64_t freq=sys_time_get_timebase_frequency(); double dFreq=((double) freq)/ 1e9; typedef uint64_t ClockSize; ClockSize newTime; //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory"); SYS_TIMEBASE_GET( newTime ); return (unsigned long int)((double(newTime-m_data->mStartTime)) / dFreq); #else #ifdef __APPLE__ uint64_t ticks = mach_absolute_time() - m_data->mStartTimeNano; static long double conversion = 0.0L; if( 0.0L == conversion ) { // attempt to get conversion to nanoseconds mach_timebase_info_data_t info; int err = mach_timebase_info( &info ); if( err ) { btAssert(0); conversion = 1.; } conversion = info.numer / info.denom; } return (ticks * conversion); #else//__APPLE__ #ifdef BT_LINUX_REALTIME timespec ts; clock_gettime(CLOCK_REALTIME,&ts); return 1000000000*ts.tv_sec + ts.tv_nsec; #else struct timeval currentTime; gettimeofday(&currentTime, 0); return (currentTime.tv_sec - m_data->mStartTime.tv_sec) * 1e9 + (currentTime.tv_usec - m_data->mStartTime.tv_usec)*1000; #endif //BT_LINUX_REALTIME #endif//__APPLE__ #endif//__CELLOS_LV2__ #endif } /// Returns the time in s since the last call to reset or since /// the Clock was created. btScalar btClock::getTimeSeconds() { static const btScalar microseconds_to_seconds = btScalar(0.000001); return btScalar(getTimeMicroseconds()) * microseconds_to_seconds; } #ifndef BT_NO_PROFILE static btClock gProfileClock; inline void Profile_Get_Ticks(unsigned long int * ticks) { *ticks = (unsigned long int)gProfileClock.getTimeMicroseconds(); } inline float Profile_Get_Tick_Rate(void) { // return 1000000.f; return 1000.f; } /*************************************************************************************************** ** ** CProfileNode ** ***************************************************************************************************/ /*********************************************************************************************** * INPUT: * * name - pointer to a static string which is the name of this profile node * * parent - parent pointer * * * * WARNINGS: * * The name is assumed to be a static pointer, only the pointer is stored and compared for * * efficiency reasons. * *=============================================================================================*/ CProfileNode::CProfileNode( const char * name, CProfileNode * parent ) : Name( name ), TotalCalls( 0 ), TotalTime( 0 ), StartTime( 0 ), RecursionCounter( 0 ), Parent( parent ), Child( NULL ), Sibling( NULL ), m_userPtr(0) { Reset(); } void CProfileNode::CleanupMemory() { delete ( Child); Child = NULL; delete ( Sibling); Sibling = NULL; } CProfileNode::~CProfileNode( void ) { CleanupMemory(); } /*********************************************************************************************** * INPUT: * * name - static string pointer to the name of the node we are searching for * * * * WARNINGS: * * All profile names are assumed to be static strings so this function uses pointer compares * * to find the named node. * *=============================================================================================*/ CProfileNode * CProfileNode::Get_Sub_Node( const char * name ) { // Try to find this sub node CProfileNode * child = Child; while ( child ) { if ( child->Name == name ) { return child; } child = child->Sibling; } // We didn't find it, so add it CProfileNode * node = new CProfileNode( name, this ); node->Sibling = Child; Child = node; return node; } void CProfileNode::Reset( void ) { TotalCalls = 0; TotalTime = 0.0f; if ( Child ) { Child->Reset(); } if ( Sibling ) { Sibling->Reset(); } } void CProfileNode::Call( void ) { TotalCalls++; if (RecursionCounter++ == 0) { Profile_Get_Ticks(&StartTime); } } bool CProfileNode::Return( void ) { if ( --RecursionCounter == 0 && TotalCalls != 0 ) { unsigned long int time; Profile_Get_Ticks(&time); time-=StartTime; TotalTime += (float)time / Profile_Get_Tick_Rate(); } return ( RecursionCounter == 0 ); } /*************************************************************************************************** ** ** CProfileIterator ** ***************************************************************************************************/ CProfileIterator::CProfileIterator( CProfileNode * start ) { CurrentParent = start; CurrentChild = CurrentParent->Get_Child(); } void CProfileIterator::First(void) { CurrentChild = CurrentParent->Get_Child(); } void CProfileIterator::Next(void) { CurrentChild = CurrentChild->Get_Sibling(); } bool CProfileIterator::Is_Done(void) { return CurrentChild == NULL; } void CProfileIterator::Enter_Child( int index ) { CurrentChild = CurrentParent->Get_Child(); while ( (CurrentChild != NULL) && (index != 0) ) { index--; CurrentChild = CurrentChild->Get_Sibling(); } if ( CurrentChild != NULL ) { CurrentParent = CurrentChild; CurrentChild = CurrentParent->Get_Child(); } } void CProfileIterator::Enter_Parent( void ) { if ( CurrentParent->Get_Parent() != NULL ) { CurrentParent = CurrentParent->Get_Parent(); } CurrentChild = CurrentParent->Get_Child(); } /*************************************************************************************************** ** ** CProfileManager ** ***************************************************************************************************/ CProfileNode gRoots[BT_QUICKPROF_MAX_THREAD_COUNT]={ CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL), CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL),CProfileNode("Root",NULL) }; CProfileNode* gCurrentNodes[BT_QUICKPROF_MAX_THREAD_COUNT]= { &gRoots[ 0], &gRoots[ 1], &gRoots[ 2], &gRoots[ 3], &gRoots[ 4], &gRoots[ 5], &gRoots[ 6], &gRoots[ 7], &gRoots[ 8], &gRoots[ 9], &gRoots[10], &gRoots[11], &gRoots[12], &gRoots[13], &gRoots[14], &gRoots[15], &gRoots[16], &gRoots[17], &gRoots[18], &gRoots[19], &gRoots[20], &gRoots[21], &gRoots[22], &gRoots[23], &gRoots[24], &gRoots[25], &gRoots[26], &gRoots[27], &gRoots[28], &gRoots[29], &gRoots[30], &gRoots[31], &gRoots[32], &gRoots[33], &gRoots[34], &gRoots[35], &gRoots[36], &gRoots[37], &gRoots[38], &gRoots[39], &gRoots[40], &gRoots[41], &gRoots[42], &gRoots[43], &gRoots[44], &gRoots[45], &gRoots[46], &gRoots[47], &gRoots[48], &gRoots[49], &gRoots[50], &gRoots[51], &gRoots[52], &gRoots[53], &gRoots[54], &gRoots[55], &gRoots[56], &gRoots[57], &gRoots[58], &gRoots[59], &gRoots[60], &gRoots[61], &gRoots[62], &gRoots[63], }; int CProfileManager::FrameCounter = 0; unsigned long int CProfileManager::ResetTime = 0; CProfileIterator * CProfileManager::Get_Iterator( void ) { int threadIndex = btQuickprofGetCurrentThreadIndex2(); if ((threadIndex<0) || threadIndex >= BT_QUICKPROF_MAX_THREAD_COUNT) return 0; return new CProfileIterator( &gRoots[threadIndex]); } void CProfileManager::CleanupMemory(void) { for (int i=0;i<BT_QUICKPROF_MAX_THREAD_COUNT;i++) { gRoots[i].CleanupMemory(); } } /*********************************************************************************************** * CProfileManager::Start_Profile -- Begin a named profile * * * * Steps one level deeper into the tree, if a child already exists with the specified name * * then it accumulates the profiling; otherwise a new child node is added to the profile tree. * * * * INPUT: * * name - name of this profiling record * * * * WARNINGS: * * The string used is assumed to be a static string; pointer compares are used throughout * * the profiling code for efficiency. * *=============================================================================================*/ void CProfileManager::Start_Profile( const char * name ) { int threadIndex = btQuickprofGetCurrentThreadIndex2(); if ((threadIndex<0) || threadIndex >= BT_QUICKPROF_MAX_THREAD_COUNT) return; if (name != gCurrentNodes[threadIndex]->Get_Name()) { gCurrentNodes[threadIndex] = gCurrentNodes[threadIndex]->Get_Sub_Node( name ); } gCurrentNodes[threadIndex]->Call(); } /*********************************************************************************************** * CProfileManager::Stop_Profile -- Stop timing and record the results. * *=============================================================================================*/ void CProfileManager::Stop_Profile( void ) { int threadIndex = btQuickprofGetCurrentThreadIndex2(); if ((threadIndex<0) || threadIndex >= BT_QUICKPROF_MAX_THREAD_COUNT) return; // Return will indicate whether we should back up to our parent (we may // be profiling a recursive function) if (gCurrentNodes[threadIndex]->Return()) { gCurrentNodes[threadIndex] = gCurrentNodes[threadIndex]->Get_Parent(); } } /*********************************************************************************************** * CProfileManager::Reset -- Reset the contents of the profiling system * * * * This resets everything except for the tree structure. All of the timing data is reset. * *=============================================================================================*/ void CProfileManager::Reset( void ) { gProfileClock.reset(); int threadIndex = btQuickprofGetCurrentThreadIndex2(); if ((threadIndex<0) || threadIndex >= BT_QUICKPROF_MAX_THREAD_COUNT) return; gRoots[threadIndex].Reset(); gRoots[threadIndex].Call(); FrameCounter = 0; Profile_Get_Ticks(&ResetTime); } /*********************************************************************************************** * CProfileManager::Increment_Frame_Counter -- Increment the frame counter * *=============================================================================================*/ void CProfileManager::Increment_Frame_Counter( void ) { FrameCounter++; } /*********************************************************************************************** * CProfileManager::Get_Time_Since_Reset -- returns the elapsed time since last reset * *=============================================================================================*/ float CProfileManager::Get_Time_Since_Reset( void ) { unsigned long int time; Profile_Get_Ticks(&time); time -= ResetTime; return (float)time / Profile_Get_Tick_Rate(); } #include <stdio.h> void CProfileManager::dumpRecursive(CProfileIterator* profileIterator, int spacing) { profileIterator->First(); if (profileIterator->Is_Done()) return; float accumulated_time=0,parent_time = profileIterator->Is_Root() ? CProfileManager::Get_Time_Since_Reset() : profileIterator->Get_Current_Parent_Total_Time(); int i; int frames_since_reset = CProfileManager::Get_Frame_Count_Since_Reset(); for (i=0;i<spacing;i++) printf("."); printf("----------------------------------\n"); for (i=0;i<spacing;i++) printf("."); printf("Profiling: %s (total running time: %.3f ms) ---\n", profileIterator->Get_Current_Parent_Name(), parent_time ); float totalTime = 0.f; int numChildren = 0; for (i = 0; !profileIterator->Is_Done(); i++,profileIterator->Next()) { numChildren++; float current_total_time = profileIterator->Get_Current_Total_Time(); accumulated_time += current_total_time; float fraction = parent_time > SIMD_EPSILON ? (current_total_time / parent_time) * 100 : 0.f; { int i; for (i=0;i<spacing;i++) printf("."); } printf("%d -- %s (%.2f %%) :: %.3f ms / frame (%d calls)\n",i, profileIterator->Get_Current_Name(), fraction,(current_total_time / (double)frames_since_reset),profileIterator->Get_Current_Total_Calls()); totalTime += current_total_time; //recurse into children } if (parent_time < accumulated_time) { //printf("what's wrong\n"); } for (i=0;i<spacing;i++) printf("."); printf("%s (%.3f %%) :: %.3f ms\n", "Unaccounted:",parent_time > SIMD_EPSILON ? ((parent_time - accumulated_time) / parent_time) * 100 : 0.f, parent_time - accumulated_time); for (i=0;i<numChildren;i++) { profileIterator->Enter_Child(i); dumpRecursive(profileIterator,spacing+3); profileIterator->Enter_Parent(); } } void CProfileManager::dumpAll() { CProfileIterator* profileIterator = 0; profileIterator = CProfileManager::Get_Iterator(); dumpRecursive(profileIterator,0); CProfileManager::Release_Iterator(profileIterator); } unsigned int btQuickprofGetCurrentThreadIndex2() { #if BT_THREADSAFE return btGetCurrentThreadIndex(); #else // #if BT_THREADSAFE const unsigned int kNullIndex = ~0U; #ifdef _WIN32 #if defined(__MINGW32__) || defined(__MINGW64__) static __thread unsigned int sThreadIndex = kNullIndex; #else __declspec( thread ) static unsigned int sThreadIndex = kNullIndex; #endif #else #ifdef __APPLE__ #if TARGET_OS_IPHONE unsigned int sThreadIndex = 0; return -1; #else static __thread unsigned int sThreadIndex = kNullIndex; #endif #else//__APPLE__ #if __linux__ static __thread unsigned int sThreadIndex = kNullIndex; #else unsigned int sThreadIndex = 0; return -1; #endif #endif//__APPLE__ #endif static int gThreadCounter=0; if ( sThreadIndex == kNullIndex ) { sThreadIndex = gThreadCounter++; } return sThreadIndex; #endif // #else // #if BT_THREADSAFE } void btEnterProfileZoneDefault(const char* name) { CProfileManager::Start_Profile( name ); } void btLeaveProfileZoneDefault() { CProfileManager::Stop_Profile(); } #else void btEnterProfileZoneDefault(const char* name) { } void btLeaveProfileZoneDefault() { } #endif //BT_NO_PROFILE static btEnterProfileZoneFunc* bts_enterFunc = btEnterProfileZoneDefault; static btLeaveProfileZoneFunc* bts_leaveFunc = btLeaveProfileZoneDefault; void btEnterProfileZone(const char* name) { (bts_enterFunc)(name); } void btLeaveProfileZone() { (bts_leaveFunc)(); } btEnterProfileZoneFunc* btGetCurrentEnterProfileZoneFunc() { return bts_enterFunc ; } btLeaveProfileZoneFunc* btGetCurrentLeaveProfileZoneFunc() { return bts_leaveFunc; } void btSetCustomEnterProfileZoneFunc(btEnterProfileZoneFunc* enterFunc) { bts_enterFunc = enterFunc; } void btSetCustomLeaveProfileZoneFunc(btLeaveProfileZoneFunc* leaveFunc) { bts_leaveFunc = leaveFunc; } CProfileSample::CProfileSample( const char * name ) { btEnterProfileZone(name); } CProfileSample::~CProfileSample( void ) { btLeaveProfileZone(); }
bsd-3-clause
m-grimaud/opentoonz
thirdparty/openblas/xianyi-OpenBLAS-e6e87a2/interface/netlib/dgemv.f
55
7512
SUBROUTINE DGEMV(TRANS,M,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) * .. Scalar Arguments .. DOUBLE PRECISION ALPHA,BETA INTEGER INCX,INCY,LDA,M,N CHARACTER TRANS * .. * .. Array Arguments .. DOUBLE PRECISION A(LDA,*),X(*),Y(*) * .. * * Purpose * ======= * * DGEMV performs one of the matrix-vector operations * * y := alpha*A*x + beta*y, or y := alpha*A**T*x + beta*y, * * where alpha and beta are scalars, x and y are vectors and A is an * m by n matrix. * * Arguments * ========== * * TRANS - CHARACTER*1. * On entry, TRANS specifies the operation to be performed as * follows: * * TRANS = 'N' or 'n' y := alpha*A*x + beta*y. * * TRANS = 'T' or 't' y := alpha*A**T*x + beta*y. * * TRANS = 'C' or 'c' y := alpha*A**T*x + beta*y. * * Unchanged on exit. * * M - INTEGER. * On entry, M specifies the number of rows of the matrix A. * M must be at least zero. * Unchanged on exit. * * N - INTEGER. * On entry, N specifies the number of columns of the matrix A. * N must be at least zero. * Unchanged on exit. * * ALPHA - DOUBLE PRECISION. * On entry, ALPHA specifies the scalar alpha. * Unchanged on exit. * * A - DOUBLE PRECISION array of DIMENSION ( LDA, n ). * Before entry, the leading m by n part of the array A must * contain the matrix of coefficients. * Unchanged on exit. * * LDA - INTEGER. * On entry, LDA specifies the first dimension of A as declared * in the calling (sub) program. LDA must be at least * max( 1, m ). * Unchanged on exit. * * X - DOUBLE PRECISION array of DIMENSION at least * ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n' * and at least * ( 1 + ( m - 1 )*abs( INCX ) ) otherwise. * Before entry, the incremented array X must contain the * vector x. * Unchanged on exit. * * INCX - INTEGER. * On entry, INCX specifies the increment for the elements of * X. INCX must not be zero. * Unchanged on exit. * * BETA - DOUBLE PRECISION. * On entry, BETA specifies the scalar beta. When BETA is * supplied as zero then Y need not be set on input. * Unchanged on exit. * * Y - DOUBLE PRECISION array of DIMENSION at least * ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n' * and at least * ( 1 + ( n - 1 )*abs( INCY ) ) otherwise. * Before entry with BETA non-zero, the incremented array Y * must contain the vector y. On exit, Y is overwritten by the * updated vector y. * * INCY - INTEGER. * On entry, INCY specifies the increment for the elements of * Y. INCY must not be zero. * Unchanged on exit. * * Further Details * =============== * * Level 2 Blas routine. * The vector and matrix arguments are not referenced when N = 0, or M = 0 * * -- Written on 22-October-1986. * Jack Dongarra, Argonne National Lab. * Jeremy Du Croz, Nag Central Office. * Sven Hammarling, Nag Central Office. * Richard Hanson, Sandia National Labs. * * ===================================================================== * * .. Parameters .. DOUBLE PRECISION ONE,ZERO PARAMETER (ONE=1.0D+0,ZERO=0.0D+0) * .. * .. Local Scalars .. DOUBLE PRECISION TEMP INTEGER I,INFO,IX,IY,J,JX,JY,KX,KY,LENX,LENY * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX * .. * * Test the input parameters. * INFO = 0 IF (.NOT.LSAME(TRANS,'N') .AND. .NOT.LSAME(TRANS,'T') .AND. + .NOT.LSAME(TRANS,'C')) THEN INFO = 1 ELSE IF (M.LT.0) THEN INFO = 2 ELSE IF (N.LT.0) THEN INFO = 3 ELSE IF (LDA.LT.MAX(1,M)) THEN INFO = 6 ELSE IF (INCX.EQ.0) THEN INFO = 8 ELSE IF (INCY.EQ.0) THEN INFO = 11 END IF IF (INFO.NE.0) THEN CALL XERBLA('DGEMV ',INFO) RETURN END IF * * Quick return if possible. * IF ((M.EQ.0) .OR. (N.EQ.0) .OR. + ((ALPHA.EQ.ZERO).AND. (BETA.EQ.ONE))) RETURN * * Set LENX and LENY, the lengths of the vectors x and y, and set * up the start points in X and Y. * IF (LSAME(TRANS,'N')) THEN LENX = N LENY = M ELSE LENX = M LENY = N END IF IF (INCX.GT.0) THEN KX = 1 ELSE KX = 1 - (LENX-1)*INCX END IF IF (INCY.GT.0) THEN KY = 1 ELSE KY = 1 - (LENY-1)*INCY END IF * * Start the operations. In this version the elements of A are * accessed sequentially with one pass through A. * * First form y := beta*y. * IF (BETA.NE.ONE) THEN IF (INCY.EQ.1) THEN IF (BETA.EQ.ZERO) THEN DO 10 I = 1,LENY Y(I) = ZERO 10 CONTINUE ELSE DO 20 I = 1,LENY Y(I) = BETA*Y(I) 20 CONTINUE END IF ELSE IY = KY IF (BETA.EQ.ZERO) THEN DO 30 I = 1,LENY Y(IY) = ZERO IY = IY + INCY 30 CONTINUE ELSE DO 40 I = 1,LENY Y(IY) = BETA*Y(IY) IY = IY + INCY 40 CONTINUE END IF END IF END IF IF (ALPHA.EQ.ZERO) RETURN IF (LSAME(TRANS,'N')) THEN * * Form y := alpha*A*x + y. * JX = KX IF (INCY.EQ.1) THEN DO 60 J = 1,N IF (X(JX).NE.ZERO) THEN TEMP = ALPHA*X(JX) DO 50 I = 1,M Y(I) = Y(I) + TEMP*A(I,J) 50 CONTINUE END IF JX = JX + INCX 60 CONTINUE ELSE DO 80 J = 1,N IF (X(JX).NE.ZERO) THEN TEMP = ALPHA*X(JX) IY = KY DO 70 I = 1,M Y(IY) = Y(IY) + TEMP*A(I,J) IY = IY + INCY 70 CONTINUE END IF JX = JX + INCX 80 CONTINUE END IF ELSE * * Form y := alpha*A**T*x + y. * JY = KY IF (INCX.EQ.1) THEN DO 100 J = 1,N TEMP = ZERO DO 90 I = 1,M TEMP = TEMP + A(I,J)*X(I) 90 CONTINUE Y(JY) = Y(JY) + ALPHA*TEMP JY = JY + INCY 100 CONTINUE ELSE DO 120 J = 1,N TEMP = ZERO IX = KX DO 110 I = 1,M TEMP = TEMP + A(I,J)*X(IX) IX = IX + INCX 110 CONTINUE Y(JY) = Y(JY) + ALPHA*TEMP JY = JY + INCY 120 CONTINUE END IF END IF * RETURN * * End of DGEMV . * END
bsd-3-clause
InfinitiveOS/external_skia
samplecode/SampleUnpremul.cpp
59
6679
/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "Resources.h" #include "SampleCode.h" #include "SkBlurMask.h" #include "SkBlurDrawLooper.h" #include "SkCanvas.h" #include "SkColorPriv.h" #include "SkForceLinking.h" #include "SkImageDecoder.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkString.h" #include "SkSystemEventTypes.h" #include "SkTypes.h" #include "SkUtils.h" #include "SkView.h" __SK_FORCE_IMAGE_DECODER_LINKING; // Defined in SampleColorFilter.cpp extern SkShader* createChecker(); /** * Interprets c as an unpremultiplied color, and returns the * premultiplied equivalent. */ static SkPMColor premultiply_unpmcolor(SkPMColor c) { U8CPU a = SkGetPackedA32(c); U8CPU r = SkGetPackedR32(c); U8CPU g = SkGetPackedG32(c); U8CPU b = SkGetPackedB32(c); return SkPreMultiplyARGB(a, r, g, b); } class UnpremulView : public SampleView { public: UnpremulView(SkString res) : fResPath(res) , fPremul(true) , fDecodeSucceeded(false) { this->nextImage(); } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) SK_OVERRIDE { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "unpremul"); return true; } SkUnichar uni; if (SampleCode::CharQ(*evt, &uni)) { char utf8[kMaxBytesInUTF8Sequence]; size_t size = SkUTF8_FromUnichar(uni, utf8); // Only consider events for single char keys if (1 == size) { switch (utf8[0]) { case fNextImageChar: this->nextImage(); return true; case fTogglePremulChar: this->togglePremul(); return true; default: break; } } } return this->INHERITED::onQuery(evt); } virtual void onDrawBackground(SkCanvas* canvas) SK_OVERRIDE { SkPaint paint; SkAutoTUnref<SkShader> shader(createChecker()); paint.setShader(shader.get()); canvas->drawPaint(paint); } virtual void onDrawContent(SkCanvas* canvas) SK_OVERRIDE { SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(24)); SkAutoTUnref<SkBlurDrawLooper> looper( SkBlurDrawLooper::Create(SK_ColorBLUE, SkBlurMask::ConvertRadiusToSigma(SkIntToScalar(2)), 0, 0)); paint.setLooper(looper); SkScalar height = paint.getFontMetrics(NULL); if (!fDecodeSucceeded) { SkString failure; if (fResPath.size() == 0) { failure.printf("resource path is required!"); } else { failure.printf("Failed to decode %s", fCurrFile.c_str()); } canvas->drawText(failure.c_str(), failure.size(), 0, height, paint); return; } // Name, size of the file, and whether or not it is premultiplied. SkString header(SkOSPath::SkBasename(fCurrFile.c_str())); header.appendf(" [%dx%d] %s", fBitmap.width(), fBitmap.height(), (fPremul ? "premultiplied" : "unpremultiplied")); canvas->drawText(header.c_str(), header.size(), 0, height, paint); canvas->translate(0, height); // Help messages header.printf("Press '%c' to move to the next image.'", fNextImageChar); canvas->drawText(header.c_str(), header.size(), 0, height, paint); canvas->translate(0, height); header.printf("Press '%c' to toggle premultiplied decode.", fTogglePremulChar); canvas->drawText(header.c_str(), header.size(), 0, height, paint); // Now draw the image itself. canvas->translate(height * 2, height * 2); if (!fPremul) { // A premultiplied bitmap cannot currently be drawn. SkAutoLockPixels alp(fBitmap); // Copy it to a bitmap which can be drawn, converting // to premultiplied: SkBitmap bm; if (!bm.allocN32Pixels(fBitmap.width(), fBitmap.height())) { SkString errMsg("allocPixels failed"); canvas->drawText(errMsg.c_str(), errMsg.size(), 0, height, paint); return; } for (int i = 0; i < fBitmap.width(); ++i) { for (int j = 0; j < fBitmap.height(); ++j) { *bm.getAddr32(i, j) = premultiply_unpmcolor(*fBitmap.getAddr32(i, j)); } } canvas->drawBitmap(bm, 0, 0); } else { canvas->drawBitmap(fBitmap, 0, 0); } } private: const SkString fResPath; SkString fCurrFile; bool fPremul; bool fDecodeSucceeded; SkBitmap fBitmap; SkOSFile::Iter fFileIter; static const char fNextImageChar = 'j'; static const char fTogglePremulChar = 'h'; void nextImage() { if (fResPath.size() == 0) { return; } SkString basename; if (!fFileIter.next(&basename)) { fFileIter.reset(fResPath.c_str()); if (!fFileIter.next(&basename)) { // Perhaps this should draw some error message? return; } } fCurrFile = SkOSPath::SkPathJoin(fResPath.c_str(), basename.c_str()); this->decodeCurrFile(); } void decodeCurrFile() { if (fCurrFile.size() == 0) { fDecodeSucceeded = false; return; } SkFILEStream stream(fCurrFile.c_str()); SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(&stream)); if (NULL == decoder.get()) { fDecodeSucceeded = false; return; } if (!fPremul) { decoder->setRequireUnpremultipliedColors(true); } fDecodeSucceeded = decoder->decode(&stream, &fBitmap, kN32_SkColorType, SkImageDecoder::kDecodePixels_Mode); this->inval(NULL); } void togglePremul() { fPremul = !fPremul; this->decodeCurrFile(); } typedef SampleView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new UnpremulView(GetResourcePath()); } static SkViewRegister reg(MyFactory);
bsd-3-clause
jmargutt/AliPhysics
PWG/Tools/yaml-cpp/src/emitterutils.cpp
68
12365
#include <iomanip> #include <sstream> #include "emitterutils.h" #include "exp.h" #include "indentation.h" #include "regex_yaml.h" #include "regeximpl.h" #include "stringsource.h" #include "yaml-cpp/binary.h" // IWYU pragma: keep #include "yaml-cpp/ostream_wrapper.h" #include "yaml-cpp/null.h" namespace YAML { namespace Utils { namespace { enum { REPLACEMENT_CHARACTER = 0xFFFD }; bool IsAnchorChar(int ch) { // test for ns-anchor-char switch (ch) { case ',': case '[': case ']': case '{': case '}': // c-flow-indicator case ' ': case '\t': // s-white case 0xFEFF: // c-byte-order-mark case 0xA: case 0xD: // b-char return false; case 0x85: return true; } if (ch < 0x20) { return false; } if (ch < 0x7E) { return true; } if (ch < 0xA0) { return false; } if (ch >= 0xD800 && ch <= 0xDFFF) { return false; } if ((ch & 0xFFFE) == 0xFFFE) { return false; } if ((ch >= 0xFDD0) && (ch <= 0xFDEF)) { return false; } if (ch > 0x10FFFF) { return false; } return true; } int Utf8BytesIndicated(char ch) { int byteVal = static_cast<unsigned char>(ch); switch (byteVal >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: return 1; case 12: case 13: return 2; case 14: return 3; case 15: return 4; default: return -1; } } bool IsTrailingByte(char ch) { return (ch & 0xC0) == 0x80; } bool GetNextCodePointAndAdvance(int& codePoint, std::string::const_iterator& first, std::string::const_iterator last) { if (first == last) return false; int nBytes = Utf8BytesIndicated(*first); if (nBytes < 1) { // Bad lead byte ++first; codePoint = REPLACEMENT_CHARACTER; return true; } if (nBytes == 1) { codePoint = *first++; return true; } // Gather bits from trailing bytes codePoint = static_cast<unsigned char>(*first) & ~(0xFF << (7 - nBytes)); ++first; --nBytes; for (; nBytes > 0; ++first, --nBytes) { if ((first == last) || !IsTrailingByte(*first)) { codePoint = REPLACEMENT_CHARACTER; break; } codePoint <<= 6; codePoint |= *first & 0x3F; } // Check for illegal code points if (codePoint > 0x10FFFF) codePoint = REPLACEMENT_CHARACTER; else if (codePoint >= 0xD800 && codePoint <= 0xDFFF) codePoint = REPLACEMENT_CHARACTER; else if ((codePoint & 0xFFFE) == 0xFFFE) codePoint = REPLACEMENT_CHARACTER; else if (codePoint >= 0xFDD0 && codePoint <= 0xFDEF) codePoint = REPLACEMENT_CHARACTER; return true; } void WriteCodePoint(ostream_wrapper& out, int codePoint) { if (codePoint < 0 || codePoint > 0x10FFFF) { codePoint = REPLACEMENT_CHARACTER; } if (codePoint < 0x7F) { out << static_cast<char>(codePoint); } else if (codePoint < 0x7FF) { out << static_cast<char>(0xC0 | (codePoint >> 6)) << static_cast<char>(0x80 | (codePoint & 0x3F)); } else if (codePoint < 0xFFFF) { out << static_cast<char>(0xE0 | (codePoint >> 12)) << static_cast<char>(0x80 | ((codePoint >> 6) & 0x3F)) << static_cast<char>(0x80 | (codePoint & 0x3F)); } else { out << static_cast<char>(0xF0 | (codePoint >> 18)) << static_cast<char>(0x80 | ((codePoint >> 12) & 0x3F)) << static_cast<char>(0x80 | ((codePoint >> 6) & 0x3F)) << static_cast<char>(0x80 | (codePoint & 0x3F)); } } bool IsValidPlainScalar(const std::string& str, FlowType::value flowType, bool allowOnlyAscii) { // check against null if (IsNullString(str)) { return false; } // check the start const RegEx& start = (flowType == FlowType::Flow ? Exp::PlainScalarInFlow() : Exp::PlainScalar()); if (!start.Matches(str)) { return false; } // and check the end for plain whitespace (which can't be faithfully kept in a // plain scalar) if (!str.empty() && *str.rbegin() == ' ') { return false; } // then check until something is disallowed static const RegEx& disallowed_flow = Exp::EndScalarInFlow() || (Exp::BlankOrBreak() + Exp::Comment()) || Exp::NotPrintable() || Exp::Utf8_ByteOrderMark() || Exp::Break() || Exp::Tab(); static const RegEx& disallowed_block = Exp::EndScalar() || (Exp::BlankOrBreak() + Exp::Comment()) || Exp::NotPrintable() || Exp::Utf8_ByteOrderMark() || Exp::Break() || Exp::Tab(); const RegEx& disallowed = flowType == FlowType::Flow ? disallowed_flow : disallowed_block; StringCharSource buffer(str.c_str(), str.size()); while (buffer) { if (disallowed.Matches(buffer)) { return false; } if (allowOnlyAscii && (0x80 <= static_cast<unsigned char>(buffer[0]))) { return false; } ++buffer; } return true; } bool IsValidSingleQuotedScalar(const std::string& str, bool escapeNonAscii) { // TODO: check for non-printable characters? for (std::size_t i = 0; i < str.size(); i++) { if (escapeNonAscii && (0x80 <= static_cast<unsigned char>(str[i]))) { return false; } if (str[i] == '\n') { return false; } } return true; } bool IsValidLiteralScalar(const std::string& str, FlowType::value flowType, bool escapeNonAscii) { if (flowType == FlowType::Flow) { return false; } // TODO: check for non-printable characters? for (std::size_t i = 0; i < str.size(); i++) { if (escapeNonAscii && (0x80 <= static_cast<unsigned char>(str[i]))) { return false; } } return true; } void WriteDoubleQuoteEscapeSequence(ostream_wrapper& out, int codePoint) { static const char hexDigits[] = "0123456789abcdef"; out << "\\"; int digits = 8; if (codePoint < 0xFF) { out << "x"; digits = 2; } else if (codePoint < 0xFFFF) { out << "u"; digits = 4; } else { out << "U"; digits = 8; } // Write digits into the escape sequence for (; digits > 0; --digits) out << hexDigits[(codePoint >> (4 * (digits - 1))) & 0xF]; } bool WriteAliasName(ostream_wrapper& out, const std::string& str) { int codePoint; for (std::string::const_iterator i = str.begin(); GetNextCodePointAndAdvance(codePoint, i, str.end());) { if (!IsAnchorChar(codePoint)) { return false; } WriteCodePoint(out, codePoint); } return true; } } StringFormat::value ComputeStringFormat(const std::string& str, EMITTER_MANIP strFormat, FlowType::value flowType, bool escapeNonAscii) { switch (strFormat) { case Auto: if (IsValidPlainScalar(str, flowType, escapeNonAscii)) { return StringFormat::Plain; } return StringFormat::DoubleQuoted; case SingleQuoted: if (IsValidSingleQuotedScalar(str, escapeNonAscii)) { return StringFormat::SingleQuoted; } return StringFormat::DoubleQuoted; case DoubleQuoted: return StringFormat::DoubleQuoted; case Literal: if (IsValidLiteralScalar(str, flowType, escapeNonAscii)) { return StringFormat::Literal; } return StringFormat::DoubleQuoted; default: break; } return StringFormat::DoubleQuoted; } bool WriteSingleQuotedString(ostream_wrapper& out, const std::string& str) { out << "'"; int codePoint; for (std::string::const_iterator i = str.begin(); GetNextCodePointAndAdvance(codePoint, i, str.end());) { if (codePoint == '\n') { return false; // We can't handle a new line and the attendant indentation // yet } if (codePoint == '\'') { out << "''"; } else { WriteCodePoint(out, codePoint); } } out << "'"; return true; } bool WriteDoubleQuotedString(ostream_wrapper& out, const std::string& str, bool escapeNonAscii) { out << "\""; int codePoint; for (std::string::const_iterator i = str.begin(); GetNextCodePointAndAdvance(codePoint, i, str.end());) { switch (codePoint) { case '\"': out << "\\\""; break; case '\\': out << "\\\\"; break; case '\n': out << "\\n"; break; case '\t': out << "\\t"; break; case '\r': out << "\\r"; break; case '\b': out << "\\b"; break; default: if (codePoint < 0x20 || (codePoint >= 0x80 && codePoint <= 0xA0)) { // Control characters and non-breaking space WriteDoubleQuoteEscapeSequence(out, codePoint); } else if (codePoint == 0xFEFF) { // Byte order marks (ZWNS) should be // escaped (YAML 1.2, sec. 5.2) WriteDoubleQuoteEscapeSequence(out, codePoint); } else if (escapeNonAscii && codePoint > 0x7E) { WriteDoubleQuoteEscapeSequence(out, codePoint); } else { WriteCodePoint(out, codePoint); } } } out << "\""; return true; } bool WriteLiteralString(ostream_wrapper& out, const std::string& str, std::size_t indent) { out << "|\n"; out << IndentTo(indent); int codePoint; for (std::string::const_iterator i = str.begin(); GetNextCodePointAndAdvance(codePoint, i, str.end());) { if (codePoint == '\n') { out << "\n" << IndentTo(indent); } else { WriteCodePoint(out, codePoint); } } return true; } bool WriteChar(ostream_wrapper& out, char ch) { if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z')) { out << ch; } else if (ch == '\"') { out << "\"\\\"\""; } else if (ch == '\t') { out << "\"\\t\""; } else if (ch == '\n') { out << "\"\\n\""; } else if (ch == '\b') { out << "\"\\b\""; } else if (ch == '\\') { out << "\"\\\\\""; } else if ((0x20 <= ch && ch <= 0x7e) || ch == ' ') { out << "\"" << ch << "\""; } else { out << "\""; WriteDoubleQuoteEscapeSequence(out, ch); out << "\""; } return true; } bool WriteComment(ostream_wrapper& out, const std::string& str, std::size_t postCommentIndent) { const std::size_t curIndent = out.col(); out << "#" << Indentation(postCommentIndent); out.set_comment(); int codePoint; for (std::string::const_iterator i = str.begin(); GetNextCodePointAndAdvance(codePoint, i, str.end());) { if (codePoint == '\n') { out << "\n" << IndentTo(curIndent) << "#" << Indentation(postCommentIndent); out.set_comment(); } else { WriteCodePoint(out, codePoint); } } return true; } bool WriteAlias(ostream_wrapper& out, const std::string& str) { out << "*"; return WriteAliasName(out, str); } bool WriteAnchor(ostream_wrapper& out, const std::string& str) { out << "&"; return WriteAliasName(out, str); } bool WriteTag(ostream_wrapper& out, const std::string& str, bool verbatim) { out << (verbatim ? "!<" : "!"); StringCharSource buffer(str.c_str(), str.size()); const RegEx& reValid = verbatim ? Exp::URI() : Exp::Tag(); while (buffer) { int n = reValid.Match(buffer); if (n <= 0) { return false; } while (--n >= 0) { out << buffer[0]; ++buffer; } } if (verbatim) { out << ">"; } return true; } bool WriteTagWithPrefix(ostream_wrapper& out, const std::string& prefix, const std::string& tag) { out << "!"; StringCharSource prefixBuffer(prefix.c_str(), prefix.size()); while (prefixBuffer) { int n = Exp::URI().Match(prefixBuffer); if (n <= 0) { return false; } while (--n >= 0) { out << prefixBuffer[0]; ++prefixBuffer; } } out << "!"; StringCharSource tagBuffer(tag.c_str(), tag.size()); while (tagBuffer) { int n = Exp::Tag().Match(tagBuffer); if (n <= 0) { return false; } while (--n >= 0) { out << tagBuffer[0]; ++tagBuffer; } } return true; } bool WriteBinary(ostream_wrapper& out, const Binary& binary) { WriteDoubleQuotedString(out, EncodeBase64(binary.data(), binary.size()), false); return true; } } }
bsd-3-clause
APCVSRepo/sdl_core_v4.0_winceport
src/3rd_party/apr-1.5.0/threadproc/beos/apr_proc_stub.c
76
2125
/* 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. */ #include <kernel/OS.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> struct pipefd { int in; int out; int err; }; int main(int argc, char *argv[]) { /* we expect the following... * * argv[0] = this stub * argv[1] = directory to run in... * argv[2] = progname to execute * rest of arguments to be passed to program */ char *progname = argv[2]; char *directory = argv[1]; struct pipefd *pfd; thread_id sender; void *buffer; char ** newargs; int i = 0; newargs = (char**)malloc(sizeof(char*) * (argc - 1)); buffer = (void*)malloc(sizeof(struct pipefd)); /* this will block until we get the data */ receive_data(&sender, buffer, sizeof(struct pipefd)); pfd = (struct pipefd*)buffer; if (pfd->in > STDERR_FILENO) { if (dup2(pfd->in, STDIN_FILENO) != STDIN_FILENO) return (-1); close (pfd->in); } if (pfd->out > STDERR_FILENO) { if (dup2(pfd->out, STDOUT_FILENO) != STDOUT_FILENO) return (-1); close (pfd->out); } if (pfd->err > STDERR_FILENO) { if (dup2(pfd->err, STDERR_FILENO) != STDERR_FILENO) return (-1); close (pfd->err); } for (i=3;i<=argc;i++){ newargs[i-3] = argv[i]; } /* tell the caller we're OK to start */ send_data(sender,1,NULL,0); if (directory != NULL) chdir(directory); execve (progname, newargs, environ); return (-1); }
bsd-3-clause
grevutiu-gabriel/phantomjs
src/qt/qtbase/src/network/kernel/qnetworkinterface.cpp
84
19975
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtNetwork module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qnetworkinterface.h" #include "qnetworkinterface_p.h" #include "qdebug.h" #include "qendian.h" #ifndef QT_NO_NETWORKINTERFACE QT_BEGIN_NAMESPACE static QList<QNetworkInterfacePrivate *> postProcess(QList<QNetworkInterfacePrivate *> list) { // Some platforms report a netmask but don't report a broadcast address // Go through all available addresses and calculate the broadcast address // from the IP and the netmask // // This is an IPv4-only thing -- IPv6 has no concept of broadcasts // The math is: // broadcast = IP | ~netmask QList<QNetworkInterfacePrivate *>::Iterator it = list.begin(); const QList<QNetworkInterfacePrivate *>::Iterator end = list.end(); for ( ; it != end; ++it) { QList<QNetworkAddressEntry>::Iterator addr_it = (*it)->addressEntries.begin(); const QList<QNetworkAddressEntry>::Iterator addr_end = (*it)->addressEntries.end(); for ( ; addr_it != addr_end; ++addr_it) { if (addr_it->ip().protocol() != QAbstractSocket::IPv4Protocol) continue; if (!addr_it->netmask().isNull() && addr_it->broadcast().isNull()) { QHostAddress bcast = addr_it->ip(); bcast = QHostAddress(bcast.toIPv4Address() | ~addr_it->netmask().toIPv4Address()); addr_it->setBroadcast(bcast); } } } return list; } Q_GLOBAL_STATIC(QNetworkInterfaceManager, manager) QNetworkInterfaceManager::QNetworkInterfaceManager() { } QNetworkInterfaceManager::~QNetworkInterfaceManager() { } QSharedDataPointer<QNetworkInterfacePrivate> QNetworkInterfaceManager::interfaceFromName(const QString &name) { QList<QSharedDataPointer<QNetworkInterfacePrivate> > interfaceList = allInterfaces(); QList<QSharedDataPointer<QNetworkInterfacePrivate> >::ConstIterator it = interfaceList.constBegin(); for ( ; it != interfaceList.constEnd(); ++it) if ((*it)->name == name) return *it; return empty; } QSharedDataPointer<QNetworkInterfacePrivate> QNetworkInterfaceManager::interfaceFromIndex(int index) { QList<QSharedDataPointer<QNetworkInterfacePrivate> > interfaceList = allInterfaces(); QList<QSharedDataPointer<QNetworkInterfacePrivate> >::ConstIterator it = interfaceList.constBegin(); for ( ; it != interfaceList.constEnd(); ++it) if ((*it)->index == index) return *it; return empty; } QList<QSharedDataPointer<QNetworkInterfacePrivate> > QNetworkInterfaceManager::allInterfaces() { QList<QNetworkInterfacePrivate *> list = postProcess(scan()); QList<QSharedDataPointer<QNetworkInterfacePrivate> > result; foreach (QNetworkInterfacePrivate *ptr, list) result << QSharedDataPointer<QNetworkInterfacePrivate>(ptr); return result; } QString QNetworkInterfacePrivate::makeHwAddress(int len, uchar *data) { QString result; for (int i = 0; i < len; ++i) { if (i) result += QLatin1Char(':'); char buf[3]; #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && defined(_MSC_VER) && _MSC_VER >= 1400 sprintf_s(buf, 3, "%02hX", ushort(data[i])); #else sprintf(buf, "%02hX", ushort(data[i])); #endif result += QLatin1String(buf); } return result; } /*! \class QNetworkAddressEntry \brief The QNetworkAddressEntry class stores one IP address supported by a network interface, along with its associated netmask and broadcast address. \since 4.2 \reentrant \ingroup network \ingroup shared \inmodule QtNetwork Each network interface can contain zero or more IP addresses, which in turn can be associated with a netmask and/or a broadcast address (depending on support from the operating system). This class represents one such group. */ /*! Constructs an empty QNetworkAddressEntry object. */ QNetworkAddressEntry::QNetworkAddressEntry() : d(new QNetworkAddressEntryPrivate) { } /*! Constructs a QNetworkAddressEntry object that is a copy of the object \a other. */ QNetworkAddressEntry::QNetworkAddressEntry(const QNetworkAddressEntry &other) : d(new QNetworkAddressEntryPrivate(*other.d.data())) { } /*! Makes a copy of the QNetworkAddressEntry object \a other. */ QNetworkAddressEntry &QNetworkAddressEntry::operator=(const QNetworkAddressEntry &other) { *d.data() = *other.d.data(); return *this; } /*! \fn void QNetworkAddressEntry::swap(QNetworkAddressEntry &other) \since 5.0 Swaps this network address entry instance with \a other. This function is very fast and never fails. */ /*! Destroys this QNetworkAddressEntry object. */ QNetworkAddressEntry::~QNetworkAddressEntry() { } /*! Returns \c true if this network address entry is the same as \a other. */ bool QNetworkAddressEntry::operator==(const QNetworkAddressEntry &other) const { if (d == other.d) return true; if (!d || !other.d) return false; return d->address == other.d->address && d->netmask == other.d->netmask && d->broadcast == other.d->broadcast; } /*! \fn bool QNetworkAddressEntry::operator!=(const QNetworkAddressEntry &other) const Returns \c true if this network address entry is different from \a other. */ /*! This function returns one IPv4 or IPv6 address found, that was found in a network interface. */ QHostAddress QNetworkAddressEntry::ip() const { return d->address; } /*! Sets the IP address the QNetworkAddressEntry object contains to \a newIp. */ void QNetworkAddressEntry::setIp(const QHostAddress &newIp) { d->address = newIp; } /*! Returns the netmask associated with the IP address. The netmask is expressed in the form of an IP address, such as 255.255.0.0. For IPv6 addresses, the prefix length is converted to an address where the number of bits set to 1 is equal to the prefix length. For a prefix length of 64 bits (the most common value), the netmask will be expressed as a QHostAddress holding the address FFFF:FFFF:FFFF:FFFF:: \sa prefixLength() */ QHostAddress QNetworkAddressEntry::netmask() const { return d->netmask; } /*! Sets the netmask that this QNetworkAddressEntry object contains to \a newNetmask. Setting the netmask also sets the prefix length to match the new netmask. \sa setPrefixLength() */ void QNetworkAddressEntry::setNetmask(const QHostAddress &newNetmask) { if (newNetmask.protocol() != ip().protocol()) { d->netmask = QNetmaskAddress(); return; } d->netmask.setAddress(newNetmask); } /*! \since 4.5 Returns the prefix length of this IP address. The prefix length matches the number of bits set to 1 in the netmask (see netmask()). For IPv4 addresses, the value is between 0 and 32. For IPv6 addresses, it's contained between 0 and 128 and is the preferred form of representing addresses. This function returns -1 if the prefix length could not be determined (i.e., netmask() returns a null QHostAddress()). \sa netmask() */ int QNetworkAddressEntry::prefixLength() const { return d->netmask.prefixLength(); } /*! \since 4.5 Sets the prefix length of this IP address to \a length. The value of \a length must be valid for this type of IP address: between 0 and 32 for IPv4 addresses, between 0 and 128 for IPv6 addresses. Setting to any invalid value is equivalent to setting to -1, which means "no prefix length". Setting the prefix length also sets the netmask (see netmask()). \sa setNetmask() */ void QNetworkAddressEntry::setPrefixLength(int length) { d->netmask.setPrefixLength(d->address.protocol(), length); } /*! Returns the broadcast address associated with the IPv4 address and netmask. It can usually be derived from those two by setting to 1 the bits of the IP address where the netmask contains a 0. (In other words, by bitwise-OR'ing the IP address with the inverse of the netmask) This member is always empty for IPv6 addresses, since the concept of broadcast has been abandoned in that system in favor of multicast. In particular, the group of hosts corresponding to all the nodes in the local network can be reached by the "all-nodes" special multicast group (address FF02::1). */ QHostAddress QNetworkAddressEntry::broadcast() const { return d->broadcast; } /*! Sets the broadcast IP address of this QNetworkAddressEntry object to \a newBroadcast. */ void QNetworkAddressEntry::setBroadcast(const QHostAddress &newBroadcast) { d->broadcast = newBroadcast; } /*! \class QNetworkInterface \brief The QNetworkInterface class provides a listing of the host's IP addresses and network interfaces. \since 4.2 \reentrant \ingroup network \ingroup shared \inmodule QtNetwork QNetworkInterface represents one network interface attached to the host where the program is being run. Each network interface may contain zero or more IP addresses, each of which is optionally associated with a netmask and/or a broadcast address. The list of such trios can be obtained with addressEntries(). Alternatively, when the netmask or the broadcast addresses aren't necessary, use the allAddresses() convenience function to obtain just the IP addresses. QNetworkInterface also reports the interface's hardware address with hardwareAddress(). Not all operating systems support reporting all features. Only the IPv4 addresses are guaranteed to be listed by this class in all platforms. In particular, IPv6 address listing is only supported on Windows XP and more recent versions, Linux, MacOS X and the BSDs. \sa QNetworkAddressEntry */ /*! \enum QNetworkInterface::InterfaceFlag Specifies the flags associated with this network interface. The possible values are: \value IsUp the network interface is active \value IsRunning the network interface has resources allocated \value CanBroadcast the network interface works in broadcast mode \value IsLoopBack the network interface is a loopback interface: that is, it's a virtual interface whose destination is the host computer itself \value IsPointToPoint the network interface is a point-to-point interface: that is, there is one, single other address that can be directly reached by it. \value CanMulticast the network interface supports multicasting Note that one network interface cannot be both broadcast-based and point-to-point. */ /*! Constructs an empty network interface object. */ QNetworkInterface::QNetworkInterface() : d(0) { } /*! Frees the resources associated with the QNetworkInterface object. */ QNetworkInterface::~QNetworkInterface() { } /*! Creates a copy of the QNetworkInterface object contained in \a other. */ QNetworkInterface::QNetworkInterface(const QNetworkInterface &other) : d(other.d) { } /*! Copies the contents of the QNetworkInterface object contained in \a other into this one. */ QNetworkInterface &QNetworkInterface::operator=(const QNetworkInterface &other) { d = other.d; return *this; } /*! \fn void QNetworkInterface::swap(QNetworkInterface &other) \since 5.0 Swaps this network interface instance with \a other. This function is very fast and never fails. */ /*! Returns \c true if this QNetworkInterface object contains valid information about a network interface. */ bool QNetworkInterface::isValid() const { return !name().isEmpty(); } /*! \since 4.5 Returns the interface system index, if known. This is an integer assigned by the operating system to identify this interface and it generally doesn't change. It matches the scope ID field in IPv6 addresses. If the index isn't known, this function returns 0. */ int QNetworkInterface::index() const { return d ? d->index : 0; } /*! Returns the name of this network interface. On Unix systems, this is a string containing the type of the interface and optionally a sequence number, such as "eth0", "lo" or "pcn0". On Windows, it's an internal ID that cannot be changed by the user. */ QString QNetworkInterface::name() const { return d ? d->name : QString(); } /*! \since 4.5 Returns the human-readable name of this network interface on Windows, such as "Local Area Connection", if the name could be determined. If it couldn't, this function returns the same as name(). The human-readable name is a name that the user can modify in the Windows Control Panel, so it may change during the execution of the program. On Unix, this function currently always returns the same as name(), since Unix systems don't store a configuration for human-readable names. */ QString QNetworkInterface::humanReadableName() const { return d ? !d->friendlyName.isEmpty() ? d->friendlyName : name() : QString(); } /*! Returns the flags associated with this network interface. */ QNetworkInterface::InterfaceFlags QNetworkInterface::flags() const { return d ? d->flags : InterfaceFlags(0); } /*! Returns the low-level hardware address for this interface. On Ethernet interfaces, this will be a MAC address in string representation, separated by colons. Other interface types may have other types of hardware addresses. Implementations should not depend on this function returning a valid MAC address. */ QString QNetworkInterface::hardwareAddress() const { return d ? d->hardwareAddress : QString(); } /*! Returns the list of IP addresses that this interface possesses along with their associated netmasks and broadcast addresses. If the netmask or broadcast address information is not necessary, you can call the allAddresses() function to obtain just the IP addresses. */ QList<QNetworkAddressEntry> QNetworkInterface::addressEntries() const { return d ? d->addressEntries : QList<QNetworkAddressEntry>(); } /*! Returns a QNetworkInterface object for the interface named \a name. If no such interface exists, this function returns an invalid QNetworkInterface object. \sa name(), isValid() */ QNetworkInterface QNetworkInterface::interfaceFromName(const QString &name) { QNetworkInterface result; result.d = manager()->interfaceFromName(name); return result; } /*! Returns a QNetworkInterface object for the interface whose internal ID is \a index. Network interfaces have a unique identifier called the "interface index" to distinguish it from other interfaces on the system. Often, this value is assigned progressively and interfaces being removed and then added again get a different value every time. This index is also found in the IPv6 address' scope ID field. */ QNetworkInterface QNetworkInterface::interfaceFromIndex(int index) { QNetworkInterface result; result.d = manager()->interfaceFromIndex(index); return result; } /*! Returns a listing of all the network interfaces found on the host machine. In case of failure it returns a list with zero elements. */ QList<QNetworkInterface> QNetworkInterface::allInterfaces() { QList<QSharedDataPointer<QNetworkInterfacePrivate> > privs = manager()->allInterfaces(); QList<QNetworkInterface> result; foreach (const QSharedDataPointer<QNetworkInterfacePrivate> &p, privs) { QNetworkInterface item; item.d = p; result << item; } return result; } /*! This convenience function returns all IP addresses found on the host machine. It is equivalent to calling addressEntries() on all the objects returned by allInterfaces() to obtain lists of QHostAddress objects then calling QHostAddress::ip() on each of these. */ QList<QHostAddress> QNetworkInterface::allAddresses() { QList<QSharedDataPointer<QNetworkInterfacePrivate> > privs = manager()->allInterfaces(); QList<QHostAddress> result; foreach (const QSharedDataPointer<QNetworkInterfacePrivate> &p, privs) { foreach (const QNetworkAddressEntry &entry, p->addressEntries) result += entry.ip(); } return result; } #ifndef QT_NO_DEBUG_STREAM static inline QDebug flagsDebug(QDebug debug, QNetworkInterface::InterfaceFlags flags) { if (flags & QNetworkInterface::IsUp) debug.nospace() << "IsUp "; if (flags & QNetworkInterface::IsRunning) debug.nospace() << "IsRunning "; if (flags & QNetworkInterface::CanBroadcast) debug.nospace() << "CanBroadcast "; if (flags & QNetworkInterface::IsLoopBack) debug.nospace() << "IsLoopBack "; if (flags & QNetworkInterface::IsPointToPoint) debug.nospace() << "IsPointToPoint "; if (flags & QNetworkInterface::CanMulticast) debug.nospace() << "CanMulticast "; return debug.nospace(); } static inline QDebug operator<<(QDebug debug, const QNetworkAddressEntry &entry) { debug.nospace() << "(address = " << entry.ip(); if (!entry.netmask().isNull()) debug.nospace() << ", netmask = " << entry.netmask(); if (!entry.broadcast().isNull()) debug.nospace() << ", broadcast = " << entry.broadcast(); debug.nospace() << ')'; return debug.space(); } QDebug operator<<(QDebug debug, const QNetworkInterface &networkInterface) { debug.nospace() << "QNetworkInterface(name = " << networkInterface.name() << ", hardware address = " << networkInterface.hardwareAddress() << ", flags = "; flagsDebug(debug, networkInterface.flags()); #if defined(Q_CC_RVCT) // RVCT gets confused with << networkInterface.addressEntries(), reason unknown. debug.nospace() << ")\n"; #else debug.nospace() << ", entries = " << networkInterface.addressEntries() << ")\n"; #endif return debug.space(); } #endif QT_END_NAMESPACE #endif // QT_NO_NETWORKINTERFACE
bsd-3-clause
gitromand/phantomjs
src/qt/qtbase/src/corelib/io/qstandardpaths_blackberry.cpp
84
3843
/*************************************************************************** ** ** Copyright (C) 2012 Research In Motion ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qstandardpaths.h" #include <qdir.h> #ifndef QT_NO_STANDARDPATHS #include <qstring.h> QT_BEGIN_NAMESPACE static QString testModeInsert() { if (QStandardPaths::isTestModeEnabled()) return QStringLiteral("/.qttest"); else return QStringLiteral(""); } QString QStandardPaths::writableLocation(StandardLocation type) { QDir sharedDir = QDir::home(); sharedDir.cd(QLatin1String("../shared")); const QString sharedRoot = sharedDir.absolutePath(); switch (type) { case AppDataLocation: case AppLocalDataLocation: return QDir::homePath() + testModeInsert(); case DesktopLocation: case HomeLocation: return QDir::homePath(); case RuntimeLocation: case TempLocation: return QDir::tempPath(); case CacheLocation: case GenericCacheLocation: return QDir::homePath() + testModeInsert() + QLatin1String("/Cache"); case ConfigLocation: case GenericConfigLocation: return QDir::homePath() + testModeInsert() + QLatin1String("/Settings"); case GenericDataLocation: return sharedRoot + testModeInsert() + QLatin1String("/misc"); case DocumentsLocation: return sharedRoot + QLatin1String("/documents"); case PicturesLocation: return sharedRoot + QLatin1String("/photos"); case FontsLocation: // this is not a writable location return QString(); case MusicLocation: return sharedRoot + QLatin1String("/music"); case MoviesLocation: return sharedRoot + QLatin1String("/videos"); case DownloadLocation: return sharedRoot + QLatin1String("/downloads"); case ApplicationsLocation: return QString(); default: break; } return QString(); } QStringList QStandardPaths::standardLocations(StandardLocation type) { QStringList dirs; if (type == FontsLocation) return QStringList(QLatin1String("/base/usr/fonts")); if (type == AppDataLocation || type == AppLocalDataLocation) dirs.append(QDir::homePath() + testModeInsert() + QLatin1String("native/assets")); const QString localDir = writableLocation(type); dirs.prepend(localDir); return dirs; } QT_END_NAMESPACE #endif // QT_NO_STANDARDPATHS
bsd-3-clause
AOKP/external_chromium_org
chrome/third_party/mozilla_security_manager/nsUsageArrayHelper.cpp
94
3267
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Netscape security libraries. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * John Gardiner Myers <jgmyers@speakeasy.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "chrome/third_party/mozilla_security_manager/nsUsageArrayHelper.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace mozilla_security_manager { void GetCertUsageStrings(CERTCertificate* cert, std::vector<std::string>* out) { SECCertificateUsage usages = 0; // TODO(wtc): See if we should use X509Certificate::Verify instead. if (CERT_VerifyCertificateNow(CERT_GetDefaultCertDB(), cert, PR_TRUE, certificateUsageCheckAllUsages, NULL, &usages) == SECSuccess) { static const struct { SECCertificateUsage usage; int string_id; } usage_string_map[] = { {certificateUsageSSLClient, IDS_CERT_USAGE_SSL_CLIENT}, {certificateUsageSSLServer, IDS_CERT_USAGE_SSL_SERVER}, {certificateUsageSSLServerWithStepUp, IDS_CERT_USAGE_SSL_SERVER_WITH_STEPUP}, {certificateUsageEmailSigner, IDS_CERT_USAGE_EMAIL_SIGNER}, {certificateUsageEmailRecipient, IDS_CERT_USAGE_EMAIL_RECEIVER}, {certificateUsageObjectSigner, IDS_CERT_USAGE_OBJECT_SIGNER}, {certificateUsageSSLCA, IDS_CERT_USAGE_SSL_CA}, {certificateUsageStatusResponder, IDS_CERT_USAGE_STATUS_RESPONDER}, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(usage_string_map); ++i) { if (usages & usage_string_map[i].usage) out->push_back(l10n_util::GetStringUTF8( usage_string_map[i].string_id)); } } } } // namespace mozilla_security_manager
bsd-3-clause
wuxianghou/phantomjs
src/qt/qtbase/src/gui/doc/snippets/code/src_gui_painting_qpainter.cpp
102
5716
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Digia Plc and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] void SimpleExampleWidget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setPen(Qt::blue); painter.setFont(QFont("Arial", 30)); painter.drawText(rect(), Qt::AlignCenter, "Qt"); } //! [0] //! [1] void MyWidget::paintEvent(QPaintEvent *) { QPainter p; p.begin(this); p.drawLine(...); // drawing code p.end(); } //! [1] //! [2] void MyWidget::paintEvent(QPaintEvent *) { QPainter p(this); p.drawLine(...); // drawing code } //! [2] //! [3] painter->begin(0); // impossible - paint device cannot be 0 QPixmap image(0, 0); painter->begin(&image); // impossible - image.isNull() == true; painter->begin(myWidget); painter2->begin(myWidget); // impossible - only one painter at a time //! [3] //! [4] void QPainter::rotate(qreal angle) { QMatrix matrix; matrix.rotate(angle); setWorldMatrix(matrix, true); } //! [4] //! [5] QPainterPath path; path.moveTo(20, 80); path.lineTo(20, 30); path.cubicTo(80, 0, 50, 50, 80, 80); QPainter painter(this); painter.drawPath(path); //! [5] //! [6] QLineF line(10.0, 80.0, 90.0, 20.0); QPainter(this); painter.drawLine(line); //! [6] //! [7] QRectF rectangle(10.0, 20.0, 80.0, 60.0); QPainter painter(this); painter.drawRect(rectangle); //! [7] //! [8] QRectF rectangle(10.0, 20.0, 80.0, 60.0); QPainter painter(this); painter.drawRoundedRect(rectangle, 20.0, 15.0); //! [8] //! [9] QRectF rectangle(10.0, 20.0, 80.0, 60.0); QPainter painter(this); painter.drawEllipse(rectangle); //! [9] //! [10] QRectF rectangle(10.0, 20.0, 80.0, 60.0); int startAngle = 30 * 16; int spanAngle = 120 * 16; QPainter painter(this); painter.drawArc(rectangle, startAngle, spanAngle); //! [10] //! [11] QRectF rectangle(10.0, 20.0, 80.0, 60.0); int startAngle = 30 * 16; int spanAngle = 120 * 16; QPainter painter(this); painter.drawPie(rectangle, startAngle, spanAngle); //! [11] //! [12] QRectF rectangle(10.0, 20.0, 80.0, 60.0); int startAngle = 30 * 16; int spanAngle = 120 * 16; QPainter painter(this); painter.drawChord(rect, startAngle, spanAngle); //! [12] //! [13] static const QPointF points[3] = { QPointF(10.0, 80.0), QPointF(20.0, 10.0), QPointF(80.0, 30.0), }; QPainter painter(this); painter.drawPolyline(points, 3); //! [13] //! [14] static const QPointF points[4] = { QPointF(10.0, 80.0), QPointF(20.0, 10.0), QPointF(80.0, 30.0), QPointF(90.0, 70.0) }; QPainter painter(this); painter.drawPolygon(points, 4); //! [14] //! [15] static const QPointF points[4] = { QPointF(10.0, 80.0), QPointF(20.0, 10.0), QPointF(80.0, 30.0), QPointF(90.0, 70.0) }; QPainter painter(this); painter.drawConvexPolygon(points, 4); //! [15] //! [16] QRectF target(10.0, 20.0, 80.0, 60.0); QRectF source(0.0, 0.0, 70.0, 40.0); QPixmap pixmap(":myPixmap.png"); QPainter(this); painter.drawPixmap(target, pixmap, source); //! [16] //! [17] QPainter painter(this); painter.drawText(rect, Qt::AlignCenter, tr("Qt\nProject")); //! [17] //! [18] QPicture picture; QPointF point(10.0, 20.0) picture.load("drawing.pic"); QPainter painter(this); painter.drawPicture(0, 0, picture); //! [18] //! [19] fillRect(rectangle, background()). //! [19] //! [20] QRectF target(10.0, 20.0, 80.0, 60.0); QRectF source(0.0, 0.0, 70.0, 40.0); QImage image(":/images/myImage.png"); QPainter painter(this); painter.drawImage(target, image, source); //! [20] //! [21] QPainter painter(this); painter.fillRect(0, 0, 128, 128, Qt::green); painter.beginNativePainting(); glEnable(GL_SCISSOR_TEST); glScissor(0, 0, 64, 64); glClearColor(1, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_SCISSOR_TEST); painter.endNativePainting(); //! [21]
bsd-3-clause
nuwaf/badvpn
ncd/modules/if.c
360
3404
/** * @file if.c * @author Ambroz Bizjak <ambrop7@gmail.com> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @section DESCRIPTION * * Conditional module. * * Synopsis: if(string cond) * Description: on initialization, transitions to UP state if cond equals "true", else * remains in the DOWN state indefinitely. * * Synopsis: ifnot(string cond) * Description: on initialization, transitions to UP state if cond does not equal "true", else * remains in the DOWN state indefinitely. */ #include <stdlib.h> #include <string.h> #include <ncd/NCDModule.h> #include <ncd/extra/value_utils.h> #include <generated/blog_channel_ncd_if.h> #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__) static void new_templ (NCDModuleInst *i, const struct NCDModuleInst_new_params *params, int is_not) { // check arguments NCDValRef arg; if (!NCDVal_ListRead(params->args, 1, &arg)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsString(arg)) { ModuleLog(i, BLOG_ERROR, "wrong type"); goto fail0; } // compute logical value of argument int c = ncd_read_boolean(arg); // signal up if needed if ((is_not && !c) || (!is_not && c)) { NCDModuleInst_Backend_Up(i); } return; fail0: NCDModuleInst_Backend_DeadError(i); } static void func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { new_templ(i, params, 0); } static void func_new_not (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { new_templ(i, params, 1); } static struct NCDModule modules[] = { { .type = "if", .func_new2 = func_new }, { .type = "ifnot", .func_new2 = func_new_not }, { .type = NULL } }; const struct NCDModuleGroup ncdmodule_if = { .modules = modules };
bsd-3-clause
MaDKaTZe/phantomjs
src/qt/qtbase/src/gui/doc/snippets/code/src_gui_qopenglshaderprogram.cpp
105
3307
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Digia Plc and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] QOpenGLShader shader(QOpenGLShader::Vertex); shader.compileSourceCode(code); QOpenGLShaderProgram program(context); program.addShader(shader); program.link(); program.bind(); //! [0] //! [1] program.addShaderFromSourceCode(QOpenGLShader::Vertex, "attribute highp vec4 vertex;\n" "uniform highp mat4 matrix;\n" "void main(void)\n" "{\n" " gl_Position = matrix * vertex;\n" "}"); program.addShaderFromSourceCode(QOpenGLShader::Fragment, "uniform mediump vec4 color;\n" "void main(void)\n" "{\n" " gl_FragColor = color;\n" "}"); program.link(); program.bind(); int vertexLocation = program.attributeLocation("vertex"); int matrixLocation = program.uniformLocation("matrix"); int colorLocation = program.uniformLocation("color"); //! [1] //! [2] static GLfloat const triangleVertices[] = { 60.0f, 10.0f, 0.0f, 110.0f, 110.0f, 0.0f, 10.0f, 110.0f, 0.0f }; QColor color(0, 255, 0, 255); QMatrix4x4 pmvMatrix; pmvMatrix.ortho(rect()); program.enableAttributeArray(vertexLocation); program.setAttributeArray(vertexLocation, triangleVertices, 3); program.setUniformValue(matrixLocation, pmvMatrix); program.setUniformValue(colorLocation, color); glDrawArrays(GL_TRIANGLES, 0, 3); program.disableAttributeArray(vertexLocation); //! [2]
bsd-3-clause
grevutiu-gabriel/phantomjs
src/qt/qtwebkit/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.cpp
115
13320
/* * Copyright (C) 2012 Igalia S.L. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "WebKitWebResource.h" #include "WebData.h" #include "WebFrameProxy.h" #include "WebKitMarshal.h" #include "WebKitURIRequest.h" #include "WebKitWebResourcePrivate.h" #include <glib/gi18n-lib.h> #include <wtf/gobject/GRefPtr.h> #include <wtf/text/CString.h> using namespace WebKit; /** * SECTION: WebKitWebResource * @Short_description: Represents a resource at the end of a URI * @Title: WebKitWebResource * * A #WebKitWebResource encapsulates content for each resource at the * end of a particular URI. For example, one #WebKitWebResource will * be created for each separate image and stylesheet when a page is * loaded. * * You can access the response and the URI for a given * #WebKitWebResource, using webkit_web_resource_get_uri() and * webkit_web_resource_get_response(), as well as the raw data, using * webkit_web_resource_get_data(). * */ enum { SENT_REQUEST, RECEIVED_DATA, FINISHED, FAILED, LAST_SIGNAL }; enum { PROP_0, PROP_URI, PROP_RESPONSE }; struct _WebKitWebResourcePrivate { RefPtr<WebFrameProxy> frame; CString uri; GRefPtr<WebKitURIResponse> response; bool isMainResource; }; WEBKIT_DEFINE_TYPE(WebKitWebResource, webkit_web_resource, G_TYPE_OBJECT) static guint signals[LAST_SIGNAL] = { 0, }; static void webkitWebResourceGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) { WebKitWebResource* resource = WEBKIT_WEB_RESOURCE(object); switch (propId) { case PROP_URI: g_value_set_string(value, webkit_web_resource_get_uri(resource)); break; case PROP_RESPONSE: g_value_set_object(value, webkit_web_resource_get_response(resource)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); } } static void webkit_web_resource_class_init(WebKitWebResourceClass* resourceClass) { GObjectClass* objectClass = G_OBJECT_CLASS(resourceClass); objectClass->get_property = webkitWebResourceGetProperty; /** * WebKitWebResource:uri: * * The current active URI of the #WebKitWebResource. * See webkit_web_resource_get_uri() for more details. */ g_object_class_install_property(objectClass, PROP_URI, g_param_spec_string("uri", _("URI"), _("The current active URI of the resource"), 0, WEBKIT_PARAM_READABLE)); /** * WebKitWebResource:response: * * The #WebKitURIResponse associated with this resource. */ g_object_class_install_property(objectClass, PROP_RESPONSE, g_param_spec_object("response", _("Response"), _("The response of the resource"), WEBKIT_TYPE_URI_RESPONSE, WEBKIT_PARAM_READABLE)); /** * WebKitWebResource::sent-request: * @resource: the #WebKitWebResource * @request: a #WebKitURIRequest * @redirected_response: a #WebKitURIResponse, or %NULL * * This signal is emitted when @request has been sent to the * server. In case of a server redirection this signal is * emitted again with the @request argument containing the new * request sent to the server due to the redirection and the * @redirected_response parameter containing the response * received by the server for the initial request. */ signals[SENT_REQUEST] = g_signal_new("sent-request", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, 0, 0, webkit_marshal_VOID__OBJECT_OBJECT, G_TYPE_NONE, 2, WEBKIT_TYPE_URI_REQUEST, WEBKIT_TYPE_URI_RESPONSE); /** * WebKitWebResource::received-data: * @resource: the #WebKitWebResource * @data_length: the length of data received in bytes * * This signal is emitted after response is received, * every time new data has been received. It's * useful to know the progress of the resource load operation. */ signals[RECEIVED_DATA] = g_signal_new("received-data", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, 0, 0, webkit_marshal_VOID__UINT64, G_TYPE_NONE, 1, G_TYPE_UINT64); /** * WebKitWebResource::finished: * @resource: the #WebKitWebResource * * This signal is emitted when the resource load finishes successfully * or due to an error. In case of errors #WebKitWebResource::failed signal * is emitted before this one. */ signals[FINISHED] = g_signal_new("finished", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, 0, 0, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); /** * WebKitWebResource::failed: * @resource: the #WebKitWebResource * @error: the #GError that was triggered * * This signal is emitted when an error occurs during the resource * load operation. */ signals[FAILED] = g_signal_new("failed", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, 0, 0, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); } static void webkitWebResourceUpdateURI(WebKitWebResource* resource, const CString& requestURI) { if (resource->priv->uri == requestURI) return; resource->priv->uri = requestURI; g_object_notify(G_OBJECT(resource), "uri"); } WebKitWebResource* webkitWebResourceCreate(WebFrameProxy* frame, WebKitURIRequest* request, bool isMainResource) { ASSERT(frame); WebKitWebResource* resource = WEBKIT_WEB_RESOURCE(g_object_new(WEBKIT_TYPE_WEB_RESOURCE, NULL)); resource->priv->frame = frame; resource->priv->uri = webkit_uri_request_get_uri(request); resource->priv->isMainResource = isMainResource; return resource; } void webkitWebResourceSentRequest(WebKitWebResource* resource, WebKitURIRequest* request, WebKitURIResponse* redirectResponse) { webkitWebResourceUpdateURI(resource, webkit_uri_request_get_uri(request)); g_signal_emit(resource, signals[SENT_REQUEST], 0, request, redirectResponse); } void webkitWebResourceSetResponse(WebKitWebResource* resource, WebKitURIResponse* response) { resource->priv->response = response; g_object_notify(G_OBJECT(resource), "response"); } void webkitWebResourceNotifyProgress(WebKitWebResource* resource, guint64 bytesReceived) { g_signal_emit(resource, signals[RECEIVED_DATA], 0, bytesReceived); } void webkitWebResourceFinished(WebKitWebResource* resource) { g_signal_emit(resource, signals[FINISHED], 0, NULL); } void webkitWebResourceFailed(WebKitWebResource* resource, GError* error) { g_signal_emit(resource, signals[FAILED], 0, error); g_signal_emit(resource, signals[FINISHED], 0, NULL); } WebFrameProxy* webkitWebResourceGetFrame(WebKitWebResource* resource) { return resource->priv->frame.get(); } /** * webkit_web_resource_get_uri: * @resource: a #WebKitWebResource * * Returns the current active URI of @resource. The active URI might change during * a load operation: * * <orderedlist> * <listitem><para> * When the resource load starts, the active URI is the requested URI * </para></listitem> * <listitem><para> * When the initial request is sent to the server, #WebKitWebResource::sent-request * signal is emitted without a redirected response, the active URI is the URI of * the request sent to the server. * </para></listitem> * <listitem><para> * In case of a server redirection, #WebKitWebResource::sent-request signal * is emitted again with a redirected response, the active URI is the URI the request * was redirected to. * </para></listitem> * <listitem><para> * When the response is received from the server, the active URI is the final * one and it will not change again. * </para></listitem> * </orderedlist> * * You can monitor the active URI by connecting to the notify::uri * signal of @resource. * * Returns: the current active URI of @resource */ const char* webkit_web_resource_get_uri(WebKitWebResource* resource) { g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); return resource->priv->uri.data(); } /** * webkit_web_resource_get_response: * @resource: a #WebKitWebResource * * Retrieves the #WebKitURIResponse of the resource load operation. * This method returns %NULL if called before the response * is received from the server. You can connect to notify::response * signal to be notified when the response is received. * * Returns: (transfer none): the #WebKitURIResponse, or %NULL if * the response hasn't been received yet. */ WebKitURIResponse* webkit_web_resource_get_response(WebKitWebResource* resource) { g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); return resource->priv->response.get(); } struct ResourceGetDataAsyncData { RefPtr<WebData> webData; }; WEBKIT_DEFINE_ASYNC_DATA_STRUCT(ResourceGetDataAsyncData) static void resourceDataCallback(WKDataRef wkData, WKErrorRef, void* context) { GRefPtr<GTask> task = adoptGRef(G_TASK(context)); ResourceGetDataAsyncData* data = static_cast<ResourceGetDataAsyncData*>(g_task_get_task_data(task.get())); data->webData = toImpl(wkData); g_task_return_boolean(task.get(), TRUE); } /** * webkit_web_resource_get_data: * @resource: a #WebKitWebResource * @cancellable: (allow-none): a #GCancellable or %NULL to ignore * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied * @user_data: (closure): the data to pass to callback function * * Asynchronously get the raw data for @resource. * * When the operation is finished, @callback will be called. You can then call * webkit_web_resource_get_data_finish() to get the result of the operation. */ void webkit_web_resource_get_data(WebKitWebResource* resource, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) { g_return_if_fail(WEBKIT_IS_WEB_RESOURCE(resource)); GTask* task = g_task_new(resource, cancellable, callback, userData); g_task_set_task_data(task, createResourceGetDataAsyncData(), reinterpret_cast<GDestroyNotify>(destroyResourceGetDataAsyncData)); if (resource->priv->isMainResource) resource->priv->frame->getMainResourceData(DataCallback::create(task, resourceDataCallback)); else { String url = String::fromUTF8(resource->priv->uri.data()); resource->priv->frame->getResourceData(WebURL::create(url).get(), DataCallback::create(task, resourceDataCallback)); } } /** * webkit_web_resource_get_data_finish: * @resource: a #WebKitWebResource * @result: a #GAsyncResult * @length: (out): return location for the length of the resource data * @error: return location for error or %NULL to ignore * * Finish an asynchronous operation started with webkit_web_resource_get_data(). * * Returns: (transfer full): a string with the data of @resource, or %NULL in case * of error. if @length is not %NULL, the size of the data will be assigned to it. */ guchar* webkit_web_resource_get_data_finish(WebKitWebResource* resource, GAsyncResult* result, gsize* length, GError** error) { g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); g_return_val_if_fail(g_task_is_valid(result, resource), 0); GTask* task = G_TASK(result); if (!g_task_propagate_boolean(task, error)) return 0; ResourceGetDataAsyncData* data = static_cast<ResourceGetDataAsyncData*>(g_task_get_task_data(task)); if (length) *length = data->webData->size(); return static_cast<guchar*>(g_memdup(data->webData->bytes(), data->webData->size())); }
bsd-3-clause
yoki/phantomjs
src/qt/qtwebkit/Source/WebKit/qt/Api/qwebdatabase.cpp
116
5514
/* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "qwebdatabase.h" #include "qwebdatabase_p.h" #include "qwebsecurityorigin.h" #include "qwebsecurityorigin_p.h" #include "DatabaseDetails.h" #include "DatabaseManager.h" using namespace WebCore; /*! \class QWebDatabase \since 4.5 \brief The QWebDatabase class provides access to HTML 5 databases created with JavaScript. \inmodule QtWebKit The upcoming HTML 5 standard includes support for SQL databases that web sites can create and access on a local computer through JavaScript. QWebDatabase is the C++ interface to these databases. Databases are grouped together in security origins. To get access to all databases defined by a security origin, use QWebSecurityOrigin::databases(). Each database has an internal name(), as well as a user-friendly name, provided by displayName(). These names are specified when creating the database in the JavaScript code. WebKit uses SQLite to create and access the local SQL databases. The location of the database file in the local file system is returned by fileName(). You can access the database directly through the \l{Qt SQL} database module. For each database the web site can define an expectedSize(). The current size of the database in bytes is returned by size(). For more information refer to the \l{http://dev.w3.org/html5/webdatabase/}{HTML5 Web SQL Database Draft Standard}. \sa QWebSecurityOrigin */ /*! Constructs a web database from \a other. */ QWebDatabase::QWebDatabase(const QWebDatabase& other) : d(other.d) { } /*! Assigns the \a other web database to this. */ QWebDatabase& QWebDatabase::operator=(const QWebDatabase& other) { d = other.d; return *this; } /*! Returns the name of the database. */ QString QWebDatabase::name() const { return d->name; } /*! Returns the name of the database in a format that is suitable for display to the user. */ QString QWebDatabase::displayName() const { #if ENABLE(SQL_DATABASE) DatabaseDetails details = DatabaseManager::manager().detailsForNameAndOrigin(d->name, d->origin.get()); return details.displayName(); #else return QString(); #endif } /*! Returns the expected size of the database in bytes as defined by the web author. */ qint64 QWebDatabase::expectedSize() const { #if ENABLE(SQL_DATABASE) DatabaseDetails details = DatabaseManager::manager().detailsForNameAndOrigin(d->name, d->origin.get()); return details.expectedUsage(); #else return 0; #endif } /*! Returns the current size of the database in bytes. */ qint64 QWebDatabase::size() const { #if ENABLE(SQL_DATABASE) DatabaseDetails details = DatabaseManager::manager().detailsForNameAndOrigin(d->name, d->origin.get()); return details.currentUsage(); #else return 0; #endif } /*! \internal */ QWebDatabase::QWebDatabase(QWebDatabasePrivate* priv) { d = priv; } /*! Returns the file name of the web database. The name can be used to access the database through the \l{Qt SQL} database module, for example: \code QWebDatabase webdb = ... QSqlDatabase sqldb = QSqlDatabase::addDatabase("QSQLITE", "myconnection"); sqldb.setDatabaseName(webdb.fileName()); if (sqldb.open()) { QStringList tables = sqldb.tables(); ... } \endcode \note Concurrent access to a database from multiple threads or processes is not very efficient because SQLite is used as WebKit's database backend. */ QString QWebDatabase::fileName() const { #if ENABLE(SQL_DATABASE) return DatabaseManager::manager().fullPathForDatabase(d->origin.get(), d->name, false); #else return QString(); #endif } /*! Returns the databases's security origin. */ QWebSecurityOrigin QWebDatabase::origin() const { QWebSecurityOriginPrivate* priv = new QWebSecurityOriginPrivate(d->origin.get()); QWebSecurityOrigin origin(priv); return origin; } /*! Removes the database \a db from its security origin. All data stored in the database \a db will be destroyed. */ void QWebDatabase::removeDatabase(const QWebDatabase& db) { #if ENABLE(SQL_DATABASE) DatabaseManager::manager().deleteDatabase(db.d->origin.get(), db.d->name); #endif } /*! \since 4.6 Deletes all web databases in the configured offline storage path. \sa QWebSettings::setOfflineStoragePath() */ void QWebDatabase::removeAllDatabases() { #if ENABLE(SQL_DATABASE) DatabaseManager::manager().deleteAllDatabases(); #endif } /*! Destroys the web database object. The data within this database is \b not destroyed. */ QWebDatabase::~QWebDatabase() { }
bsd-3-clause
VinceZK/phantomjs
src/qt/qtwebkit/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.cpp
117
3755
/* * Copyright (C) 2012 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WKEinaSharedString.h" #include <WebKit2/WKAPICast.h> #include <WebKit2/WKString.h> #include <WebKit2/WKURL.h> #include <wtf/text/CString.h> using namespace WebKit; template <typename WKRefType> ALWAYS_INLINE const char* fromRefType(WKRefType strRef, bool adopt = false) { const char* res = 0; if (strRef) { res = eina_stringshare_add(toImpl(strRef)->string().utf8().data()); ASSERT(res); if (adopt) WKRelease(strRef); } return res; } WKEinaSharedString::WKEinaSharedString(const WKEinaSharedString& other) : m_string(eina_stringshare_ref(other.m_string)) { } WKEinaSharedString::WKEinaSharedString(const char* str) : m_string(eina_stringshare_add(str)) { } WKEinaSharedString::WKEinaSharedString(WKAdoptTag adoptTag, WKStringRef stringRef) : m_string(fromRefType(stringRef, /*adopt*/ true)) { ASSERT_UNUSED(adoptTag, adoptTag == AdoptWK); // Guard for future enum changes. } WKEinaSharedString::WKEinaSharedString(WKStringRef stringRef) : m_string(fromRefType(stringRef)) { } WKEinaSharedString::WKEinaSharedString(WKAdoptTag adoptTag, WKURLRef urlRef) : m_string(fromRefType(urlRef, /*adopt*/ true)) { ASSERT_UNUSED(adoptTag, adoptTag == AdoptWK); // Guard for future enum changes. } WKEinaSharedString::WKEinaSharedString(WKURLRef urlRef) : m_string(fromRefType(urlRef)) { } WKEinaSharedString::~WKEinaSharedString() { if (m_string) eina_stringshare_del(m_string); } WKEinaSharedString& WKEinaSharedString::operator=(const WKEinaSharedString& other) { if (this != &other) { if (m_string) eina_stringshare_del(m_string); m_string = eina_stringshare_ref(other.m_string); } return *this; } WKEinaSharedString& WKEinaSharedString::operator=(const char* str) { eina_stringshare_replace(&m_string, str); return *this; } bool WKEinaSharedString::operator==(const char* str) const { return (!str || !m_string) ? (str == m_string) : !strcmp(m_string, str); } WKEinaSharedString WKEinaSharedString::adopt(Eina_Stringshare* string) { WKEinaSharedString sharedString; sharedString.m_string = static_cast<const char*>(string); return sharedString; } Eina_Stringshare* WKEinaSharedString::leakString() { Eina_Stringshare* sharedString = m_string; m_string = 0; return sharedString; }
bsd-3-clause
Andrey-Pavlov/phantomjs
src/qt/qtwebkit/Source/WebKit2/WebProcess/Cookies/soup/WebCookieManagerSoup.cpp
118
3978
/* * Copyright (C) 2011 Samsung Electronics. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebCookieManager.h" #include "ChildProcess.h" #include "WebKitSoupCookieJarSqlite.h" #include <WebCore/CookieJarSoup.h> #include <WebCore/ResourceHandle.h> #include <libsoup/soup.h> #include <wtf/gobject/GRefPtr.h> #include <wtf/text/CString.h> using namespace WebCore; namespace WebKit { void WebCookieManager::platformSetHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { SoupCookieJar* cookieJar = WebCore::soupCookieJar(); SoupCookieJarAcceptPolicy soupPolicy; soupPolicy = SOUP_COOKIE_JAR_ACCEPT_ALWAYS; switch (policy) { case HTTPCookieAcceptPolicyAlways: soupPolicy = SOUP_COOKIE_JAR_ACCEPT_ALWAYS; break; case HTTPCookieAcceptPolicyNever: soupPolicy = SOUP_COOKIE_JAR_ACCEPT_NEVER; break; case HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain: soupPolicy = SOUP_COOKIE_JAR_ACCEPT_NO_THIRD_PARTY; break; } soup_cookie_jar_set_accept_policy(cookieJar, soupPolicy); } HTTPCookieAcceptPolicy WebCookieManager::platformGetHTTPCookieAcceptPolicy() { SoupCookieJar* cookieJar = WebCore::soupCookieJar(); SoupCookieJarAcceptPolicy soupPolicy; HTTPCookieAcceptPolicy policy; soupPolicy = soup_cookie_jar_get_accept_policy(cookieJar); switch (soupPolicy) { case SOUP_COOKIE_JAR_ACCEPT_ALWAYS: policy = HTTPCookieAcceptPolicyAlways; break; case SOUP_COOKIE_JAR_ACCEPT_NEVER: policy = HTTPCookieAcceptPolicyNever; break; case SOUP_COOKIE_JAR_ACCEPT_NO_THIRD_PARTY: policy = HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain; break; default: policy = HTTPCookieAcceptPolicyAlways; } return policy; } void WebCookieManager::setCookiePersistentStorage(const String& storagePath, uint32_t storageType) { GRefPtr<SoupCookieJar> jar; switch (storageType) { case SoupCookiePersistentStorageText: jar = adoptGRef(soup_cookie_jar_text_new(storagePath.utf8().data(), FALSE)); break; case SoupCookiePersistentStorageSQLite: jar = adoptGRef(webkitSoupCookieJarSqliteNew(storagePath)); break; default: ASSERT_NOT_REACHED(); } SoupCookieJar* currentJar = WebCore::soupCookieJar(); soup_cookie_jar_set_accept_policy(jar.get(), soup_cookie_jar_get_accept_policy(currentJar)); SoupSession* session = ResourceHandle::defaultSession(); soup_session_remove_feature(session, SOUP_SESSION_FEATURE(currentJar)); soup_session_add_feature(session, SOUP_SESSION_FEATURE(jar.get())); WebCore::setSoupCookieJar(jar.get()); } } // namespace WebKit
bsd-3-clause
bettiolo/phantomjs
src/qt/qtwebkit/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.cpp
118
4595
/* * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebApplicationCacheManagerProxy.h" #include "SecurityOriginData.h" #include "WebApplicationCacheManagerMessages.h" #include "WebApplicationCacheManagerProxyMessages.h" #include "WebContext.h" #include "WebSecurityOrigin.h" namespace WebKit { const char* WebApplicationCacheManagerProxy::supplementName() { return "WebApplicationCacheManagerProxy"; } PassRefPtr<WebApplicationCacheManagerProxy> WebApplicationCacheManagerProxy::create(WebContext* context) { return adoptRef(new WebApplicationCacheManagerProxy(context)); } WebApplicationCacheManagerProxy::WebApplicationCacheManagerProxy(WebContext* context) : WebContextSupplement(context) { context->addMessageReceiver(Messages::WebApplicationCacheManagerProxy::messageReceiverName(), this); } WebApplicationCacheManagerProxy::~WebApplicationCacheManagerProxy() { } void WebApplicationCacheManagerProxy::contextDestroyed() { invalidateCallbackMap(m_arrayCallbacks); } void WebApplicationCacheManagerProxy::processDidClose(WebProcessProxy*) { invalidateCallbackMap(m_arrayCallbacks); } bool WebApplicationCacheManagerProxy::shouldTerminate(WebProcessProxy*) const { return m_arrayCallbacks.isEmpty(); } void WebApplicationCacheManagerProxy::refWebContextSupplement() { APIObject::ref(); } void WebApplicationCacheManagerProxy::derefWebContextSupplement() { APIObject::deref(); } void WebApplicationCacheManagerProxy::getApplicationCacheOrigins(PassRefPtr<ArrayCallback> prpCallback) { if (!context()) return; RefPtr<ArrayCallback> callback = prpCallback; uint64_t callbackID = callback->callbackID(); m_arrayCallbacks.set(callbackID, callback.release()); // FIXME (Multi-WebProcess): <rdar://problem/12239765> Make manipulating cache information work with per-tab WebProcess. context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::GetApplicationCacheOrigins(callbackID)); } void WebApplicationCacheManagerProxy::didGetApplicationCacheOrigins(const Vector<SecurityOriginData>& originDatas, uint64_t callbackID) { RefPtr<ArrayCallback> callback = m_arrayCallbacks.take(callbackID); performAPICallbackWithSecurityOriginDataVector(originDatas, callback.get()); } void WebApplicationCacheManagerProxy::deleteEntriesForOrigin(WebSecurityOrigin* origin) { if (!context()) return; SecurityOriginData securityOriginData; securityOriginData.protocol = origin->protocol(); securityOriginData.host = origin->host(); securityOriginData.port = origin->port(); // FIXME (Multi-WebProcess): <rdar://problem/12239765> Make manipulating cache information work with per-tab WebProcess. context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::DeleteEntriesForOrigin(securityOriginData)); } void WebApplicationCacheManagerProxy::deleteAllEntries() { if (!context()) return; // FIXME (Multi-WebProcess): <rdar://problem/12239765> Make manipulating cache information work with per-tab WebProcess. context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::DeleteAllEntries()); } } // namespace WebKit
bsd-3-clause
mapbased/phantomjs
src/qt/qtwebkit/Source/WebCore/inspector/InspectorValues.cpp
119
21225
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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. */ #include "config.h" #include "InspectorValues.h" #include <wtf/DecimalNumber.h> #include <wtf/dtoa.h> #include <wtf/text/StringBuilder.h> namespace WebCore { namespace { static const int stackLimit = 1000; enum Token { OBJECT_BEGIN, OBJECT_END, ARRAY_BEGIN, ARRAY_END, STRING, NUMBER, BOOL_TRUE, BOOL_FALSE, NULL_TOKEN, LIST_SEPARATOR, OBJECT_PAIR_SEPARATOR, INVALID_TOKEN, }; const char* const nullString = "null"; const char* const trueString = "true"; const char* const falseString = "false"; bool parseConstToken(const UChar* start, const UChar* end, const UChar** tokenEnd, const char* token) { while (start < end && *token != '\0' && *start++ == *token++) { } if (*token != '\0') return false; *tokenEnd = start; return true; } bool readInt(const UChar* start, const UChar* end, const UChar** tokenEnd, bool canHaveLeadingZeros) { if (start == end) return false; bool haveLeadingZero = '0' == *start; int length = 0; while (start < end && '0' <= *start && *start <= '9') { ++start; ++length; } if (!length) return false; if (!canHaveLeadingZeros && length > 1 && haveLeadingZero) return false; *tokenEnd = start; return true; } bool parseNumberToken(const UChar* start, const UChar* end, const UChar** tokenEnd) { // We just grab the number here. We validate the size in DecodeNumber. // According to RFC4627, a valid number is: [minus] int [frac] [exp] if (start == end) return false; UChar c = *start; if ('-' == c) ++start; if (!readInt(start, end, &start, false)) return false; if (start == end) { *tokenEnd = start; return true; } // Optional fraction part c = *start; if ('.' == c) { ++start; if (!readInt(start, end, &start, true)) return false; if (start == end) { *tokenEnd = start; return true; } c = *start; } // Optional exponent part if ('e' == c || 'E' == c) { ++start; if (start == end) return false; c = *start; if ('-' == c || '+' == c) { ++start; if (start == end) return false; } if (!readInt(start, end, &start, true)) return false; } *tokenEnd = start; return true; } bool readHexDigits(const UChar* start, const UChar* end, const UChar** tokenEnd, int digits) { if (end - start < digits) return false; for (int i = 0; i < digits; ++i) { UChar c = *start++; if (!(('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'))) return false; } *tokenEnd = start; return true; } bool parseStringToken(const UChar* start, const UChar* end, const UChar** tokenEnd) { while (start < end) { UChar c = *start++; if ('\\' == c) { c = *start++; // Make sure the escaped char is valid. switch (c) { case 'x': if (!readHexDigits(start, end, &start, 2)) return false; break; case 'u': if (!readHexDigits(start, end, &start, 4)) return false; break; case '\\': case '/': case 'b': case 'f': case 'n': case 'r': case 't': case 'v': case '"': break; default: return false; } } else if ('"' == c) { *tokenEnd = start; return true; } } return false; } Token parseToken(const UChar* start, const UChar* end, const UChar** tokenStart, const UChar** tokenEnd) { while (start < end && isSpaceOrNewline(*start)) ++start; if (start == end) return INVALID_TOKEN; *tokenStart = start; switch (*start) { case 'n': if (parseConstToken(start, end, tokenEnd, nullString)) return NULL_TOKEN; break; case 't': if (parseConstToken(start, end, tokenEnd, trueString)) return BOOL_TRUE; break; case 'f': if (parseConstToken(start, end, tokenEnd, falseString)) return BOOL_FALSE; break; case '[': *tokenEnd = start + 1; return ARRAY_BEGIN; case ']': *tokenEnd = start + 1; return ARRAY_END; case ',': *tokenEnd = start + 1; return LIST_SEPARATOR; case '{': *tokenEnd = start + 1; return OBJECT_BEGIN; case '}': *tokenEnd = start + 1; return OBJECT_END; case ':': *tokenEnd = start + 1; return OBJECT_PAIR_SEPARATOR; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': if (parseNumberToken(start, end, tokenEnd)) return NUMBER; break; case '"': if (parseStringToken(start + 1, end, tokenEnd)) return STRING; break; } return INVALID_TOKEN; } inline int hexToInt(UChar c) { if ('0' <= c && c <= '9') return c - '0'; if ('A' <= c && c <= 'F') return c - 'A' + 10; if ('a' <= c && c <= 'f') return c - 'a' + 10; ASSERT_NOT_REACHED(); return 0; } bool decodeString(const UChar* start, const UChar* end, StringBuilder* output) { while (start < end) { UChar c = *start++; if ('\\' != c) { output->append(c); continue; } c = *start++; switch (c) { case '"': case '/': case '\\': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\v'; break; case 'x': c = (hexToInt(*start) << 4) + hexToInt(*(start + 1)); start += 2; break; case 'u': c = (hexToInt(*start) << 12) + (hexToInt(*(start + 1)) << 8) + (hexToInt(*(start + 2)) << 4) + hexToInt(*(start + 3)); start += 4; break; default: return false; } output->append(c); } return true; } bool decodeString(const UChar* start, const UChar* end, String* output) { if (start == end) { *output = ""; return true; } if (start > end) return false; StringBuilder buffer; buffer.reserveCapacity(end - start); if (!decodeString(start, end, &buffer)) return false; *output = buffer.toString(); return true; } PassRefPtr<InspectorValue> buildValue(const UChar* start, const UChar* end, const UChar** valueTokenEnd, int depth) { if (depth > stackLimit) return 0; RefPtr<InspectorValue> result; const UChar* tokenStart; const UChar* tokenEnd; Token token = parseToken(start, end, &tokenStart, &tokenEnd); switch (token) { case INVALID_TOKEN: return 0; case NULL_TOKEN: result = InspectorValue::null(); break; case BOOL_TRUE: result = InspectorBasicValue::create(true); break; case BOOL_FALSE: result = InspectorBasicValue::create(false); break; case NUMBER: { bool ok; double value = charactersToDouble(tokenStart, tokenEnd - tokenStart, &ok); if (!ok) return 0; result = InspectorBasicValue::create(value); break; } case STRING: { String value; bool ok = decodeString(tokenStart + 1, tokenEnd - 1, &value); if (!ok) return 0; result = InspectorString::create(value); break; } case ARRAY_BEGIN: { RefPtr<InspectorArray> array = InspectorArray::create(); start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); while (token != ARRAY_END) { RefPtr<InspectorValue> arrayNode = buildValue(start, end, &tokenEnd, depth + 1); if (!arrayNode) return 0; array->pushValue(arrayNode); // After a list value, we expect a comma or the end of the list. start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); if (token == LIST_SEPARATOR) { start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); if (token == ARRAY_END) return 0; } else if (token != ARRAY_END) { // Unexpected value after list value. Bail out. return 0; } } if (token != ARRAY_END) return 0; result = array.release(); break; } case OBJECT_BEGIN: { RefPtr<InspectorObject> object = InspectorObject::create(); start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); while (token != OBJECT_END) { if (token != STRING) return 0; String key; if (!decodeString(tokenStart + 1, tokenEnd - 1, &key)) return 0; start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); if (token != OBJECT_PAIR_SEPARATOR) return 0; start = tokenEnd; RefPtr<InspectorValue> value = buildValue(start, end, &tokenEnd, depth + 1); if (!value) return 0; object->setValue(key, value); start = tokenEnd; // After a key/value pair, we expect a comma or the end of the // object. token = parseToken(start, end, &tokenStart, &tokenEnd); if (token == LIST_SEPARATOR) { start = tokenEnd; token = parseToken(start, end, &tokenStart, &tokenEnd); if (token == OBJECT_END) return 0; } else if (token != OBJECT_END) { // Unexpected value after last object value. Bail out. return 0; } } if (token != OBJECT_END) return 0; result = object.release(); break; } default: // We got a token that's not a value. return 0; } *valueTokenEnd = tokenEnd; return result.release(); } inline bool escapeChar(UChar c, StringBuilder* dst) { switch (c) { case '\b': dst->append("\\b", 2); break; case '\f': dst->append("\\f", 2); break; case '\n': dst->append("\\n", 2); break; case '\r': dst->append("\\r", 2); break; case '\t': dst->append("\\t", 2); break; case '\\': dst->append("\\\\", 2); break; case '"': dst->append("\\\"", 2); break; default: return false; } return true; } inline void doubleQuoteString(const String& str, StringBuilder* dst) { dst->append('"'); for (unsigned i = 0; i < str.length(); ++i) { UChar c = str[i]; if (!escapeChar(c, dst)) { if (c < 32 || c > 126 || c == '<' || c == '>') { // 1. Escaping <, > to prevent script execution. // 2. Technically, we could also pass through c > 126 as UTF8, but this // is also optional. It would also be a pain to implement here. unsigned int symbol = static_cast<unsigned int>(c); String symbolCode = String::format("\\u%04X", symbol); dst->append(symbolCode.characters(), symbolCode.length()); } else dst->append(c); } } dst->append('"'); } } // anonymous namespace bool InspectorValue::asBoolean(bool*) const { return false; } bool InspectorValue::asNumber(double*) const { return false; } bool InspectorValue::asNumber(long*) const { return false; } bool InspectorValue::asNumber(int*) const { return false; } bool InspectorValue::asNumber(unsigned long*) const { return false; } bool InspectorValue::asNumber(unsigned int*) const { return false; } bool InspectorValue::asString(String*) const { return false; } bool InspectorValue::asValue(RefPtr<InspectorValue>* output) { *output = this; return true; } bool InspectorValue::asObject(RefPtr<InspectorObject>*) { return false; } bool InspectorValue::asArray(RefPtr<InspectorArray>*) { return false; } PassRefPtr<InspectorObject> InspectorValue::asObject() { return 0; } PassRefPtr<InspectorArray> InspectorValue::asArray() { return 0; } PassRefPtr<InspectorValue> InspectorValue::parseJSON(const String& json) { const UChar* start = json.characters(); const UChar* end = json.characters() + json.length(); const UChar *tokenEnd; RefPtr<InspectorValue> value = buildValue(start, end, &tokenEnd, 0); if (!value || tokenEnd != end) return 0; return value.release(); } String InspectorValue::toJSONString() const { StringBuilder result; result.reserveCapacity(512); writeJSON(&result); return result.toString(); } void InspectorValue::writeJSON(StringBuilder* output) const { ASSERT(m_type == TypeNull); output->append(nullString, 4); } bool InspectorBasicValue::asBoolean(bool* output) const { if (type() != TypeBoolean) return false; *output = m_boolValue; return true; } bool InspectorBasicValue::asNumber(double* output) const { if (type() != TypeNumber) return false; *output = m_doubleValue; return true; } bool InspectorBasicValue::asNumber(long* output) const { if (type() != TypeNumber) return false; *output = static_cast<long>(m_doubleValue); return true; } bool InspectorBasicValue::asNumber(int* output) const { if (type() != TypeNumber) return false; *output = static_cast<int>(m_doubleValue); return true; } bool InspectorBasicValue::asNumber(unsigned long* output) const { if (type() != TypeNumber) return false; *output = static_cast<unsigned long>(m_doubleValue); return true; } bool InspectorBasicValue::asNumber(unsigned int* output) const { if (type() != TypeNumber) return false; *output = static_cast<unsigned int>(m_doubleValue); return true; } void InspectorBasicValue::writeJSON(StringBuilder* output) const { ASSERT(type() == TypeBoolean || type() == TypeNumber); if (type() == TypeBoolean) { if (m_boolValue) output->append(trueString, 4); else output->append(falseString, 5); } else if (type() == TypeNumber) { NumberToLStringBuffer buffer; if (!std::isfinite(m_doubleValue)) { output->append(nullString, 4); return; } DecimalNumber decimal = m_doubleValue; unsigned length = 0; if (decimal.bufferLengthForStringDecimal() > WTF::NumberToStringBufferLength) { // Not enough room for decimal. Use exponential format. if (decimal.bufferLengthForStringExponential() > WTF::NumberToStringBufferLength) { // Fallback for an abnormal case if it's too little even for exponential. output->append("NaN", 3); return; } length = decimal.toStringExponential(buffer, WTF::NumberToStringBufferLength); } else length = decimal.toStringDecimal(buffer, WTF::NumberToStringBufferLength); output->append(buffer, length); } } bool InspectorString::asString(String* output) const { *output = m_stringValue; return true; } void InspectorString::writeJSON(StringBuilder* output) const { ASSERT(type() == TypeString); doubleQuoteString(m_stringValue, output); } InspectorObjectBase::~InspectorObjectBase() { } bool InspectorObjectBase::asObject(RefPtr<InspectorObject>* output) { COMPILE_ASSERT(sizeof(InspectorObject) == sizeof(InspectorObjectBase), cannot_cast); *output = static_cast<InspectorObject*>(this); return true; } PassRefPtr<InspectorObject> InspectorObjectBase::asObject() { return openAccessors(); } InspectorObject* InspectorObjectBase::openAccessors() { COMPILE_ASSERT(sizeof(InspectorObject) == sizeof(InspectorObjectBase), cannot_cast); return static_cast<InspectorObject*>(this); } bool InspectorObjectBase::getBoolean(const String& name, bool* output) const { RefPtr<InspectorValue> value = get(name); if (!value) return false; return value->asBoolean(output); } bool InspectorObjectBase::getString(const String& name, String* output) const { RefPtr<InspectorValue> value = get(name); if (!value) return false; return value->asString(output); } PassRefPtr<InspectorObject> InspectorObjectBase::getObject(const String& name) const { PassRefPtr<InspectorValue> value = get(name); if (!value) return 0; return value->asObject(); } PassRefPtr<InspectorArray> InspectorObjectBase::getArray(const String& name) const { PassRefPtr<InspectorValue> value = get(name); if (!value) return 0; return value->asArray(); } PassRefPtr<InspectorValue> InspectorObjectBase::get(const String& name) const { Dictionary::const_iterator it = m_data.find(name); if (it == m_data.end()) return 0; return it->value; } void InspectorObjectBase::remove(const String& name) { m_data.remove(name); for (size_t i = 0; i < m_order.size(); ++i) { if (m_order[i] == name) { m_order.remove(i); break; } } } void InspectorObjectBase::writeJSON(StringBuilder* output) const { output->append('{'); for (size_t i = 0; i < m_order.size(); ++i) { Dictionary::const_iterator it = m_data.find(m_order[i]); ASSERT(it != m_data.end()); if (i) output->append(','); doubleQuoteString(it->key, output); output->append(':'); it->value->writeJSON(output); } output->append('}'); } InspectorObjectBase::InspectorObjectBase() : InspectorValue(TypeObject) , m_data() , m_order() { } InspectorArrayBase::~InspectorArrayBase() { } bool InspectorArrayBase::asArray(RefPtr<InspectorArray>* output) { COMPILE_ASSERT(sizeof(InspectorArrayBase) == sizeof(InspectorArray), cannot_cast); *output = static_cast<InspectorArray*>(this); return true; } PassRefPtr<InspectorArray> InspectorArrayBase::asArray() { COMPILE_ASSERT(sizeof(InspectorArrayBase) == sizeof(InspectorArray), cannot_cast); return static_cast<InspectorArray*>(this); } void InspectorArrayBase::writeJSON(StringBuilder* output) const { output->append('['); for (Vector<RefPtr<InspectorValue> >::const_iterator it = m_data.begin(); it != m_data.end(); ++it) { if (it != m_data.begin()) output->append(','); (*it)->writeJSON(output); } output->append(']'); } InspectorArrayBase::InspectorArrayBase() : InspectorValue(TypeArray) , m_data() { } PassRefPtr<InspectorValue> InspectorArrayBase::get(size_t index) { ASSERT_WITH_SECURITY_IMPLICATION(index < m_data.size()); return m_data[index]; } } // namespace WebCore
bsd-3-clause
Lkhagvadelger/phantomjs
src/qt/qtwebkit/Source/WebKit2/WebProcess/WebCoreSupport/efl/WebContextMenuClientEfl.cpp
121
1896
/* * Copyright (C) 2011 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if ENABLE(CONTEXT_MENUS) #include "WebContextMenuClient.h" #include <WebCore/NotImplemented.h> using namespace WebCore; namespace WebKit { void WebContextMenuClient::lookUpInDictionary(Frame*) { notImplemented(); } bool WebContextMenuClient::isSpeaking() { notImplemented(); return false; } void WebContextMenuClient::speak(const String&) { notImplemented(); } void WebContextMenuClient::stopSpeaking() { notImplemented(); } } // namespace WebKit #endif // ENABLE(CONTEXT_MENUS)
bsd-3-clause
gitromand/phantomjs
src/qt/qtwebkit/Source/WebCore/platform/graphics/filters/SourceAlpha.cpp
123
2493
/* * Copyright (C) 2009 Dirk Schulze <krit@webkit.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #if ENABLE(FILTERS) #include "SourceAlpha.h" #include "Color.h" #include "Filter.h" #include "GraphicsContext.h" #include "RenderTreeAsText.h" #include "TextStream.h" #include <wtf/StdLibExtras.h> #include <wtf/text/WTFString.h> namespace WebCore { PassRefPtr<SourceAlpha> SourceAlpha::create(Filter* filter) { return adoptRef(new SourceAlpha(filter)); } const AtomicString& SourceAlpha::effectName() { DEFINE_STATIC_LOCAL(const AtomicString, s_effectName, ("SourceAlpha", AtomicString::ConstructFromLiteral)); return s_effectName; } void SourceAlpha::determineAbsolutePaintRect() { Filter* filter = this->filter(); FloatRect paintRect = filter->sourceImageRect(); paintRect.scale(filter->filterResolution().width(), filter->filterResolution().height()); setAbsolutePaintRect(enclosingIntRect(paintRect)); } void SourceAlpha::platformApplySoftware() { ImageBuffer* resultImage = createImageBufferResult(); Filter* filter = this->filter(); if (!resultImage || !filter->sourceImage()) return; setIsAlphaImage(true); FloatRect imageRect(FloatPoint(), absolutePaintRect().size()); GraphicsContext* filterContext = resultImage->context(); filterContext->fillRect(imageRect, Color::black, ColorSpaceDeviceRGB); filterContext->drawImageBuffer(filter->sourceImage(), ColorSpaceDeviceRGB, IntPoint(), CompositeDestinationIn); } void SourceAlpha::dump() { } TextStream& SourceAlpha::externalRepresentation(TextStream& ts, int indent) const { writeIndent(ts, indent); ts << "[SourceAlpha]\n"; return ts; } } // namespace WebCore #endif // ENABLE(FILTERS)
bsd-3-clause
lseyesl/phantomjs
src/qt/qtwebkit/Source/WebCore/platform/qt/DeviceOrientationProviderQt.cpp
125
2729
/* * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "DeviceOrientationProviderQt.h" namespace WebCore { DeviceOrientationProviderQt::DeviceOrientationProviderQt() : m_controller(0) { m_sensor.addFilter(this); m_lastOrientation = DeviceOrientationData::create(); } DeviceOrientationProviderQt::~DeviceOrientationProviderQt() { } void DeviceOrientationProviderQt::setController(DeviceOrientationController* controller) { if (!controller) stop(); m_controller = controller; } void DeviceOrientationProviderQt::start() { m_sensor.start(); } void DeviceOrientationProviderQt::stop() { m_sensor.stop(); } bool DeviceOrientationProviderQt::filter(QRotationReading* reading) { if (m_controller) { // Provide device orientation data according W3C spec: // http://dev.w3.org/geo/api/spec-source-orientation.html // Qt mobility (QtSensors in Qt5) provide these data via QRotationSensor // using the QRotationReading class: // - the rotation around z axis (alpha) is given as z in QRotationReading; // - the rotation around x axis (beta) is given as x in QRotationReading; // - the rotation around y axis (gamma) is given as y in QRotationReading; // See: http://doc.qt.nokia.com/qtmobility-1.0/qrotationreading.html // The Z (alpha) rotation angle is checked via hasAlpha() private method, // depending if the device is able do detect the alpha rotation. X (beta) and // Y (gamma) axis are availble in this context. m_lastOrientation = DeviceOrientationData::create(hasAlpha(), reading->z(), /* x available */ true, reading->x(), /* y available */ true, reading->y()); m_controller->didChangeDeviceOrientation(m_lastOrientation.get()); } // We are the only filter, so no need to propagate. return false; } }
bsd-3-clause
Omegaphora/external_chromium_org
third_party/sqlite/src/test/threadtest1.c
382
7841
/* ** 2002 January 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements a simple standalone program used to test whether ** or not the SQLite library is threadsafe. ** ** Testing the thread safety of SQLite is difficult because there are very ** few places in the code that are even potentially unsafe, and those ** places execute for very short periods of time. So even if the library ** is compiled with its mutexes disabled, it is likely to work correctly ** in a multi-threaded program most of the time. ** ** This file is NOT part of the standard SQLite library. It is used for ** testing only. */ #include "sqlite.h" #include <pthread.h> #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /* ** Enable for tracing */ static int verbose = 0; /* ** Come here to die. */ static void Exit(int rc){ exit(rc); } extern char *sqlite3_mprintf(const char *zFormat, ...); extern char *sqlite3_vmprintf(const char *zFormat, va_list); /* ** When a lock occurs, yield. */ static int db_is_locked(void *NotUsed, int iCount){ /* sched_yield(); */ if( verbose ) printf("BUSY %s #%d\n", (char*)NotUsed, iCount); usleep(100); return iCount<25; } /* ** Used to accumulate query results by db_query() */ struct QueryResult { const char *zFile; /* Filename - used for error reporting */ int nElem; /* Number of used entries in azElem[] */ int nAlloc; /* Number of slots allocated for azElem[] */ char **azElem; /* The result of the query */ }; /* ** The callback function for db_query */ static int db_query_callback( void *pUser, /* Pointer to the QueryResult structure */ int nArg, /* Number of columns in this result row */ char **azArg, /* Text of data in all columns */ char **NotUsed /* Names of the columns */ ){ struct QueryResult *pResult = (struct QueryResult*)pUser; int i; if( pResult->nElem + nArg >= pResult->nAlloc ){ if( pResult->nAlloc==0 ){ pResult->nAlloc = nArg+1; }else{ pResult->nAlloc = pResult->nAlloc*2 + nArg + 1; } pResult->azElem = realloc( pResult->azElem, pResult->nAlloc*sizeof(char*)); if( pResult->azElem==0 ){ fprintf(stdout,"%s: malloc failed\n", pResult->zFile); return 1; } } if( azArg==0 ) return 0; for(i=0; i<nArg; i++){ pResult->azElem[pResult->nElem++] = sqlite3_mprintf("%s",azArg[i] ? azArg[i] : ""); } return 0; } /* ** Execute a query against the database. NULL values are returned ** as an empty string. The list is terminated by a single NULL pointer. */ char **db_query(sqlite *db, const char *zFile, const char *zFormat, ...){ char *zSql; int rc; char *zErrMsg = 0; va_list ap; struct QueryResult sResult; va_start(ap, zFormat); zSql = sqlite3_vmprintf(zFormat, ap); va_end(ap); memset(&sResult, 0, sizeof(sResult)); sResult.zFile = zFile; if( verbose ) printf("QUERY %s: %s\n", zFile, zSql); rc = sqlite3_exec(db, zSql, db_query_callback, &sResult, &zErrMsg); if( rc==SQLITE_SCHEMA ){ if( zErrMsg ) free(zErrMsg); rc = sqlite3_exec(db, zSql, db_query_callback, &sResult, &zErrMsg); } if( verbose ) printf("DONE %s %s\n", zFile, zSql); if( zErrMsg ){ fprintf(stdout,"%s: query failed: %s - %s\n", zFile, zSql, zErrMsg); free(zErrMsg); free(zSql); Exit(1); } sqlite3_free(zSql); if( sResult.azElem==0 ){ db_query_callback(&sResult, 0, 0, 0); } sResult.azElem[sResult.nElem] = 0; return sResult.azElem; } /* ** Execute an SQL statement. */ void db_execute(sqlite *db, const char *zFile, const char *zFormat, ...){ char *zSql; int rc; char *zErrMsg = 0; va_list ap; va_start(ap, zFormat); zSql = sqlite3_vmprintf(zFormat, ap); va_end(ap); if( verbose ) printf("EXEC %s: %s\n", zFile, zSql); do{ rc = sqlite3_exec(db, zSql, 0, 0, &zErrMsg); }while( rc==SQLITE_BUSY ); if( verbose ) printf("DONE %s: %s\n", zFile, zSql); if( zErrMsg ){ fprintf(stdout,"%s: command failed: %s - %s\n", zFile, zSql, zErrMsg); free(zErrMsg); sqlite3_free(zSql); Exit(1); } sqlite3_free(zSql); } /* ** Free the results of a db_query() call. */ void db_query_free(char **az){ int i; for(i=0; az[i]; i++){ sqlite3_free(az[i]); } free(az); } /* ** Check results */ void db_check(const char *zFile, const char *zMsg, char **az, ...){ va_list ap; int i; char *z; va_start(ap, az); for(i=0; (z = va_arg(ap, char*))!=0; i++){ if( az[i]==0 || strcmp(az[i],z)!=0 ){ fprintf(stdout,"%s: %s: bad result in column %d: %s\n", zFile, zMsg, i+1, az[i]); db_query_free(az); Exit(1); } } va_end(ap); db_query_free(az); } pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t sig = PTHREAD_COND_INITIALIZER; int thread_cnt = 0; static void *worker_bee(void *pArg){ const char *zFilename = (char*)pArg; char *azErr; int i, cnt; int t = atoi(zFilename); char **az; sqlite *db; pthread_mutex_lock(&lock); thread_cnt++; pthread_mutex_unlock(&lock); printf("%s: START\n", zFilename); fflush(stdout); for(cnt=0; cnt<10; cnt++){ sqlite3_open(&zFilename[2], &db); if( db==0 ){ fprintf(stdout,"%s: can't open\n", zFilename); Exit(1); } sqlite3_busy_handler(db, db_is_locked, zFilename); db_execute(db, zFilename, "CREATE TABLE t%d(a,b,c);", t); for(i=1; i<=100; i++){ db_execute(db, zFilename, "INSERT INTO t%d VALUES(%d,%d,%d);", t, i, i*2, i*i); } az = db_query(db, zFilename, "SELECT count(*) FROM t%d", t); db_check(zFilename, "tX size", az, "100", 0); az = db_query(db, zFilename, "SELECT avg(b) FROM t%d", t); db_check(zFilename, "tX avg", az, "101", 0); db_execute(db, zFilename, "DELETE FROM t%d WHERE a>50", t); az = db_query(db, zFilename, "SELECT avg(b) FROM t%d", t); db_check(zFilename, "tX avg2", az, "51", 0); for(i=1; i<=50; i++){ char z1[30], z2[30]; az = db_query(db, zFilename, "SELECT b, c FROM t%d WHERE a=%d", t, i); sprintf(z1, "%d", i*2); sprintf(z2, "%d", i*i); db_check(zFilename, "readback", az, z1, z2, 0); } db_execute(db, zFilename, "DROP TABLE t%d;", t); sqlite3_close(db); } printf("%s: END\n", zFilename); /* unlink(zFilename); */ fflush(stdout); pthread_mutex_lock(&lock); thread_cnt--; if( thread_cnt<=0 ){ pthread_cond_signal(&sig); } pthread_mutex_unlock(&lock); return 0; } int main(int argc, char **argv){ char *zFile; int i, n; pthread_t id; if( argc>2 && strcmp(argv[1], "-v")==0 ){ verbose = 1; argc--; argv++; } if( argc<2 || (n=atoi(argv[1]))<1 ) n = 10; for(i=0; i<n; i++){ char zBuf[200]; sprintf(zBuf, "testdb-%d", (i+1)/2); unlink(zBuf); } for(i=0; i<n; i++){ zFile = sqlite3_mprintf("%d.testdb-%d", i%2+1, (i+2)/2); if( (i%2)==0 ){ /* Remove both the database file and any old journal for the file ** being used by this thread and the next one. */ char *zDb = &zFile[2]; char *zJournal = sqlite3_mprintf("%s-journal", zDb); unlink(zDb); unlink(zJournal); free(zJournal); } pthread_create(&id, 0, worker_bee, (void*)zFile); pthread_detach(id); } pthread_mutex_lock(&lock); while( thread_cnt>0 ){ pthread_cond_wait(&sig, &lock); } pthread_mutex_unlock(&lock); for(i=0; i<n; i++){ char zBuf[200]; sprintf(zBuf, "testdb-%d", (i+1)/2); unlink(zBuf); } return 0; }
bsd-3-clause
codeaurora-unoffical/platform-external-skia
experimental/PdfViewer/pdfparser/native/pdfapi/SkPdfFDFDictionary_autogen.cpp
127
5227
/* * Copyright 2013 Google Inc. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkPdfFDFDictionary_autogen.h" #include "SkPdfNativeDoc.h" SkPdfFileSpec SkPdfFDFDictionary::F(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("F", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && false) || (doc == NULL && ret != NULL && ret->isReference())) return ret->fileSpecValue(); // TODO(edisonn): warn about missing default value for optional fields return SkPdfFileSpec(); } bool SkPdfFDFDictionary::has_F() const { return get("F", "") != NULL; } SkPdfArray* SkPdfFDFDictionary::ID(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("ID", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isArray()) || (doc == NULL && ret != NULL && ret->isReference())) return (SkPdfArray*)ret; // TODO(edisonn): warn about missing default value for optional fields return NULL; } bool SkPdfFDFDictionary::has_ID() const { return get("ID", "") != NULL; } SkPdfArray* SkPdfFDFDictionary::Fields(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("Fields", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isArray()) || (doc == NULL && ret != NULL && ret->isReference())) return (SkPdfArray*)ret; // TODO(edisonn): warn about missing default value for optional fields return NULL; } bool SkPdfFDFDictionary::has_Fields() const { return get("Fields", "") != NULL; } SkString SkPdfFDFDictionary::Status(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("Status", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isAnyString()) || (doc == NULL && ret != NULL && ret->isReference())) return ret->stringValue2(); // TODO(edisonn): warn about missing default value for optional fields return SkString(); } bool SkPdfFDFDictionary::has_Status() const { return get("Status", "") != NULL; } SkPdfArray* SkPdfFDFDictionary::Pages(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("Pages", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isArray()) || (doc == NULL && ret != NULL && ret->isReference())) return (SkPdfArray*)ret; // TODO(edisonn): warn about missing default value for optional fields return NULL; } bool SkPdfFDFDictionary::has_Pages() const { return get("Pages", "") != NULL; } SkString SkPdfFDFDictionary::Encoding(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("Encoding", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isName()) || (doc == NULL && ret != NULL && ret->isReference())) return ret->nameValue2(); // TODO(edisonn): warn about missing default value for optional fields return SkString(); } bool SkPdfFDFDictionary::has_Encoding() const { return get("Encoding", "") != NULL; } SkPdfArray* SkPdfFDFDictionary::Annots(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("Annots", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isArray()) || (doc == NULL && ret != NULL && ret->isReference())) return (SkPdfArray*)ret; // TODO(edisonn): warn about missing default value for optional fields return NULL; } bool SkPdfFDFDictionary::has_Annots() const { return get("Annots", "") != NULL; } SkPdfStream* SkPdfFDFDictionary::Differences(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("Differences", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->hasStream()) || (doc == NULL && ret != NULL && ret->isReference())) return ret->getStream(); // TODO(edisonn): warn about missing default value for optional fields return NULL; } bool SkPdfFDFDictionary::has_Differences() const { return get("Differences", "") != NULL; } SkString SkPdfFDFDictionary::Target(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("Target", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isAnyString()) || (doc == NULL && ret != NULL && ret->isReference())) return ret->stringValue2(); // TODO(edisonn): warn about missing default value for optional fields return SkString(); } bool SkPdfFDFDictionary::has_Target() const { return get("Target", "") != NULL; } SkPdfArray* SkPdfFDFDictionary::EmbeddedFDFs(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("EmbeddedFDFs", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isArray()) || (doc == NULL && ret != NULL && ret->isReference())) return (SkPdfArray*)ret; // TODO(edisonn): warn about missing default value for optional fields return NULL; } bool SkPdfFDFDictionary::has_EmbeddedFDFs() const { return get("EmbeddedFDFs", "") != NULL; } SkPdfDictionary* SkPdfFDFDictionary::JavaScript(SkPdfNativeDoc* doc) { SkPdfNativeObject* ret = get("JavaScript", ""); if (doc) {ret = doc->resolveReference(ret);} if ((ret != NULL && ret->isDictionary()) || (doc == NULL && ret != NULL && ret->isReference())) return (SkPdfDictionary*)ret; // TODO(edisonn): warn about missing default value for optional fields return NULL; } bool SkPdfFDFDictionary::has_JavaScript() const { return get("JavaScript", "") != NULL; }
bsd-3-clause
ChromiumWebApps/chromium
third_party/libevent/evdns.c
133
86438
/* $Id: evdns.c 6979 2006-08-04 18:31:13Z nickm $ */ /* The original version of this module was written by Adam Langley; for * a history of modifications, check out the subversion logs. * * When editing this module, try to keep it re-mergeable by Adam. Don't * reformat the whitespace, add Tor dependencies, or so on. * * TODO: * - Support IPv6 and PTR records. * - Replace all externally visible magic numbers with #defined constants. * - Write doccumentation for APIs of all external functions. */ /* Async DNS Library * Adam Langley <agl@imperialviolet.org> * http://www.imperialviolet.org/eventdns.html * Public Domain code * * This software is Public Domain. To view a copy of the public domain dedication, * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. * * I ask and expect, but do not require, that all derivative works contain an * attribution similar to: * Parts developed by Adam Langley <agl@imperialviolet.org> * * You may wish to replace the word "Parts" with something else depending on * the amount of original code. * * (Derivative works does not include programs which link against, run or include * the source verbatim in their source distributions) * * Version: 0.1b */ #include <sys/types.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef DNS_USE_FTIME_FOR_ID #include <sys/timeb.h> #endif #ifndef DNS_USE_CPU_CLOCK_FOR_ID #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID #ifndef DNS_USE_OPENSSL_FOR_ID #ifndef DNS_USE_FTIME_FOR_ID #error Must configure at least one id generation method. #error Please see the documentation. #endif #endif #endif #endif /* #define _POSIX_C_SOURCE 200507 */ #define _GNU_SOURCE #ifdef DNS_USE_CPU_CLOCK_FOR_ID #ifdef DNS_USE_OPENSSL_FOR_ID #error Multiple id options selected #endif #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID #error Multiple id options selected #endif #include <time.h> #endif #ifdef DNS_USE_OPENSSL_FOR_ID #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID #error Multiple id options selected #endif #include <openssl/rand.h> #endif #ifndef _FORTIFY_SOURCE #define _FORTIFY_SOURCE 3 #endif #include <string.h> #include <fcntl.h> #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef HAVE_STDINT_H #include <stdint.h> #endif #include <stdlib.h> #include <string.h> #include <errno.h> #include <assert.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <limits.h> #include <sys/stat.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "evdns.h" #include "evutil.h" #include "log.h" #ifdef WIN32 #include <winsock2.h> #include <windows.h> #include <iphlpapi.h> #include <io.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #endif #ifdef HAVE_NETINET_IN6_H #include <netinet/in6.h> #endif #define EVDNS_LOG_DEBUG 0 #define EVDNS_LOG_WARN 1 #ifndef HOST_NAME_MAX #define HOST_NAME_MAX 255 #endif #include <stdio.h> #undef MIN #define MIN(a,b) ((a)<(b)?(a):(b)) #ifdef __USE_ISOC99B /* libevent doesn't work without this */ typedef ev_uint8_t u_char; typedef unsigned int uint; #endif #include "event.h" #define u64 ev_uint64_t #define u32 ev_uint32_t #define u16 ev_uint16_t #define u8 ev_uint8_t #ifdef WIN32 #define open _open #define read _read #define close _close #define strdup _strdup #endif #define MAX_ADDRS 32 /* maximum number of addresses from a single packet */ /* which we bother recording */ #define TYPE_A EVDNS_TYPE_A #define TYPE_CNAME 5 #define TYPE_PTR EVDNS_TYPE_PTR #define TYPE_AAAA EVDNS_TYPE_AAAA #define CLASS_INET EVDNS_CLASS_INET struct request { u8 *request; /* the dns packet data */ unsigned int request_len; int reissue_count; int tx_count; /* the number of times that this packet has been sent */ unsigned int request_type; /* TYPE_PTR or TYPE_A */ void *user_pointer; /* the pointer given to us for this request */ evdns_callback_type user_callback; struct nameserver *ns; /* the server which we last sent it */ /* elements used by the searching code */ int search_index; struct search_state *search_state; char *search_origname; /* needs to be free()ed */ int search_flags; /* these objects are kept in a circular list */ struct request *next, *prev; struct event timeout_event; u16 trans_id; /* the transaction id */ char request_appended; /* true if the request pointer is data which follows this struct */ char transmit_me; /* needs to be transmitted */ }; #ifndef HAVE_STRUCT_IN6_ADDR struct in6_addr { u8 s6_addr[16]; }; #endif struct reply { unsigned int type; unsigned int have_answer; union { struct { u32 addrcount; u32 addresses[MAX_ADDRS]; } a; struct { u32 addrcount; struct in6_addr addresses[MAX_ADDRS]; } aaaa; struct { char name[HOST_NAME_MAX]; } ptr; } data; }; struct nameserver { int socket; /* a connected UDP socket */ u32 address; u16 port; int failed_times; /* number of times which we have given this server a chance */ int timedout; /* number of times in a row a request has timed out */ struct event event; /* these objects are kept in a circular list */ struct nameserver *next, *prev; struct event timeout_event; /* used to keep the timeout for */ /* when we next probe this server. */ /* Valid if state == 0 */ char state; /* zero if we think that this server is down */ char choked; /* true if we have an EAGAIN from this server's socket */ char write_waiting; /* true if we are waiting for EV_WRITE events */ }; static struct request *req_head = NULL, *req_waiting_head = NULL; static struct nameserver *server_head = NULL; /* Represents a local port where we're listening for DNS requests. Right now, */ /* only UDP is supported. */ struct evdns_server_port { int socket; /* socket we use to read queries and write replies. */ int refcnt; /* reference count. */ char choked; /* Are we currently blocked from writing? */ char closing; /* Are we trying to close this port, pending writes? */ evdns_request_callback_fn_type user_callback; /* Fn to handle requests */ void *user_data; /* Opaque pointer passed to user_callback */ struct event event; /* Read/write event */ /* circular list of replies that we want to write. */ struct server_request *pending_replies; }; /* Represents part of a reply being built. (That is, a single RR.) */ struct server_reply_item { struct server_reply_item *next; /* next item in sequence. */ char *name; /* name part of the RR */ u16 type : 16; /* The RR type */ u16 class : 16; /* The RR class (usually CLASS_INET) */ u32 ttl; /* The RR TTL */ char is_name; /* True iff data is a label */ u16 datalen; /* Length of data; -1 if data is a label */ void *data; /* The contents of the RR */ }; /* Represents a request that we've received as a DNS server, and holds */ /* the components of the reply as we're constructing it. */ struct server_request { /* Pointers to the next and previous entries on the list of replies */ /* that we're waiting to write. Only set if we have tried to respond */ /* and gotten EAGAIN. */ struct server_request *next_pending; struct server_request *prev_pending; u16 trans_id; /* Transaction id. */ struct evdns_server_port *port; /* Which port received this request on? */ struct sockaddr_storage addr; /* Where to send the response */ socklen_t addrlen; /* length of addr */ int n_answer; /* how many answer RRs have been set? */ int n_authority; /* how many authority RRs have been set? */ int n_additional; /* how many additional RRs have been set? */ struct server_reply_item *answer; /* linked list of answer RRs */ struct server_reply_item *authority; /* linked list of authority RRs */ struct server_reply_item *additional; /* linked list of additional RRs */ /* Constructed response. Only set once we're ready to send a reply. */ /* Once this is set, the RR fields are cleared, and no more should be set. */ char *response; size_t response_len; /* Caller-visible fields: flags, questions. */ struct evdns_server_request base; }; /* helper macro */ #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0)) /* Given a pointer to an evdns_server_request, get the corresponding */ /* server_request. */ #define TO_SERVER_REQUEST(base_ptr) \ ((struct server_request*) \ (((char*)(base_ptr) - OFFSET_OF(struct server_request, base)))) /* The number of good nameservers that we have */ static int global_good_nameservers = 0; /* inflight requests are contained in the req_head list */ /* and are actually going out across the network */ static int global_requests_inflight = 0; /* requests which aren't inflight are in the waiting list */ /* and are counted here */ static int global_requests_waiting = 0; static int global_max_requests_inflight = 64; static struct timeval global_timeout = {5, 0}; /* 5 seconds */ static int global_max_reissues = 1; /* a reissue occurs when we get some errors from the server */ static int global_max_retransmits = 3; /* number of times we'll retransmit a request which timed out */ /* number of timeouts in a row before we consider this server to be down */ static int global_max_nameserver_timeout = 3; /* These are the timeout values for nameservers. If we find a nameserver is down */ /* we try to probe it at intervals as given below. Values are in seconds. */ static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}}; static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval); static struct nameserver *nameserver_pick(void); static void evdns_request_insert(struct request *req, struct request **head); static void nameserver_ready_callback(int fd, short events, void *arg); static int evdns_transmit(void); static int evdns_request_transmit(struct request *req); static void nameserver_send_probe(struct nameserver *const ns); static void search_request_finished(struct request *const); static int search_try_next(struct request *const req); static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg); static void evdns_requests_pump_waiting_queue(void); static u16 transaction_id_pick(void); static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr); static void request_submit(struct request *const req); static int server_request_free(struct server_request *req); static void server_request_free_answers(struct server_request *req); static void server_port_free(struct evdns_server_port *port); static void server_port_ready_callback(int fd, short events, void *arg); static int strtoint(const char *const str); #ifdef WIN32 static int last_error(int sock) { int optval, optvallen=sizeof(optval); int err = WSAGetLastError(); if (err == WSAEWOULDBLOCK && sock >= 0) { if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen)) return err; if (optval) return optval; } return err; } static int error_is_eagain(int err) { return err == EAGAIN || err == WSAEWOULDBLOCK; } static int inet_aton(const char *c, struct in_addr *addr) { ev_uint32_t r; if (strcmp(c, "255.255.255.255") == 0) { addr->s_addr = 0xffffffffu; } else { r = inet_addr(c); if (r == INADDR_NONE) return 0; addr->s_addr = r; } return 1; } #else #define last_error(sock) (errno) #define error_is_eagain(err) ((err) == EAGAIN) #endif #define CLOSE_SOCKET(s) EVUTIL_CLOSESOCKET(s) #define ISSPACE(c) isspace((int)(unsigned char)(c)) #define ISDIGIT(c) isdigit((int)(unsigned char)(c)) static const char * debug_ntoa(u32 address) { static char buf[32]; u32 a = ntohl(address); evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d", (int)(u8)((a>>24)&0xff), (int)(u8)((a>>16)&0xff), (int)(u8)((a>>8 )&0xff), (int)(u8)((a )&0xff)); return buf; } static evdns_debug_log_fn_type evdns_log_fn = NULL; void evdns_set_log_fn(evdns_debug_log_fn_type fn) { evdns_log_fn = fn; } #ifdef __GNUC__ #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3))) #else #define EVDNS_LOG_CHECK #endif static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK; static void _evdns_log(int warn, const char *fmt, ...) { va_list args; static char buf[512]; if (!evdns_log_fn) return; va_start(args,fmt); evutil_vsnprintf(buf, sizeof(buf), fmt, args); buf[sizeof(buf)-1] = '\0'; evdns_log_fn(warn, buf); va_end(args); } #define log _evdns_log /* This walks the list of inflight requests to find the */ /* one with a matching transaction id. Returns NULL on */ /* failure */ static struct request * request_find_from_trans_id(u16 trans_id) { struct request *req = req_head, *const started_at = req_head; if (req) { do { if (req->trans_id == trans_id) return req; req = req->next; } while (req != started_at); } return NULL; } /* a libevent callback function which is called when a nameserver */ /* has gone down and we want to test if it has came back to life yet */ static void nameserver_prod_callback(int fd, short events, void *arg) { struct nameserver *const ns = (struct nameserver *) arg; (void)fd; (void)events; nameserver_send_probe(ns); } /* a libevent callback which is called when a nameserver probe (to see if */ /* it has come back to life) times out. We increment the count of failed_times */ /* and wait longer to send the next probe packet. */ static void nameserver_probe_failed(struct nameserver *const ns) { const struct timeval * timeout; (void) evtimer_del(&ns->timeout_event); if (ns->state == 1) { /* This can happen if the nameserver acts in a way which makes us mark */ /* it as bad and then starts sending good replies. */ return; } timeout = &global_nameserver_timeouts[MIN(ns->failed_times, global_nameserver_timeouts_length - 1)]; ns->failed_times++; if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) { log(EVDNS_LOG_WARN, "Error from libevent when adding timer event for %s", debug_ntoa(ns->address)); /* ???? Do more? */ } } /* called when a nameserver has been deemed to have failed. For example, too */ /* many packets have timed out etc */ static void nameserver_failed(struct nameserver *const ns, const char *msg) { struct request *req, *started_at; /* if this nameserver has already been marked as failed */ /* then don't do anything */ if (!ns->state) return; log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s", debug_ntoa(ns->address), msg); global_good_nameservers--; assert(global_good_nameservers >= 0); if (global_good_nameservers == 0) { log(EVDNS_LOG_WARN, "All nameservers have failed"); } ns->state = 0; ns->failed_times = 1; if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) { log(EVDNS_LOG_WARN, "Error from libevent when adding timer event for %s", debug_ntoa(ns->address)); /* ???? Do more? */ } /* walk the list of inflight requests to see if any can be reassigned to */ /* a different server. Requests in the waiting queue don't have a */ /* nameserver assigned yet */ /* if we don't have *any* good nameservers then there's no point */ /* trying to reassign requests to one */ if (!global_good_nameservers) return; req = req_head; started_at = req_head; if (req) { do { if (req->tx_count == 0 && req->ns == ns) { /* still waiting to go out, can be moved */ /* to another server */ req->ns = nameserver_pick(); } req = req->next; } while (req != started_at); } } static void nameserver_up(struct nameserver *const ns) { if (ns->state) return; log(EVDNS_LOG_WARN, "Nameserver %s is back up", debug_ntoa(ns->address)); evtimer_del(&ns->timeout_event); ns->state = 1; ns->failed_times = 0; ns->timedout = 0; global_good_nameservers++; } static void request_trans_id_set(struct request *const req, const u16 trans_id) { req->trans_id = trans_id; *((u16 *) req->request) = htons(trans_id); } /* Called to remove a request from a list and dealloc it. */ /* head is a pointer to the head of the list it should be */ /* removed from or NULL if the request isn't in a list. */ static void request_finished(struct request *const req, struct request **head) { if (head) { if (req->next == req) { /* only item in the list */ *head = NULL; } else { req->next->prev = req->prev; req->prev->next = req->next; if (*head == req) *head = req->next; } } log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx", (unsigned long) req); evtimer_del(&req->timeout_event); search_request_finished(req); global_requests_inflight--; if (!req->request_appended) { /* need to free the request data on it's own */ free(req->request); } else { /* the request data is appended onto the header */ /* so everything gets free()ed when we: */ } free(req); evdns_requests_pump_waiting_queue(); } /* This is called when a server returns a funny error code. */ /* We try the request again with another server. */ /* */ /* return: */ /* 0 ok */ /* 1 failed/reissue is pointless */ static int request_reissue(struct request *req) { const struct nameserver *const last_ns = req->ns; /* the last nameserver should have been marked as failing */ /* by the caller of this function, therefore pick will try */ /* not to return it */ req->ns = nameserver_pick(); if (req->ns == last_ns) { /* ... but pick did return it */ /* not a lot of point in trying again with the */ /* same server */ return 1; } req->reissue_count++; req->tx_count = 0; req->transmit_me = 1; return 0; } /* this function looks for space on the inflight queue and promotes */ /* requests from the waiting queue if it can. */ static void evdns_requests_pump_waiting_queue(void) { while (global_requests_inflight < global_max_requests_inflight && global_requests_waiting) { struct request *req; /* move a request from the waiting queue to the inflight queue */ assert(req_waiting_head); if (req_waiting_head->next == req_waiting_head) { /* only one item in the queue */ req = req_waiting_head; req_waiting_head = NULL; } else { req = req_waiting_head; req->next->prev = req->prev; req->prev->next = req->next; req_waiting_head = req->next; } global_requests_waiting--; global_requests_inflight++; req->ns = nameserver_pick(); request_trans_id_set(req, transaction_id_pick()); evdns_request_insert(req, &req_head); evdns_request_transmit(req); evdns_transmit(); } } static void reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) { switch (req->request_type) { case TYPE_A: if (reply) req->user_callback(DNS_ERR_NONE, DNS_IPv4_A, reply->data.a.addrcount, ttl, reply->data.a.addresses, req->user_pointer); else req->user_callback(err, 0, 0, 0, NULL, req->user_pointer); return; case TYPE_PTR: if (reply) { char *name = reply->data.ptr.name; req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl, &name, req->user_pointer); } else { req->user_callback(err, 0, 0, 0, NULL, req->user_pointer); } return; case TYPE_AAAA: if (reply) req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA, reply->data.aaaa.addrcount, ttl, reply->data.aaaa.addresses, req->user_pointer); else req->user_callback(err, 0, 0, 0, NULL, req->user_pointer); return; } assert(0); } /* this processes a parsed reply packet */ static void reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) { int error; static const int error_codes[] = { DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED }; if (flags & 0x020f || !reply || !reply->have_answer) { /* there was an error */ if (flags & 0x0200) { error = DNS_ERR_TRUNCATED; } else { u16 error_code = (flags & 0x000f) - 1; if (error_code > 4) { error = DNS_ERR_UNKNOWN; } else { error = error_codes[error_code]; } } switch(error) { case DNS_ERR_NOTIMPL: case DNS_ERR_REFUSED: /* we regard these errors as marking a bad nameserver */ if (req->reissue_count < global_max_reissues) { char msg[64]; evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)", error, evdns_err_to_string(error)); nameserver_failed(req->ns, msg); if (!request_reissue(req)) return; } break; case DNS_ERR_SERVERFAILED: /* rcode 2 (servfailed) sometimes means "we * are broken" and sometimes (with some binds) * means "that request was very confusing." * Treat this as a timeout, not a failure. */ log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; " "will allow the request to time out.", debug_ntoa(req->ns->address)); break; default: /* we got a good reply from the nameserver */ nameserver_up(req->ns); } if (req->search_state && req->request_type != TYPE_PTR) { /* if we have a list of domains to search in, * try the next one */ if (!search_try_next(req)) { /* a new request was issued so this * request is finished and */ /* the user callback will be made when * that request (or a */ /* child of it) finishes. */ request_finished(req, &req_head); return; } } /* all else failed. Pass the failure up */ reply_callback(req, 0, error, NULL); request_finished(req, &req_head); } else { /* all ok, tell the user */ reply_callback(req, ttl, 0, reply); nameserver_up(req->ns); request_finished(req, &req_head); } } static int name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) { int name_end = -1; int j = *idx; int ptr_count = 0; #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0) #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0) #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0) char *cp = name_out; const char *const end = name_out + name_out_len; /* Normally, names are a series of length prefixed strings terminated */ /* with a length of 0 (the lengths are u8's < 63). */ /* However, the length can start with a pair of 1 bits and that */ /* means that the next 14 bits are a pointer within the current */ /* packet. */ for(;;) { u8 label_len; if (j >= length) return -1; GET8(label_len); if (!label_len) break; if (label_len & 0xc0) { u8 ptr_low; GET8(ptr_low); if (name_end < 0) name_end = j; j = (((int)label_len & 0x3f) << 8) + ptr_low; /* Make sure that the target offset is in-bounds. */ if (j < 0 || j >= length) return -1; /* If we've jumped more times than there are characters in the * message, we must have a loop. */ if (++ptr_count > length) return -1; continue; } if (label_len > 63) return -1; if (cp != name_out) { if (cp + 1 >= end) return -1; *cp++ = '.'; } if (cp + label_len >= end) return -1; memcpy(cp, packet + j, label_len); cp += label_len; j += label_len; } if (cp >= end) return -1; *cp = '\0'; if (name_end < 0) *idx = j; else *idx = name_end; return 0; err: return -1; } /* parses a raw request from a nameserver */ static int reply_parse(u8 *packet, int length) { int j = 0, k = 0; /* index into packet */ u16 _t; /* used by the macros */ u32 _t32; /* used by the macros */ char tmp_name[256], cmp_name[256]; /* used by the macros */ u16 trans_id, questions, answers, authority, additional, datalength; u16 flags = 0; u32 ttl, ttl_r = 0xffffffff; struct reply reply; struct request *req = NULL; unsigned int i; GET16(trans_id); GET16(flags); GET16(questions); GET16(answers); GET16(authority); GET16(additional); (void) authority; /* suppress "unused variable" warnings. */ (void) additional; /* suppress "unused variable" warnings. */ req = request_find_from_trans_id(trans_id); if (!req) return -1; memset(&reply, 0, sizeof(reply)); /* If it's not an answer, it doesn't correspond to any request. */ if (!(flags & 0x8000)) return -1; /* must be an answer */ if (flags & 0x020f) { /* there was an error */ goto err; } /* if (!answers) return; */ /* must have an answer of some form */ /* This macro skips a name in the DNS reply. */ #define SKIP_NAME \ do { tmp_name[0] = '\0'; \ if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\ goto err; \ } while(0) #define TEST_NAME \ do { tmp_name[0] = '\0'; \ cmp_name[0] = '\0'; \ k = j; \ if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\ goto err; \ if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0) \ goto err; \ if (memcmp(tmp_name, cmp_name, strlen (tmp_name)) != 0) \ return (-1); /* we ignore mismatching names */ \ } while(0) reply.type = req->request_type; /* skip over each question in the reply */ for (i = 0; i < questions; ++i) { /* the question looks like * <label:name><u16:type><u16:class> */ TEST_NAME; j += 4; if (j > length) goto err; } /* now we have the answer section which looks like * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...> */ for (i = 0; i < answers; ++i) { u16 type, class; SKIP_NAME; GET16(type); GET16(class); GET32(ttl); GET16(datalength); if (type == TYPE_A && class == CLASS_INET) { int addrcount, addrtocopy; if (req->request_type != TYPE_A) { j += datalength; continue; } if ((datalength & 3) != 0) /* not an even number of As. */ goto err; addrcount = datalength >> 2; addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount); ttl_r = MIN(ttl_r, ttl); /* we only bother with the first four addresses. */ if (j + 4*addrtocopy > length) goto err; memcpy(&reply.data.a.addresses[reply.data.a.addrcount], packet + j, 4*addrtocopy); j += 4*addrtocopy; reply.data.a.addrcount += addrtocopy; reply.have_answer = 1; if (reply.data.a.addrcount == MAX_ADDRS) break; } else if (type == TYPE_PTR && class == CLASS_INET) { if (req->request_type != TYPE_PTR) { j += datalength; continue; } if (name_parse(packet, length, &j, reply.data.ptr.name, sizeof(reply.data.ptr.name))<0) goto err; ttl_r = MIN(ttl_r, ttl); reply.have_answer = 1; break; } else if (type == TYPE_AAAA && class == CLASS_INET) { int addrcount, addrtocopy; if (req->request_type != TYPE_AAAA) { j += datalength; continue; } if ((datalength & 15) != 0) /* not an even number of AAAAs. */ goto err; addrcount = datalength >> 4; /* each address is 16 bytes long */ addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount); ttl_r = MIN(ttl_r, ttl); /* we only bother with the first four addresses. */ if (j + 16*addrtocopy > length) goto err; memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount], packet + j, 16*addrtocopy); reply.data.aaaa.addrcount += addrtocopy; j += 16*addrtocopy; reply.have_answer = 1; if (reply.data.aaaa.addrcount == MAX_ADDRS) break; } else { /* skip over any other type of resource */ j += datalength; } } reply_handle(req, flags, ttl_r, &reply); return 0; err: if (req) reply_handle(req, flags, 0, NULL); return -1; } /* Parse a raw request (packet,length) sent to a nameserver port (port) from */ /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */ /* callback. */ static int request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen) { int j = 0; /* index into packet */ u16 _t; /* used by the macros */ char tmp_name[256]; /* used by the macros */ int i; u16 trans_id, flags, questions, answers, authority, additional; struct server_request *server_req = NULL; /* Get the header fields */ GET16(trans_id); GET16(flags); GET16(questions); GET16(answers); GET16(authority); GET16(additional); if (flags & 0x8000) return -1; /* Must not be an answer. */ flags &= 0x0110; /* Only RD and CD get preserved. */ server_req = malloc(sizeof(struct server_request)); if (server_req == NULL) return -1; memset(server_req, 0, sizeof(struct server_request)); server_req->trans_id = trans_id; memcpy(&server_req->addr, addr, addrlen); server_req->addrlen = addrlen; server_req->base.flags = flags; server_req->base.nquestions = 0; server_req->base.questions = malloc(sizeof(struct evdns_server_question *) * questions); if (server_req->base.questions == NULL) goto err; for (i = 0; i < questions; ++i) { u16 type, class; struct evdns_server_question *q; int namelen; if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) goto err; GET16(type); GET16(class); namelen = strlen(tmp_name); q = malloc(sizeof(struct evdns_server_question) + namelen); if (!q) goto err; q->type = type; q->dns_question_class = class; memcpy(q->name, tmp_name, namelen+1); server_req->base.questions[server_req->base.nquestions++] = q; } /* Ignore answers, authority, and additional. */ server_req->port = port; port->refcnt++; /* Only standard queries are supported. */ if (flags & 0x7800) { evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL); return -1; } port->user_callback(&(server_req->base), port->user_data); return 0; err: if (server_req) { if (server_req->base.questions) { for (i = 0; i < server_req->base.nquestions; ++i) free(server_req->base.questions[i]); free(server_req->base.questions); } free(server_req); } return -1; #undef SKIP_NAME #undef GET32 #undef GET16 #undef GET8 } static u16 default_transaction_id_fn(void) { u16 trans_id; #ifdef DNS_USE_CPU_CLOCK_FOR_ID struct timespec ts; static int clkid = -1; if (clkid == -1) { clkid = CLOCK_REALTIME; #ifdef CLOCK_MONOTONIC if (clock_gettime(CLOCK_MONOTONIC, &ts) != -1) clkid = CLOCK_MONOTONIC; #endif } if (clock_gettime(clkid, &ts) == -1) event_err(1, "clock_gettime"); trans_id = ts.tv_nsec & 0xffff; #endif #ifdef DNS_USE_FTIME_FOR_ID struct _timeb tb; _ftime(&tb); trans_id = tb.millitm & 0xffff; #endif #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID struct timeval tv; evutil_gettimeofday(&tv, NULL); trans_id = tv.tv_usec & 0xffff; #endif #ifdef DNS_USE_OPENSSL_FOR_ID if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) { /* in the case that the RAND call fails we back */ /* down to using gettimeofday. */ /* struct timeval tv; evutil_gettimeofday(&tv, NULL); trans_id = tv.tv_usec & 0xffff; */ abort(); } #endif return trans_id; } static ev_uint16_t (*trans_id_function)(void) = default_transaction_id_fn; void evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void)) { if (fn) trans_id_function = fn; else trans_id_function = default_transaction_id_fn; } /* Try to choose a strong transaction id which isn't already in flight */ static u16 transaction_id_pick(void) { for (;;) { const struct request *req = req_head, *started_at; u16 trans_id = trans_id_function(); if (trans_id == 0xffff) continue; /* now check to see if that id is already inflight */ req = started_at = req_head; if (req) { do { if (req->trans_id == trans_id) break; req = req->next; } while (req != started_at); } /* we didn't find it, so this is a good id */ if (req == started_at) return trans_id; } } /* choose a namesever to use. This function will try to ignore */ /* nameservers which we think are down and load balance across the rest */ /* by updating the server_head global each time. */ static struct nameserver * nameserver_pick(void) { struct nameserver *started_at = server_head, *picked; if (!server_head) return NULL; /* if we don't have any good nameservers then there's no */ /* point in trying to find one. */ if (!global_good_nameservers) { server_head = server_head->next; return server_head; } /* remember that nameservers are in a circular list */ for (;;) { if (server_head->state) { /* we think this server is currently good */ picked = server_head; server_head = server_head->next; return picked; } server_head = server_head->next; if (server_head == started_at) { /* all the nameservers seem to be down */ /* so we just return this one and hope for the */ /* best */ assert(global_good_nameservers == 0); picked = server_head; server_head = server_head->next; return picked; } } } static int address_is_correct(struct nameserver *ns, struct sockaddr *sa, socklen_t slen) { struct sockaddr_in *sin = (struct sockaddr_in*) sa; if (sa->sa_family != AF_INET || slen != sizeof(struct sockaddr_in)) return 0; if (sin->sin_addr.s_addr != ns->address) return 0; return 1; } /* this is called when a namesever socket is ready for reading */ static void nameserver_read(struct nameserver *ns) { u8 packet[1500]; struct sockaddr_storage ss; socklen_t addrlen = sizeof(ss); for (;;) { const int r = recvfrom(ns->socket, packet, sizeof(packet), 0, (struct sockaddr*)&ss, &addrlen); if (r < 0) { int err = last_error(ns->socket); if (error_is_eagain(err)) return; nameserver_failed(ns, strerror(err)); return; } if (!address_is_correct(ns, (struct sockaddr*)&ss, addrlen)) { log(EVDNS_LOG_WARN, "Address mismatch on received " "DNS packet."); return; } ns->timedout = 0; reply_parse(packet, r); } } /* Read a packet from a DNS client on a server port s, parse it, and */ /* act accordingly. */ static void server_port_read(struct evdns_server_port *s) { u8 packet[1500]; struct sockaddr_storage addr; socklen_t addrlen; int r; for (;;) { addrlen = sizeof(struct sockaddr_storage); r = recvfrom(s->socket, packet, sizeof(packet), 0, (struct sockaddr*) &addr, &addrlen); if (r < 0) { int err = last_error(s->socket); if (error_is_eagain(err)) return; log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.", strerror(err), err); return; } request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen); } } /* Try to write all pending replies on a given DNS server port. */ static void server_port_flush(struct evdns_server_port *port) { while (port->pending_replies) { struct server_request *req = port->pending_replies; int r = sendto(port->socket, req->response, req->response_len, 0, (struct sockaddr*) &req->addr, req->addrlen); if (r < 0) { int err = last_error(port->socket); if (error_is_eagain(err)) return; log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", strerror(err), err); } if (server_request_free(req)) { /* we released the last reference to req->port. */ return; } } /* We have no more pending requests; stop listening for 'writeable' events. */ (void) event_del(&port->event); event_set(&port->event, port->socket, EV_READ | EV_PERSIST, server_port_ready_callback, port); if (event_add(&port->event, NULL) < 0) { log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server."); /* ???? Do more? */ } } /* set if we are waiting for the ability to write to this server. */ /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */ /* we stop these events. */ static void nameserver_write_waiting(struct nameserver *ns, char waiting) { if (ns->write_waiting == waiting) return; ns->write_waiting = waiting; (void) event_del(&ns->event); event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST, nameserver_ready_callback, ns); if (event_add(&ns->event, NULL) < 0) { log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s", debug_ntoa(ns->address)); /* ???? Do more? */ } } /* a callback function. Called by libevent when the kernel says that */ /* a nameserver socket is ready for writing or reading */ static void nameserver_ready_callback(int fd, short events, void *arg) { struct nameserver *ns = (struct nameserver *) arg; (void)fd; if (events & EV_WRITE) { ns->choked = 0; if (!evdns_transmit()) { nameserver_write_waiting(ns, 0); } } if (events & EV_READ) { nameserver_read(ns); } } /* a callback function. Called by libevent when the kernel says that */ /* a server socket is ready for writing or reading. */ static void server_port_ready_callback(int fd, short events, void *arg) { struct evdns_server_port *port = (struct evdns_server_port *) arg; (void) fd; if (events & EV_WRITE) { port->choked = 0; server_port_flush(port); } if (events & EV_READ) { server_port_read(port); } } /* This is an inefficient representation; only use it via the dnslabel_table_* * functions, so that is can be safely replaced with something smarter later. */ #define MAX_LABELS 128 /* Structures used to implement name compression */ struct dnslabel_entry { char *v; off_t pos; }; struct dnslabel_table { int n_labels; /* number of current entries */ /* map from name to position in message */ struct dnslabel_entry labels[MAX_LABELS]; }; /* Initialize dnslabel_table. */ static void dnslabel_table_init(struct dnslabel_table *table) { table->n_labels = 0; } /* Free all storage held by table, but not the table itself. */ static void dnslabel_clear(struct dnslabel_table *table) { int i; for (i = 0; i < table->n_labels; ++i) free(table->labels[i].v); table->n_labels = 0; } /* return the position of the label in the current message, or -1 if the label */ /* hasn't been used yet. */ static int dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label) { int i; for (i = 0; i < table->n_labels; ++i) { if (!strcmp(label, table->labels[i].v)) return table->labels[i].pos; } return -1; } /* remember that we've used the label at position pos */ static int dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos) { char *v; int p; if (table->n_labels == MAX_LABELS) return (-1); v = strdup(label); if (v == NULL) return (-1); p = table->n_labels++; table->labels[p].v = v; table->labels[p].pos = pos; return (0); } /* Converts a string to a length-prefixed set of DNS labels, starting */ /* at buf[j]. name and buf must not overlap. name_len should be the length */ /* of name. table is optional, and is used for compression. */ /* */ /* Input: abc.def */ /* Output: <3>abc<3>def<0> */ /* */ /* Returns the first index after the encoded name, or negative on error. */ /* -1 label was > 63 bytes */ /* -2 name too long to fit in buffer. */ /* */ static off_t dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j, const char *name, const int name_len, struct dnslabel_table *table) { const char *end = name + name_len; int ref = 0; u16 _t; #define APPEND16(x) do { \ if (j + 2 > (off_t)buf_len) \ goto overflow; \ _t = htons(x); \ memcpy(buf + j, &_t, 2); \ j += 2; \ } while (0) #define APPEND32(x) do { \ if (j + 4 > (off_t)buf_len) \ goto overflow; \ _t32 = htonl(x); \ memcpy(buf + j, &_t32, 4); \ j += 4; \ } while (0) if (name_len > 255) return -2; for (;;) { const char *const start = name; if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) { APPEND16(ref | 0xc000); return j; } name = strchr(name, '.'); if (!name) { const unsigned int label_len = end - start; if (label_len > 63) return -1; if ((size_t)(j+label_len+1) > buf_len) return -2; if (table) dnslabel_table_add(table, start, j); buf[j++] = label_len; memcpy(buf + j, start, end - start); j += end - start; break; } else { /* append length of the label. */ const unsigned int label_len = name - start; if (label_len > 63) return -1; if ((size_t)(j+label_len+1) > buf_len) return -2; if (table) dnslabel_table_add(table, start, j); buf[j++] = label_len; memcpy(buf + j, start, name - start); j += name - start; /* hop over the '.' */ name++; } } /* the labels must be terminated by a 0. */ /* It's possible that the name ended in a . */ /* in which case the zero is already there */ if (!j || buf[j-1]) buf[j++] = 0; return j; overflow: return (-2); } /* Finds the length of a dns request for a DNS name of the given */ /* length. The actual request may be smaller than the value returned */ /* here */ static int evdns_request_len(const int name_len) { return 96 + /* length of the DNS standard header */ name_len + 2 + 4; /* space for the resource type */ } /* build a dns request packet into buf. buf should be at least as long */ /* as evdns_request_len told you it should be. */ /* */ /* Returns the amount of space used. Negative on error. */ static int evdns_request_data_build(const char *const name, const int name_len, const u16 trans_id, const u16 type, const u16 class, u8 *const buf, size_t buf_len) { off_t j = 0; /* current offset into buf */ u16 _t; /* used by the macros */ APPEND16(trans_id); APPEND16(0x0100); /* standard query, recusion needed */ APPEND16(1); /* one question */ APPEND16(0); /* no answers */ APPEND16(0); /* no authority */ APPEND16(0); /* no additional */ j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL); if (j < 0) { return (int)j; } APPEND16(type); APPEND16(class); return (int)j; overflow: return (-1); } /* exported function */ struct evdns_server_port * evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data) { struct evdns_server_port *port; if (!(port = malloc(sizeof(struct evdns_server_port)))) return NULL; memset(port, 0, sizeof(struct evdns_server_port)); assert(!is_tcp); /* TCP sockets not yet implemented */ port->socket = socket; port->refcnt = 1; port->choked = 0; port->closing = 0; port->user_callback = cb; port->user_data = user_data; port->pending_replies = NULL; event_set(&port->event, port->socket, EV_READ | EV_PERSIST, server_port_ready_callback, port); event_add(&port->event, NULL); /* check return. */ return port; } /* exported function */ void evdns_close_server_port(struct evdns_server_port *port) { if (--port->refcnt == 0) server_port_free(port); port->closing = 1; } /* exported function */ int evdns_server_request_add_reply(struct evdns_server_request *_req, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data) { struct server_request *req = TO_SERVER_REQUEST(_req); struct server_reply_item **itemp, *item; int *countp; if (req->response) /* have we already answered? */ return (-1); switch (section) { case EVDNS_ANSWER_SECTION: itemp = &req->answer; countp = &req->n_answer; break; case EVDNS_AUTHORITY_SECTION: itemp = &req->authority; countp = &req->n_authority; break; case EVDNS_ADDITIONAL_SECTION: itemp = &req->additional; countp = &req->n_additional; break; default: return (-1); } while (*itemp) { itemp = &((*itemp)->next); } item = malloc(sizeof(struct server_reply_item)); if (!item) return -1; item->next = NULL; if (!(item->name = strdup(name))) { free(item); return -1; } item->type = type; item->dns_question_class = class; item->ttl = ttl; item->is_name = is_name != 0; item->datalen = 0; item->data = NULL; if (data) { if (item->is_name) { if (!(item->data = strdup(data))) { free(item->name); free(item); return -1; } item->datalen = (u16)-1; } else { if (!(item->data = malloc(datalen))) { free(item->name); free(item); return -1; } item->datalen = datalen; memcpy(item->data, data, datalen); } } *itemp = item; ++(*countp); return 0; } /* exported function */ int evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl) { return evdns_server_request_add_reply( req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET, ttl, n*4, 0, addrs); } /* exported function */ int evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl) { return evdns_server_request_add_reply( req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET, ttl, n*16, 0, addrs); } /* exported function */ int evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl) { u32 a; char buf[32]; assert(in || inaddr_name); assert(!(in && inaddr_name)); if (in) { a = ntohl(in->s_addr); evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa", (int)(u8)((a )&0xff), (int)(u8)((a>>8 )&0xff), (int)(u8)((a>>16)&0xff), (int)(u8)((a>>24)&0xff)); inaddr_name = buf; } return evdns_server_request_add_reply( req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET, ttl, -1, 1, hostname); } /* exported function */ int evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl) { return evdns_server_request_add_reply( req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET, ttl, -1, 1, cname); } static int evdns_server_request_format_response(struct server_request *req, int err) { unsigned char buf[1500]; size_t buf_len = sizeof(buf); off_t j = 0, r; u16 _t; u32 _t32; int i; u16 flags; struct dnslabel_table table; if (err < 0 || err > 15) return -1; /* Set response bit and error code; copy OPCODE and RD fields from * question; copy RA and AA if set by caller. */ flags = req->base.flags; flags |= (0x8000 | err); dnslabel_table_init(&table); APPEND16(req->trans_id); APPEND16(flags); APPEND16(req->base.nquestions); APPEND16(req->n_answer); APPEND16(req->n_authority); APPEND16(req->n_additional); /* Add questions. */ for (i=0; i < req->base.nquestions; ++i) { const char *s = req->base.questions[i]->name; j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table); if (j < 0) { dnslabel_clear(&table); return (int) j; } APPEND16(req->base.questions[i]->type); APPEND16(req->base.questions[i]->dns_question_class); } /* Add answer, authority, and additional sections. */ for (i=0; i<3; ++i) { struct server_reply_item *item; if (i==0) item = req->answer; else if (i==1) item = req->authority; else item = req->additional; while (item) { r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table); if (r < 0) goto overflow; j = r; APPEND16(item->type); APPEND16(item->dns_question_class); APPEND32(item->ttl); if (item->is_name) { off_t len_idx = j, name_start; j += 2; name_start = j; r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table); if (r < 0) goto overflow; j = r; _t = htons( (short) (j-name_start) ); memcpy(buf+len_idx, &_t, 2); } else { APPEND16(item->datalen); if (j+item->datalen > (off_t)buf_len) goto overflow; memcpy(buf+j, item->data, item->datalen); j += item->datalen; } item = item->next; } } if (j > 512) { overflow: j = 512; buf[2] |= 0x02; /* set the truncated bit. */ } req->response_len = j; if (!(req->response = malloc(req->response_len))) { server_request_free_answers(req); dnslabel_clear(&table); return (-1); } memcpy(req->response, buf, req->response_len); server_request_free_answers(req); dnslabel_clear(&table); return (0); } /* exported function */ int evdns_server_request_respond(struct evdns_server_request *_req, int err) { struct server_request *req = TO_SERVER_REQUEST(_req); struct evdns_server_port *port = req->port; int r; if (!req->response) { if ((r = evdns_server_request_format_response(req, err))<0) return r; } r = sendto(port->socket, req->response, req->response_len, 0, (struct sockaddr*) &req->addr, req->addrlen); if (r<0) { int sock_err = last_error(port->socket); if (! error_is_eagain(sock_err)) return -1; if (port->pending_replies) { req->prev_pending = port->pending_replies->prev_pending; req->next_pending = port->pending_replies; req->prev_pending->next_pending = req->next_pending->prev_pending = req; } else { req->prev_pending = req->next_pending = req; port->pending_replies = req; port->choked = 1; (void) event_del(&port->event); event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port); if (event_add(&port->event, NULL) < 0) { log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server"); } } return 1; } if (server_request_free(req)) return 0; if (port->pending_replies) server_port_flush(port); return 0; } /* Free all storage held by RRs in req. */ static void server_request_free_answers(struct server_request *req) { struct server_reply_item *victim, *next, **list; int i; for (i = 0; i < 3; ++i) { if (i==0) list = &req->answer; else if (i==1) list = &req->authority; else list = &req->additional; victim = *list; while (victim) { next = victim->next; free(victim->name); if (victim->data) free(victim->data); free(victim); victim = next; } *list = NULL; } } /* Free all storage held by req, and remove links to it. */ /* return true iff we just wound up freeing the server_port. */ static int server_request_free(struct server_request *req) { int i, rc=1; if (req->base.questions) { for (i = 0; i < req->base.nquestions; ++i) free(req->base.questions[i]); free(req->base.questions); } if (req->port) { if (req->port->pending_replies == req) { if (req->next_pending) req->port->pending_replies = req->next_pending; else req->port->pending_replies = NULL; } rc = --req->port->refcnt; } if (req->response) { free(req->response); } server_request_free_answers(req); if (req->next_pending && req->next_pending != req) { req->next_pending->prev_pending = req->prev_pending; req->prev_pending->next_pending = req->next_pending; } if (rc == 0) { server_port_free(req->port); free(req); return (1); } free(req); return (0); } /* Free all storage held by an evdns_server_port. Only called when */ static void server_port_free(struct evdns_server_port *port) { assert(port); assert(!port->refcnt); assert(!port->pending_replies); if (port->socket > 0) { CLOSE_SOCKET(port->socket); port->socket = -1; } (void) event_del(&port->event); /* XXXX actually free the port? -NM */ } /* exported function */ int evdns_server_request_drop(struct evdns_server_request *_req) { struct server_request *req = TO_SERVER_REQUEST(_req); server_request_free(req); return 0; } /* exported function */ int evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len) { struct server_request *req = TO_SERVER_REQUEST(_req); if (addr_len < (int)req->addrlen) return -1; memcpy(sa, &(req->addr), req->addrlen); return req->addrlen; } #undef APPEND16 #undef APPEND32 /* this is a libevent callback function which is called when a request */ /* has timed out. */ static void evdns_request_timeout_callback(int fd, short events, void *arg) { struct request *const req = (struct request *) arg; (void) fd; (void) events; log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg); req->ns->timedout++; if (req->ns->timedout > global_max_nameserver_timeout) { req->ns->timedout = 0; nameserver_failed(req->ns, "request timed out."); } (void) evtimer_del(&req->timeout_event); if (req->tx_count >= global_max_retransmits) { /* this request has failed */ reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL); request_finished(req, &req_head); } else { /* retransmit it */ evdns_request_transmit(req); } } /* try to send a request to a given server. */ /* */ /* return: */ /* 0 ok */ /* 1 temporary failure */ /* 2 other failure */ static int evdns_request_transmit_to(struct request *req, struct nameserver *server) { struct sockaddr_in sin; int r; memset(&sin, 0, sizeof(sin)); sin.sin_addr.s_addr = req->ns->address; sin.sin_port = req->ns->port; sin.sin_family = AF_INET; r = sendto(server->socket, req->request, req->request_len, 0, (struct sockaddr*)&sin, sizeof(sin)); if (r < 0) { int err = last_error(server->socket); if (error_is_eagain(err)) return 1; nameserver_failed(req->ns, strerror(err)); return 2; } else if (r != (int)req->request_len) { return 1; /* short write */ } else { return 0; } } /* try to send a request, updating the fields of the request */ /* as needed */ /* */ /* return: */ /* 0 ok */ /* 1 failed */ static int evdns_request_transmit(struct request *req) { int retcode = 0, r; /* if we fail to send this packet then this flag marks it */ /* for evdns_transmit */ req->transmit_me = 1; if (req->trans_id == 0xffff) abort(); if (req->ns->choked) { /* don't bother trying to write to a socket */ /* which we have had EAGAIN from */ return 1; } r = evdns_request_transmit_to(req, req->ns); switch (r) { case 1: /* temp failure */ req->ns->choked = 1; nameserver_write_waiting(req->ns, 1); return 1; case 2: /* failed in some other way */ retcode = 1; /* fall through */ default: /* all ok */ log(EVDNS_LOG_DEBUG, "Setting timeout for request %lx", (unsigned long) req); if (evtimer_add(&req->timeout_event, &global_timeout) < 0) { log(EVDNS_LOG_WARN, "Error from libevent when adding timer for request %lx", (unsigned long) req); /* ???? Do more? */ } req->tx_count++; req->transmit_me = 0; return retcode; } } static void nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) { struct nameserver *const ns = (struct nameserver *) arg; (void) type; (void) count; (void) ttl; (void) addresses; if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) { /* this is a good reply */ nameserver_up(ns); } else nameserver_probe_failed(ns); } static void nameserver_send_probe(struct nameserver *const ns) { struct request *req; /* here we need to send a probe to a given nameserver */ /* in the hope that it is up now. */ log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntoa(ns->address)); req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns); if (!req) return; /* we force this into the inflight queue no matter what */ request_trans_id_set(req, transaction_id_pick()); req->ns = ns; request_submit(req); } /* returns: */ /* 0 didn't try to transmit anything */ /* 1 tried to transmit something */ static int evdns_transmit(void) { char did_try_to_transmit = 0; if (req_head) { struct request *const started_at = req_head, *req = req_head; /* first transmit all the requests which are currently waiting */ do { if (req->transmit_me) { did_try_to_transmit = 1; evdns_request_transmit(req); } req = req->next; } while (req != started_at); } return did_try_to_transmit; } /* exported function */ int evdns_count_nameservers(void) { const struct nameserver *server = server_head; int n = 0; if (!server) return 0; do { ++n; server = server->next; } while (server != server_head); return n; } /* exported function */ int evdns_clear_nameservers_and_suspend(void) { struct nameserver *server = server_head, *started_at = server_head; struct request *req = req_head, *req_started_at = req_head; if (!server) return 0; while (1) { struct nameserver *next = server->next; (void) event_del(&server->event); if (evtimer_initialized(&server->timeout_event)) (void) evtimer_del(&server->timeout_event); if (server->socket >= 0) CLOSE_SOCKET(server->socket); free(server); if (next == started_at) break; server = next; } server_head = NULL; global_good_nameservers = 0; while (req) { struct request *next = req->next; req->tx_count = req->reissue_count = 0; req->ns = NULL; /* ???? What to do about searches? */ (void) evtimer_del(&req->timeout_event); req->trans_id = 0; req->transmit_me = 0; global_requests_waiting++; evdns_request_insert(req, &req_waiting_head); /* We want to insert these suspended elements at the front of * the waiting queue, since they were pending before any of * the waiting entries were added. This is a circular list, * so we can just shift the start back by one.*/ req_waiting_head = req_waiting_head->prev; if (next == req_started_at) break; req = next; } req_head = NULL; global_requests_inflight = 0; return 0; } /* exported function */ int evdns_resume(void) { evdns_requests_pump_waiting_queue(); return 0; } static int _evdns_nameserver_add_impl(unsigned long int address, int port) { /* first check to see if we already have this nameserver */ const struct nameserver *server = server_head, *const started_at = server_head; struct nameserver *ns; int err = 0; if (server) { do { if (server->address == address) return 3; server = server->next; } while (server != started_at); } ns = (struct nameserver *) malloc(sizeof(struct nameserver)); if (!ns) return -1; memset(ns, 0, sizeof(struct nameserver)); evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns); ns->socket = socket(PF_INET, SOCK_DGRAM, 0); if (ns->socket < 0) { err = 1; goto out1; } evutil_make_socket_nonblocking(ns->socket); ns->address = address; ns->port = htons(port); ns->state = 1; event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns); if (event_add(&ns->event, NULL) < 0) { err = 2; goto out2; } log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntoa(address)); /* insert this nameserver into the list of them */ if (!server_head) { ns->next = ns->prev = ns; server_head = ns; } else { ns->next = server_head->next; ns->prev = server_head; server_head->next = ns; if (server_head->prev == server_head) { server_head->prev = ns; } } global_good_nameservers++; return 0; out2: CLOSE_SOCKET(ns->socket); out1: free(ns); log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntoa(address), err); return err; } /* exported function */ int evdns_nameserver_add(unsigned long int address) { return _evdns_nameserver_add_impl(address, 53); } /* exported function */ int evdns_nameserver_ip_add(const char *ip_as_string) { struct in_addr ina; int port; char buf[20]; const char *cp; cp = strchr(ip_as_string, ':'); if (! cp) { cp = ip_as_string; port = 53; } else { port = strtoint(cp+1); if (port < 0 || port > 65535) { return 4; } if ((cp-ip_as_string) >= (int)sizeof(buf)) { return 4; } memcpy(buf, ip_as_string, cp-ip_as_string); buf[cp-ip_as_string] = '\0'; cp = buf; } if (!inet_aton(cp, &ina)) { return 4; } return _evdns_nameserver_add_impl(ina.s_addr, port); } /* insert into the tail of the queue */ static void evdns_request_insert(struct request *req, struct request **head) { if (!*head) { *head = req; req->next = req->prev = req; return; } req->prev = (*head)->prev; req->prev->next = req; req->next = *head; (*head)->prev = req; } static int string_num_dots(const char *s) { int count = 0; while ((s = strchr(s, '.'))) { s++; count++; } return count; } static struct request * request_new(int type, const char *name, int flags, evdns_callback_type callback, void *user_ptr) { const char issuing_now = (global_requests_inflight < global_max_requests_inflight) ? 1 : 0; const int name_len = strlen(name); const int request_max_len = evdns_request_len(name_len); const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff; /* the request data is alloced in a single block with the header */ struct request *const req = (struct request *) malloc(sizeof(struct request) + request_max_len); int rlen; (void) flags; if (!req) return NULL; memset(req, 0, sizeof(struct request)); evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req); /* request data lives just after the header */ req->request = ((u8 *) req) + sizeof(struct request); /* denotes that the request data shouldn't be free()ed */ req->request_appended = 1; rlen = evdns_request_data_build(name, name_len, trans_id, type, CLASS_INET, req->request, request_max_len); if (rlen < 0) goto err1; req->request_len = rlen; req->trans_id = trans_id; req->tx_count = 0; req->request_type = type; req->user_pointer = user_ptr; req->user_callback = callback; req->ns = issuing_now ? nameserver_pick() : NULL; req->next = req->prev = NULL; return req; err1: free(req); return NULL; } static void request_submit(struct request *const req) { if (req->ns) { /* if it has a nameserver assigned then this is going */ /* straight into the inflight queue */ evdns_request_insert(req, &req_head); global_requests_inflight++; evdns_request_transmit(req); } else { evdns_request_insert(req, &req_waiting_head); global_requests_waiting++; } } /* exported function */ int evdns_resolve_ipv4(const char *name, int flags, evdns_callback_type callback, void *ptr) { log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name); if (flags & DNS_QUERY_NO_SEARCH) { struct request *const req = request_new(TYPE_A, name, flags, callback, ptr); if (req == NULL) return (1); request_submit(req); return (0); } else { return (search_request_new(TYPE_A, name, flags, callback, ptr)); } } /* exported function */ int evdns_resolve_ipv6(const char *name, int flags, evdns_callback_type callback, void *ptr) { log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name); if (flags & DNS_QUERY_NO_SEARCH) { struct request *const req = request_new(TYPE_AAAA, name, flags, callback, ptr); if (req == NULL) return (1); request_submit(req); return (0); } else { return (search_request_new(TYPE_AAAA, name, flags, callback, ptr)); } } int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) { char buf[32]; struct request *req; u32 a; assert(in); a = ntohl(in->s_addr); evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa", (int)(u8)((a )&0xff), (int)(u8)((a>>8 )&0xff), (int)(u8)((a>>16)&0xff), (int)(u8)((a>>24)&0xff)); log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf); req = request_new(TYPE_PTR, buf, flags, callback, ptr); if (!req) return 1; request_submit(req); return 0; } int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) { /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */ char buf[73]; char *cp; struct request *req; int i; assert(in); cp = buf; for (i=15; i >= 0; --i) { u8 byte = in->s6_addr[i]; *cp++ = "0123456789abcdef"[byte & 0x0f]; *cp++ = '.'; *cp++ = "0123456789abcdef"[byte >> 4]; *cp++ = '.'; } assert(cp + strlen("ip6.arpa") < buf+sizeof(buf)); memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1); log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf); req = request_new(TYPE_PTR, buf, flags, callback, ptr); if (!req) return 1; request_submit(req); return 0; } /*/////////////////////////////////////////////////////////////////// */ /* Search support */ /* */ /* the libc resolver has support for searching a number of domains */ /* to find a name. If nothing else then it takes the single domain */ /* from the gethostname() call. */ /* */ /* It can also be configured via the domain and search options in a */ /* resolv.conf. */ /* */ /* The ndots option controls how many dots it takes for the resolver */ /* to decide that a name is non-local and so try a raw lookup first. */ struct search_domain { int len; struct search_domain *next; /* the text string is appended to this structure */ }; struct search_state { int refcount; int ndots; int num_domains; struct search_domain *head; }; static struct search_state *global_search_state = NULL; static void search_state_decref(struct search_state *const state) { if (!state) return; state->refcount--; if (!state->refcount) { struct search_domain *next, *dom; for (dom = state->head; dom; dom = next) { next = dom->next; free(dom); } free(state); } } static struct search_state * search_state_new(void) { struct search_state *state = (struct search_state *) malloc(sizeof(struct search_state)); if (!state) return NULL; memset(state, 0, sizeof(struct search_state)); state->refcount = 1; state->ndots = 1; return state; } static void search_postfix_clear(void) { search_state_decref(global_search_state); global_search_state = search_state_new(); } /* exported function */ void evdns_search_clear(void) { search_postfix_clear(); } static void search_postfix_add(const char *domain) { int domain_len; struct search_domain *sdomain; while (domain[0] == '.') domain++; domain_len = strlen(domain); if (!global_search_state) global_search_state = search_state_new(); if (!global_search_state) return; global_search_state->num_domains++; sdomain = (struct search_domain *) malloc(sizeof(struct search_domain) + domain_len); if (!sdomain) return; memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len); sdomain->next = global_search_state->head; sdomain->len = domain_len; global_search_state->head = sdomain; } /* reverse the order of members in the postfix list. This is needed because, */ /* when parsing resolv.conf we push elements in the wrong order */ static void search_reverse(void) { struct search_domain *cur, *prev = NULL, *next; cur = global_search_state->head; while (cur) { next = cur->next; cur->next = prev; prev = cur; cur = next; } global_search_state->head = prev; } /* exported function */ void evdns_search_add(const char *domain) { search_postfix_add(domain); } /* exported function */ void evdns_search_ndots_set(const int ndots) { if (!global_search_state) global_search_state = search_state_new(); if (!global_search_state) return; global_search_state->ndots = ndots; } static void search_set_from_hostname(void) { char hostname[HOST_NAME_MAX + 1], *domainname; search_postfix_clear(); if (gethostname(hostname, sizeof(hostname))) return; domainname = strchr(hostname, '.'); if (!domainname) return; search_postfix_add(domainname); } /* warning: returns malloced string */ static char * search_make_new(const struct search_state *const state, int n, const char *const base_name) { const int base_len = strlen(base_name); const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1; struct search_domain *dom; for (dom = state->head; dom; dom = dom->next) { if (!n--) { /* this is the postfix we want */ /* the actual postfix string is kept at the end of the structure */ const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain); const int postfix_len = dom->len; char *const newname = (char *) malloc(base_len + need_to_append_dot + postfix_len + 1); if (!newname) return NULL; memcpy(newname, base_name, base_len); if (need_to_append_dot) newname[base_len] = '.'; memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len); newname[base_len + need_to_append_dot + postfix_len] = 0; return newname; } } /* we ran off the end of the list and still didn't find the requested string */ abort(); return NULL; /* unreachable; stops warnings in some compilers. */ } static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) { assert(type == TYPE_A || type == TYPE_AAAA); if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) && global_search_state && global_search_state->num_domains) { /* we have some domains to search */ struct request *req; if (string_num_dots(name) >= global_search_state->ndots) { req = request_new(type, name, flags, user_callback, user_arg); if (!req) return 1; req->search_index = -1; } else { char *const new_name = search_make_new(global_search_state, 0, name); if (!new_name) return 1; req = request_new(type, new_name, flags, user_callback, user_arg); free(new_name); if (!req) return 1; req->search_index = 0; } req->search_origname = strdup(name); req->search_state = global_search_state; req->search_flags = flags; global_search_state->refcount++; request_submit(req); return 0; } else { struct request *const req = request_new(type, name, flags, user_callback, user_arg); if (!req) return 1; request_submit(req); return 0; } } /* this is called when a request has failed to find a name. We need to check */ /* if it is part of a search and, if so, try the next name in the list */ /* returns: */ /* 0 another request has been submitted */ /* 1 no more requests needed */ static int search_try_next(struct request *const req) { if (req->search_state) { /* it is part of a search */ char *new_name; struct request *newreq; req->search_index++; if (req->search_index >= req->search_state->num_domains) { /* no more postfixes to try, however we may need to try */ /* this name without a postfix */ if (string_num_dots(req->search_origname) < req->search_state->ndots) { /* yep, we need to try it raw */ newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer); log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname); if (newreq) { request_submit(newreq); return 0; } } return 1; } new_name = search_make_new(req->search_state, req->search_index, req->search_origname); if (!new_name) return 1; log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index); newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer); free(new_name); if (!newreq) return 1; newreq->search_origname = req->search_origname; req->search_origname = NULL; newreq->search_state = req->search_state; newreq->search_flags = req->search_flags; newreq->search_index = req->search_index; newreq->search_state->refcount++; request_submit(newreq); return 0; } return 1; } static void search_request_finished(struct request *const req) { if (req->search_state) { search_state_decref(req->search_state); req->search_state = NULL; } if (req->search_origname) { free(req->search_origname); req->search_origname = NULL; } } /*/////////////////////////////////////////////////////////////////// */ /* Parsing resolv.conf files */ static void evdns_resolv_set_defaults(int flags) { /* if the file isn't found then we assume a local resolver */ if (flags & DNS_OPTION_SEARCH) search_set_from_hostname(); if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1"); } #ifndef HAVE_STRTOK_R static char * strtok_r(char *s, const char *delim, char **state) { return strtok(s, delim); } #endif /* helper version of atoi which returns -1 on error */ static int strtoint(const char *const str) { char *endptr; const int r = strtol(str, &endptr, 10); if (*endptr) return -1; return r; } /* helper version of atoi that returns -1 on error and clips to bounds. */ static int strtoint_clipped(const char *const str, int min, int max) { int r = strtoint(str); if (r == -1) return r; else if (r<min) return min; else if (r>max) return max; else return r; } /* exported function */ int evdns_set_option(const char *option, const char *val, int flags) { if (!strncmp(option, "ndots:", 6)) { const int ndots = strtoint(val); if (ndots == -1) return -1; if (!(flags & DNS_OPTION_SEARCH)) return 0; log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots); if (!global_search_state) global_search_state = search_state_new(); if (!global_search_state) return -1; global_search_state->ndots = ndots; } else if (!strncmp(option, "timeout:", 8)) { const int timeout = strtoint(val); if (timeout == -1) return -1; if (!(flags & DNS_OPTION_MISC)) return 0; log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout); global_timeout.tv_sec = timeout; } else if (!strncmp(option, "max-timeouts:", 12)) { const int maxtimeout = strtoint_clipped(val, 1, 255); if (maxtimeout == -1) return -1; if (!(flags & DNS_OPTION_MISC)) return 0; log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d", maxtimeout); global_max_nameserver_timeout = maxtimeout; } else if (!strncmp(option, "max-inflight:", 13)) { const int maxinflight = strtoint_clipped(val, 1, 65000); if (maxinflight == -1) return -1; if (!(flags & DNS_OPTION_MISC)) return 0; log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d", maxinflight); global_max_requests_inflight = maxinflight; } else if (!strncmp(option, "attempts:", 9)) { int retries = strtoint(val); if (retries == -1) return -1; if (retries > 255) retries = 255; if (!(flags & DNS_OPTION_MISC)) return 0; log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries); global_max_retransmits = retries; } return 0; } static void resolv_conf_parse_line(char *const start, int flags) { char *strtok_state; static const char *const delims = " \t"; #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state) char *const first_token = strtok_r(start, delims, &strtok_state); if (!first_token) return; if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) { const char *const nameserver = NEXT_TOKEN; struct in_addr ina; if (inet_aton(nameserver, &ina)) { /* address is valid */ evdns_nameserver_add(ina.s_addr); } } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) { const char *const domain = NEXT_TOKEN; if (domain) { search_postfix_clear(); search_postfix_add(domain); } } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) { const char *domain; search_postfix_clear(); while ((domain = NEXT_TOKEN)) { search_postfix_add(domain); } search_reverse(); } else if (!strcmp(first_token, "options")) { const char *option; while ((option = NEXT_TOKEN)) { const char *val = strchr(option, ':'); evdns_set_option(option, val ? val+1 : "", flags); } } #undef NEXT_TOKEN } /* exported function */ /* returns: */ /* 0 no errors */ /* 1 failed to open file */ /* 2 failed to stat file */ /* 3 file too large */ /* 4 out of memory */ /* 5 short read from file */ int evdns_resolv_conf_parse(int flags, const char *const filename) { struct stat st; int fd, n, r; u8 *resolv; char *start; int err = 0; log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename); fd = open(filename, O_RDONLY); if (fd < 0) { evdns_resolv_set_defaults(flags); return 1; } if (fstat(fd, &st)) { err = 2; goto out1; } if (!st.st_size) { evdns_resolv_set_defaults(flags); err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0; goto out1; } if (st.st_size > 65535) { err = 3; goto out1; } /* no resolv.conf should be any bigger */ resolv = (u8 *) malloc((size_t)st.st_size + 1); if (!resolv) { err = 4; goto out1; } n = 0; while ((r = read(fd, resolv+n, (size_t)st.st_size-n)) > 0) { n += r; if (n == st.st_size) break; assert(n < st.st_size); } if (r < 0) { err = 5; goto out2; } resolv[n] = 0; /* we malloced an extra byte; this should be fine. */ start = (char *) resolv; for (;;) { char *const newline = strchr(start, '\n'); if (!newline) { resolv_conf_parse_line(start, flags); break; } else { *newline = 0; resolv_conf_parse_line(start, flags); start = newline + 1; } } if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) { /* no nameservers were configured. */ evdns_nameserver_ip_add("127.0.0.1"); err = 6; } if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) { search_set_from_hostname(); } out2: free(resolv); out1: close(fd); return err; } #ifdef WIN32 /* Add multiple nameservers from a space-or-comma-separated list. */ static int evdns_nameserver_ip_add_line(const char *ips) { const char *addr; char *buf; int r; while (*ips) { while (ISSPACE(*ips) || *ips == ',' || *ips == '\t') ++ips; addr = ips; while (ISDIGIT(*ips) || *ips == '.' || *ips == ':') ++ips; buf = malloc(ips-addr+1); if (!buf) return 4; memcpy(buf, addr, ips-addr); buf[ips-addr] = '\0'; r = evdns_nameserver_ip_add(buf); free(buf); if (r) return r; } return 0; } typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*); /* Use the windows GetNetworkParams interface in iphlpapi.dll to */ /* figure out what our nameservers are. */ static int load_nameservers_with_getnetworkparams(void) { /* Based on MSDN examples and inspection of c-ares code. */ FIXED_INFO *fixed; HMODULE handle = 0; ULONG size = sizeof(FIXED_INFO); void *buf = NULL; int status = 0, r, added_any; IP_ADDR_STRING *ns; GetNetworkParams_fn_t fn; if (!(handle = LoadLibrary("iphlpapi.dll"))) { log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll"); status = -1; goto done; } if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) { log(EVDNS_LOG_WARN, "Could not get address of function."); status = -1; goto done; } buf = malloc(size); if (!buf) { status = 4; goto done; } fixed = buf; r = fn(fixed, &size); if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) { status = -1; goto done; } if (r != ERROR_SUCCESS) { free(buf); buf = malloc(size); if (!buf) { status = 4; goto done; } fixed = buf; r = fn(fixed, &size); if (r != ERROR_SUCCESS) { log(EVDNS_LOG_DEBUG, "fn() failed."); status = -1; goto done; } } assert(fixed); added_any = 0; ns = &(fixed->DnsServerList); while (ns) { r = evdns_nameserver_ip_add_line(ns->IpAddress.String); if (r) { log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d", (ns->IpAddress.String),(int)GetLastError()); status = r; goto done; } else { log(EVDNS_LOG_DEBUG,"Succesfully added %s as nameserver",ns->IpAddress.String); } added_any++; ns = ns->Next; } if (!added_any) { log(EVDNS_LOG_DEBUG, "No nameservers added."); status = -1; } done: if (buf) free(buf); if (handle) FreeLibrary(handle); return status; } static int config_nameserver_from_reg_key(HKEY key, const char *subkey) { char *buf; DWORD bufsz = 0, type = 0; int status = 0; if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz) != ERROR_MORE_DATA) return -1; if (!(buf = malloc(bufsz))) return -1; if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz) == ERROR_SUCCESS && bufsz > 1) { status = evdns_nameserver_ip_add_line(buf); } free(buf); return status; } #define SERVICES_KEY "System\\CurrentControlSet\\Services\\" #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP" #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters" static int load_nameservers_from_registry(void) { int found = 0; int r; #define TRY(k, name) \ if (!found && config_nameserver_from_reg_key(k,name) == 0) { \ log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \ found = 1; \ } else if (!found) { \ log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \ #k,#name); \ } if (((int)GetVersion()) > 0) { /* NT */ HKEY nt_key = 0, interfaces_key = 0; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ, &nt_key) != ERROR_SUCCESS) { log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError()); return -1; } r = RegOpenKeyEx(nt_key, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &interfaces_key); if (r != ERROR_SUCCESS) { log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError()); return -1; } TRY(nt_key, "NameServer"); TRY(nt_key, "DhcpNameServer"); TRY(interfaces_key, "NameServer"); TRY(interfaces_key, "DhcpNameServer"); RegCloseKey(interfaces_key); RegCloseKey(nt_key); } else { HKEY win_key = 0; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0, KEY_READ, &win_key) != ERROR_SUCCESS) { log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError()); return -1; } TRY(win_key, "NameServer"); RegCloseKey(win_key); } if (found == 0) { log(EVDNS_LOG_WARN,"Didn't find any nameservers."); } return found ? 0 : -1; #undef TRY } int evdns_config_windows_nameservers(void) { if (load_nameservers_with_getnetworkparams() == 0) return 0; return load_nameservers_from_registry(); } #endif int evdns_init(void) { int res = 0; #ifdef WIN32 res = evdns_config_windows_nameservers(); #else res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf"); #endif return (res); } const char * evdns_err_to_string(int err) { switch (err) { case DNS_ERR_NONE: return "no error"; case DNS_ERR_FORMAT: return "misformatted query"; case DNS_ERR_SERVERFAILED: return "server failed"; case DNS_ERR_NOTEXIST: return "name does not exist"; case DNS_ERR_NOTIMPL: return "query not implemented"; case DNS_ERR_REFUSED: return "refused"; case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed"; case DNS_ERR_UNKNOWN: return "unknown"; case DNS_ERR_TIMEOUT: return "request timed out"; case DNS_ERR_SHUTDOWN: return "dns subsystem shut down"; default: return "[Unknown error code]"; } } void evdns_shutdown(int fail_requests) { struct nameserver *server, *server_next; struct search_domain *dom, *dom_next; while (req_head) { if (fail_requests) reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL); request_finished(req_head, &req_head); } while (req_waiting_head) { if (fail_requests) reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL); request_finished(req_waiting_head, &req_waiting_head); } global_requests_inflight = global_requests_waiting = 0; for (server = server_head; server; server = server_next) { server_next = server->next; if (server->socket >= 0) CLOSE_SOCKET(server->socket); (void) event_del(&server->event); if (server->state == 0) (void) event_del(&server->timeout_event); free(server); if (server_next == server_head) break; } server_head = NULL; global_good_nameservers = 0; if (global_search_state) { for (dom = global_search_state->head; dom; dom = dom_next) { dom_next = dom->next; free(dom); } free(global_search_state); global_search_state = NULL; } evdns_log_fn = NULL; } #ifdef EVDNS_MAIN void main_callback(int result, char type, int count, int ttl, void *addrs, void *orig) { char *n = (char*)orig; int i; for (i = 0; i < count; ++i) { if (type == DNS_IPv4_A) { printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i])); } else if (type == DNS_PTR) { printf("%s: %s\n", n, ((char**)addrs)[i]); } } if (!count) { printf("%s: No answer (%d)\n", n, result); } fflush(stdout); } void evdns_server_callback(struct evdns_server_request *req, void *data) { int i, r; (void)data; /* dummy; give 192.168.11.11 as an answer for all A questions, * give foo.bar.example.com as an answer for all PTR questions. */ for (i = 0; i < req->nquestions; ++i) { u32 ans = htonl(0xc0a80b0bUL); if (req->questions[i]->type == EVDNS_TYPE_A && req->questions[i]->dns_question_class == EVDNS_CLASS_INET) { printf(" -- replying for %s (A)\n", req->questions[i]->name); r = evdns_server_request_add_a_reply(req, req->questions[i]->name, 1, &ans, 10); if (r<0) printf("eeep, didn't work.\n"); } else if (req->questions[i]->type == EVDNS_TYPE_PTR && req->questions[i]->dns_question_class == EVDNS_CLASS_INET) { printf(" -- replying for %s (PTR)\n", req->questions[i]->name); r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name, "foo.bar.example.com", 10); } else { printf(" -- skipping %s [%d %d]\n", req->questions[i]->name, req->questions[i]->type, req->questions[i]->dns_question_class); } } r = evdns_request_respond(req, 0); if (r<0) printf("eeek, couldn't send reply.\n"); } void logfn(int is_warn, const char *msg) { (void) is_warn; fprintf(stderr, "%s\n", msg); } int main(int c, char **v) { int idx; int reverse = 0, verbose = 1, servertest = 0; if (c<2) { fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]); fprintf(stderr, "syntax: %s [-servertest]\n", v[0]); return 1; } idx = 1; while (idx < c && v[idx][0] == '-') { if (!strcmp(v[idx], "-x")) reverse = 1; else if (!strcmp(v[idx], "-v")) verbose = 1; else if (!strcmp(v[idx], "-servertest")) servertest = 1; else fprintf(stderr, "Unknown option %s\n", v[idx]); ++idx; } event_init(); if (verbose) evdns_set_log_fn(logfn); evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf"); if (servertest) { int sock; struct sockaddr_in my_addr; sock = socket(PF_INET, SOCK_DGRAM, 0); evutil_make_socket_nonblocking(sock); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(10053); my_addr.sin_addr.s_addr = INADDR_ANY; if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) { perror("bind"); exit(1); } evdns_add_server_port(sock, 0, evdns_server_callback, NULL); } for (; idx < c; ++idx) { if (reverse) { struct in_addr addr; if (!inet_aton(v[idx], &addr)) { fprintf(stderr, "Skipping non-IP %s\n", v[idx]); continue; } fprintf(stderr, "resolving %s...\n",v[idx]); evdns_resolve_reverse(&addr, 0, main_callback, v[idx]); } else { fprintf(stderr, "resolving (fwd) %s...\n",v[idx]); evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]); } } fflush(stdout); event_dispatch(); return 0; } #endif
bsd-3-clause
ar-android/fresco
imagepipeline/src/main/jni/imagepipeline/png/png_stream_wrappers.cpp
137
1878
/* * 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. */ #include <algorithm> #include <iterator> #include <jni.h> #include <png.h> #include "exceptions.h" #include "java_globals.h" #include "png_stream_wrappers.h" namespace facebook { namespace imagepipeline { namespace png { void pngNoOpFlush(png_structp png_ptr) { } void pngWriteToJavaOutputStream( png_structp png_ptr, png_bytep data, png_size_t length) { PngOutputStreamWrapper* os_wrapper = reinterpret_cast<PngOutputStreamWrapper*>(png_get_io_ptr(png_ptr)); os_wrapper->write(png_ptr, data, length); } PngOutputStreamWrapper::PngOutputStreamWrapper( JNIEnv* env, jobject os, const int bufferSize) : env_(env), os_(os), bufferSize_(bufferSize) { buffer_ = env_->NewByteArray(bufferSize_); RETURN_IF_EXCEPTION_PENDING; } void PngOutputStreamWrapper::write( png_structp png_ptr, png_bytep data, png_size_t length) { while (length > 0) { const int portion_length = std::min<int>(bufferSize_, length); env_->SetByteArrayRegion( buffer_, 0, reinterpret_cast<jsize>(portion_length), reinterpret_cast<jbyte*>(data)); if (env_->ExceptionCheck()) { png_error(png_ptr, "Error when copying data to java array."); } env_->CallVoidMethod( os_, midOutputStreamWriteWithBounds, buffer_, 0, reinterpret_cast<jint>(portion_length)); if (env_->ExceptionCheck()) { png_error(png_ptr, "Error when writing data to OutputStream."); } std::advance(data, portion_length); length -= portion_length; } } } } }
bsd-3-clause
junmin-zhu/chromium-rivertrail
third_party/sqlite/src/ext/async/sqlite3async.c
145
54487
/* ** 2005 December 14 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** $Id: sqlite3async.c,v 1.7 2009/07/18 11:52:04 danielk1977 Exp $ ** ** This file contains the implementation of an asynchronous IO backend ** for SQLite. */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ASYNCIO) #include "sqlite3async.h" #include "sqlite3.h" #include <stdarg.h> #include <string.h> #include <assert.h> /* Useful macros used in several places */ #define MIN(x,y) ((x)<(y)?(x):(y)) #define MAX(x,y) ((x)>(y)?(x):(y)) #ifndef SQLITE_AMALGAMATION /* Macro to mark parameters as unused and silence compiler warnings. */ #define UNUSED_PARAMETER(x) (void)(x) #endif /* Forward references */ typedef struct AsyncWrite AsyncWrite; typedef struct AsyncFile AsyncFile; typedef struct AsyncFileData AsyncFileData; typedef struct AsyncFileLock AsyncFileLock; typedef struct AsyncLock AsyncLock; /* Enable for debugging */ #ifndef NDEBUG #include <stdio.h> static int sqlite3async_trace = 0; # define ASYNC_TRACE(X) if( sqlite3async_trace ) asyncTrace X static void asyncTrace(const char *zFormat, ...){ char *z; va_list ap; va_start(ap, zFormat); z = sqlite3_vmprintf(zFormat, ap); va_end(ap); fprintf(stderr, "[%d] %s", 0 /* (int)pthread_self() */, z); sqlite3_free(z); } #else # define ASYNC_TRACE(X) #endif /* ** THREAD SAFETY NOTES ** ** Basic rules: ** ** * Both read and write access to the global write-op queue must be ** protected by the async.queueMutex. As are the async.ioError and ** async.nFile variables. ** ** * The async.pLock list and all AsyncLock and AsyncFileLock ** structures must be protected by the async.lockMutex mutex. ** ** * The file handles from the underlying system are not assumed to ** be thread safe. ** ** * See the last two paragraphs under "The Writer Thread" for ** an assumption to do with file-handle synchronization by the Os. ** ** Deadlock prevention: ** ** There are three mutex used by the system: the "writer" mutex, ** the "queue" mutex and the "lock" mutex. Rules are: ** ** * It is illegal to block on the writer mutex when any other mutex ** are held, and ** ** * It is illegal to block on the queue mutex when the lock mutex ** is held. ** ** i.e. mutex's must be grabbed in the order "writer", "queue", "lock". ** ** File system operations (invoked by SQLite thread): ** ** xOpen ** xDelete ** xFileExists ** ** File handle operations (invoked by SQLite thread): ** ** asyncWrite, asyncClose, asyncTruncate, asyncSync ** ** The operations above add an entry to the global write-op list. They ** prepare the entry, acquire the async.queueMutex momentarily while ** list pointers are manipulated to insert the new entry, then release ** the mutex and signal the writer thread to wake up in case it happens ** to be asleep. ** ** ** asyncRead, asyncFileSize. ** ** Read operations. Both of these read from both the underlying file ** first then adjust their result based on pending writes in the ** write-op queue. So async.queueMutex is held for the duration ** of these operations to prevent other threads from changing the ** queue in mid operation. ** ** ** asyncLock, asyncUnlock, asyncCheckReservedLock ** ** These primitives implement in-process locking using a hash table ** on the file name. Files are locked correctly for connections coming ** from the same process. But other processes cannot see these locks ** and will therefore not honor them. ** ** ** The writer thread: ** ** The async.writerMutex is used to make sure only there is only ** a single writer thread running at a time. ** ** Inside the writer thread is a loop that works like this: ** ** WHILE (write-op list is not empty) ** Do IO operation at head of write-op list ** Remove entry from head of write-op list ** END WHILE ** ** The async.queueMutex is always held during the <write-op list is ** not empty> test, and when the entry is removed from the head ** of the write-op list. Sometimes it is held for the interim ** period (while the IO is performed), and sometimes it is ** relinquished. It is relinquished if (a) the IO op is an ** ASYNC_CLOSE or (b) when the file handle was opened, two of ** the underlying systems handles were opened on the same ** file-system entry. ** ** If condition (b) above is true, then one file-handle ** (AsyncFile.pBaseRead) is used exclusively by sqlite threads to read the ** file, the other (AsyncFile.pBaseWrite) by sqlite3_async_flush() ** threads to perform write() operations. This means that read ** operations are not blocked by asynchronous writes (although ** asynchronous writes may still be blocked by reads). ** ** This assumes that the OS keeps two handles open on the same file ** properly in sync. That is, any read operation that starts after a ** write operation on the same file system entry has completed returns ** data consistent with the write. We also assume that if one thread ** reads a file while another is writing it all bytes other than the ** ones actually being written contain valid data. ** ** If the above assumptions are not true, set the preprocessor symbol ** SQLITE_ASYNC_TWO_FILEHANDLES to 0. */ #ifndef NDEBUG # define TESTONLY( X ) X #else # define TESTONLY( X ) #endif /* ** PORTING FUNCTIONS ** ** There are two definitions of the following functions. One for pthreads ** compatible systems and one for Win32. These functions isolate the OS ** specific code required by each platform. ** ** The system uses three mutexes and a single condition variable. To ** block on a mutex, async_mutex_enter() is called. The parameter passed ** to async_mutex_enter(), which must be one of ASYNC_MUTEX_LOCK, ** ASYNC_MUTEX_QUEUE or ASYNC_MUTEX_WRITER, identifies which of the three ** mutexes to lock. Similarly, to unlock a mutex, async_mutex_leave() is ** called with a parameter identifying the mutex being unlocked. Mutexes ** are not recursive - it is an error to call async_mutex_enter() to ** lock a mutex that is already locked, or to call async_mutex_leave() ** to unlock a mutex that is not currently locked. ** ** The async_cond_wait() and async_cond_signal() functions are modelled ** on the pthreads functions with similar names. The first parameter to ** both functions is always ASYNC_COND_QUEUE. When async_cond_wait() ** is called the mutex identified by the second parameter must be held. ** The mutex is unlocked, and the calling thread simultaneously begins ** waiting for the condition variable to be signalled by another thread. ** After another thread signals the condition variable, the calling ** thread stops waiting, locks mutex eMutex and returns. The ** async_cond_signal() function is used to signal the condition variable. ** It is assumed that the mutex used by the thread calling async_cond_wait() ** is held by the caller of async_cond_signal() (otherwise there would be ** a race condition). ** ** It is guaranteed that no other thread will call async_cond_wait() when ** there is already a thread waiting on the condition variable. ** ** The async_sched_yield() function is called to suggest to the operating ** system that it would be a good time to shift the current thread off the ** CPU. The system will still work if this function is not implemented ** (it is not currently implemented for win32), but it might be marginally ** more efficient if it is. */ static void async_mutex_enter(int eMutex); static void async_mutex_leave(int eMutex); static void async_cond_wait(int eCond, int eMutex); static void async_cond_signal(int eCond); static void async_sched_yield(void); /* ** There are also two definitions of the following. async_os_initialize() ** is called when the asynchronous VFS is first installed, and os_shutdown() ** is called when it is uninstalled (from within sqlite3async_shutdown()). ** ** For pthreads builds, both of these functions are no-ops. For win32, ** they provide an opportunity to initialize and finalize the required ** mutex and condition variables. ** ** If async_os_initialize() returns other than zero, then the initialization ** fails and SQLITE_ERROR is returned to the user. */ static int async_os_initialize(void); static void async_os_shutdown(void); /* Values for use as the 'eMutex' argument of the above functions. The ** integer values assigned to these constants are important for assert() ** statements that verify that mutexes are locked in the correct order. ** Specifically, it is unsafe to try to lock mutex N while holding a lock ** on mutex M if (M<=N). */ #define ASYNC_MUTEX_LOCK 0 #define ASYNC_MUTEX_QUEUE 1 #define ASYNC_MUTEX_WRITER 2 /* Values for use as the 'eCond' argument of the above functions. */ #define ASYNC_COND_QUEUE 0 /************************************************************************* ** Start of OS specific code. */ #if SQLITE_OS_WIN || defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) #include <windows.h> /* The following block contains the win32 specific code. */ #define mutex_held(X) (GetCurrentThreadId()==primitives.aHolder[X]) static struct AsyncPrimitives { int isInit; DWORD aHolder[3]; CRITICAL_SECTION aMutex[3]; HANDLE aCond[1]; } primitives = { 0 }; static int async_os_initialize(void){ if( !primitives.isInit ){ primitives.aCond[0] = CreateEvent(NULL, TRUE, FALSE, 0); if( primitives.aCond[0]==NULL ){ return 1; } InitializeCriticalSection(&primitives.aMutex[0]); InitializeCriticalSection(&primitives.aMutex[1]); InitializeCriticalSection(&primitives.aMutex[2]); primitives.isInit = 1; } return 0; } static void async_os_shutdown(void){ if( primitives.isInit ){ DeleteCriticalSection(&primitives.aMutex[0]); DeleteCriticalSection(&primitives.aMutex[1]); DeleteCriticalSection(&primitives.aMutex[2]); CloseHandle(primitives.aCond[0]); primitives.isInit = 0; } } /* The following block contains the Win32 specific code. */ static void async_mutex_enter(int eMutex){ assert( eMutex==0 || eMutex==1 || eMutex==2 ); assert( eMutex!=2 || (!mutex_held(0) && !mutex_held(1) && !mutex_held(2)) ); assert( eMutex!=1 || (!mutex_held(0) && !mutex_held(1)) ); assert( eMutex!=0 || (!mutex_held(0)) ); EnterCriticalSection(&primitives.aMutex[eMutex]); TESTONLY( primitives.aHolder[eMutex] = GetCurrentThreadId(); ) } static void async_mutex_leave(int eMutex){ assert( eMutex==0 || eMutex==1 || eMutex==2 ); assert( mutex_held(eMutex) ); TESTONLY( primitives.aHolder[eMutex] = 0; ) LeaveCriticalSection(&primitives.aMutex[eMutex]); } static void async_cond_wait(int eCond, int eMutex){ ResetEvent(primitives.aCond[eCond]); async_mutex_leave(eMutex); WaitForSingleObject(primitives.aCond[eCond], INFINITE); async_mutex_enter(eMutex); } static void async_cond_signal(int eCond){ assert( mutex_held(ASYNC_MUTEX_QUEUE) ); SetEvent(primitives.aCond[eCond]); } static void async_sched_yield(void){ Sleep(0); } #else /* The following block contains the pthreads specific code. */ #include <pthread.h> #include <sched.h> #define mutex_held(X) pthread_equal(primitives.aHolder[X], pthread_self()) static int async_os_initialize(void) {return 0;} static void async_os_shutdown(void) {} static struct AsyncPrimitives { pthread_mutex_t aMutex[3]; pthread_cond_t aCond[1]; pthread_t aHolder[3]; } primitives = { { PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER } , { PTHREAD_COND_INITIALIZER } , { 0, 0, 0 } }; static void async_mutex_enter(int eMutex){ assert( eMutex==0 || eMutex==1 || eMutex==2 ); assert( eMutex!=2 || (!mutex_held(0) && !mutex_held(1) && !mutex_held(2)) ); assert( eMutex!=1 || (!mutex_held(0) && !mutex_held(1)) ); assert( eMutex!=0 || (!mutex_held(0)) ); pthread_mutex_lock(&primitives.aMutex[eMutex]); TESTONLY( primitives.aHolder[eMutex] = pthread_self(); ) } static void async_mutex_leave(int eMutex){ assert( eMutex==0 || eMutex==1 || eMutex==2 ); assert( mutex_held(eMutex) ); TESTONLY( primitives.aHolder[eMutex] = 0; ) pthread_mutex_unlock(&primitives.aMutex[eMutex]); } static void async_cond_wait(int eCond, int eMutex){ assert( eMutex==0 || eMutex==1 || eMutex==2 ); assert( mutex_held(eMutex) ); TESTONLY( primitives.aHolder[eMutex] = 0; ) pthread_cond_wait(&primitives.aCond[eCond], &primitives.aMutex[eMutex]); TESTONLY( primitives.aHolder[eMutex] = pthread_self(); ) } static void async_cond_signal(int eCond){ assert( mutex_held(ASYNC_MUTEX_QUEUE) ); pthread_cond_signal(&primitives.aCond[eCond]); } static void async_sched_yield(void){ sched_yield(); } #endif /* ** End of OS specific code. *************************************************************************/ #define assert_mutex_is_held(X) assert( mutex_held(X) ) #ifndef SQLITE_ASYNC_TWO_FILEHANDLES /* #define SQLITE_ASYNC_TWO_FILEHANDLES 0 */ #define SQLITE_ASYNC_TWO_FILEHANDLES 1 #endif /* ** State information is held in the static variable "async" defined ** as the following structure. ** ** Both async.ioError and async.nFile are protected by async.queueMutex. */ static struct TestAsyncStaticData { AsyncWrite *pQueueFirst; /* Next write operation to be processed */ AsyncWrite *pQueueLast; /* Last write operation on the list */ AsyncLock *pLock; /* Linked list of all AsyncLock structures */ volatile int ioDelay; /* Extra delay between write operations */ volatile int eHalt; /* One of the SQLITEASYNC_HALT_XXX values */ volatile int bLockFiles; /* Current value of "lockfiles" parameter */ int ioError; /* True if an IO error has occurred */ int nFile; /* Number of open files (from sqlite pov) */ } async = { 0,0,0,0,0,1,0,0 }; /* Possible values of AsyncWrite.op */ #define ASYNC_NOOP 0 #define ASYNC_WRITE 1 #define ASYNC_SYNC 2 #define ASYNC_TRUNCATE 3 #define ASYNC_CLOSE 4 #define ASYNC_DELETE 5 #define ASYNC_OPENEXCLUSIVE 6 #define ASYNC_UNLOCK 7 /* Names of opcodes. Used for debugging only. ** Make sure these stay in sync with the macros above! */ static const char *azOpcodeName[] = { "NOOP", "WRITE", "SYNC", "TRUNCATE", "CLOSE", "DELETE", "OPENEX", "UNLOCK" }; /* ** Entries on the write-op queue are instances of the AsyncWrite ** structure, defined here. ** ** The interpretation of the iOffset and nByte variables varies depending ** on the value of AsyncWrite.op: ** ** ASYNC_NOOP: ** No values used. ** ** ASYNC_WRITE: ** iOffset -> Offset in file to write to. ** nByte -> Number of bytes of data to write (pointed to by zBuf). ** ** ASYNC_SYNC: ** nByte -> flags to pass to sqlite3OsSync(). ** ** ASYNC_TRUNCATE: ** iOffset -> Size to truncate file to. ** nByte -> Unused. ** ** ASYNC_CLOSE: ** iOffset -> Unused. ** nByte -> Unused. ** ** ASYNC_DELETE: ** iOffset -> Contains the "syncDir" flag. ** nByte -> Number of bytes of zBuf points to (file name). ** ** ASYNC_OPENEXCLUSIVE: ** iOffset -> Value of "delflag". ** nByte -> Number of bytes of zBuf points to (file name). ** ** ASYNC_UNLOCK: ** nByte -> Argument to sqlite3OsUnlock(). ** ** ** For an ASYNC_WRITE operation, zBuf points to the data to write to the file. ** This space is sqlite3_malloc()d along with the AsyncWrite structure in a ** single blob, so is deleted when sqlite3_free() is called on the parent ** structure. */ struct AsyncWrite { AsyncFileData *pFileData; /* File to write data to or sync */ int op; /* One of ASYNC_xxx etc. */ sqlite_int64 iOffset; /* See above */ int nByte; /* See above */ char *zBuf; /* Data to write to file (or NULL if op!=ASYNC_WRITE) */ AsyncWrite *pNext; /* Next write operation (to any file) */ }; /* ** An instance of this structure is created for each distinct open file ** (i.e. if two handles are opened on the one file, only one of these ** structures is allocated) and stored in the async.aLock hash table. The ** keys for async.aLock are the full pathnames of the opened files. ** ** AsyncLock.pList points to the head of a linked list of AsyncFileLock ** structures, one for each handle currently open on the file. ** ** If the opened file is not a main-database (the SQLITE_OPEN_MAIN_DB is ** not passed to the sqlite3OsOpen() call), or if async.bLockFiles is ** false, variables AsyncLock.pFile and AsyncLock.eLock are never used. ** Otherwise, pFile is a file handle opened on the file in question and ** used to obtain the file-system locks required by database connections ** within this process. ** ** See comments above the asyncLock() function for more details on ** the implementation of database locking used by this backend. */ struct AsyncLock { char *zFile; int nFile; sqlite3_file *pFile; int eLock; AsyncFileLock *pList; AsyncLock *pNext; /* Next in linked list headed by async.pLock */ }; /* ** An instance of the following structure is allocated along with each ** AsyncFileData structure (see AsyncFileData.lock), but is only used if the ** file was opened with the SQLITE_OPEN_MAIN_DB. */ struct AsyncFileLock { int eLock; /* Internally visible lock state (sqlite pov) */ int eAsyncLock; /* Lock-state with write-queue unlock */ AsyncFileLock *pNext; }; /* ** The AsyncFile structure is a subclass of sqlite3_file used for ** asynchronous IO. ** ** All of the actual data for the structure is stored in the structure ** pointed to by AsyncFile.pData, which is allocated as part of the ** sqlite3OsOpen() using sqlite3_malloc(). The reason for this is that the ** lifetime of the AsyncFile structure is ended by the caller after OsClose() ** is called, but the data in AsyncFileData may be required by the ** writer thread after that point. */ struct AsyncFile { sqlite3_io_methods *pMethod; AsyncFileData *pData; }; struct AsyncFileData { char *zName; /* Underlying OS filename - used for debugging */ int nName; /* Number of characters in zName */ sqlite3_file *pBaseRead; /* Read handle to the underlying Os file */ sqlite3_file *pBaseWrite; /* Write handle to the underlying Os file */ AsyncFileLock lock; /* Lock state for this handle */ AsyncLock *pLock; /* AsyncLock object for this file system entry */ AsyncWrite closeOp; /* Preallocated close operation */ }; /* ** Add an entry to the end of the global write-op list. pWrite should point ** to an AsyncWrite structure allocated using sqlite3_malloc(). The writer ** thread will call sqlite3_free() to free the structure after the specified ** operation has been completed. ** ** Once an AsyncWrite structure has been added to the list, it becomes the ** property of the writer thread and must not be read or modified by the ** caller. */ static void addAsyncWrite(AsyncWrite *pWrite){ /* We must hold the queue mutex in order to modify the queue pointers */ if( pWrite->op!=ASYNC_UNLOCK ){ async_mutex_enter(ASYNC_MUTEX_QUEUE); } /* Add the record to the end of the write-op queue */ assert( !pWrite->pNext ); if( async.pQueueLast ){ assert( async.pQueueFirst ); async.pQueueLast->pNext = pWrite; }else{ async.pQueueFirst = pWrite; } async.pQueueLast = pWrite; ASYNC_TRACE(("PUSH %p (%s %s %d)\n", pWrite, azOpcodeName[pWrite->op], pWrite->pFileData ? pWrite->pFileData->zName : "-", pWrite->iOffset)); if( pWrite->op==ASYNC_CLOSE ){ async.nFile--; } /* The writer thread might have been idle because there was nothing ** on the write-op queue for it to do. So wake it up. */ async_cond_signal(ASYNC_COND_QUEUE); /* Drop the queue mutex */ if( pWrite->op!=ASYNC_UNLOCK ){ async_mutex_leave(ASYNC_MUTEX_QUEUE); } } /* ** Increment async.nFile in a thread-safe manner. */ static void incrOpenFileCount(void){ /* We must hold the queue mutex in order to modify async.nFile */ async_mutex_enter(ASYNC_MUTEX_QUEUE); if( async.nFile==0 ){ async.ioError = SQLITE_OK; } async.nFile++; async_mutex_leave(ASYNC_MUTEX_QUEUE); } /* ** This is a utility function to allocate and populate a new AsyncWrite ** structure and insert it (via addAsyncWrite() ) into the global list. */ static int addNewAsyncWrite( AsyncFileData *pFileData, int op, sqlite3_int64 iOffset, int nByte, const char *zByte ){ AsyncWrite *p; if( op!=ASYNC_CLOSE && async.ioError ){ return async.ioError; } p = sqlite3_malloc(sizeof(AsyncWrite) + (zByte?nByte:0)); if( !p ){ /* The upper layer does not expect operations like OsWrite() to ** return SQLITE_NOMEM. This is partly because under normal conditions ** SQLite is required to do rollback without calling malloc(). So ** if malloc() fails here, treat it as an I/O error. The above ** layer knows how to handle that. */ return SQLITE_IOERR; } p->op = op; p->iOffset = iOffset; p->nByte = nByte; p->pFileData = pFileData; p->pNext = 0; if( zByte ){ p->zBuf = (char *)&p[1]; memcpy(p->zBuf, zByte, nByte); }else{ p->zBuf = 0; } addAsyncWrite(p); return SQLITE_OK; } /* ** Close the file. This just adds an entry to the write-op list, the file is ** not actually closed. */ static int asyncClose(sqlite3_file *pFile){ AsyncFileData *p = ((AsyncFile *)pFile)->pData; /* Unlock the file, if it is locked */ async_mutex_enter(ASYNC_MUTEX_LOCK); p->lock.eLock = 0; async_mutex_leave(ASYNC_MUTEX_LOCK); addAsyncWrite(&p->closeOp); return SQLITE_OK; } /* ** Implementation of sqlite3OsWrite() for asynchronous files. Instead of ** writing to the underlying file, this function adds an entry to the end of ** the global AsyncWrite list. Either SQLITE_OK or SQLITE_NOMEM may be ** returned. */ static int asyncWrite( sqlite3_file *pFile, const void *pBuf, int amt, sqlite3_int64 iOff ){ AsyncFileData *p = ((AsyncFile *)pFile)->pData; return addNewAsyncWrite(p, ASYNC_WRITE, iOff, amt, pBuf); } /* ** Read data from the file. First we read from the filesystem, then adjust ** the contents of the buffer based on ASYNC_WRITE operations in the ** write-op queue. ** ** This method holds the mutex from start to finish. */ static int asyncRead( sqlite3_file *pFile, void *zOut, int iAmt, sqlite3_int64 iOffset ){ AsyncFileData *p = ((AsyncFile *)pFile)->pData; int rc = SQLITE_OK; sqlite3_int64 filesize = 0; sqlite3_file *pBase = p->pBaseRead; sqlite3_int64 iAmt64 = (sqlite3_int64)iAmt; /* Grab the write queue mutex for the duration of the call */ async_mutex_enter(ASYNC_MUTEX_QUEUE); /* If an I/O error has previously occurred in this virtual file ** system, then all subsequent operations fail. */ if( async.ioError!=SQLITE_OK ){ rc = async.ioError; goto asyncread_out; } if( pBase->pMethods ){ sqlite3_int64 nRead; rc = pBase->pMethods->xFileSize(pBase, &filesize); if( rc!=SQLITE_OK ){ goto asyncread_out; } nRead = MIN(filesize - iOffset, iAmt64); if( nRead>0 ){ rc = pBase->pMethods->xRead(pBase, zOut, (int)nRead, iOffset); ASYNC_TRACE(("READ %s %d bytes at %d\n", p->zName, nRead, iOffset)); } } if( rc==SQLITE_OK ){ AsyncWrite *pWrite; char *zName = p->zName; for(pWrite=async.pQueueFirst; pWrite; pWrite = pWrite->pNext){ if( pWrite->op==ASYNC_WRITE && ( (pWrite->pFileData==p) || (zName && pWrite->pFileData->zName==zName) )){ sqlite3_int64 nCopy; sqlite3_int64 nByte64 = (sqlite3_int64)pWrite->nByte; /* Set variable iBeginIn to the offset in buffer pWrite->zBuf[] from ** which data should be copied. Set iBeginOut to the offset within ** the output buffer to which data should be copied. If either of ** these offsets is a negative number, set them to 0. */ sqlite3_int64 iBeginOut = (pWrite->iOffset-iOffset); sqlite3_int64 iBeginIn = -iBeginOut; if( iBeginIn<0 ) iBeginIn = 0; if( iBeginOut<0 ) iBeginOut = 0; filesize = MAX(filesize, pWrite->iOffset+nByte64); nCopy = MIN(nByte64-iBeginIn, iAmt64-iBeginOut); if( nCopy>0 ){ memcpy(&((char *)zOut)[iBeginOut], &pWrite->zBuf[iBeginIn], (size_t)nCopy); ASYNC_TRACE(("OVERREAD %d bytes at %d\n", nCopy, iBeginOut+iOffset)); } } } } asyncread_out: async_mutex_leave(ASYNC_MUTEX_QUEUE); if( rc==SQLITE_OK && filesize<(iOffset+iAmt) ){ rc = SQLITE_IOERR_SHORT_READ; } return rc; } /* ** Truncate the file to nByte bytes in length. This just adds an entry to ** the write-op list, no IO actually takes place. */ static int asyncTruncate(sqlite3_file *pFile, sqlite3_int64 nByte){ AsyncFileData *p = ((AsyncFile *)pFile)->pData; return addNewAsyncWrite(p, ASYNC_TRUNCATE, nByte, 0, 0); } /* ** Sync the file. This just adds an entry to the write-op list, the ** sync() is done later by sqlite3_async_flush(). */ static int asyncSync(sqlite3_file *pFile, int flags){ AsyncFileData *p = ((AsyncFile *)pFile)->pData; return addNewAsyncWrite(p, ASYNC_SYNC, 0, flags, 0); } /* ** Read the size of the file. First we read the size of the file system ** entry, then adjust for any ASYNC_WRITE or ASYNC_TRUNCATE operations ** currently in the write-op list. ** ** This method holds the mutex from start to finish. */ int asyncFileSize(sqlite3_file *pFile, sqlite3_int64 *piSize){ AsyncFileData *p = ((AsyncFile *)pFile)->pData; int rc = SQLITE_OK; sqlite3_int64 s = 0; sqlite3_file *pBase; async_mutex_enter(ASYNC_MUTEX_QUEUE); /* Read the filesystem size from the base file. If pMethods is NULL, this ** means the file hasn't been opened yet. In this case all relevant data ** must be in the write-op queue anyway, so we can omit reading from the ** file-system. */ pBase = p->pBaseRead; if( pBase->pMethods ){ rc = pBase->pMethods->xFileSize(pBase, &s); } if( rc==SQLITE_OK ){ AsyncWrite *pWrite; for(pWrite=async.pQueueFirst; pWrite; pWrite = pWrite->pNext){ if( pWrite->op==ASYNC_DELETE && p->zName && strcmp(p->zName, pWrite->zBuf)==0 ){ s = 0; }else if( pWrite->pFileData && ( (pWrite->pFileData==p) || (p->zName && pWrite->pFileData->zName==p->zName) )){ switch( pWrite->op ){ case ASYNC_WRITE: s = MAX(pWrite->iOffset + (sqlite3_int64)(pWrite->nByte), s); break; case ASYNC_TRUNCATE: s = MIN(s, pWrite->iOffset); break; } } } *piSize = s; } async_mutex_leave(ASYNC_MUTEX_QUEUE); return rc; } /* ** Lock or unlock the actual file-system entry. */ static int getFileLock(AsyncLock *pLock){ int rc = SQLITE_OK; AsyncFileLock *pIter; int eRequired = 0; if( pLock->pFile ){ for(pIter=pLock->pList; pIter; pIter=pIter->pNext){ assert(pIter->eAsyncLock>=pIter->eLock); if( pIter->eAsyncLock>eRequired ){ eRequired = pIter->eAsyncLock; assert(eRequired>=0 && eRequired<=SQLITE_LOCK_EXCLUSIVE); } } if( eRequired>pLock->eLock ){ rc = pLock->pFile->pMethods->xLock(pLock->pFile, eRequired); if( rc==SQLITE_OK ){ pLock->eLock = eRequired; } } else if( eRequired<pLock->eLock && eRequired<=SQLITE_LOCK_SHARED ){ rc = pLock->pFile->pMethods->xUnlock(pLock->pFile, eRequired); if( rc==SQLITE_OK ){ pLock->eLock = eRequired; } } } return rc; } /* ** Return the AsyncLock structure from the global async.pLock list ** associated with the file-system entry identified by path zName ** (a string of nName bytes). If no such structure exists, return 0. */ static AsyncLock *findLock(const char *zName, int nName){ AsyncLock *p = async.pLock; while( p && (p->nFile!=nName || memcmp(p->zFile, zName, nName)) ){ p = p->pNext; } return p; } /* ** The following two methods - asyncLock() and asyncUnlock() - are used ** to obtain and release locks on database files opened with the ** asynchronous backend. */ static int asyncLock(sqlite3_file *pFile, int eLock){ int rc = SQLITE_OK; AsyncFileData *p = ((AsyncFile *)pFile)->pData; if( p->zName ){ async_mutex_enter(ASYNC_MUTEX_LOCK); if( p->lock.eLock<eLock ){ AsyncLock *pLock = p->pLock; AsyncFileLock *pIter; assert(pLock && pLock->pList); for(pIter=pLock->pList; pIter; pIter=pIter->pNext){ if( pIter!=&p->lock && ( (eLock==SQLITE_LOCK_EXCLUSIVE && pIter->eLock>=SQLITE_LOCK_SHARED) || (eLock==SQLITE_LOCK_PENDING && pIter->eLock>=SQLITE_LOCK_RESERVED) || (eLock==SQLITE_LOCK_RESERVED && pIter->eLock>=SQLITE_LOCK_RESERVED) || (eLock==SQLITE_LOCK_SHARED && pIter->eLock>=SQLITE_LOCK_PENDING) )){ rc = SQLITE_BUSY; } } if( rc==SQLITE_OK ){ p->lock.eLock = eLock; p->lock.eAsyncLock = MAX(p->lock.eAsyncLock, eLock); } assert(p->lock.eAsyncLock>=p->lock.eLock); if( rc==SQLITE_OK ){ rc = getFileLock(pLock); } } async_mutex_leave(ASYNC_MUTEX_LOCK); } ASYNC_TRACE(("LOCK %d (%s) rc=%d\n", eLock, p->zName, rc)); return rc; } static int asyncUnlock(sqlite3_file *pFile, int eLock){ int rc = SQLITE_OK; AsyncFileData *p = ((AsyncFile *)pFile)->pData; if( p->zName ){ AsyncFileLock *pLock = &p->lock; async_mutex_enter(ASYNC_MUTEX_QUEUE); async_mutex_enter(ASYNC_MUTEX_LOCK); pLock->eLock = MIN(pLock->eLock, eLock); rc = addNewAsyncWrite(p, ASYNC_UNLOCK, 0, eLock, 0); async_mutex_leave(ASYNC_MUTEX_LOCK); async_mutex_leave(ASYNC_MUTEX_QUEUE); } return rc; } /* ** This function is called when the pager layer first opens a database file ** and is checking for a hot-journal. */ static int asyncCheckReservedLock(sqlite3_file *pFile, int *pResOut){ int ret = 0; AsyncFileLock *pIter; AsyncFileData *p = ((AsyncFile *)pFile)->pData; async_mutex_enter(ASYNC_MUTEX_LOCK); for(pIter=p->pLock->pList; pIter; pIter=pIter->pNext){ if( pIter->eLock>=SQLITE_LOCK_RESERVED ){ ret = 1; break; } } async_mutex_leave(ASYNC_MUTEX_LOCK); ASYNC_TRACE(("CHECK-LOCK %d (%s)\n", ret, p->zName)); *pResOut = ret; return SQLITE_OK; } /* ** sqlite3_file_control() implementation. */ static int asyncFileControl(sqlite3_file *id, int op, void *pArg){ switch( op ){ case SQLITE_FCNTL_LOCKSTATE: { async_mutex_enter(ASYNC_MUTEX_LOCK); *(int*)pArg = ((AsyncFile*)id)->pData->lock.eLock; async_mutex_leave(ASYNC_MUTEX_LOCK); return SQLITE_OK; } } return SQLITE_ERROR; } /* ** Return the device characteristics and sector-size of the device. It ** is tricky to implement these correctly, as this backend might ** not have an open file handle at this point. */ static int asyncSectorSize(sqlite3_file *pFile){ UNUSED_PARAMETER(pFile); return 512; } static int asyncDeviceCharacteristics(sqlite3_file *pFile){ UNUSED_PARAMETER(pFile); return 0; } static int unlinkAsyncFile(AsyncFileData *pData){ AsyncFileLock **ppIter; int rc = SQLITE_OK; if( pData->zName ){ AsyncLock *pLock = pData->pLock; for(ppIter=&pLock->pList; *ppIter; ppIter=&((*ppIter)->pNext)){ if( (*ppIter)==&pData->lock ){ *ppIter = pData->lock.pNext; break; } } if( !pLock->pList ){ AsyncLock **pp; if( pLock->pFile ){ pLock->pFile->pMethods->xClose(pLock->pFile); } for(pp=&async.pLock; *pp!=pLock; pp=&((*pp)->pNext)); *pp = pLock->pNext; sqlite3_free(pLock); }else{ rc = getFileLock(pLock); } } return rc; } /* ** The parameter passed to this function is a copy of a 'flags' parameter ** passed to this modules xOpen() method. This function returns true ** if the file should be opened asynchronously, or false if it should ** be opened immediately. ** ** If the file is to be opened asynchronously, then asyncOpen() will add ** an entry to the event queue and the file will not actually be opened ** until the event is processed. Otherwise, the file is opened directly ** by the caller. */ static int doAsynchronousOpen(int flags){ return (flags&SQLITE_OPEN_CREATE) && ( (flags&SQLITE_OPEN_MAIN_JOURNAL) || (flags&SQLITE_OPEN_TEMP_JOURNAL) || (flags&SQLITE_OPEN_DELETEONCLOSE) ); } /* ** Open a file. */ static int asyncOpen( sqlite3_vfs *pAsyncVfs, const char *zName, sqlite3_file *pFile, int flags, int *pOutFlags ){ static sqlite3_io_methods async_methods = { 1, /* iVersion */ asyncClose, /* xClose */ asyncRead, /* xRead */ asyncWrite, /* xWrite */ asyncTruncate, /* xTruncate */ asyncSync, /* xSync */ asyncFileSize, /* xFileSize */ asyncLock, /* xLock */ asyncUnlock, /* xUnlock */ asyncCheckReservedLock, /* xCheckReservedLock */ asyncFileControl, /* xFileControl */ asyncSectorSize, /* xSectorSize */ asyncDeviceCharacteristics /* xDeviceCharacteristics */ }; sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; AsyncFile *p = (AsyncFile *)pFile; int nName = 0; int rc = SQLITE_OK; int nByte; AsyncFileData *pData; AsyncLock *pLock = 0; char *z; int isAsyncOpen = doAsynchronousOpen(flags); /* If zName is NULL, then the upper layer is requesting an anonymous file */ if( zName ){ nName = (int)strlen(zName)+1; } nByte = ( sizeof(AsyncFileData) + /* AsyncFileData structure */ 2 * pVfs->szOsFile + /* AsyncFileData.pBaseRead and pBaseWrite */ nName /* AsyncFileData.zName */ ); z = sqlite3_malloc(nByte); if( !z ){ return SQLITE_NOMEM; } memset(z, 0, nByte); pData = (AsyncFileData*)z; z += sizeof(pData[0]); pData->pBaseRead = (sqlite3_file*)z; z += pVfs->szOsFile; pData->pBaseWrite = (sqlite3_file*)z; pData->closeOp.pFileData = pData; pData->closeOp.op = ASYNC_CLOSE; if( zName ){ z += pVfs->szOsFile; pData->zName = z; pData->nName = nName; memcpy(pData->zName, zName, nName); } if( !isAsyncOpen ){ int flagsout; rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseRead, flags, &flagsout); if( rc==SQLITE_OK && (flagsout&SQLITE_OPEN_READWRITE) && (flags&SQLITE_OPEN_EXCLUSIVE)==0 ){ rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseWrite, flags, 0); } if( pOutFlags ){ *pOutFlags = flagsout; } } async_mutex_enter(ASYNC_MUTEX_LOCK); if( zName && rc==SQLITE_OK ){ pLock = findLock(pData->zName, pData->nName); if( !pLock ){ int nByte = pVfs->szOsFile + sizeof(AsyncLock) + pData->nName + 1; pLock = (AsyncLock *)sqlite3_malloc(nByte); if( pLock ){ memset(pLock, 0, nByte); if( async.bLockFiles && (flags&SQLITE_OPEN_MAIN_DB) ){ pLock->pFile = (sqlite3_file *)&pLock[1]; rc = pVfs->xOpen(pVfs, pData->zName, pLock->pFile, flags, 0); if( rc!=SQLITE_OK ){ sqlite3_free(pLock); pLock = 0; } } if( pLock ){ pLock->nFile = pData->nName; pLock->zFile = &((char *)(&pLock[1]))[pVfs->szOsFile]; memcpy(pLock->zFile, pData->zName, pLock->nFile); pLock->pNext = async.pLock; async.pLock = pLock; } }else{ rc = SQLITE_NOMEM; } } } if( rc==SQLITE_OK ){ p->pMethod = &async_methods; p->pData = pData; /* Link AsyncFileData.lock into the linked list of ** AsyncFileLock structures for this file. */ if( zName ){ pData->lock.pNext = pLock->pList; pLock->pList = &pData->lock; pData->zName = pLock->zFile; } }else{ if( pData->pBaseRead->pMethods ){ pData->pBaseRead->pMethods->xClose(pData->pBaseRead); } if( pData->pBaseWrite->pMethods ){ pData->pBaseWrite->pMethods->xClose(pData->pBaseWrite); } sqlite3_free(pData); } async_mutex_leave(ASYNC_MUTEX_LOCK); if( rc==SQLITE_OK ){ pData->pLock = pLock; } if( rc==SQLITE_OK && isAsyncOpen ){ rc = addNewAsyncWrite(pData, ASYNC_OPENEXCLUSIVE, (sqlite3_int64)flags,0,0); if( rc==SQLITE_OK ){ if( pOutFlags ) *pOutFlags = flags; }else{ async_mutex_enter(ASYNC_MUTEX_LOCK); unlinkAsyncFile(pData); async_mutex_leave(ASYNC_MUTEX_LOCK); sqlite3_free(pData); } } if( rc!=SQLITE_OK ){ p->pMethod = 0; }else{ incrOpenFileCount(); } return rc; } /* ** Implementation of sqlite3OsDelete. Add an entry to the end of the ** write-op queue to perform the delete. */ static int asyncDelete(sqlite3_vfs *pAsyncVfs, const char *z, int syncDir){ UNUSED_PARAMETER(pAsyncVfs); return addNewAsyncWrite(0, ASYNC_DELETE, syncDir, (int)strlen(z)+1, z); } /* ** Implementation of sqlite3OsAccess. This method holds the mutex from ** start to finish. */ static int asyncAccess( sqlite3_vfs *pAsyncVfs, const char *zName, int flags, int *pResOut ){ int rc; int ret; AsyncWrite *p; sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; assert(flags==SQLITE_ACCESS_READWRITE || flags==SQLITE_ACCESS_READ || flags==SQLITE_ACCESS_EXISTS ); async_mutex_enter(ASYNC_MUTEX_QUEUE); rc = pVfs->xAccess(pVfs, zName, flags, &ret); if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){ for(p=async.pQueueFirst; p; p = p->pNext){ if( p->op==ASYNC_DELETE && 0==strcmp(p->zBuf, zName) ){ ret = 0; }else if( p->op==ASYNC_OPENEXCLUSIVE && p->pFileData->zName && 0==strcmp(p->pFileData->zName, zName) ){ ret = 1; } } } ASYNC_TRACE(("ACCESS(%s): %s = %d\n", flags==SQLITE_ACCESS_READWRITE?"read-write": flags==SQLITE_ACCESS_READ?"read":"exists" , zName, ret) ); async_mutex_leave(ASYNC_MUTEX_QUEUE); *pResOut = ret; return rc; } /* ** Fill in zPathOut with the full path to the file identified by zPath. */ static int asyncFullPathname( sqlite3_vfs *pAsyncVfs, const char *zPath, int nPathOut, char *zPathOut ){ int rc; sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; rc = pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); /* Because of the way intra-process file locking works, this backend ** needs to return a canonical path. The following block assumes the ** file-system uses unix style paths. */ if( rc==SQLITE_OK ){ int i, j; char *z = zPathOut; int n = (int)strlen(z); while( n>1 && z[n-1]=='/' ){ n--; } for(i=j=0; i<n; i++){ if( z[i]=='/' ){ if( z[i+1]=='/' ) continue; if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){ i += 1; continue; } if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){ while( j>0 && z[j-1]!='/' ){ j--; } if( j>0 ){ j--; } i += 2; continue; } } z[j++] = z[i]; } z[j] = 0; } return rc; } static void *asyncDlOpen(sqlite3_vfs *pAsyncVfs, const char *zPath){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; return pVfs->xDlOpen(pVfs, zPath); } static void asyncDlError(sqlite3_vfs *pAsyncVfs, int nByte, char *zErrMsg){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; pVfs->xDlError(pVfs, nByte, zErrMsg); } static void (*asyncDlSym( sqlite3_vfs *pAsyncVfs, void *pHandle, const char *zSymbol ))(void){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; return pVfs->xDlSym(pVfs, pHandle, zSymbol); } static void asyncDlClose(sqlite3_vfs *pAsyncVfs, void *pHandle){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; pVfs->xDlClose(pVfs, pHandle); } static int asyncRandomness(sqlite3_vfs *pAsyncVfs, int nByte, char *zBufOut){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; return pVfs->xRandomness(pVfs, nByte, zBufOut); } static int asyncSleep(sqlite3_vfs *pAsyncVfs, int nMicro){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; return pVfs->xSleep(pVfs, nMicro); } static int asyncCurrentTime(sqlite3_vfs *pAsyncVfs, double *pTimeOut){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData; return pVfs->xCurrentTime(pVfs, pTimeOut); } static sqlite3_vfs async_vfs = { 1, /* iVersion */ sizeof(AsyncFile), /* szOsFile */ 0, /* mxPathname */ 0, /* pNext */ SQLITEASYNC_VFSNAME, /* zName */ 0, /* pAppData */ asyncOpen, /* xOpen */ asyncDelete, /* xDelete */ asyncAccess, /* xAccess */ asyncFullPathname, /* xFullPathname */ asyncDlOpen, /* xDlOpen */ asyncDlError, /* xDlError */ asyncDlSym, /* xDlSym */ asyncDlClose, /* xDlClose */ asyncRandomness, /* xDlError */ asyncSleep, /* xDlSym */ asyncCurrentTime /* xDlClose */ }; /* ** This procedure runs in a separate thread, reading messages off of the ** write queue and processing them one by one. ** ** If async.writerHaltNow is true, then this procedure exits ** after processing a single message. ** ** If async.writerHaltWhenIdle is true, then this procedure exits when ** the write queue is empty. ** ** If both of the above variables are false, this procedure runs ** indefinately, waiting for operations to be added to the write queue ** and processing them in the order in which they arrive. ** ** An artifical delay of async.ioDelay milliseconds is inserted before ** each write operation in order to simulate the effect of a slow disk. ** ** Only one instance of this procedure may be running at a time. */ static void asyncWriterThread(void){ sqlite3_vfs *pVfs = (sqlite3_vfs *)(async_vfs.pAppData); AsyncWrite *p = 0; int rc = SQLITE_OK; int holdingMutex = 0; async_mutex_enter(ASYNC_MUTEX_WRITER); while( async.eHalt!=SQLITEASYNC_HALT_NOW ){ int doNotFree = 0; sqlite3_file *pBase = 0; if( !holdingMutex ){ async_mutex_enter(ASYNC_MUTEX_QUEUE); } while( (p = async.pQueueFirst)==0 ){ if( async.eHalt!=SQLITEASYNC_HALT_NEVER ){ async_mutex_leave(ASYNC_MUTEX_QUEUE); break; }else{ ASYNC_TRACE(("IDLE\n")); async_cond_wait(ASYNC_COND_QUEUE, ASYNC_MUTEX_QUEUE); ASYNC_TRACE(("WAKEUP\n")); } } if( p==0 ) break; holdingMutex = 1; /* Right now this thread is holding the mutex on the write-op queue. ** Variable 'p' points to the first entry in the write-op queue. In ** the general case, we hold on to the mutex for the entire body of ** the loop. ** ** However in the cases enumerated below, we relinquish the mutex, ** perform the IO, and then re-request the mutex before removing 'p' from ** the head of the write-op queue. The idea is to increase concurrency with ** sqlite threads. ** ** * An ASYNC_CLOSE operation. ** * An ASYNC_OPENEXCLUSIVE operation. For this one, we relinquish ** the mutex, call the underlying xOpenExclusive() function, then ** re-aquire the mutex before seting the AsyncFile.pBaseRead ** variable. ** * ASYNC_SYNC and ASYNC_WRITE operations, if ** SQLITE_ASYNC_TWO_FILEHANDLES was set at compile time and two ** file-handles are open for the particular file being "synced". */ if( async.ioError!=SQLITE_OK && p->op!=ASYNC_CLOSE ){ p->op = ASYNC_NOOP; } if( p->pFileData ){ pBase = p->pFileData->pBaseWrite; if( p->op==ASYNC_CLOSE || p->op==ASYNC_OPENEXCLUSIVE || (pBase->pMethods && (p->op==ASYNC_SYNC || p->op==ASYNC_WRITE) ) ){ async_mutex_leave(ASYNC_MUTEX_QUEUE); holdingMutex = 0; } if( !pBase->pMethods ){ pBase = p->pFileData->pBaseRead; } } switch( p->op ){ case ASYNC_NOOP: break; case ASYNC_WRITE: assert( pBase ); ASYNC_TRACE(("WRITE %s %d bytes at %d\n", p->pFileData->zName, p->nByte, p->iOffset)); rc = pBase->pMethods->xWrite(pBase, (void *)(p->zBuf), p->nByte, p->iOffset); break; case ASYNC_SYNC: assert( pBase ); ASYNC_TRACE(("SYNC %s\n", p->pFileData->zName)); rc = pBase->pMethods->xSync(pBase, p->nByte); break; case ASYNC_TRUNCATE: assert( pBase ); ASYNC_TRACE(("TRUNCATE %s to %d bytes\n", p->pFileData->zName, p->iOffset)); rc = pBase->pMethods->xTruncate(pBase, p->iOffset); break; case ASYNC_CLOSE: { AsyncFileData *pData = p->pFileData; ASYNC_TRACE(("CLOSE %s\n", p->pFileData->zName)); if( pData->pBaseWrite->pMethods ){ pData->pBaseWrite->pMethods->xClose(pData->pBaseWrite); } if( pData->pBaseRead->pMethods ){ pData->pBaseRead->pMethods->xClose(pData->pBaseRead); } /* Unlink AsyncFileData.lock from the linked list of AsyncFileLock ** structures for this file. Obtain the async.lockMutex mutex ** before doing so. */ async_mutex_enter(ASYNC_MUTEX_LOCK); rc = unlinkAsyncFile(pData); async_mutex_leave(ASYNC_MUTEX_LOCK); if( !holdingMutex ){ async_mutex_enter(ASYNC_MUTEX_QUEUE); holdingMutex = 1; } assert_mutex_is_held(ASYNC_MUTEX_QUEUE); async.pQueueFirst = p->pNext; sqlite3_free(pData); doNotFree = 1; break; } case ASYNC_UNLOCK: { AsyncWrite *pIter; AsyncFileData *pData = p->pFileData; int eLock = p->nByte; /* When a file is locked by SQLite using the async backend, it is ** locked within the 'real' file-system synchronously. When it is ** unlocked, an ASYNC_UNLOCK event is added to the write-queue to ** unlock the file asynchronously. The design of the async backend ** requires that the 'real' file-system file be locked from the ** time that SQLite first locks it (and probably reads from it) ** until all asynchronous write events that were scheduled before ** SQLite unlocked the file have been processed. ** ** This is more complex if SQLite locks and unlocks the file multiple ** times in quick succession. For example, if SQLite does: ** ** lock, write, unlock, lock, write, unlock ** ** Each "lock" operation locks the file immediately. Each "write" ** and "unlock" operation adds an event to the event queue. If the ** second "lock" operation is performed before the first "unlock" ** operation has been processed asynchronously, then the first ** "unlock" cannot be safely processed as is, since this would mean ** the file was unlocked when the second "write" operation is ** processed. To work around this, when processing an ASYNC_UNLOCK ** operation, SQLite: ** ** 1) Unlocks the file to the minimum of the argument passed to ** the xUnlock() call and the current lock from SQLite's point ** of view, and ** ** 2) Only unlocks the file at all if this event is the last ** ASYNC_UNLOCK event on this file in the write-queue. */ assert( holdingMutex==1 ); assert( async.pQueueFirst==p ); for(pIter=async.pQueueFirst->pNext; pIter; pIter=pIter->pNext){ if( pIter->pFileData==pData && pIter->op==ASYNC_UNLOCK ) break; } if( !pIter ){ async_mutex_enter(ASYNC_MUTEX_LOCK); pData->lock.eAsyncLock = MIN( pData->lock.eAsyncLock, MAX(pData->lock.eLock, eLock) ); assert(pData->lock.eAsyncLock>=pData->lock.eLock); rc = getFileLock(pData->pLock); async_mutex_leave(ASYNC_MUTEX_LOCK); } break; } case ASYNC_DELETE: ASYNC_TRACE(("DELETE %s\n", p->zBuf)); rc = pVfs->xDelete(pVfs, p->zBuf, (int)p->iOffset); break; case ASYNC_OPENEXCLUSIVE: { int flags = (int)p->iOffset; AsyncFileData *pData = p->pFileData; ASYNC_TRACE(("OPEN %s flags=%d\n", p->zBuf, (int)p->iOffset)); assert(pData->pBaseRead->pMethods==0 && pData->pBaseWrite->pMethods==0); rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseRead, flags, 0); assert( holdingMutex==0 ); async_mutex_enter(ASYNC_MUTEX_QUEUE); holdingMutex = 1; break; } default: assert(!"Illegal value for AsyncWrite.op"); } /* If we didn't hang on to the mutex during the IO op, obtain it now ** so that the AsyncWrite structure can be safely removed from the ** global write-op queue. */ if( !holdingMutex ){ async_mutex_enter(ASYNC_MUTEX_QUEUE); holdingMutex = 1; } /* ASYNC_TRACE(("UNLINK %p\n", p)); */ if( p==async.pQueueLast ){ async.pQueueLast = 0; } if( !doNotFree ){ assert_mutex_is_held(ASYNC_MUTEX_QUEUE); async.pQueueFirst = p->pNext; sqlite3_free(p); } assert( holdingMutex ); /* An IO error has occurred. We cannot report the error back to the ** connection that requested the I/O since the error happened ** asynchronously. The connection has already moved on. There ** really is nobody to report the error to. ** ** The file for which the error occurred may have been a database or ** journal file. Regardless, none of the currently queued operations ** associated with the same database should now be performed. Nor should ** any subsequently requested IO on either a database or journal file ** handle for the same database be accepted until the main database ** file handle has been closed and reopened. ** ** Furthermore, no further IO should be queued or performed on any file ** handle associated with a database that may have been part of a ** multi-file transaction that included the database associated with ** the IO error (i.e. a database ATTACHed to the same handle at some ** point in time). */ if( rc!=SQLITE_OK ){ async.ioError = rc; } if( async.ioError && !async.pQueueFirst ){ async_mutex_enter(ASYNC_MUTEX_LOCK); if( 0==async.pLock ){ async.ioError = SQLITE_OK; } async_mutex_leave(ASYNC_MUTEX_LOCK); } /* Drop the queue mutex before continuing to the next write operation ** in order to give other threads a chance to work with the write queue. */ if( !async.pQueueFirst || !async.ioError ){ async_mutex_leave(ASYNC_MUTEX_QUEUE); holdingMutex = 0; if( async.ioDelay>0 ){ pVfs->xSleep(pVfs, async.ioDelay*1000); }else{ async_sched_yield(); } } } async_mutex_leave(ASYNC_MUTEX_WRITER); return; } /* ** Install the asynchronous VFS. */ int sqlite3async_initialize(const char *zParent, int isDefault){ int rc = SQLITE_OK; if( async_vfs.pAppData==0 ){ sqlite3_vfs *pParent = sqlite3_vfs_find(zParent); if( !pParent || async_os_initialize() ){ rc = SQLITE_ERROR; }else if( SQLITE_OK!=(rc = sqlite3_vfs_register(&async_vfs, isDefault)) ){ async_os_shutdown(); }else{ async_vfs.pAppData = (void *)pParent; async_vfs.mxPathname = ((sqlite3_vfs *)async_vfs.pAppData)->mxPathname; } } return rc; } /* ** Uninstall the asynchronous VFS. */ void sqlite3async_shutdown(void){ if( async_vfs.pAppData ){ async_os_shutdown(); sqlite3_vfs_unregister((sqlite3_vfs *)&async_vfs); async_vfs.pAppData = 0; } } /* ** Process events on the write-queue. */ void sqlite3async_run(void){ asyncWriterThread(); } /* ** Control/configure the asynchronous IO system. */ int sqlite3async_control(int op, ...){ va_list ap; va_start(ap, op); switch( op ){ case SQLITEASYNC_HALT: { int eWhen = va_arg(ap, int); if( eWhen!=SQLITEASYNC_HALT_NEVER && eWhen!=SQLITEASYNC_HALT_NOW && eWhen!=SQLITEASYNC_HALT_IDLE ){ return SQLITE_MISUSE; } async.eHalt = eWhen; async_mutex_enter(ASYNC_MUTEX_QUEUE); async_cond_signal(ASYNC_COND_QUEUE); async_mutex_leave(ASYNC_MUTEX_QUEUE); break; } case SQLITEASYNC_DELAY: { int iDelay = va_arg(ap, int); if( iDelay<0 ){ return SQLITE_MISUSE; } async.ioDelay = iDelay; break; } case SQLITEASYNC_LOCKFILES: { int bLock = va_arg(ap, int); async_mutex_enter(ASYNC_MUTEX_QUEUE); if( async.nFile || async.pQueueFirst ){ async_mutex_leave(ASYNC_MUTEX_QUEUE); return SQLITE_MISUSE; } async.bLockFiles = bLock; async_mutex_leave(ASYNC_MUTEX_QUEUE); break; } case SQLITEASYNC_GET_HALT: { int *peWhen = va_arg(ap, int *); *peWhen = async.eHalt; break; } case SQLITEASYNC_GET_DELAY: { int *piDelay = va_arg(ap, int *); *piDelay = async.ioDelay; break; } case SQLITEASYNC_GET_LOCKFILES: { int *piDelay = va_arg(ap, int *); *piDelay = async.bLockFiles; break; } default: return SQLITE_ERROR; } return SQLITE_OK; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ASYNCIO) */
bsd-3-clause
viewdy/phantomjs2
src/qt/qtwebkit/Source/WebCore/platform/graphics/cairo/PlatformPathCairo.cpp
148
1160
/* * Copyright (C) 2011 Collabora Ltd. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "PlatformPathCairo.h" #include <cairo.h> namespace WebCore { static cairo_surface_t* getPathSurface() { return cairo_image_surface_create(CAIRO_FORMAT_A8, 1, 1); } static cairo_surface_t* gPathSurface = getPathSurface(); CairoPath::CairoPath() : m_cr(adoptRef(cairo_create(gPathSurface))) { } }
bsd-3-clause
vanpact/scipy
scipy/special/cdflib/gaminv.f
151
10511
SUBROUTINE gaminv(a,x,x0,p,q,ierr) C ---------------------------------------------------------------------- C INVERSE INCOMPLETE GAMMA RATIO FUNCTION C C GIVEN POSITIVE A, AND NONEGATIVE P AND Q WHERE P + Q = 1. C THEN X IS COMPUTED WHERE P(A,X) = P AND Q(A,X) = Q. SCHRODER C ITERATION IS EMPLOYED. THE ROUTINE ATTEMPTS TO COMPUTE X C TO 10 SIGNIFICANT DIGITS IF THIS IS POSSIBLE FOR THE C PARTICULAR COMPUTER ARITHMETIC BEING USED. C C ------------ C C X IS A VARIABLE. IF P = 0 THEN X IS ASSIGNED THE VALUE 0, C AND IF Q = 0 THEN X IS SET TO THE LARGEST FLOATING POINT C NUMBER AVAILABLE. OTHERWISE, GAMINV ATTEMPTS TO OBTAIN C A SOLUTION FOR P(A,X) = P AND Q(A,X) = Q. IF THE ROUTINE C IS SUCCESSFUL THEN THE SOLUTION IS STORED IN X. C C X0 IS AN OPTIONAL INITIAL APPROXIMATION FOR X. IF THE USER C DOES NOT WISH TO SUPPLY AN INITIAL APPROXIMATION, THEN SET C X0 .LE. 0. C C IERR IS A VARIABLE THAT REPORTS THE STATUS OF THE RESULTS. C WHEN THE ROUTINE TERMINATES, IERR HAS ONE OF THE FOLLOWING C VALUES ... C C IERR = 0 THE SOLUTION WAS OBTAINED. ITERATION WAS C NOT USED. C IERR.GT.0 THE SOLUTION WAS OBTAINED. IERR ITERATIONS C WERE PERFORMED. C IERR = -2 (INPUT ERROR) A .LE. 0 C IERR = -3 NO SOLUTION WAS OBTAINED. THE RATIO Q/A C IS TOO LARGE. C IERR = -4 (INPUT ERROR) P + Q .NE. 1 C IERR = -6 20 ITERATIONS WERE PERFORMED. THE MOST C RECENT VALUE OBTAINED FOR X IS GIVEN. C THIS CANNOT OCCUR IF X0 .LE. 0. C IERR = -7 ITERATION FAILED. NO VALUE IS GIVEN FOR X. C THIS MAY OCCUR WHEN X IS APPROXIMATELY 0. C IERR = -8 A VALUE FOR X HAS BEEN OBTAINED, BUT THE C ROUTINE IS NOT CERTAIN OF ITS ACCURACY. C ITERATION CANNOT BE PERFORMED IN THIS C CASE. IF X0 .LE. 0, THIS CAN OCCUR ONLY C WHEN P OR Q IS APPROXIMATELY 0. IF X0 IS C POSITIVE THEN THIS CAN OCCUR WHEN A IS C EXCEEDINGLY CLOSE TO X AND A IS EXTREMELY C LARGE (SAY A .GE. 1.E20). C ---------------------------------------------------------------------- C WRITTEN BY ALFRED H. MORRIS, JR. C NAVAL SURFACE WEAPONS CENTER C DAHLGREN, VIRGINIA C ------------------- C .. Scalar Arguments .. DOUBLE PRECISION a,p,q,x,x0 INTEGER ierr C .. C .. Local Scalars .. DOUBLE PRECISION a0,a1,a2,a3,am1,amax,ap1,ap2,ap3,apn,b,b1,b2,b3, + b4,c,c1,c2,c3,c4,c5,d,e,e2,eps,g,h,ln10,pn,qg,qn, + r,rta,s,s2,sum,t,tol,u,w,xmax,xmin,xn,y,z INTEGER iop C .. C .. Local Arrays .. DOUBLE PRECISION amin(2),bmin(2),dmin(2),emin(2),eps0(2) C .. C .. External Functions .. DOUBLE PRECISION alnrel,gamln,gamln1,gamma,rcomp,spmpar EXTERNAL alnrel,gamln,gamln1,gamma,rcomp,spmpar C .. C .. External Subroutines .. EXTERNAL gratio C .. C .. Intrinsic Functions .. INTRINSIC abs,dble,dlog,dmax1,exp,sqrt C .. C .. Data statements .. C ------------------- C LN10 = LN(10) C C = EULER CONSTANT C ------------------- C ------------------- C ------------------- C ------------------- DATA ln10/2.302585D0/ DATA c/.577215664901533D0/ DATA a0/3.31125922108741D0/,a1/11.6616720288968D0/, + a2/4.28342155967104D0/,a3/.213623493715853D0/ DATA b1/6.61053765625462D0/,b2/6.40691597760039D0/, + b3/1.27364489782223D0/,b4/.036117081018842D0/ DATA eps0(1)/1.D-10/,eps0(2)/1.D-08/ DATA amin(1)/500.0D0/,amin(2)/100.0D0/ DATA bmin(1)/1.D-28/,bmin(2)/1.D-13/ DATA dmin(1)/1.D-06/,dmin(2)/1.D-04/ DATA emin(1)/2.D-03/,emin(2)/6.D-03/ DATA tol/1.D-5/ C .. C .. Executable Statements .. C ------------------- C ****** E, XMIN, AND XMAX ARE MACHINE DEPENDENT CONSTANTS. C E IS THE SMALLEST NUMBER FOR WHICH 1.0 + E .GT. 1.0. C XMIN IS THE SMALLEST POSITIVE NUMBER AND XMAX IS THE C LARGEST POSITIVE NUMBER. C e = spmpar(1) xmin = spmpar(2) xmax = spmpar(3) C ------------------- x = 0.0D0 IF (a.LE.0.0D0) GO TO 300 t = dble(p) + dble(q) - 1.D0 IF (abs(t).GT.e) GO TO 320 C ierr = 0 IF (p.EQ.0.0D0) RETURN IF (q.EQ.0.0D0) GO TO 270 IF (a.EQ.1.0D0) GO TO 280 C e2 = 2.0D0*e amax = 0.4D-10/ (e*e) iop = 1 IF (e.GT.1.D-10) iop = 2 eps = eps0(iop) xn = x0 IF (x0.GT.0.0D0) GO TO 160 C C SELECTION OF THE INITIAL APPROXIMATION XN OF X C WHEN A .LT. 1 C IF (a.GT.1.0D0) GO TO 80 g = gamma(a+1.0D0) qg = q*g IF (qg.EQ.0.0D0) GO TO 360 b = qg/a IF (qg.GT.0.6D0*a) GO TO 40 IF (a.GE.0.30D0 .OR. b.LT.0.35D0) GO TO 10 t = exp(- (b+c)) u = t*exp(t) xn = t*exp(u) GO TO 160 C 10 IF (b.GE.0.45D0) GO TO 40 IF (b.EQ.0.0D0) GO TO 360 y = -dlog(b) s = 0.5D0 + (0.5D0-a) z = dlog(y) t = y - s*z IF (b.LT.0.15D0) GO TO 20 xn = y - s*dlog(t) - dlog(1.0D0+s/ (t+1.0D0)) GO TO 220 20 IF (b.LE.0.01D0) GO TO 30 u = ((t+2.0D0* (3.0D0-a))*t+ (2.0D0-a)* (3.0D0-a))/ + ((t+ (5.0D0-a))*t+2.0D0) xn = y - s*dlog(t) - dlog(u) GO TO 220 30 c1 = -s*z c2 = -s* (1.0D0+c1) c3 = s* ((0.5D0*c1+ (2.0D0-a))*c1+ (2.5D0-1.5D0*a)) c4 = -s* (((c1/3.0D0+ (2.5D0-1.5D0*a))*c1+ ((a-6.0D0)*a+7.0D0))* + c1+ ((11.0D0*a-46)*a+47.0D0)/6.0D0) c5 = -s* ((((-c1/4.0D0+ (11.0D0*a-17.0D0)/6.0D0)*c1+ ((-3.0D0*a+ + 13.0D0)*a-13.0D0))*c1+0.5D0* (((2.0D0*a-25.0D0)*a+72.0D0)*a- + 61.0D0))*c1+ (((25.0D0*a-195.0D0)*a+477.0D0)*a-379.0D0)/ + 12.0D0) xn = ((((c5/y+c4)/y+c3)/y+c2)/y+c1) + y IF (a.GT.1.0D0) GO TO 220 IF (b.GT.bmin(iop)) GO TO 220 x = xn RETURN C 40 IF (b*q.GT.1.D-8) GO TO 50 xn = exp(- (q/a+c)) GO TO 70 50 IF (p.LE.0.9D0) GO TO 60 xn = exp((alnrel(-q)+gamln1(a))/a) GO TO 70 60 xn = exp(dlog(p*g)/a) 70 IF (xn.EQ.0.0D0) GO TO 310 t = 0.5D0 + (0.5D0-xn/ (a+1.0D0)) xn = xn/t GO TO 160 C C SELECTION OF THE INITIAL APPROXIMATION XN OF X C WHEN A .GT. 1 C 80 IF (q.LE.0.5D0) GO TO 90 w = dlog(p) GO TO 100 90 w = dlog(q) 100 t = sqrt(-2.0D0*w) s = t - (((a3*t+a2)*t+a1)*t+a0)/ ((((b4*t+b3)*t+b2)*t+b1)*t+1.0D0) IF (q.GT.0.5D0) s = -s C rta = sqrt(a) s2 = s*s xn = a + s*rta + (s2-1.0D0)/3.0D0 + s* (s2-7.0D0)/ (36.0D0*rta) - + ((3.0D0*s2+7.0D0)*s2-16.0D0)/ (810.0D0*a) + + s* ((9.0D0*s2+256.0D0)*s2-433.0D0)/ (38880.0D0*a*rta) xn = dmax1(xn,0.0D0) IF (a.LT.amin(iop)) GO TO 110 x = xn d = 0.5D0 + (0.5D0-x/a) IF (abs(d).LE.dmin(iop)) RETURN C 110 IF (p.LE.0.5D0) GO TO 130 IF (xn.LT.3.0D0*a) GO TO 220 y = - (w+gamln(a)) d = dmax1(2.0D0,a* (a-1.0D0)) IF (y.LT.ln10*d) GO TO 120 s = 1.0D0 - a z = dlog(y) GO TO 30 120 t = a - 1.0D0 xn = y + t*dlog(xn) - alnrel(-t/ (xn+1.0D0)) xn = y + t*dlog(xn) - alnrel(-t/ (xn+1.0D0)) GO TO 220 C 130 ap1 = a + 1.0D0 IF (xn.GT.0.70D0*ap1) GO TO 170 w = w + gamln(ap1) IF (xn.GT.0.15D0*ap1) GO TO 140 ap2 = a + 2.0D0 ap3 = a + 3.0D0 x = exp((w+x)/a) x = exp((w+x-dlog(1.0D0+ (x/ap1)* (1.0D0+x/ap2)))/a) x = exp((w+x-dlog(1.0D0+ (x/ap1)* (1.0D0+x/ap2)))/a) x = exp((w+x-dlog(1.0D0+ (x/ap1)* (1.0D0+ (x/ap2)* (1.0D0+ + x/ap3))))/a) xn = x IF (xn.GT.1.D-2*ap1) GO TO 140 IF (xn.LE.emin(iop)*ap1) RETURN GO TO 170 C 140 apn = ap1 t = xn/apn sum = 1.0D0 + t 150 apn = apn + 1.0D0 t = t* (xn/apn) sum = sum + t IF (t.GT.1.D-4) GO TO 150 t = w - dlog(sum) xn = exp((xn+t)/a) xn = xn* (1.0D0- (a*dlog(xn)-xn-t)/ (a-xn)) GO TO 170 C C SCHRODER ITERATION USING P C 160 IF (p.GT.0.5D0) GO TO 220 170 IF (p.LE.1.D10*xmin) GO TO 350 am1 = (a-0.5D0) - 0.5D0 180 IF (a.LE.amax) GO TO 190 d = 0.5D0 + (0.5D0-xn/a) IF (abs(d).LE.e2) GO TO 350 C 190 IF (ierr.GE.20) GO TO 330 ierr = ierr + 1 CALL gratio(a,xn,pn,qn,0) IF (pn.EQ.0.0D0 .OR. qn.EQ.0.0D0) GO TO 350 r = rcomp(a,xn) IF (r.EQ.0.0D0) GO TO 350 t = (pn-p)/r w = 0.5D0* (am1-xn) IF (abs(t).LE.0.1D0 .AND. abs(w*t).LE.0.1D0) GO TO 200 x = xn* (1.0D0-t) IF (x.LE.0.0D0) GO TO 340 d = abs(t) GO TO 210 C 200 h = t* (1.0D0+w*t) x = xn* (1.0D0-h) IF (x.LE.0.0D0) GO TO 340 IF (abs(w).GE.1.0D0 .AND. abs(w)*t*t.LE.eps) RETURN d = abs(h) 210 xn = x IF (d.GT.tol) GO TO 180 IF (d.LE.eps) RETURN IF (abs(p-pn).LE.tol*p) RETURN GO TO 180 C C SCHRODER ITERATION USING Q C 220 IF (q.LE.1.D10*xmin) GO TO 350 am1 = (a-0.5D0) - 0.5D0 230 IF (a.LE.amax) GO TO 240 d = 0.5D0 + (0.5D0-xn/a) IF (abs(d).LE.e2) GO TO 350 C 240 IF (ierr.GE.20) GO TO 330 ierr = ierr + 1 CALL gratio(a,xn,pn,qn,0) IF (pn.EQ.0.0D0 .OR. qn.EQ.0.0D0) GO TO 350 r = rcomp(a,xn) IF (r.EQ.0.0D0) GO TO 350 t = (q-qn)/r w = 0.5D0* (am1-xn) IF (abs(t).LE.0.1D0 .AND. abs(w*t).LE.0.1D0) GO TO 250 x = xn* (1.0D0-t) IF (x.LE.0.0D0) GO TO 340 d = abs(t) GO TO 260 C 250 h = t* (1.0D0+w*t) x = xn* (1.0D0-h) IF (x.LE.0.0D0) GO TO 340 IF (abs(w).GE.1.0D0 .AND. abs(w)*t*t.LE.eps) RETURN d = abs(h) 260 xn = x IF (d.GT.tol) GO TO 230 IF (d.LE.eps) RETURN IF (abs(q-qn).LE.tol*q) RETURN GO TO 230 C C SPECIAL CASES C 270 x = xmax RETURN C 280 IF (q.LT.0.9D0) GO TO 290 x = -alnrel(-p) RETURN 290 x = -dlog(q) RETURN C C ERROR RETURN C 300 ierr = -2 RETURN C 310 ierr = -3 RETURN C 320 ierr = -4 RETURN C 330 ierr = -6 RETURN C 340 ierr = -7 RETURN C 350 x = xn ierr = -8 RETURN C 360 x = xmax ierr = -8 RETURN END
bsd-3-clause
shining-yang/redis
src/notify.c
161
5418
/* * Copyright (c) 2013, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "server.h" /* This file implements keyspace events notification via Pub/Sub ad * described at http://redis.io/topics/keyspace-events. */ /* Turn a string representing notification classes into an integer * representing notification classes flags xored. * * The function returns -1 if the input contains characters not mapping to * any class. */ int keyspaceEventsStringToFlags(char *classes) { char *p = classes; int c, flags = 0; while((c = *p++) != '\0') { switch(c) { case 'A': flags |= NOTIFY_ALL; break; case 'g': flags |= NOTIFY_GENERIC; break; case '$': flags |= NOTIFY_STRING; break; case 'l': flags |= NOTIFY_LIST; break; case 's': flags |= NOTIFY_SET; break; case 'h': flags |= NOTIFY_HASH; break; case 'z': flags |= NOTIFY_ZSET; break; case 'x': flags |= NOTIFY_EXPIRED; break; case 'e': flags |= NOTIFY_EVICTED; break; case 'K': flags |= NOTIFY_KEYSPACE; break; case 'E': flags |= NOTIFY_KEYEVENT; break; default: return -1; } } return flags; } /* This function does exactly the revese of the function above: it gets * as input an integer with the xored flags and returns a string representing * the selected classes. The string returned is an sds string that needs to * be released with sdsfree(). */ sds keyspaceEventsFlagsToString(int flags) { sds res; res = sdsempty(); if ((flags & NOTIFY_ALL) == NOTIFY_ALL) { res = sdscatlen(res,"A",1); } else { if (flags & NOTIFY_GENERIC) res = sdscatlen(res,"g",1); if (flags & NOTIFY_STRING) res = sdscatlen(res,"$",1); if (flags & NOTIFY_LIST) res = sdscatlen(res,"l",1); if (flags & NOTIFY_SET) res = sdscatlen(res,"s",1); if (flags & NOTIFY_HASH) res = sdscatlen(res,"h",1); if (flags & NOTIFY_ZSET) res = sdscatlen(res,"z",1); if (flags & NOTIFY_EXPIRED) res = sdscatlen(res,"x",1); if (flags & NOTIFY_EVICTED) res = sdscatlen(res,"e",1); } if (flags & NOTIFY_KEYSPACE) res = sdscatlen(res,"K",1); if (flags & NOTIFY_KEYEVENT) res = sdscatlen(res,"E",1); return res; } /* The API provided to the rest of the Redis core is a simple function: * * notifyKeyspaceEvent(char *event, robj *key, int dbid); * * 'event' is a C string representing the event name. * 'key' is a Redis object representing the key name. * 'dbid' is the database ID where the key lives. */ void notifyKeyspaceEvent(int type, char *event, robj *key, int dbid) { sds chan; robj *chanobj, *eventobj; int len = -1; char buf[24]; /* If notifications for this class of events are off, return ASAP. */ if (!(server.notify_keyspace_events & type)) return; eventobj = createStringObject(event,strlen(event)); /* __keyspace@<db>__:<key> <event> notifications. */ if (server.notify_keyspace_events & NOTIFY_KEYSPACE) { chan = sdsnewlen("__keyspace@",11); len = ll2string(buf,sizeof(buf),dbid); chan = sdscatlen(chan, buf, len); chan = sdscatlen(chan, "__:", 3); chan = sdscatsds(chan, key->ptr); chanobj = createObject(OBJ_STRING, chan); pubsubPublishMessage(chanobj, eventobj); decrRefCount(chanobj); } /* __keyevente@<db>__:<event> <key> notifications. */ if (server.notify_keyspace_events & NOTIFY_KEYEVENT) { chan = sdsnewlen("__keyevent@",11); if (len == -1) len = ll2string(buf,sizeof(buf),dbid); chan = sdscatlen(chan, buf, len); chan = sdscatlen(chan, "__:", 3); chan = sdscatsds(chan, eventobj->ptr); chanobj = createObject(OBJ_STRING, chan); pubsubPublishMessage(chanobj, key); decrRefCount(chanobj); } decrRefCount(eventobj); }
bsd-3-clause
jackyh/qt210_ics_external_speex
libspeex/lsp_tables_nb.c
1000
8315
/* Copyright (C) 2002 Jean-Marc Valin File: lsp_tables_nb.c Codebooks for LSPs in narrowband CELP mode Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. */ const signed char cdbk_nb[640]={ 30,19,38,34,40,32,46,43,58,43, 5,-18,-25,-40,-33,-55,-52,20,34,28, -20,-63,-97,-92,61,53,47,49,53,75, -14,-53,-77,-79,0,-3,-5,19,22,26, -9,-53,-55,66,90,72,85,68,74,52, -4,-41,-58,-31,-18,-31,27,32,30,18, 24,3,8,5,-12,-3,26,28,74,63, -2,-39,-67,-77,-106,-74,59,59,73,65, 44,40,71,72,82,83,98,88,89,60, -6,-31,-47,-48,-13,-39,-9,7,2,79, -1,-39,-60,-17,87,81,65,50,45,19, -21,-67,-91,-87,-41,-50,7,18,39,74, 10,-31,-28,39,24,13,23,5,56,45, 29,10,-5,-13,-11,-35,-18,-8,-10,-8, -25,-71,-77,-21,2,16,50,63,87,87, 5,-32,-40,-51,-68,0,12,6,54,34, 5,-12,32,52,68,64,69,59,65,45, 14,-16,-31,-40,-65,-67,41,49,47,37, -11,-52,-75,-84,-4,57,48,42,42,33, -11,-51,-68,-6,13,0,8,-8,26,32, -23,-53,0,36,56,76,97,105,111,97, -1,-28,-39,-40,-43,-54,-44,-40,-18,35, 16,-20,-19,-28,-42,29,47,38,74,45, 3,-29,-48,-62,-80,-104,-33,56,59,59, 10,17,46,72,84,101,117,123,123,106, -7,-33,-49,-51,-70,-67,-27,-31,70,67, -16,-62,-85,-20,82,71,86,80,85,74, -19,-58,-75,-45,-29,-33,-18,-25,45,57, -12,-42,-5,12,28,36,52,64,81,82, 13,-9,-27,-28,22,3,2,22,26,6, -6,-44,-51,2,15,10,48,43,49,34, -19,-62,-84,-89,-102,-24,8,17,61,68, 39,24,23,19,16,-5,12,15,27,15, -8,-44,-49,-60,-18,-32,-28,52,54,62, -8,-48,-77,-70,66,101,83,63,61,37, -12,-50,-75,-64,33,17,13,25,15,77, 1,-42,-29,72,64,46,49,31,61,44, -8,-47,-54,-46,-30,19,20,-1,-16,0, 16,-12,-18,-9,-26,-27,-10,-22,53,45, -10,-47,-75,-82,-105,-109,8,25,49,77, 50,65,114,117,124,118,115,96,90,61, -9,-45,-63,-60,-75,-57,8,11,20,29, 0,-35,-49,-43,40,47,35,40,55,38, -24,-76,-103,-112,-27,3,23,34,52,75, 8,-29,-43,12,63,38,35,29,24,8, 25,11,1,-15,-18,-43,-7,37,40,21, -20,-56,-19,-19,-4,-2,11,29,51,63, -2,-44,-62,-75,-89,30,57,51,74,51, 50,46,68,64,65,52,63,55,65,43, 18,-9,-26,-35,-55,-69,3,6,8,17, -15,-61,-86,-97,1,86,93,74,78,67, -1,-38,-66,-48,48,39,29,25,17,-1, 13,13,29,39,50,51,69,82,97,98, -2,-36,-46,-27,-16,-30,-13,-4,-7,-4, 25,-5,-11,-6,-25,-21,33,12,31,29, -8,-38,-52,-63,-68,-89,-33,-1,10,74, -2,-15,59,91,105,105,101,87,84,62, -7,-33,-50,-35,-54,-47,25,17,82,81, -13,-56,-83,21,58,31,42,25,72,65, -24,-66,-91,-56,9,-2,21,10,69,75, 2,-24,11,22,25,28,38,34,48,33, 7,-29,-26,17,15,-1,14,0,-2,0, -6,-41,-67,6,-2,-9,19,2,85,74, -22,-67,-84,-71,-50,3,11,-9,2,62}; const signed char cdbk_nb_low1[320]={ -34,-52,-15,45,2, 23,21,52,24,-33, -9,-1,9,-44,-41, -13,-17,44,22,-17, -6,-4,-1,22,38, 26,16,2,50,27, -35,-34,-9,-41,6, 0,-16,-34,51,8, -14,-31,-49,15,-33, 45,49,33,-11,-37, -62,-54,45,11,-5, -72,11,-1,-12,-11, 24,27,-11,-43,46, 43,33,-12,-9,-1, 1,-4,-23,-57,-71, 11,8,16,17,-8, -20,-31,-41,53,48, -16,3,65,-24,-8, -23,-32,-37,-32,-49, -10,-17,6,38,5, -9,-17,-46,8,52, 3,6,45,40,39, -7,-6,-34,-74,31, 8,1,-16,43,68, -11,-19,-31,4,6, 0,-6,-17,-16,-38, -16,-30,2,9,-39, -16,-1,43,-10,48, 3,3,-16,-31,-3, 62,68,43,13,3, -10,8,20,-56,12, 12,-2,-18,22,-15, -40,-36,1,7,41, 0,1,46,-6,-62, -4,-12,-2,-11,-83, -13,-2,91,33,-10, 0,4,-11,-16,79, 32,37,14,9,51, -21,-28,-56,-34,0, 21,9,-26,11,28, -42,-54,-23,-2,-15, 31,30,8,-39,-66, -39,-36,31,-28,-40, -46,35,40,22,24, 33,48,23,-34,14, 40,32,17,27,-3, 25,26,-13,-61,-17, 11,4,31,60,-6, -26,-41,-64,13,16, -26,54,31,-11,-23, -9,-11,-34,-71,-21, -34,-35,55,50,29, -22,-27,-50,-38,57, 33,42,57,48,26, 11,0,-49,-31,26, -4,-14,5,78,37, 17,0,-49,-12,-23, 26,14,2,2,-43, -17,-12,10,-8,-4, 8,18,12,-6,20, -12,-6,-13,-25,34, 15,40,49,7,8, 13,20,20,-19,-22, -2,-8,2,51,-51}; const signed char cdbk_nb_low2[320]={ -6,53,-21,-24,4, 26,17,-4,-37,25, 17,-36,-13,31,3, -6,27,15,-10,31, 28,26,-10,-10,-40, 16,-7,15,13,41, -9,0,-4,50,-6, -7,14,38,22,0, -48,2,1,-13,-19, 32,-3,-60,11,-17, -1,-24,-34,-1,35, -5,-27,28,44,13, 25,15,42,-11,15, 51,35,-36,20,8, -4,-12,-29,19,-47, 49,-15,-4,16,-29, -39,14,-30,4,25, -9,-5,-51,-14,-3, -40,-32,38,5,-9, -8,-4,-1,-22,71, -3,14,26,-18,-22, 24,-41,-25,-24,6, 23,19,-10,39,-26, -27,65,45,2,-7, -26,-8,22,-12,16, 15,16,-35,-5,33, -21,-8,0,23,33, 34,6,21,36,6, -7,-22,8,-37,-14, 31,38,11,-4,-3, -39,-32,-8,32,-23, -6,-12,16,20,-28, -4,23,13,-52,-1, 22,6,-33,-40,-6, 4,-62,13,5,-26, 35,39,11,2,57, -11,9,-20,-28,-33, 52,-5,-6,-2,22, -14,-16,-48,35,1, -58,20,13,33,-1, -74,56,-18,-22,-31, 12,6,-14,4,-2, -9,-47,10,-3,29, -17,-5,61,14,47, -12,2,72,-39,-17, 92,64,-53,-51,-15, -30,-38,-41,-29,-28, 27,9,36,9,-35, -42,81,-21,20,25, -16,-5,-17,-35,21, 15,-28,48,2,-2, 9,-19,29,-40,30, -18,-18,18,-16,-57, 15,-20,-12,-15,-37, -15,33,-39,21,-22, -13,35,11,13,-38, -63,29,23,-27,32, 18,3,-26,42,33, -64,-66,-17,16,56, 2,36,3,31,21, -41,-39,8,-57,14, 37,-2,19,-36,-19, -23,-29,-16,1,-3, -8,-10,31,64,-65}; const signed char cdbk_nb_high1[320]={ -26,-8,29,21,4, 19,-39,33,-7,-36, 56,54,48,40,29, -4,-24,-42,-66,-43, -60,19,-2,37,41, -10,-37,-60,-64,18, -22,77,73,40,25, 4,19,-19,-66,-2, 11,5,21,14,26, -25,-86,-4,18,1, 26,-37,10,37,-1, 24,-12,-59,-11,20, -6,34,-16,-16,42, 19,-28,-51,53,32, 4,10,62,21,-12, -34,27,4,-48,-48, -50,-49,31,-7,-21, -42,-25,-4,-43,-22, 59,2,27,12,-9, -6,-16,-8,-32,-58, -16,-29,-5,41,23, -30,-33,-46,-13,-10, -38,52,52,1,-17, -9,10,26,-25,-6, 33,-20,53,55,25, -32,-5,-42,23,21, 66,5,-28,20,9, 75,29,-7,-42,-39, 15,3,-23,21,6, 11,1,-29,14,63, 10,54,26,-24,-51, -49,7,-23,-51,15, -66,1,60,25,10, 0,-30,-4,-15,17, 19,59,40,4,-5, 33,6,-22,-58,-70, -5,23,-6,60,44, -29,-16,-47,-29,52, -19,50,28,16,35, 31,36,0,-21,6, 21,27,22,42,7, -66,-40,-8,7,19, 46,0,-4,60,36, 45,-7,-29,-6,-32, -39,2,6,-9,33, 20,-51,-34,18,-6, 19,6,11,5,-19, -29,-2,42,-11,-45, -21,-55,57,37,2, -14,-67,-16,-27,-38, 69,48,19,2,-17, 20,-20,-16,-34,-17, -25,-61,10,73,45, 16,-40,-64,-17,-29, -22,56,17,-39,8, -11,8,-25,-18,-13, -19,8,54,57,36, -17,-26,-4,6,-21, 40,42,-4,20,31, 53,10,-34,-53,31, -17,35,0,15,-6, -20,-63,-73,22,25, 29,17,8,-29,-39, -69,18,15,-15,-5}; const signed char cdbk_nb_high2[320]={ 11,47,16,-9,-46, -32,26,-64,34,-5, 38,-7,47,20,2, -73,-99,-3,-45,20, 70,-52,15,-6,-7, -82,31,21,47,51, 39,-3,9,0,-41, -7,-15,-54,2,0, 27,-31,9,-45,-22, -38,-24,-24,8,-33, 23,5,50,-36,-17, -18,-51,-2,13,19, 43,12,-15,-12,61, 38,38,7,13,0, 6,-1,3,62,9, 27,22,-33,38,-35, -9,30,-43,-9,-32, -1,4,-4,1,-5, -11,-8,38,31,11, -10,-42,-21,-37,1, 43,15,-13,-35,-19, -18,15,23,-26,59, 1,-21,53,8,-41, -50,-14,-28,4,21, 25,-28,-40,5,-40, -41,4,51,-33,-8, -8,1,17,-60,12, 25,-41,17,34,43, 19,45,7,-37,24, -15,56,-2,35,-10, 48,4,-47,-2,5, -5,-54,5,-3,-33, -10,30,-2,-44,-24, -38,9,-9,42,4, 6,-56,44,-16,9, -40,-26,18,-20,10, 28,-41,-21,-4,13, -18,32,-30,-3,37, 15,22,28,50,-40, 3,-29,-64,7,51, -19,-11,17,-27,-40, -64,24,-12,-7,-27, 3,37,48,-1,2, -9,-38,-34,46,1, 27,-6,19,-13,26, 10,34,20,25,40, 50,-6,-7,30,9, -24,0,-23,71,-61, 22,58,-34,-4,2, -49,-33,25,30,-8, -6,-16,77,2,38, -8,-35,-6,-30,56, 78,31,33,-20,13, -39,20,22,4,21, -8,4,-6,10,-83, -41,9,-25,-43,15, -7,-12,-34,-39,-37, -33,19,30,16,-33, 42,-25,25,-68,44, -15,-11,-4,23,50, 14,4,-39,-43,20, -30,60,9,-20,7, 16,19,-33,37,29, 16,-35,7,38,-27};
bsd-3-clause
lokeshjindal15/pd-gem5
kernel_dvfs/linux-linaro-tracking-gem5/drivers/regulator/lp3971.c
244
11942
/* * Regulator driver for National Semiconductors LP3971 PMIC chip * * Copyright (C) 2009 Samsung Electronics * Author: Marek Szyprowski <m.szyprowski@samsung.com> * * Based on wm8350.c * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <linux/bug.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/regulator/driver.h> #include <linux/regulator/lp3971.h> #include <linux/slab.h> struct lp3971 { struct device *dev; struct mutex io_lock; struct i2c_client *i2c; }; static u8 lp3971_reg_read(struct lp3971 *lp3971, u8 reg); static int lp3971_set_bits(struct lp3971 *lp3971, u8 reg, u16 mask, u16 val); #define LP3971_SYS_CONTROL1_REG 0x07 /* System control register 1 initial value, bits 4 and 5 are EPROM programmable */ #define SYS_CONTROL1_INIT_VAL 0x40 #define SYS_CONTROL1_INIT_MASK 0xCF #define LP3971_BUCK_VOL_ENABLE_REG 0x10 #define LP3971_BUCK_VOL_CHANGE_REG 0x20 /* Voltage control registers shift: LP3971_BUCK1 -> 0 LP3971_BUCK2 -> 4 LP3971_BUCK3 -> 6 */ #define BUCK_VOL_CHANGE_SHIFT(x) (((!!x) << 2) | (x & ~0x01)) #define BUCK_VOL_CHANGE_FLAG_GO 0x01 #define BUCK_VOL_CHANGE_FLAG_TARGET 0x02 #define BUCK_VOL_CHANGE_FLAG_MASK 0x03 #define LP3971_BUCK1_BASE 0x23 #define LP3971_BUCK2_BASE 0x29 #define LP3971_BUCK3_BASE 0x32 static const int buck_base_addr[] = { LP3971_BUCK1_BASE, LP3971_BUCK2_BASE, LP3971_BUCK3_BASE, }; #define LP3971_BUCK_TARGET_VOL1_REG(x) (buck_base_addr[x]) #define LP3971_BUCK_TARGET_VOL2_REG(x) (buck_base_addr[x]+1) static const unsigned int buck_voltage_map[] = { 0, 800000, 850000, 900000, 950000, 1000000, 1050000, 1100000, 1150000, 1200000, 1250000, 1300000, 1350000, 1400000, 1450000, 1500000, 1550000, 1600000, 1650000, 1700000, 1800000, 1900000, 2500000, 2800000, 3000000, 3300000, }; #define BUCK_TARGET_VOL_MASK 0x3f #define LP3971_BUCK_RAMP_REG(x) (buck_base_addr[x]+2) #define LP3971_LDO_ENABLE_REG 0x12 #define LP3971_LDO_VOL_CONTR_BASE 0x39 /* Voltage control registers: LP3971_LDO1 -> LP3971_LDO_VOL_CONTR_BASE + 0 LP3971_LDO2 -> LP3971_LDO_VOL_CONTR_BASE + 0 LP3971_LDO3 -> LP3971_LDO_VOL_CONTR_BASE + 1 LP3971_LDO4 -> LP3971_LDO_VOL_CONTR_BASE + 1 LP3971_LDO5 -> LP3971_LDO_VOL_CONTR_BASE + 2 */ #define LP3971_LDO_VOL_CONTR_REG(x) (LP3971_LDO_VOL_CONTR_BASE + (x >> 1)) /* Voltage control registers shift: LP3971_LDO1 -> 0, LP3971_LDO2 -> 4 LP3971_LDO3 -> 0, LP3971_LDO4 -> 4 LP3971_LDO5 -> 0 */ #define LDO_VOL_CONTR_SHIFT(x) ((x & 1) << 2) #define LDO_VOL_CONTR_MASK 0x0f static const unsigned int ldo45_voltage_map[] = { 1000000, 1050000, 1100000, 1150000, 1200000, 1250000, 1300000, 1350000, 1400000, 1500000, 1800000, 1900000, 2500000, 2800000, 3000000, 3300000, }; static const unsigned int ldo123_voltage_map[] = { 1800000, 1900000, 2000000, 2100000, 2200000, 2300000, 2400000, 2500000, 2600000, 2700000, 2800000, 2900000, 3000000, 3100000, 3200000, 3300000, }; #define LDO_VOL_MIN_IDX 0x00 #define LDO_VOL_MAX_IDX 0x0f static int lp3971_ldo_is_enabled(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev) - LP3971_LDO1; u16 mask = 1 << (1 + ldo); u16 val; val = lp3971_reg_read(lp3971, LP3971_LDO_ENABLE_REG); return (val & mask) != 0; } static int lp3971_ldo_enable(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev) - LP3971_LDO1; u16 mask = 1 << (1 + ldo); return lp3971_set_bits(lp3971, LP3971_LDO_ENABLE_REG, mask, mask); } static int lp3971_ldo_disable(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev) - LP3971_LDO1; u16 mask = 1 << (1 + ldo); return lp3971_set_bits(lp3971, LP3971_LDO_ENABLE_REG, mask, 0); } static int lp3971_ldo_get_voltage_sel(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev) - LP3971_LDO1; u16 val, reg; reg = lp3971_reg_read(lp3971, LP3971_LDO_VOL_CONTR_REG(ldo)); val = (reg >> LDO_VOL_CONTR_SHIFT(ldo)) & LDO_VOL_CONTR_MASK; return val; } static int lp3971_ldo_set_voltage_sel(struct regulator_dev *dev, unsigned int selector) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev) - LP3971_LDO1; return lp3971_set_bits(lp3971, LP3971_LDO_VOL_CONTR_REG(ldo), LDO_VOL_CONTR_MASK << LDO_VOL_CONTR_SHIFT(ldo), selector << LDO_VOL_CONTR_SHIFT(ldo)); } static struct regulator_ops lp3971_ldo_ops = { .list_voltage = regulator_list_voltage_table, .map_voltage = regulator_map_voltage_ascend, .is_enabled = lp3971_ldo_is_enabled, .enable = lp3971_ldo_enable, .disable = lp3971_ldo_disable, .get_voltage_sel = lp3971_ldo_get_voltage_sel, .set_voltage_sel = lp3971_ldo_set_voltage_sel, }; static int lp3971_dcdc_is_enabled(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int buck = rdev_get_id(dev) - LP3971_DCDC1; u16 mask = 1 << (buck * 2); u16 val; val = lp3971_reg_read(lp3971, LP3971_BUCK_VOL_ENABLE_REG); return (val & mask) != 0; } static int lp3971_dcdc_enable(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int buck = rdev_get_id(dev) - LP3971_DCDC1; u16 mask = 1 << (buck * 2); return lp3971_set_bits(lp3971, LP3971_BUCK_VOL_ENABLE_REG, mask, mask); } static int lp3971_dcdc_disable(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int buck = rdev_get_id(dev) - LP3971_DCDC1; u16 mask = 1 << (buck * 2); return lp3971_set_bits(lp3971, LP3971_BUCK_VOL_ENABLE_REG, mask, 0); } static int lp3971_dcdc_get_voltage_sel(struct regulator_dev *dev) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int buck = rdev_get_id(dev) - LP3971_DCDC1; u16 reg; reg = lp3971_reg_read(lp3971, LP3971_BUCK_TARGET_VOL1_REG(buck)); reg &= BUCK_TARGET_VOL_MASK; return reg; } static int lp3971_dcdc_set_voltage_sel(struct regulator_dev *dev, unsigned int selector) { struct lp3971 *lp3971 = rdev_get_drvdata(dev); int buck = rdev_get_id(dev) - LP3971_DCDC1; int ret; ret = lp3971_set_bits(lp3971, LP3971_BUCK_TARGET_VOL1_REG(buck), BUCK_TARGET_VOL_MASK, selector); if (ret) return ret; ret = lp3971_set_bits(lp3971, LP3971_BUCK_VOL_CHANGE_REG, BUCK_VOL_CHANGE_FLAG_MASK << BUCK_VOL_CHANGE_SHIFT(buck), BUCK_VOL_CHANGE_FLAG_GO << BUCK_VOL_CHANGE_SHIFT(buck)); if (ret) return ret; return lp3971_set_bits(lp3971, LP3971_BUCK_VOL_CHANGE_REG, BUCK_VOL_CHANGE_FLAG_MASK << BUCK_VOL_CHANGE_SHIFT(buck), 0 << BUCK_VOL_CHANGE_SHIFT(buck)); } static struct regulator_ops lp3971_dcdc_ops = { .list_voltage = regulator_list_voltage_table, .map_voltage = regulator_map_voltage_ascend, .is_enabled = lp3971_dcdc_is_enabled, .enable = lp3971_dcdc_enable, .disable = lp3971_dcdc_disable, .get_voltage_sel = lp3971_dcdc_get_voltage_sel, .set_voltage_sel = lp3971_dcdc_set_voltage_sel, }; static const struct regulator_desc regulators[] = { { .name = "LDO1", .id = LP3971_LDO1, .ops = &lp3971_ldo_ops, .n_voltages = ARRAY_SIZE(ldo123_voltage_map), .volt_table = ldo123_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "LDO2", .id = LP3971_LDO2, .ops = &lp3971_ldo_ops, .n_voltages = ARRAY_SIZE(ldo123_voltage_map), .volt_table = ldo123_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "LDO3", .id = LP3971_LDO3, .ops = &lp3971_ldo_ops, .n_voltages = ARRAY_SIZE(ldo123_voltage_map), .volt_table = ldo123_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "LDO4", .id = LP3971_LDO4, .ops = &lp3971_ldo_ops, .n_voltages = ARRAY_SIZE(ldo45_voltage_map), .volt_table = ldo45_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "LDO5", .id = LP3971_LDO5, .ops = &lp3971_ldo_ops, .n_voltages = ARRAY_SIZE(ldo45_voltage_map), .volt_table = ldo45_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "DCDC1", .id = LP3971_DCDC1, .ops = &lp3971_dcdc_ops, .n_voltages = ARRAY_SIZE(buck_voltage_map), .volt_table = buck_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "DCDC2", .id = LP3971_DCDC2, .ops = &lp3971_dcdc_ops, .n_voltages = ARRAY_SIZE(buck_voltage_map), .volt_table = buck_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, { .name = "DCDC3", .id = LP3971_DCDC3, .ops = &lp3971_dcdc_ops, .n_voltages = ARRAY_SIZE(buck_voltage_map), .volt_table = buck_voltage_map, .type = REGULATOR_VOLTAGE, .owner = THIS_MODULE, }, }; static int lp3971_i2c_read(struct i2c_client *i2c, char reg, int count, u16 *dest) { int ret; if (count != 1) return -EIO; ret = i2c_smbus_read_byte_data(i2c, reg); if (ret < 0) return -EIO; *dest = ret; return 0; } static int lp3971_i2c_write(struct i2c_client *i2c, char reg, int count, const u16 *src) { if (count != 1) return -EIO; return i2c_smbus_write_byte_data(i2c, reg, *src); } static u8 lp3971_reg_read(struct lp3971 *lp3971, u8 reg) { u16 val = 0; mutex_lock(&lp3971->io_lock); lp3971_i2c_read(lp3971->i2c, reg, 1, &val); dev_dbg(lp3971->dev, "reg read 0x%02x -> 0x%02x\n", (int)reg, (unsigned)val&0xff); mutex_unlock(&lp3971->io_lock); return val & 0xff; } static int lp3971_set_bits(struct lp3971 *lp3971, u8 reg, u16 mask, u16 val) { u16 tmp; int ret; mutex_lock(&lp3971->io_lock); ret = lp3971_i2c_read(lp3971->i2c, reg, 1, &tmp); tmp = (tmp & ~mask) | val; if (ret == 0) { ret = lp3971_i2c_write(lp3971->i2c, reg, 1, &tmp); dev_dbg(lp3971->dev, "reg write 0x%02x -> 0x%02x\n", (int)reg, (unsigned)val&0xff); } mutex_unlock(&lp3971->io_lock); return ret; } static int setup_regulators(struct lp3971 *lp3971, struct lp3971_platform_data *pdata) { int i, err; /* Instantiate the regulators */ for (i = 0; i < pdata->num_regulators; i++) { struct regulator_config config = { }; struct lp3971_regulator_subdev *reg = &pdata->regulators[i]; struct regulator_dev *rdev; config.dev = lp3971->dev; config.init_data = reg->initdata; config.driver_data = lp3971; rdev = devm_regulator_register(lp3971->dev, &regulators[reg->id], &config); if (IS_ERR(rdev)) { err = PTR_ERR(rdev); dev_err(lp3971->dev, "regulator init failed: %d\n", err); return err; } } return 0; } static int lp3971_i2c_probe(struct i2c_client *i2c, const struct i2c_device_id *id) { struct lp3971 *lp3971; struct lp3971_platform_data *pdata = dev_get_platdata(&i2c->dev); int ret; u16 val; if (!pdata) { dev_dbg(&i2c->dev, "No platform init data supplied\n"); return -ENODEV; } lp3971 = devm_kzalloc(&i2c->dev, sizeof(struct lp3971), GFP_KERNEL); if (lp3971 == NULL) return -ENOMEM; lp3971->i2c = i2c; lp3971->dev = &i2c->dev; mutex_init(&lp3971->io_lock); /* Detect LP3971 */ ret = lp3971_i2c_read(i2c, LP3971_SYS_CONTROL1_REG, 1, &val); if (ret == 0 && (val & SYS_CONTROL1_INIT_MASK) != SYS_CONTROL1_INIT_VAL) ret = -ENODEV; if (ret < 0) { dev_err(&i2c->dev, "failed to detect device\n"); return ret; } ret = setup_regulators(lp3971, pdata); if (ret < 0) return ret; i2c_set_clientdata(i2c, lp3971); return 0; } static const struct i2c_device_id lp3971_i2c_id[] = { { "lp3971", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, lp3971_i2c_id); static struct i2c_driver lp3971_i2c_driver = { .driver = { .name = "LP3971", .owner = THIS_MODULE, }, .probe = lp3971_i2c_probe, .id_table = lp3971_i2c_id, }; module_i2c_driver(lp3971_i2c_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Marek Szyprowski <m.szyprowski@samsung.com>"); MODULE_DESCRIPTION("LP3971 PMIC driver");
bsd-3-clause
roisagiv/webrtc-ios
third_party/libjpeg/jquant1.c
1787
31294
/* * jquant1.c * * Copyright (C) 1991-1996, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains 1-pass color quantization (color mapping) routines. * These routines provide mapping to a fixed color map using equally spaced * color values. Optional Floyd-Steinberg or ordered dithering is available. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #ifdef QUANT_1PASS_SUPPORTED /* * The main purpose of 1-pass quantization is to provide a fast, if not very * high quality, colormapped output capability. A 2-pass quantizer usually * gives better visual quality; however, for quantized grayscale output this * quantizer is perfectly adequate. Dithering is highly recommended with this * quantizer, though you can turn it off if you really want to. * * In 1-pass quantization the colormap must be chosen in advance of seeing the * image. We use a map consisting of all combinations of Ncolors[i] color * values for the i'th component. The Ncolors[] values are chosen so that * their product, the total number of colors, is no more than that requested. * (In most cases, the product will be somewhat less.) * * Since the colormap is orthogonal, the representative value for each color * component can be determined without considering the other components; * then these indexes can be combined into a colormap index by a standard * N-dimensional-array-subscript calculation. Most of the arithmetic involved * can be precalculated and stored in the lookup table colorindex[]. * colorindex[i][j] maps pixel value j in component i to the nearest * representative value (grid plane) for that component; this index is * multiplied by the array stride for component i, so that the * index of the colormap entry closest to a given pixel value is just * sum( colorindex[component-number][pixel-component-value] ) * Aside from being fast, this scheme allows for variable spacing between * representative values with no additional lookup cost. * * If gamma correction has been applied in color conversion, it might be wise * to adjust the color grid spacing so that the representative colors are * equidistant in linear space. At this writing, gamma correction is not * implemented by jdcolor, so nothing is done here. */ /* Declarations for ordered dithering. * * We use a standard 16x16 ordered dither array. The basic concept of ordered * dithering is described in many references, for instance Dale Schumacher's * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991). * In place of Schumacher's comparisons against a "threshold" value, we add a * "dither" value to the input pixel and then round the result to the nearest * output value. The dither value is equivalent to (0.5 - threshold) times * the distance between output values. For ordered dithering, we assume that * the output colors are equally spaced; if not, results will probably be * worse, since the dither may be too much or too little at a given point. * * The normal calculation would be to form pixel value + dither, range-limit * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual. * We can skip the separate range-limiting step by extending the colorindex * table in both directions. */ #define ODITHER_SIZE 16 /* dimension of dither matrix */ /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */ #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */ #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */ typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE]; typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE]; static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = { /* Bayer's order-4 dither array. Generated by the code given in * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I. * The values in this array must range from 0 to ODITHER_CELLS-1. */ { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 }, { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 }, { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 }, { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 }, { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 }, { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 }, { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 }, { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 }, { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 }, { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 }, { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 }, { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 }, { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 }, { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 }, { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 }, { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 } }; /* Declarations for Floyd-Steinberg dithering. * * Errors are accumulated into the array fserrors[], at a resolution of * 1/16th of a pixel count. The error at a given pixel is propagated * to its not-yet-processed neighbors using the standard F-S fractions, * ... (here) 7/16 * 3/16 5/16 1/16 * We work left-to-right on even rows, right-to-left on odd rows. * * We can get away with a single array (holding one row's worth of errors) * by using it to store the current row's errors at pixel columns not yet * processed, but the next row's errors at columns already processed. We * need only a few extra variables to hold the errors immediately around the * current column. (If we are lucky, those variables are in registers, but * even if not, they're probably cheaper to access than array elements are.) * * The fserrors[] array is indexed [component#][position]. * We provide (#columns + 2) entries per component; the extra entry at each * end saves us from special-casing the first and last pixels. * * Note: on a wide image, we might not have enough room in a PC's near data * segment to hold the error array; so it is allocated with alloc_large. */ #if BITS_IN_JSAMPLE == 8 typedef INT16 FSERROR; /* 16 bits should be enough */ typedef int LOCFSERROR; /* use 'int' for calculation temps */ #else typedef INT32 FSERROR; /* may need more than 16 bits */ typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */ #endif typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */ /* Private subobject */ #define MAX_Q_COMPS 4 /* max components I can handle */ typedef struct { struct jpeg_color_quantizer pub; /* public fields */ /* Initially allocated colormap is saved here */ JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */ int sv_actual; /* number of entries in use */ JSAMPARRAY colorindex; /* Precomputed mapping for speed */ /* colorindex[i][j] = index of color closest to pixel value j in component i, * premultiplied as described above. Since colormap indexes must fit into * JSAMPLEs, the entries of this array will too. */ boolean is_padded; /* is the colorindex padded for odither? */ int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */ /* Variables for ordered dithering */ int row_index; /* cur row's vertical index in dither matrix */ ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */ /* Variables for Floyd-Steinberg dithering */ FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */ boolean on_odd_row; /* flag to remember which row we are on */ } my_cquantizer; typedef my_cquantizer * my_cquantize_ptr; /* * Policy-making subroutines for create_colormap and create_colorindex. * These routines determine the colormap to be used. The rest of the module * only assumes that the colormap is orthogonal. * * * select_ncolors decides how to divvy up the available colors * among the components. * * output_value defines the set of representative values for a component. * * largest_input_value defines the mapping from input values to * representative values for a component. * Note that the latter two routines may impose different policies for * different components, though this is not currently done. */ LOCAL(int) select_ncolors (j_decompress_ptr cinfo, int Ncolors[]) /* Determine allocation of desired colors to components, */ /* and fill in Ncolors[] array to indicate choice. */ /* Return value is total number of colors (product of Ncolors[] values). */ { int nc = cinfo->out_color_components; /* number of color components */ int max_colors = cinfo->desired_number_of_colors; int total_colors, iroot, i, j; boolean changed; long temp; static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE }; /* We can allocate at least the nc'th root of max_colors per component. */ /* Compute floor(nc'th root of max_colors). */ iroot = 1; do { iroot++; temp = iroot; /* set temp = iroot ** nc */ for (i = 1; i < nc; i++) temp *= iroot; } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */ iroot--; /* now iroot = floor(root) */ /* Must have at least 2 color values per component */ if (iroot < 2) ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp); /* Initialize to iroot color values for each component */ total_colors = 1; for (i = 0; i < nc; i++) { Ncolors[i] = iroot; total_colors *= iroot; } /* We may be able to increment the count for one or more components without * exceeding max_colors, though we know not all can be incremented. * Sometimes, the first component can be incremented more than once! * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.) * In RGB colorspace, try to increment G first, then R, then B. */ do { changed = FALSE; for (i = 0; i < nc; i++) { j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i); /* calculate new total_colors if Ncolors[j] is incremented */ temp = total_colors / Ncolors[j]; temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */ if (temp > (long) max_colors) break; /* won't fit, done with this pass */ Ncolors[j]++; /* OK, apply the increment */ total_colors = (int) temp; changed = TRUE; } } while (changed); return total_colors; } LOCAL(int) output_value (j_decompress_ptr cinfo, int ci, int j, int maxj) /* Return j'th output value, where j will range from 0 to maxj */ /* The output values must fall in 0..MAXJSAMPLE in increasing order */ { /* We always provide values 0 and MAXJSAMPLE for each component; * any additional values are equally spaced between these limits. * (Forcing the upper and lower values to the limits ensures that * dithering can't produce a color outside the selected gamut.) */ return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj); } LOCAL(int) largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj) /* Return largest input value that should map to j'th output value */ /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */ { /* Breakpoints are halfway between values returned by output_value */ return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj)); } /* * Create the colormap. */ LOCAL(void) create_colormap (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; JSAMPARRAY colormap; /* Created colormap */ int total_colors; /* Number of distinct output colors */ int i,j,k, nci, blksize, blkdist, ptr, val; /* Select number of colors for each component */ total_colors = select_ncolors(cinfo, cquantize->Ncolors); /* Report selected color counts */ if (cinfo->out_color_components == 3) TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS, total_colors, cquantize->Ncolors[0], cquantize->Ncolors[1], cquantize->Ncolors[2]); else TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors); /* Allocate and fill in the colormap. */ /* The colors are ordered in the map in standard row-major order, */ /* i.e. rightmost (highest-indexed) color changes most rapidly. */ colormap = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components); /* blksize is number of adjacent repeated entries for a component */ /* blkdist is distance between groups of identical entries for a component */ blkdist = total_colors; for (i = 0; i < cinfo->out_color_components; i++) { /* fill in colormap entries for i'th color component */ nci = cquantize->Ncolors[i]; /* # of distinct values for this color */ blksize = blkdist / nci; for (j = 0; j < nci; j++) { /* Compute j'th output value (out of nci) for component */ val = output_value(cinfo, i, j, nci-1); /* Fill in all colormap entries that have this value of this component */ for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) { /* fill in blksize entries beginning at ptr */ for (k = 0; k < blksize; k++) colormap[i][ptr+k] = (JSAMPLE) val; } } blkdist = blksize; /* blksize of this color is blkdist of next */ } /* Save the colormap in private storage, * where it will survive color quantization mode changes. */ cquantize->sv_colormap = colormap; cquantize->sv_actual = total_colors; } /* * Create the color index table. */ LOCAL(void) create_colorindex (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; JSAMPROW indexptr; int i,j,k, nci, blksize, val, pad; /* For ordered dither, we pad the color index tables by MAXJSAMPLE in * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE). * This is not necessary in the other dithering modes. However, we * flag whether it was done in case user changes dithering mode. */ if (cinfo->dither_mode == JDITHER_ORDERED) { pad = MAXJSAMPLE*2; cquantize->is_padded = TRUE; } else { pad = 0; cquantize->is_padded = FALSE; } cquantize->colorindex = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) (MAXJSAMPLE+1 + pad), (JDIMENSION) cinfo->out_color_components); /* blksize is number of adjacent repeated entries for a component */ blksize = cquantize->sv_actual; for (i = 0; i < cinfo->out_color_components; i++) { /* fill in colorindex entries for i'th color component */ nci = cquantize->Ncolors[i]; /* # of distinct values for this color */ blksize = blksize / nci; /* adjust colorindex pointers to provide padding at negative indexes. */ if (pad) cquantize->colorindex[i] += MAXJSAMPLE; /* in loop, val = index of current output value, */ /* and k = largest j that maps to current val */ indexptr = cquantize->colorindex[i]; val = 0; k = largest_input_value(cinfo, i, 0, nci-1); for (j = 0; j <= MAXJSAMPLE; j++) { while (j > k) /* advance val if past boundary */ k = largest_input_value(cinfo, i, ++val, nci-1); /* premultiply so that no multiplication needed in main processing */ indexptr[j] = (JSAMPLE) (val * blksize); } /* Pad at both ends if necessary */ if (pad) for (j = 1; j <= MAXJSAMPLE; j++) { indexptr[-j] = indexptr[0]; indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE]; } } } /* * Create an ordered-dither array for a component having ncolors * distinct output values. */ LOCAL(ODITHER_MATRIX_PTR) make_odither_array (j_decompress_ptr cinfo, int ncolors) { ODITHER_MATRIX_PTR odither; int j,k; INT32 num,den; odither = (ODITHER_MATRIX_PTR) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(ODITHER_MATRIX)); /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1). * Hence the dither value for the matrix cell with fill order f * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1). * On 16-bit-int machine, be careful to avoid overflow. */ den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1)); for (j = 0; j < ODITHER_SIZE; j++) { for (k = 0; k < ODITHER_SIZE; k++) { num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k]))) * MAXJSAMPLE; /* Ensure round towards zero despite C's lack of consistency * about rounding negative values in integer division... */ odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den); } } return odither; } /* * Create the ordered-dither tables. * Components having the same number of representative colors may * share a dither table. */ LOCAL(void) create_odither_tables (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; ODITHER_MATRIX_PTR odither; int i, j, nci; for (i = 0; i < cinfo->out_color_components; i++) { nci = cquantize->Ncolors[i]; /* # of distinct values for this color */ odither = NULL; /* search for matching prior component */ for (j = 0; j < i; j++) { if (nci == cquantize->Ncolors[j]) { odither = cquantize->odither[j]; break; } } if (odither == NULL) /* need a new table? */ odither = make_odither_array(cinfo, nci); cquantize->odither[i] = odither; } } /* * Map some rows of pixels to the output colormapped representation. */ METHODDEF(void) color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* General case, no dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; JSAMPARRAY colorindex = cquantize->colorindex; register int pixcode, ci; register JSAMPROW ptrin, ptrout; int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; register int nc = cinfo->out_color_components; for (row = 0; row < num_rows; row++) { ptrin = input_buf[row]; ptrout = output_buf[row]; for (col = width; col > 0; col--) { pixcode = 0; for (ci = 0; ci < nc; ci++) { pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]); } *ptrout++ = (JSAMPLE) pixcode; } } } METHODDEF(void) color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* Fast path for out_color_components==3, no dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; register int pixcode; register JSAMPROW ptrin, ptrout; JSAMPROW colorindex0 = cquantize->colorindex[0]; JSAMPROW colorindex1 = cquantize->colorindex[1]; JSAMPROW colorindex2 = cquantize->colorindex[2]; int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; for (row = 0; row < num_rows; row++) { ptrin = input_buf[row]; ptrout = output_buf[row]; for (col = width; col > 0; col--) { pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]); pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]); pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]); *ptrout++ = (JSAMPLE) pixcode; } } } METHODDEF(void) quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* General case, with ordered dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; register JSAMPROW input_ptr; register JSAMPROW output_ptr; JSAMPROW colorindex_ci; int * dither; /* points to active row of dither matrix */ int row_index, col_index; /* current indexes into dither matrix */ int nc = cinfo->out_color_components; int ci; int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; for (row = 0; row < num_rows; row++) { /* Initialize output values to 0 so can process components separately */ jzero_far((void FAR *) output_buf[row], (size_t) (width * SIZEOF(JSAMPLE))); row_index = cquantize->row_index; for (ci = 0; ci < nc; ci++) { input_ptr = input_buf[row] + ci; output_ptr = output_buf[row]; colorindex_ci = cquantize->colorindex[ci]; dither = cquantize->odither[ci][row_index]; col_index = 0; for (col = width; col > 0; col--) { /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE, * select output value, accumulate into output code for this pixel. * Range-limiting need not be done explicitly, as we have extended * the colorindex table to produce the right answers for out-of-range * inputs. The maximum dither is +- MAXJSAMPLE; this sets the * required amount of padding. */ *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]]; input_ptr += nc; output_ptr++; col_index = (col_index + 1) & ODITHER_MASK; } } /* Advance row index for next row */ row_index = (row_index + 1) & ODITHER_MASK; cquantize->row_index = row_index; } } METHODDEF(void) quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* Fast path for out_color_components==3, with ordered dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; register int pixcode; register JSAMPROW input_ptr; register JSAMPROW output_ptr; JSAMPROW colorindex0 = cquantize->colorindex[0]; JSAMPROW colorindex1 = cquantize->colorindex[1]; JSAMPROW colorindex2 = cquantize->colorindex[2]; int * dither0; /* points to active row of dither matrix */ int * dither1; int * dither2; int row_index, col_index; /* current indexes into dither matrix */ int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; for (row = 0; row < num_rows; row++) { row_index = cquantize->row_index; input_ptr = input_buf[row]; output_ptr = output_buf[row]; dither0 = cquantize->odither[0][row_index]; dither1 = cquantize->odither[1][row_index]; dither2 = cquantize->odither[2][row_index]; col_index = 0; for (col = width; col > 0; col--) { pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) + dither0[col_index]]); pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) + dither1[col_index]]); pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) + dither2[col_index]]); *output_ptr++ = (JSAMPLE) pixcode; col_index = (col_index + 1) & ODITHER_MASK; } row_index = (row_index + 1) & ODITHER_MASK; cquantize->row_index = row_index; } } METHODDEF(void) quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows) /* General case, with Floyd-Steinberg dithering */ { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; register LOCFSERROR cur; /* current error or pixel value */ LOCFSERROR belowerr; /* error for pixel below cur */ LOCFSERROR bpreverr; /* error for below/prev col */ LOCFSERROR bnexterr; /* error for below/next col */ LOCFSERROR delta; register FSERRPTR errorptr; /* => fserrors[] at column before current */ register JSAMPROW input_ptr; register JSAMPROW output_ptr; JSAMPROW colorindex_ci; JSAMPROW colormap_ci; int pixcode; int nc = cinfo->out_color_components; int dir; /* 1 for left-to-right, -1 for right-to-left */ int dirnc; /* dir * nc */ int ci; int row; JDIMENSION col; JDIMENSION width = cinfo->output_width; JSAMPLE *range_limit = cinfo->sample_range_limit; SHIFT_TEMPS for (row = 0; row < num_rows; row++) { /* Initialize output values to 0 so can process components separately */ jzero_far((void FAR *) output_buf[row], (size_t) (width * SIZEOF(JSAMPLE))); for (ci = 0; ci < nc; ci++) { input_ptr = input_buf[row] + ci; output_ptr = output_buf[row]; if (cquantize->on_odd_row) { /* work right to left in this row */ input_ptr += (width-1) * nc; /* so point to rightmost pixel */ output_ptr += width-1; dir = -1; dirnc = -nc; errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */ } else { /* work left to right in this row */ dir = 1; dirnc = nc; errorptr = cquantize->fserrors[ci]; /* => entry before first column */ } colorindex_ci = cquantize->colorindex[ci]; colormap_ci = cquantize->sv_colormap[ci]; /* Preset error values: no error propagated to first pixel from left */ cur = 0; /* and no error propagated to row below yet */ belowerr = bpreverr = 0; for (col = width; col > 0; col--) { /* cur holds the error propagated from the previous pixel on the * current line. Add the error propagated from the previous line * to form the complete error correction term for this pixel, and * round the error term (which is expressed * 16) to an integer. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct * for either sign of the error value. * Note: errorptr points to *previous* column's array entry. */ cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4); /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE. * The maximum error is +- MAXJSAMPLE; this sets the required size * of the range_limit array. */ cur += GETJSAMPLE(*input_ptr); cur = GETJSAMPLE(range_limit[cur]); /* Select output value, accumulate into output code for this pixel */ pixcode = GETJSAMPLE(colorindex_ci[cur]); *output_ptr += (JSAMPLE) pixcode; /* Compute actual representation error at this pixel */ /* Note: we can do this even though we don't have the final */ /* pixel code, because the colormap is orthogonal. */ cur -= GETJSAMPLE(colormap_ci[pixcode]); /* Compute error fractions to be propagated to adjacent pixels. * Add these into the running sums, and simultaneously shift the * next-line error sums left by 1 column. */ bnexterr = cur; delta = cur * 2; cur += delta; /* form error * 3 */ errorptr[0] = (FSERROR) (bpreverr + cur); cur += delta; /* form error * 5 */ bpreverr = belowerr + cur; belowerr = bnexterr; cur += delta; /* form error * 7 */ /* At this point cur contains the 7/16 error value to be propagated * to the next pixel on the current line, and all the errors for the * next line have been shifted over. We are therefore ready to move on. */ input_ptr += dirnc; /* advance input ptr to next column */ output_ptr += dir; /* advance output ptr to next column */ errorptr += dir; /* advance errorptr to current column */ } /* Post-loop cleanup: we must unload the final error value into the * final fserrors[] entry. Note we need not unload belowerr because * it is for the dummy column before or after the actual array. */ errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */ } cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE); } } /* * Allocate workspace for Floyd-Steinberg errors. */ LOCAL(void) alloc_fs_workspace (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; size_t arraysize; int i; arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR)); for (i = 0; i < cinfo->out_color_components; i++) { cquantize->fserrors[i] = (FSERRPTR) (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize); } } /* * Initialize for one-pass color quantization. */ METHODDEF(void) start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan) { my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize; size_t arraysize; int i; /* Install my colormap. */ cinfo->colormap = cquantize->sv_colormap; cinfo->actual_number_of_colors = cquantize->sv_actual; /* Initialize for desired dithering mode. */ switch (cinfo->dither_mode) { case JDITHER_NONE: if (cinfo->out_color_components == 3) cquantize->pub.color_quantize = color_quantize3; else cquantize->pub.color_quantize = color_quantize; break; case JDITHER_ORDERED: if (cinfo->out_color_components == 3) cquantize->pub.color_quantize = quantize3_ord_dither; else cquantize->pub.color_quantize = quantize_ord_dither; cquantize->row_index = 0; /* initialize state for ordered dither */ /* If user changed to ordered dither from another mode, * we must recreate the color index table with padding. * This will cost extra space, but probably isn't very likely. */ if (! cquantize->is_padded) create_colorindex(cinfo); /* Create ordered-dither tables if we didn't already. */ if (cquantize->odither[0] == NULL) create_odither_tables(cinfo); break; case JDITHER_FS: cquantize->pub.color_quantize = quantize_fs_dither; cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */ /* Allocate Floyd-Steinberg workspace if didn't already. */ if (cquantize->fserrors[0] == NULL) alloc_fs_workspace(cinfo); /* Initialize the propagated errors to zero. */ arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR)); for (i = 0; i < cinfo->out_color_components; i++) jzero_far((void FAR *) cquantize->fserrors[i], arraysize); break; default: ERREXIT(cinfo, JERR_NOT_COMPILED); break; } } /* * Finish up at the end of the pass. */ METHODDEF(void) finish_pass_1_quant (j_decompress_ptr cinfo) { /* no work in 1-pass case */ } /* * Switch to a new external colormap between output passes. * Shouldn't get to this module! */ METHODDEF(void) new_color_map_1_quant (j_decompress_ptr cinfo) { ERREXIT(cinfo, JERR_MODE_CHANGE); } /* * Module initialization routine for 1-pass color quantization. */ GLOBAL(void) jinit_1pass_quantizer (j_decompress_ptr cinfo) { my_cquantize_ptr cquantize; cquantize = (my_cquantize_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_cquantizer)); cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize; cquantize->pub.start_pass = start_pass_1_quant; cquantize->pub.finish_pass = finish_pass_1_quant; cquantize->pub.new_color_map = new_color_map_1_quant; cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */ cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */ /* Make sure my internal arrays won't overflow */ if (cinfo->out_color_components > MAX_Q_COMPS) ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS); /* Make sure colormap indexes can be represented by JSAMPLEs */ if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1)) ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1); /* Create the colormap and color index table. */ create_colormap(cinfo); create_colorindex(cinfo); /* Allocate Floyd-Steinberg workspace now if requested. * We do this now since it is FAR storage and may affect the memory * manager's space calculations. If the user changes to FS dither * mode in a later pass, we will allocate the space then, and will * possibly overrun the max_memory_to_use setting. */ if (cinfo->dither_mode == JDITHER_FS) alloc_fs_workspace(cinfo); } #endif /* QUANT_1PASS_SUPPORTED */
bsd-3-clause
goertzenator/yamler
c_src/libyaml/reader.c
51
16543
#include "yaml_private.h" /* * Declarations. */ static int yaml_parser_set_reader_error(yaml_parser_t *parser, const char *problem, size_t offset, int value); static int yaml_parser_update_raw_buffer(yaml_parser_t *parser); static int yaml_parser_determine_encoding(yaml_parser_t *parser); YAML_DECLARE(int) yaml_parser_update_buffer(yaml_parser_t *parser, size_t length); /* * Set the reader error and return 0. */ static int yaml_parser_set_reader_error(yaml_parser_t *parser, const char *problem, size_t offset, int value) { parser->error = YAML_READER_ERROR; parser->problem = problem; parser->problem_offset = offset; parser->problem_value = value; return 0; } /* * Byte order marks. */ #define BOM_UTF8 "\xef\xbb\xbf" #define BOM_UTF16LE "\xff\xfe" #define BOM_UTF16BE "\xfe\xff" /* * Determine the input stream encoding by checking the BOM symbol. If no BOM is * found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. */ static int yaml_parser_determine_encoding(yaml_parser_t *parser) { /* Ensure that we had enough bytes in the raw buffer. */ while (!parser->eof && parser->raw_buffer.last - parser->raw_buffer.pointer < 3) { if (!yaml_parser_update_raw_buffer(parser)) { return 0; } } /* Determine the encoding. */ if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 2 && !memcmp(parser->raw_buffer.pointer, BOM_UTF16LE, 2)) { parser->encoding = YAML_UTF16LE_ENCODING; parser->raw_buffer.pointer += 2; parser->offset += 2; } else if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 2 && !memcmp(parser->raw_buffer.pointer, BOM_UTF16BE, 2)) { parser->encoding = YAML_UTF16BE_ENCODING; parser->raw_buffer.pointer += 2; parser->offset += 2; } else if (parser->raw_buffer.last - parser->raw_buffer.pointer >= 3 && !memcmp(parser->raw_buffer.pointer, BOM_UTF8, 3)) { parser->encoding = YAML_UTF8_ENCODING; parser->raw_buffer.pointer += 3; parser->offset += 3; } else { parser->encoding = YAML_UTF8_ENCODING; } return 1; } /* * Update the raw buffer. */ static int yaml_parser_update_raw_buffer(yaml_parser_t *parser) { size_t size_read = 0; /* Return if the raw buffer is full. */ if (parser->raw_buffer.start == parser->raw_buffer.pointer && parser->raw_buffer.last == parser->raw_buffer.end) return 1; /* Return on EOF. */ if (parser->eof) return 1; /* Move the remaining bytes in the raw buffer to the beginning. */ if (parser->raw_buffer.start < parser->raw_buffer.pointer && parser->raw_buffer.pointer < parser->raw_buffer.last) { memmove(parser->raw_buffer.start, parser->raw_buffer.pointer, parser->raw_buffer.last - parser->raw_buffer.pointer); } parser->raw_buffer.last -= parser->raw_buffer.pointer - parser->raw_buffer.start; parser->raw_buffer.pointer = parser->raw_buffer.start; /* Call the read handler to fill the buffer. */ if (!parser->read_handler(parser->read_handler_data, parser->raw_buffer.last, parser->raw_buffer.end - parser->raw_buffer.last, &size_read)) { return yaml_parser_set_reader_error(parser, "input error", parser->offset, -1); } parser->raw_buffer.last += size_read; if (!size_read) { parser->eof = 1; } return 1; } /* * Ensure that the buffer contains at least `length` characters. * Return 1 on success, 0 on failure. * * The length is supposed to be significantly less that the buffer size. */ YAML_DECLARE(int) yaml_parser_update_buffer(yaml_parser_t *parser, size_t length) { int first = 1; assert(parser->read_handler); /* Read handler must be set. */ /* If the EOF flag is set and the raw buffer is empty, do nothing. */ if (parser->eof && parser->raw_buffer.pointer == parser->raw_buffer.last) return 1; /* Return if the buffer contains enough characters. */ if (parser->unread >= length) return 1; /* Determine the input encoding if it is not known yet. */ if (!parser->encoding) { if (!yaml_parser_determine_encoding(parser)) return 0; } /* Move the unread characters to the beginning of the buffer. */ if (parser->buffer.start < parser->buffer.pointer && parser->buffer.pointer < parser->buffer.last) { size_t size = parser->buffer.last - parser->buffer.pointer; memmove(parser->buffer.start, parser->buffer.pointer, size); parser->buffer.pointer = parser->buffer.start; parser->buffer.last = parser->buffer.start + size; } else if (parser->buffer.pointer == parser->buffer.last) { parser->buffer.pointer = parser->buffer.start; parser->buffer.last = parser->buffer.start; } /* Fill the buffer until it has enough characters. */ while (parser->unread < length) { /* Fill the raw buffer if necessary. */ if (!first || parser->raw_buffer.pointer == parser->raw_buffer.last) { if (!yaml_parser_update_raw_buffer(parser)) return 0; } first = 0; /* Decode the raw buffer. */ while (parser->raw_buffer.pointer != parser->raw_buffer.last) { unsigned int value = 0, value2 = 0; int incomplete = 0; unsigned char octet; unsigned int width = 0; int low, high; size_t k; size_t raw_unread = parser->raw_buffer.last - parser->raw_buffer.pointer; /* Decode the next character. */ switch (parser->encoding) { case YAML_UTF8_ENCODING: /* * Decode a UTF-8 character. Check RFC 3629 * (http://www.ietf.org/rfc/rfc3629.txt) for more details. * * The following table (taken from the RFC) is used for * decoding. * * Char. number range | UTF-8 octet sequence * (hexadecimal) | (binary) * --------------------+------------------------------------ * 0000 0000-0000 007F | 0xxxxxxx * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * * Additionally, the characters in the range 0xD800-0xDFFF * are prohibited as they are reserved for use with UTF-16 * surrogate pairs. */ /* Determine the length of the UTF-8 sequence. */ octet = parser->raw_buffer.pointer[0]; width = (octet & 0x80) == 0x00 ? 1 : (octet & 0xE0) == 0xC0 ? 2 : (octet & 0xF0) == 0xE0 ? 3 : (octet & 0xF8) == 0xF0 ? 4 : 0; /* Check if the leading octet is valid. */ if (!width) return yaml_parser_set_reader_error(parser, "invalid leading UTF-8 octet", parser->offset, octet); /* Check if the raw buffer contains an incomplete character. */ if (width > raw_unread) { if (parser->eof) { return yaml_parser_set_reader_error(parser, "incomplete UTF-8 octet sequence", parser->offset, -1); } incomplete = 1; break; } /* Decode the leading octet. */ value = (octet & 0x80) == 0x00 ? octet & 0x7F : (octet & 0xE0) == 0xC0 ? octet & 0x1F : (octet & 0xF0) == 0xE0 ? octet & 0x0F : (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; /* Check and decode the trailing octets. */ for (k = 1; k < width; k ++) { octet = parser->raw_buffer.pointer[k]; /* Check if the octet is valid. */ if ((octet & 0xC0) != 0x80) return yaml_parser_set_reader_error(parser, "invalid trailing UTF-8 octet", parser->offset+k, octet); /* Decode the octet. */ value = (value << 6) + (octet & 0x3F); } /* Check the length of the sequence against the value. */ if (!((width == 1) || (width == 2 && value >= 0x80) || (width == 3 && value >= 0x800) || (width == 4 && value >= 0x10000))) return yaml_parser_set_reader_error(parser, "invalid length of a UTF-8 sequence", parser->offset, -1); /* Check the range of the value. */ if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) return yaml_parser_set_reader_error(parser, "invalid Unicode character", parser->offset, value); break; case YAML_UTF16LE_ENCODING: case YAML_UTF16BE_ENCODING: low = (parser->encoding == YAML_UTF16LE_ENCODING ? 0 : 1); high = (parser->encoding == YAML_UTF16LE_ENCODING ? 1 : 0); /* * The UTF-16 encoding is not as simple as one might * naively think. Check RFC 2781 * (http://www.ietf.org/rfc/rfc2781.txt). * * Normally, two subsequent bytes describe a Unicode * character. However a special technique (called a * surrogate pair) is used for specifying character * values larger than 0xFFFF. * * A surrogate pair consists of two pseudo-characters: * high surrogate area (0xD800-0xDBFF) * low surrogate area (0xDC00-0xDFFF) * * The following formulas are used for decoding * and encoding characters using surrogate pairs: * * U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) * U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) * W1 = 110110yyyyyyyyyy * W2 = 110111xxxxxxxxxx * * where U is the character value, W1 is the high surrogate * area, W2 is the low surrogate area. */ /* Check for incomplete UTF-16 character. */ if (raw_unread < 2) { if (parser->eof) { return yaml_parser_set_reader_error(parser, "incomplete UTF-16 character", parser->offset, -1); } incomplete = 1; break; } /* Get the character. */ value = parser->raw_buffer.pointer[low] + (parser->raw_buffer.pointer[high] << 8); /* Check for unexpected low surrogate area. */ if ((value & 0xFC00) == 0xDC00) return yaml_parser_set_reader_error(parser, "unexpected low surrogate area", parser->offset, value); /* Check for a high surrogate area. */ if ((value & 0xFC00) == 0xD800) { width = 4; /* Check for incomplete surrogate pair. */ if (raw_unread < 4) { if (parser->eof) { return yaml_parser_set_reader_error(parser, "incomplete UTF-16 surrogate pair", parser->offset, -1); } incomplete = 1; break; } /* Get the next character. */ value2 = parser->raw_buffer.pointer[low+2] + (parser->raw_buffer.pointer[high+2] << 8); /* Check for a low surrogate area. */ if ((value2 & 0xFC00) != 0xDC00) return yaml_parser_set_reader_error(parser, "expected low surrogate area", parser->offset+2, value2); /* Generate the value of the surrogate pair. */ value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF); } else { width = 2; } break; default: assert(1); /* Impossible. */ } /* Check if the raw buffer contains enough bytes to form a character. */ if (incomplete) break; /* * Check if the character is in the allowed range: * #x9 | #xA | #xD | [#x20-#x7E] (8 bit) * | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) * | [#x10000-#x10FFFF] (32 bit) */ if (! (value == 0x09 || value == 0x0A || value == 0x0D || (value >= 0x20 && value <= 0x7E) || (value == 0x85) || (value >= 0xA0 && value <= 0xD7FF) || (value >= 0xE000 && value <= 0xFFFD) || (value >= 0x10000 && value <= 0x10FFFF))) return yaml_parser_set_reader_error(parser, "control characters are not allowed", parser->offset, value); /* Move the raw pointers. */ parser->raw_buffer.pointer += width; parser->offset += width; /* Finally put the character into the buffer. */ /* 0000 0000-0000 007F -> 0xxxxxxx */ if (value <= 0x7F) { *(parser->buffer.last++) = value; } /* 0000 0080-0000 07FF -> 110xxxxx 10xxxxxx */ else if (value <= 0x7FF) { *(parser->buffer.last++) = 0xC0 + (value >> 6); *(parser->buffer.last++) = 0x80 + (value & 0x3F); } /* 0000 0800-0000 FFFF -> 1110xxxx 10xxxxxx 10xxxxxx */ else if (value <= 0xFFFF) { *(parser->buffer.last++) = 0xE0 + (value >> 12); *(parser->buffer.last++) = 0x80 + ((value >> 6) & 0x3F); *(parser->buffer.last++) = 0x80 + (value & 0x3F); } /* 0001 0000-0010 FFFF -> 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ else { *(parser->buffer.last++) = 0xF0 + (value >> 18); *(parser->buffer.last++) = 0x80 + ((value >> 12) & 0x3F); *(parser->buffer.last++) = 0x80 + ((value >> 6) & 0x3F); *(parser->buffer.last++) = 0x80 + (value & 0x3F); } parser->unread ++; } /* On EOF, put NUL into the buffer and return. */ if (parser->eof) { *(parser->buffer.last++) = '\0'; parser->unread ++; return 1; } } return 1; }
isc
publicloudapp/csrutil
linux-4.3/drivers/scsi/NCR5380.c
768
90487
/* * NCR 5380 generic driver routines. These should make it *trivial* * to implement 5380 SCSI drivers under Linux with a non-trantor * architecture. * * Note that these routines also work with NR53c400 family chips. * * Copyright 1993, Drew Eckhardt * Visionary Computing * (Unix and Linux consulting and custom programming) * drew@colorado.edu * +1 (303) 666-5836 * * For more information, please consult * * NCR 5380 Family * SCSI Protocol Controller * Databook * * NCR Microelectronics * 1635 Aeroplaza Drive * Colorado Springs, CO 80916 * 1+ (719) 578-3400 * 1+ (800) 334-5454 */ /* * Revision 1.10 1998/9/2 Alan Cox * (alan@lxorguk.ukuu.org.uk) * Fixed up the timer lockups reported so far. Things still suck. Looking * forward to 2.3 and per device request queues. Then it'll be possible to * SMP thread this beast and improve life no end. * Revision 1.9 1997/7/27 Ronald van Cuijlenborg * (ronald.van.cuijlenborg@tip.nl or nutty@dds.nl) * (hopefully) fixed and enhanced USLEEP * added support for DTC3181E card (for Mustek scanner) * * Revision 1.8 Ingmar Baumgart * (ingmar@gonzo.schwaben.de) * added support for NCR53C400a card * * Revision 1.7 1996/3/2 Ray Van Tassle (rayvt@comm.mot.com) * added proc_info * added support needed for DTC 3180/3280 * fixed a couple of bugs * * Revision 1.5 1994/01/19 09:14:57 drew * Fixed udelay() hack that was being used on DATAOUT phases * instead of a proper wait for the final handshake. * * Revision 1.4 1994/01/19 06:44:25 drew * *** empty log message *** * * Revision 1.3 1994/01/19 05:24:40 drew * Added support for TCR LAST_BYTE_SENT bit. * * Revision 1.2 1994/01/15 06:14:11 drew * REAL DMA support, bug fixes. * * Revision 1.1 1994/01/15 06:00:54 drew * Initial revision * */ /* * Further development / testing that should be done : * 1. Cleanup the NCR5380_transfer_dma function and DMA operation complete * code so that everything does the same thing that's done at the * end of a pseudo-DMA read operation. * * 2. Fix REAL_DMA (interrupt driven, polled works fine) - * basically, transfer size needs to be reduced by one * and the last byte read as is done with PSEUDO_DMA. * * 4. Test SCSI-II tagged queueing (I have no devices which support * tagged queueing) * * 5. Test linked command handling code after Eric is ready with * the high level code. */ #include <scsi/scsi_dbg.h> #include <scsi/scsi_transport_spi.h> #if (NDEBUG & NDEBUG_LISTS) #define LIST(x,y) {printk("LINE:%d Adding %p to %p\n", __LINE__, (void*)(x), (void*)(y)); if ((x)==(y)) udelay(5); } #define REMOVE(w,x,y,z) {printk("LINE:%d Removing: %p->%p %p->%p \n", __LINE__, (void*)(w), (void*)(x), (void*)(y), (void*)(z)); if ((x)==(y)) udelay(5); } #else #define LIST(x,y) #define REMOVE(w,x,y,z) #endif #ifndef notyet #undef LINKED #undef REAL_DMA #endif #ifdef REAL_DMA_POLL #undef READ_OVERRUNS #define READ_OVERRUNS #endif #ifdef BOARD_REQUIRES_NO_DELAY #define io_recovery_delay(x) #else #define io_recovery_delay(x) udelay(x) #endif /* * Design * * This is a generic 5380 driver. To use it on a different platform, * one simply writes appropriate system specific macros (ie, data * transfer - some PC's will use the I/O bus, 68K's must use * memory mapped) and drops this file in their 'C' wrapper. * * (Note from hch: unfortunately it was not enough for the different * m68k folks and instead of improving this driver they copied it * and hacked it up for their needs. As a consequence they lost * most updates to this driver. Maybe someone will fix all these * drivers to use a common core one day..) * * As far as command queueing, two queues are maintained for * each 5380 in the system - commands that haven't been issued yet, * and commands that are currently executing. This means that an * unlimited number of commands may be queued, letting * more commands propagate from the higher driver levels giving higher * throughput. Note that both I_T_L and I_T_L_Q nexuses are supported, * allowing multiple commands to propagate all the way to a SCSI-II device * while a command is already executing. * * * Issues specific to the NCR5380 : * * When used in a PIO or pseudo-dma mode, the NCR5380 is a braindead * piece of hardware that requires you to sit in a loop polling for * the REQ signal as long as you are connected. Some devices are * brain dead (ie, many TEXEL CD ROM drives) and won't disconnect * while doing long seek operations. * * The workaround for this is to keep track of devices that have * disconnected. If the device hasn't disconnected, for commands that * should disconnect, we do something like * * while (!REQ is asserted) { sleep for N usecs; poll for M usecs } * * Some tweaking of N and M needs to be done. An algorithm based * on "time to data" would give the best results as long as short time * to datas (ie, on the same track) were considered, however these * broken devices are the exception rather than the rule and I'd rather * spend my time optimizing for the normal case. * * Architecture : * * At the heart of the design is a coroutine, NCR5380_main, * which is started from a workqueue for each NCR5380 host in the * system. It attempts to establish I_T_L or I_T_L_Q nexuses by * removing the commands from the issue queue and calling * NCR5380_select() if a nexus is not established. * * Once a nexus is established, the NCR5380_information_transfer() * phase goes through the various phases as instructed by the target. * if the target goes into MSG IN and sends a DISCONNECT message, * the command structure is placed into the per instance disconnected * queue, and NCR5380_main tries to find more work. If the target is * idle for too long, the system will try to sleep. * * If a command has disconnected, eventually an interrupt will trigger, * calling NCR5380_intr() which will in turn call NCR5380_reselect * to reestablish a nexus. This will run main if necessary. * * On command termination, the done function will be called as * appropriate. * * SCSI pointers are maintained in the SCp field of SCSI command * structures, being initialized after the command is connected * in NCR5380_select, and set as appropriate in NCR5380_information_transfer. * Note that in violation of the standard, an implicit SAVE POINTERS operation * is done, since some BROKEN disks fail to issue an explicit SAVE POINTERS. */ /* * Using this file : * This file a skeleton Linux SCSI driver for the NCR 5380 series * of chips. To use it, you write an architecture specific functions * and macros and include this file in your driver. * * These macros control options : * AUTOPROBE_IRQ - if defined, the NCR5380_probe_irq() function will be * defined. * * AUTOSENSE - if defined, REQUEST SENSE will be performed automatically * for commands that return with a CHECK CONDITION status. * * DIFFERENTIAL - if defined, NCR53c81 chips will use external differential * transceivers. * * DONT_USE_INTR - if defined, never use interrupts, even if we probe or * override-configure an IRQ. * * LIMIT_TRANSFERSIZE - if defined, limit the pseudo-dma transfers to 512 * bytes at a time. Since interrupts are disabled by default during * these transfers, we might need this to give reasonable interrupt * service time if the transfer size gets too large. * * LINKED - if defined, linked commands are supported. * * PSEUDO_DMA - if defined, PSEUDO DMA is used during the data transfer phases. * * REAL_DMA - if defined, REAL DMA is used during the data transfer phases. * * REAL_DMA_POLL - if defined, REAL DMA is used but the driver doesn't * rely on phase mismatch and EOP interrupts to determine end * of phase. * * UNSAFE - leave interrupts enabled during pseudo-DMA transfers. You * only really want to use this if you're having a problem with * dropped characters during high speed communications, and even * then, you're going to be better off twiddling with transfersize * in the high level code. * * Defaults for these will be provided although the user may want to adjust * these to allocate CPU resources to the SCSI driver or "real" code. * * USLEEP_SLEEP - amount of time, in jiffies, to sleep * * USLEEP_POLL - amount of time, in jiffies, to poll * * These macros MUST be defined : * NCR5380_local_declare() - declare any local variables needed for your * transfer routines. * * NCR5380_setup(instance) - initialize any local variables needed from a given * instance of the host adapter for NCR5380_{read,write,pread,pwrite} * * NCR5380_read(register) - read from the specified register * * NCR5380_write(register, value) - write to the specific register * * NCR5380_implementation_fields - additional fields needed for this * specific implementation of the NCR5380 * * Either real DMA *or* pseudo DMA may be implemented * REAL functions : * NCR5380_REAL_DMA should be defined if real DMA is to be used. * Note that the DMA setup functions should return the number of bytes * that they were able to program the controller for. * * Also note that generic i386/PC versions of these macros are * available as NCR5380_i386_dma_write_setup, * NCR5380_i386_dma_read_setup, and NCR5380_i386_dma_residual. * * NCR5380_dma_write_setup(instance, src, count) - initialize * NCR5380_dma_read_setup(instance, dst, count) - initialize * NCR5380_dma_residual(instance); - residual count * * PSEUDO functions : * NCR5380_pwrite(instance, src, count) * NCR5380_pread(instance, dst, count); * * The generic driver is initialized by calling NCR5380_init(instance), * after setting the appropriate host specific fields and ID. If the * driver wishes to autoprobe for an IRQ line, the NCR5380_probe_irq(instance, * possible) function may be used. */ static int do_abort(struct Scsi_Host *host); static void do_reset(struct Scsi_Host *host); /* * initialize_SCp - init the scsi pointer field * @cmd: command block to set up * * Set up the internal fields in the SCSI command. */ static inline void initialize_SCp(struct scsi_cmnd *cmd) { /* * Initialize the Scsi Pointer field so that all of the commands in the * various queues are valid. */ if (scsi_bufflen(cmd)) { cmd->SCp.buffer = scsi_sglist(cmd); cmd->SCp.buffers_residual = scsi_sg_count(cmd) - 1; cmd->SCp.ptr = sg_virt(cmd->SCp.buffer); cmd->SCp.this_residual = cmd->SCp.buffer->length; } else { cmd->SCp.buffer = NULL; cmd->SCp.buffers_residual = 0; cmd->SCp.ptr = NULL; cmd->SCp.this_residual = 0; } } /** * NCR5380_poll_politely - wait for NCR5380 status bits * @instance: controller to poll * @reg: 5380 register to poll * @bit: Bitmask to check * @val: Value required to exit * * Polls the NCR5380 in a reasonably efficient manner waiting for * an event to occur, after a short quick poll we begin giving the * CPU back in non IRQ contexts * * Returns the value of the register or a negative error code. */ static int NCR5380_poll_politely(struct Scsi_Host *instance, int reg, int bit, int val, int t) { NCR5380_local_declare(); int n = 500; /* At about 8uS a cycle for the cpu access */ unsigned long end = jiffies + t; int r; NCR5380_setup(instance); while( n-- > 0) { r = NCR5380_read(reg); if((r & bit) == val) return 0; cpu_relax(); } /* t time yet ? */ while(time_before(jiffies, end)) { r = NCR5380_read(reg); if((r & bit) == val) return 0; if(!in_interrupt()) cond_resched(); else cpu_relax(); } return -ETIMEDOUT; } static struct { unsigned char value; const char *name; } phases[] __maybe_unused = { {PHASE_DATAOUT, "DATAOUT"}, {PHASE_DATAIN, "DATAIN"}, {PHASE_CMDOUT, "CMDOUT"}, {PHASE_STATIN, "STATIN"}, {PHASE_MSGOUT, "MSGOUT"}, {PHASE_MSGIN, "MSGIN"}, {PHASE_UNKNOWN, "UNKNOWN"} }; #if NDEBUG static struct { unsigned char mask; const char *name; } signals[] = { {SR_DBP, "PARITY"}, {SR_RST, "RST"}, {SR_BSY, "BSY"}, {SR_REQ, "REQ"}, {SR_MSG, "MSG"}, {SR_CD, "CD"}, {SR_IO, "IO"}, {SR_SEL, "SEL"}, {0, NULL} }, basrs[] = { {BASR_ATN, "ATN"}, {BASR_ACK, "ACK"}, {0, NULL} }, icrs[] = { {ICR_ASSERT_RST, "ASSERT RST"}, {ICR_ASSERT_ACK, "ASSERT ACK"}, {ICR_ASSERT_BSY, "ASSERT BSY"}, {ICR_ASSERT_SEL, "ASSERT SEL"}, {ICR_ASSERT_ATN, "ASSERT ATN"}, {ICR_ASSERT_DATA, "ASSERT DATA"}, {0, NULL} }, mrs[] = { {MR_BLOCK_DMA_MODE, "MODE BLOCK DMA"}, {MR_TARGET, "MODE TARGET"}, {MR_ENABLE_PAR_CHECK, "MODE PARITY CHECK"}, {MR_ENABLE_PAR_INTR, "MODE PARITY INTR"}, {MR_MONITOR_BSY, "MODE MONITOR BSY"}, {MR_DMA_MODE, "MODE DMA"}, {MR_ARBITRATE, "MODE ARBITRATION"}, {0, NULL} }; /** * NCR5380_print - print scsi bus signals * @instance: adapter state to dump * * Print the SCSI bus signals for debugging purposes * * Locks: caller holds hostdata lock (not essential) */ static void NCR5380_print(struct Scsi_Host *instance) { NCR5380_local_declare(); unsigned char status, data, basr, mr, icr, i; NCR5380_setup(instance); data = NCR5380_read(CURRENT_SCSI_DATA_REG); status = NCR5380_read(STATUS_REG); mr = NCR5380_read(MODE_REG); icr = NCR5380_read(INITIATOR_COMMAND_REG); basr = NCR5380_read(BUS_AND_STATUS_REG); printk("STATUS_REG: %02x ", status); for (i = 0; signals[i].mask; ++i) if (status & signals[i].mask) printk(",%s", signals[i].name); printk("\nBASR: %02x ", basr); for (i = 0; basrs[i].mask; ++i) if (basr & basrs[i].mask) printk(",%s", basrs[i].name); printk("\nICR: %02x ", icr); for (i = 0; icrs[i].mask; ++i) if (icr & icrs[i].mask) printk(",%s", icrs[i].name); printk("\nMODE: %02x ", mr); for (i = 0; mrs[i].mask; ++i) if (mr & mrs[i].mask) printk(",%s", mrs[i].name); printk("\n"); } /* * NCR5380_print_phase - show SCSI phase * @instance: adapter to dump * * Print the current SCSI phase for debugging purposes * * Locks: none */ static void NCR5380_print_phase(struct Scsi_Host *instance) { NCR5380_local_declare(); unsigned char status; int i; NCR5380_setup(instance); status = NCR5380_read(STATUS_REG); if (!(status & SR_REQ)) printk("scsi%d : REQ not asserted, phase unknown.\n", instance->host_no); else { for (i = 0; (phases[i].value != PHASE_UNKNOWN) && (phases[i].value != (status & PHASE_MASK)); ++i); printk("scsi%d : phase %s\n", instance->host_no, phases[i].name); } } #endif /* * These need tweaking, and would probably work best as per-device * flags initialized differently for disk, tape, cd, etc devices. * People with broken devices are free to experiment as to what gives * the best results for them. * * USLEEP_SLEEP should be a minimum seek time. * * USLEEP_POLL should be a maximum rotational latency. */ #ifndef USLEEP_SLEEP /* 20 ms (reasonable hard disk speed) */ #define USLEEP_SLEEP msecs_to_jiffies(20) #endif /* 300 RPM (floppy speed) */ #ifndef USLEEP_POLL #define USLEEP_POLL msecs_to_jiffies(200) #endif #ifndef USLEEP_WAITLONG /* RvC: (reasonable time to wait on select error) */ #define USLEEP_WAITLONG USLEEP_SLEEP #endif /* * Function : int should_disconnect (unsigned char cmd) * * Purpose : decide whether a command would normally disconnect or * not, since if it won't disconnect we should go to sleep. * * Input : cmd - opcode of SCSI command * * Returns : DISCONNECT_LONG if we should disconnect for a really long * time (ie always, sleep, look for REQ active, sleep), * DISCONNECT_TIME_TO_DATA if we would only disconnect for a normal * time-to-data delay, DISCONNECT_NONE if this command would return * immediately. * * Future sleep algorithms based on time to data can exploit * something like this so they can differentiate between "normal" * (ie, read, write, seek) and unusual commands (ie, * format). * * Note : We don't deal with commands that handle an immediate disconnect, * */ static int should_disconnect(unsigned char cmd) { switch (cmd) { case READ_6: case WRITE_6: case SEEK_6: case READ_10: case WRITE_10: case SEEK_10: return DISCONNECT_TIME_TO_DATA; case FORMAT_UNIT: case SEARCH_HIGH: case SEARCH_LOW: case SEARCH_EQUAL: return DISCONNECT_LONG; default: return DISCONNECT_NONE; } } static void NCR5380_set_timer(struct NCR5380_hostdata *hostdata, unsigned long timeout) { hostdata->time_expires = jiffies + timeout; schedule_delayed_work(&hostdata->coroutine, timeout); } static int probe_irq __initdata = 0; /** * probe_intr - helper for IRQ autoprobe * @irq: interrupt number * @dev_id: unused * @regs: unused * * Set a flag to indicate the IRQ in question was received. This is * used by the IRQ probe code. */ static irqreturn_t __init probe_intr(int irq, void *dev_id) { probe_irq = irq; return IRQ_HANDLED; } /** * NCR5380_probe_irq - find the IRQ of an NCR5380 * @instance: NCR5380 controller * @possible: bitmask of ISA IRQ lines * * Autoprobe for the IRQ line used by the NCR5380 by triggering an IRQ * and then looking to see what interrupt actually turned up. * * Locks: none, irqs must be enabled on entry */ static int __init __maybe_unused NCR5380_probe_irq(struct Scsi_Host *instance, int possible) { NCR5380_local_declare(); struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; unsigned long timeout; int trying_irqs, i, mask; NCR5380_setup(instance); for (trying_irqs = 0, i = 1, mask = 2; i < 16; ++i, mask <<= 1) if ((mask & possible) && (request_irq(i, &probe_intr, 0, "NCR-probe", NULL) == 0)) trying_irqs |= mask; timeout = jiffies + msecs_to_jiffies(250); probe_irq = NO_IRQ; /* * A interrupt is triggered whenever BSY = false, SEL = true * and a bit set in the SELECT_ENABLE_REG is asserted on the * SCSI bus. * * Note that the bus is only driven when the phase control signals * (I/O, C/D, and MSG) match those in the TCR, so we must reset that * to zero. */ NCR5380_write(TARGET_COMMAND_REG, 0); NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask); NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_SEL); while (probe_irq == NO_IRQ && time_before(jiffies, timeout)) schedule_timeout_uninterruptible(1); NCR5380_write(SELECT_ENABLE_REG, 0); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); for (i = 1, mask = 2; i < 16; ++i, mask <<= 1) if (trying_irqs & mask) free_irq(i, NULL); return probe_irq; } /** * NCR58380_info - report driver and host information * @instance: relevant scsi host instance * * For use as the host template info() handler. * * Locks: none */ static const char *NCR5380_info(struct Scsi_Host *instance) { struct NCR5380_hostdata *hostdata = shost_priv(instance); return hostdata->info; } static void prepare_info(struct Scsi_Host *instance) { struct NCR5380_hostdata *hostdata = shost_priv(instance); snprintf(hostdata->info, sizeof(hostdata->info), "%s, io_port 0x%lx, n_io_port %d, " "base 0x%lx, irq %d, " "can_queue %d, cmd_per_lun %d, " "sg_tablesize %d, this_id %d, " "flags { %s%s%s}, " #if defined(USLEEP_POLL) && defined(USLEEP_WAITLONG) "USLEEP_POLL %lu, USLEEP_WAITLONG %lu, " #endif "options { %s} ", instance->hostt->name, instance->io_port, instance->n_io_port, instance->base, instance->irq, instance->can_queue, instance->cmd_per_lun, instance->sg_tablesize, instance->this_id, hostdata->flags & FLAG_NCR53C400 ? "NCR53C400 " : "", hostdata->flags & FLAG_DTC3181E ? "DTC3181E " : "", hostdata->flags & FLAG_NO_PSEUDO_DMA ? "NO_PSEUDO_DMA " : "", #if defined(USLEEP_POLL) && defined(USLEEP_WAITLONG) USLEEP_POLL, USLEEP_WAITLONG, #endif #ifdef AUTOPROBE_IRQ "AUTOPROBE_IRQ " #endif #ifdef DIFFERENTIAL "DIFFERENTIAL " #endif #ifdef REAL_DMA "REAL_DMA " #endif #ifdef REAL_DMA_POLL "REAL_DMA_POLL " #endif #ifdef PARITY "PARITY " #endif #ifdef PSEUDO_DMA "PSEUDO_DMA " #endif #ifdef UNSAFE "UNSAFE " #endif #ifdef NCR53C400 "NCR53C400 " #endif ""); } /** * NCR5380_print_status - dump controller info * @instance: controller to dump * * Print commands in the various queues, called from NCR5380_abort * and NCR5380_debug to aid debugging. * * Locks: called functions disable irqs */ static void NCR5380_print_status(struct Scsi_Host *instance) { NCR5380_dprint(NDEBUG_ANY, instance); NCR5380_dprint_phase(NDEBUG_ANY, instance); } #ifdef PSEUDO_DMA /******************************************/ /* * /proc/scsi/[dtc pas16 t128 generic]/[0-ASC_NUM_BOARD_SUPPORTED] * * *buffer: I/O buffer * **start: if inout == FALSE pointer into buffer where user read should start * offset: current offset * length: length of buffer * hostno: Scsi_Host host_no * inout: TRUE - user is writing; FALSE - user is reading * * Return the number of bytes read from or written */ static int __maybe_unused NCR5380_write_info(struct Scsi_Host *instance, char *buffer, int length) { struct NCR5380_hostdata *hostdata = shost_priv(instance); hostdata->spin_max_r = 0; hostdata->spin_max_w = 0; return 0; } #endif static void lprint_Scsi_Cmnd(struct scsi_cmnd *cmd, struct seq_file *m); static void lprint_command(unsigned char *cmd, struct seq_file *m); static void lprint_opcode(int opcode, struct seq_file *m); static int __maybe_unused NCR5380_show_info(struct seq_file *m, struct Scsi_Host *instance) { struct NCR5380_hostdata *hostdata; struct scsi_cmnd *ptr; hostdata = (struct NCR5380_hostdata *) instance->hostdata; #ifdef PSEUDO_DMA seq_printf(m, "Highwater I/O busy spin counts: write %d, read %d\n", hostdata->spin_max_w, hostdata->spin_max_r); #endif spin_lock_irq(instance->host_lock); if (!hostdata->connected) seq_printf(m, "scsi%d: no currently connected command\n", instance->host_no); else lprint_Scsi_Cmnd((struct scsi_cmnd *) hostdata->connected, m); seq_printf(m, "scsi%d: issue_queue\n", instance->host_no); for (ptr = (struct scsi_cmnd *) hostdata->issue_queue; ptr; ptr = (struct scsi_cmnd *) ptr->host_scribble) lprint_Scsi_Cmnd(ptr, m); seq_printf(m, "scsi%d: disconnected_queue\n", instance->host_no); for (ptr = (struct scsi_cmnd *) hostdata->disconnected_queue; ptr; ptr = (struct scsi_cmnd *) ptr->host_scribble) lprint_Scsi_Cmnd(ptr, m); spin_unlock_irq(instance->host_lock); return 0; } static void lprint_Scsi_Cmnd(struct scsi_cmnd *cmd, struct seq_file *m) { seq_printf(m, "scsi%d : destination target %d, lun %llu\n", cmd->device->host->host_no, cmd->device->id, cmd->device->lun); seq_puts(m, " command = "); lprint_command(cmd->cmnd, m); } static void lprint_command(unsigned char *command, struct seq_file *m) { int i, s; lprint_opcode(command[0], m); for (i = 1, s = COMMAND_SIZE(command[0]); i < s; ++i) seq_printf(m, "%02x ", command[i]); seq_putc(m, '\n'); } static void lprint_opcode(int opcode, struct seq_file *m) { seq_printf(m, "%2d (0x%02x)", opcode, opcode); } /** * NCR5380_init - initialise an NCR5380 * @instance: adapter to configure * @flags: control flags * * Initializes *instance and corresponding 5380 chip, * with flags OR'd into the initial flags value. * * Notes : I assume that the host, hostno, and id bits have been * set correctly. I don't care about the irq and other fields. * * Returns 0 for success * * Locks: interrupts must be enabled when we are called */ static int NCR5380_init(struct Scsi_Host *instance, int flags) { NCR5380_local_declare(); int i, pass; unsigned long timeout; struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; if(in_interrupt()) printk(KERN_ERR "NCR5380_init called with interrupts off!\n"); /* * On NCR53C400 boards, NCR5380 registers are mapped 8 past * the base address. */ #ifdef NCR53C400 if (flags & FLAG_NCR53C400) instance->NCR5380_instance_name += NCR53C400_address_adjust; #endif NCR5380_setup(instance); hostdata->aborted = 0; hostdata->id_mask = 1 << instance->this_id; for (i = hostdata->id_mask; i <= 0x80; i <<= 1) if (i > hostdata->id_mask) hostdata->id_higher_mask |= i; for (i = 0; i < 8; ++i) hostdata->busy[i] = 0; #ifdef REAL_DMA hostdata->dmalen = 0; #endif hostdata->targets_present = 0; hostdata->connected = NULL; hostdata->issue_queue = NULL; hostdata->disconnected_queue = NULL; INIT_DELAYED_WORK(&hostdata->coroutine, NCR5380_main); /* The CHECK code seems to break the 53C400. Will check it later maybe */ if (flags & FLAG_NCR53C400) hostdata->flags = FLAG_HAS_LAST_BYTE_SENT | flags; else hostdata->flags = FLAG_CHECK_LAST_BYTE_SENT | flags; hostdata->host = instance; hostdata->time_expires = 0; prepare_info(instance); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); NCR5380_write(MODE_REG, MR_BASE); NCR5380_write(TARGET_COMMAND_REG, 0); NCR5380_write(SELECT_ENABLE_REG, 0); #ifdef NCR53C400 if (hostdata->flags & FLAG_NCR53C400) { NCR5380_write(C400_CONTROL_STATUS_REG, CSR_BASE); } #endif /* * Detect and correct bus wedge problems. * * If the system crashed, it may have crashed in a state * where a SCSI command was still executing, and the * SCSI bus is not in a BUS FREE STATE. * * If this is the case, we'll try to abort the currently * established nexus which we know nothing about, and that * failing, do a hard reset of the SCSI bus */ for (pass = 1; (NCR5380_read(STATUS_REG) & SR_BSY) && pass <= 6; ++pass) { switch (pass) { case 1: case 3: case 5: printk(KERN_INFO "scsi%d: SCSI bus busy, waiting up to five seconds\n", instance->host_no); timeout = jiffies + 5 * HZ; NCR5380_poll_politely(instance, STATUS_REG, SR_BSY, 0, 5*HZ); break; case 2: printk(KERN_WARNING "scsi%d: bus busy, attempting abort\n", instance->host_no); do_abort(instance); break; case 4: printk(KERN_WARNING "scsi%d: bus busy, attempting reset\n", instance->host_no); do_reset(instance); break; case 6: printk(KERN_ERR "scsi%d: bus locked solid or invalid override\n", instance->host_no); return -ENXIO; } } return 0; } /** * NCR5380_exit - remove an NCR5380 * @instance: adapter to remove */ static void NCR5380_exit(struct Scsi_Host *instance) { struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; cancel_delayed_work_sync(&hostdata->coroutine); } /** * NCR5380_queue_command - queue a command * @cmd: SCSI command * @done: completion handler * * cmd is added to the per instance issue_queue, with minor * twiddling done to the host specific fields of cmd. If the * main coroutine is not running, it is restarted. * * Locks: host lock taken by caller */ static int NCR5380_queue_command_lck(struct scsi_cmnd *cmd, void (*done) (struct scsi_cmnd *)) { struct Scsi_Host *instance = cmd->device->host; struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; struct scsi_cmnd *tmp; #if (NDEBUG & NDEBUG_NO_WRITE) switch (cmd->cmnd[0]) { case WRITE_6: case WRITE_10: printk("scsi%d : WRITE attempted with NO_WRITE debugging flag set\n", instance->host_no); cmd->result = (DID_ERROR << 16); done(cmd); return 0; } #endif /* (NDEBUG & NDEBUG_NO_WRITE) */ /* * We use the host_scribble field as a pointer to the next command * in a queue */ cmd->host_scribble = NULL; cmd->scsi_done = done; cmd->result = 0; /* * Insert the cmd into the issue queue. Note that REQUEST SENSE * commands are added to the head of the queue since any command will * clear the contingent allegiance condition that exists and the * sense data is only guaranteed to be valid while the condition exists. */ if (!(hostdata->issue_queue) || (cmd->cmnd[0] == REQUEST_SENSE)) { LIST(cmd, hostdata->issue_queue); cmd->host_scribble = (unsigned char *) hostdata->issue_queue; hostdata->issue_queue = cmd; } else { for (tmp = (struct scsi_cmnd *) hostdata->issue_queue; tmp->host_scribble; tmp = (struct scsi_cmnd *) tmp->host_scribble); LIST(cmd, tmp); tmp->host_scribble = (unsigned char *) cmd; } dprintk(NDEBUG_QUEUES, "scsi%d : command added to %s of queue\n", instance->host_no, (cmd->cmnd[0] == REQUEST_SENSE) ? "head" : "tail"); /* Run the coroutine if it isn't already running. */ /* Kick off command processing */ schedule_delayed_work(&hostdata->coroutine, 0); return 0; } static DEF_SCSI_QCMD(NCR5380_queue_command) /** * NCR5380_main - NCR state machines * * NCR5380_main is a coroutine that runs as long as more work can * be done on the NCR5380 host adapters in a system. Both * NCR5380_queue_command() and NCR5380_intr() will try to start it * in case it is not running. * * Locks: called as its own thread with no locks held. Takes the * host lock and called routines may take the isa dma lock. */ static void NCR5380_main(struct work_struct *work) { struct NCR5380_hostdata *hostdata = container_of(work, struct NCR5380_hostdata, coroutine.work); struct Scsi_Host *instance = hostdata->host; struct scsi_cmnd *tmp, *prev; int done; spin_lock_irq(instance->host_lock); do { /* Lock held here */ done = 1; if (!hostdata->connected && !hostdata->selecting) { dprintk(NDEBUG_MAIN, "scsi%d : not connected\n", instance->host_no); /* * Search through the issue_queue for a command destined * for a target that's not busy. */ for (tmp = (struct scsi_cmnd *) hostdata->issue_queue, prev = NULL; tmp; prev = tmp, tmp = (struct scsi_cmnd *) tmp->host_scribble) { if (prev != tmp) dprintk(NDEBUG_LISTS, "MAIN tmp=%p target=%d busy=%d lun=%llu\n", tmp, tmp->device->id, hostdata->busy[tmp->device->id], tmp->device->lun); /* When we find one, remove it from the issue queue. */ if (!(hostdata->busy[tmp->device->id] & (1 << (u8)(tmp->device->lun & 0xff)))) { if (prev) { REMOVE(prev, prev->host_scribble, tmp, tmp->host_scribble); prev->host_scribble = tmp->host_scribble; } else { REMOVE(-1, hostdata->issue_queue, tmp, tmp->host_scribble); hostdata->issue_queue = (struct scsi_cmnd *) tmp->host_scribble; } tmp->host_scribble = NULL; /* * Attempt to establish an I_T_L nexus here. * On success, instance->hostdata->connected is set. * On failure, we must add the command back to the * issue queue so we can keep trying. */ dprintk(NDEBUG_MAIN|NDEBUG_QUEUES, "scsi%d : main() : command for target %d lun %llu removed from issue_queue\n", instance->host_no, tmp->device->id, tmp->device->lun); /* * A successful selection is defined as one that * leaves us with the command connected and * in hostdata->connected, OR has terminated the * command. * * With successful commands, we fall through * and see if we can do an information transfer, * with failures we will restart. */ hostdata->selecting = NULL; /* RvC: have to preset this to indicate a new command is being performed */ /* * REQUEST SENSE commands are issued without tagged * queueing, even on SCSI-II devices because the * contingent allegiance condition exists for the * entire unit. */ if (!NCR5380_select(instance, tmp)) { break; } else { LIST(tmp, hostdata->issue_queue); tmp->host_scribble = (unsigned char *) hostdata->issue_queue; hostdata->issue_queue = tmp; done = 0; dprintk(NDEBUG_MAIN|NDEBUG_QUEUES, "scsi%d : main(): select() failed, returned to issue_queue\n", instance->host_no); } /* lock held here still */ } /* if target/lun is not busy */ } /* for */ /* exited locked */ } /* if (!hostdata->connected) */ if (hostdata->selecting) { tmp = (struct scsi_cmnd *) hostdata->selecting; /* Selection will drop and retake the lock */ if (!NCR5380_select(instance, tmp)) { /* Ok ?? */ } else { /* RvC: device failed, so we wait a long time this is needed for Mustek scanners, that do not respond to commands immediately after a scan */ printk(KERN_DEBUG "scsi%d: device %d did not respond in time\n", instance->host_no, tmp->device->id); LIST(tmp, hostdata->issue_queue); tmp->host_scribble = (unsigned char *) hostdata->issue_queue; hostdata->issue_queue = tmp; NCR5380_set_timer(hostdata, USLEEP_WAITLONG); } } /* if hostdata->selecting */ if (hostdata->connected #ifdef REAL_DMA && !hostdata->dmalen #endif && (!hostdata->time_expires || time_before_eq(hostdata->time_expires, jiffies)) ) { dprintk(NDEBUG_MAIN, "scsi%d : main() : performing information transfer\n", instance->host_no); NCR5380_information_transfer(instance); dprintk(NDEBUG_MAIN, "scsi%d : main() : done set false\n", instance->host_no); done = 0; } else break; } while (!done); spin_unlock_irq(instance->host_lock); } #ifndef DONT_USE_INTR /** * NCR5380_intr - generic NCR5380 irq handler * @irq: interrupt number * @dev_id: device info * * Handle interrupts, reestablishing I_T_L or I_T_L_Q nexuses * from the disconnected queue, and restarting NCR5380_main() * as required. * * Locks: takes the needed instance locks */ static irqreturn_t NCR5380_intr(int dummy, void *dev_id) { NCR5380_local_declare(); struct Scsi_Host *instance = dev_id; struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; int done; unsigned char basr; unsigned long flags; dprintk(NDEBUG_INTR, "scsi : NCR5380 irq %d triggered\n", instance->irq); do { done = 1; spin_lock_irqsave(instance->host_lock, flags); /* Look for pending interrupts */ NCR5380_setup(instance); basr = NCR5380_read(BUS_AND_STATUS_REG); /* XXX dispatch to appropriate routine if found and done=0 */ if (basr & BASR_IRQ) { NCR5380_dprint(NDEBUG_INTR, instance); if ((NCR5380_read(STATUS_REG) & (SR_SEL | SR_IO)) == (SR_SEL | SR_IO)) { done = 0; dprintk(NDEBUG_INTR, "scsi%d : SEL interrupt\n", instance->host_no); NCR5380_reselect(instance); (void) NCR5380_read(RESET_PARITY_INTERRUPT_REG); } else if (basr & BASR_PARITY_ERROR) { dprintk(NDEBUG_INTR, "scsi%d : PARITY interrupt\n", instance->host_no); (void) NCR5380_read(RESET_PARITY_INTERRUPT_REG); } else if ((NCR5380_read(STATUS_REG) & SR_RST) == SR_RST) { dprintk(NDEBUG_INTR, "scsi%d : RESET interrupt\n", instance->host_no); (void) NCR5380_read(RESET_PARITY_INTERRUPT_REG); } else { #if defined(REAL_DMA) /* * We should only get PHASE MISMATCH and EOP interrupts * if we have DMA enabled, so do a sanity check based on * the current setting of the MODE register. */ if ((NCR5380_read(MODE_REG) & MR_DMA) && ((basr & BASR_END_DMA_TRANSFER) || !(basr & BASR_PHASE_MATCH))) { int transferred; if (!hostdata->connected) panic("scsi%d : received end of DMA interrupt with no connected cmd\n", instance->hostno); transferred = (hostdata->dmalen - NCR5380_dma_residual(instance)); hostdata->connected->SCp.this_residual -= transferred; hostdata->connected->SCp.ptr += transferred; hostdata->dmalen = 0; (void) NCR5380_read(RESET_PARITY_INTERRUPT_REG); /* FIXME: we need to poll briefly then defer a workqueue task ! */ NCR5380_poll_politely(hostdata, BUS_AND_STATUS_REG, BASR_ACK, 0, 2*HZ); NCR5380_write(MODE_REG, MR_BASE); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); } #else dprintk(NDEBUG_INTR, "scsi : unknown interrupt, BASR 0x%X, MR 0x%X, SR 0x%x\n", basr, NCR5380_read(MODE_REG), NCR5380_read(STATUS_REG)); (void) NCR5380_read(RESET_PARITY_INTERRUPT_REG); #endif } } /* if BASR_IRQ */ spin_unlock_irqrestore(instance->host_lock, flags); if(!done) schedule_delayed_work(&hostdata->coroutine, 0); } while (!done); return IRQ_HANDLED; } #endif /* * Function : int NCR5380_select(struct Scsi_Host *instance, * struct scsi_cmnd *cmd) * * Purpose : establishes I_T_L or I_T_L_Q nexus for new or existing command, * including ARBITRATION, SELECTION, and initial message out for * IDENTIFY and queue messages. * * Inputs : instance - instantiation of the 5380 driver on which this * target lives, cmd - SCSI command to execute. * * Returns : -1 if selection could not execute for some reason, * 0 if selection succeeded or failed because the target * did not respond. * * Side effects : * If bus busy, arbitration failed, etc, NCR5380_select() will exit * with registers as they should have been on entry - ie * SELECT_ENABLE will be set appropriately, the NCR5380 * will cease to drive any SCSI bus signals. * * If successful : I_T_L or I_T_L_Q nexus will be established, * instance->connected will be set to cmd. * SELECT interrupt will be disabled. * * If failed (no target) : cmd->scsi_done() will be called, and the * cmd->result host byte set to DID_BAD_TARGET. * * Locks: caller holds hostdata lock in IRQ mode */ static int NCR5380_select(struct Scsi_Host *instance, struct scsi_cmnd *cmd) { NCR5380_local_declare(); struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; unsigned char tmp[3], phase; unsigned char *data; int len; unsigned long timeout; unsigned char value; int err; NCR5380_setup(instance); if (hostdata->selecting) goto part2; hostdata->restart_select = 0; NCR5380_dprint(NDEBUG_ARBITRATION, instance); dprintk(NDEBUG_ARBITRATION, "scsi%d : starting arbitration, id = %d\n", instance->host_no, instance->this_id); /* * Set the phase bits to 0, otherwise the NCR5380 won't drive the * data bus during SELECTION. */ NCR5380_write(TARGET_COMMAND_REG, 0); /* * Start arbitration. */ NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask); NCR5380_write(MODE_REG, MR_ARBITRATE); /* We can be relaxed here, interrupts are on, we are in workqueue context, the birds are singing in the trees */ spin_unlock_irq(instance->host_lock); err = NCR5380_poll_politely(instance, INITIATOR_COMMAND_REG, ICR_ARBITRATION_PROGRESS, ICR_ARBITRATION_PROGRESS, 5*HZ); spin_lock_irq(instance->host_lock); if (err < 0) { printk(KERN_DEBUG "scsi: arbitration timeout at %d\n", __LINE__); NCR5380_write(MODE_REG, MR_BASE); NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask); goto failed; } dprintk(NDEBUG_ARBITRATION, "scsi%d : arbitration complete\n", instance->host_no); /* * The arbitration delay is 2.2us, but this is a minimum and there is * no maximum so we can safely sleep for ceil(2.2) usecs to accommodate * the integral nature of udelay(). * */ udelay(3); /* Check for lost arbitration */ if ((NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) || (NCR5380_read(CURRENT_SCSI_DATA_REG) & hostdata->id_higher_mask) || (NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST)) { NCR5380_write(MODE_REG, MR_BASE); dprintk(NDEBUG_ARBITRATION, "scsi%d : lost arbitration, deasserting MR_ARBITRATE\n", instance->host_no); goto failed; } NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_SEL); if (!(hostdata->flags & FLAG_DTC3181E) && /* RvC: DTC3181E has some trouble with this * so we simply removed it. Seems to work with * only Mustek scanner attached */ (NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST)) { NCR5380_write(MODE_REG, MR_BASE); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); dprintk(NDEBUG_ARBITRATION, "scsi%d : lost arbitration, deasserting ICR_ASSERT_SEL\n", instance->host_no); goto failed; } /* * Again, bus clear + bus settle time is 1.2us, however, this is * a minimum so we'll udelay ceil(1.2) */ udelay(2); dprintk(NDEBUG_ARBITRATION, "scsi%d : won arbitration\n", instance->host_no); /* * Now that we have won arbitration, start Selection process, asserting * the host and target ID's on the SCSI bus. */ NCR5380_write(OUTPUT_DATA_REG, (hostdata->id_mask | (1 << scmd_id(cmd)))); /* * Raise ATN while SEL is true before BSY goes false from arbitration, * since this is the only way to guarantee that we'll get a MESSAGE OUT * phase immediately after selection. */ NCR5380_write(INITIATOR_COMMAND_REG, (ICR_BASE | ICR_ASSERT_BSY | ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_SEL)); NCR5380_write(MODE_REG, MR_BASE); /* * Reselect interrupts must be turned off prior to the dropping of BSY, * otherwise we will trigger an interrupt. */ NCR5380_write(SELECT_ENABLE_REG, 0); /* * The initiator shall then wait at least two deskew delays and release * the BSY signal. */ udelay(1); /* wingel -- wait two bus deskew delay >2*45ns */ /* Reset BSY */ NCR5380_write(INITIATOR_COMMAND_REG, (ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_SEL)); /* * Something weird happens when we cease to drive BSY - looks * like the board/chip is letting us do another read before the * appropriate propagation delay has expired, and we're confusing * a BSY signal from ourselves as the target's response to SELECTION. * * A small delay (the 'C++' frontend breaks the pipeline with an * unnecessary jump, making it work on my 386-33/Trantor T128, the * tighter 'C' code breaks and requires this) solves the problem - * the 1 us delay is arbitrary, and only used because this delay will * be the same on other platforms and since it works here, it should * work there. * * wingel suggests that this could be due to failing to wait * one deskew delay. */ udelay(1); dprintk(NDEBUG_SELECTION, "scsi%d : selecting target %d\n", instance->host_no, scmd_id(cmd)); /* * The SCSI specification calls for a 250 ms timeout for the actual * selection. */ timeout = jiffies + msecs_to_jiffies(250); /* * XXX very interesting - we're seeing a bounce where the BSY we * asserted is being reflected / still asserted (propagation delay?) * and it's detecting as true. Sigh. */ hostdata->select_time = 0; /* we count the clock ticks at which we polled */ hostdata->selecting = cmd; part2: /* RvC: here we enter after a sleeping period, or immediately after execution of part 1 we poll only once ech clock tick */ value = NCR5380_read(STATUS_REG) & (SR_BSY | SR_IO); if (!value && (hostdata->select_time < HZ/4)) { /* RvC: we still must wait for a device response */ hostdata->select_time++; /* after 25 ticks the device has failed */ NCR5380_set_timer(hostdata, 1); return 0; /* RvC: we return here with hostdata->selecting set, to go to sleep */ } hostdata->selecting = NULL;/* clear this pointer, because we passed the waiting period */ if ((NCR5380_read(STATUS_REG) & (SR_SEL | SR_IO)) == (SR_SEL | SR_IO)) { NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); NCR5380_reselect(instance); printk("scsi%d : reselection after won arbitration?\n", instance->host_no); NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask); return -1; } /* * No less than two deskew delays after the initiator detects the * BSY signal is true, it shall release the SEL signal and may * change the DATA BUS. -wingel */ udelay(1); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN); if (!(NCR5380_read(STATUS_REG) & SR_BSY)) { NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); if (hostdata->targets_present & (1 << scmd_id(cmd))) { printk(KERN_DEBUG "scsi%d : weirdness\n", instance->host_no); if (hostdata->restart_select) printk(KERN_DEBUG "\trestart select\n"); NCR5380_dprint(NDEBUG_SELECTION, instance); NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask); return -1; } cmd->result = DID_BAD_TARGET << 16; cmd->scsi_done(cmd); NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask); dprintk(NDEBUG_SELECTION, "scsi%d : target did not respond within 250ms\n", instance->host_no); NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask); return 0; } hostdata->targets_present |= (1 << scmd_id(cmd)); /* * Since we followed the SCSI spec, and raised ATN while SEL * was true but before BSY was false during selection, the information * transfer phase should be a MESSAGE OUT phase so that we can send the * IDENTIFY message. * * If SCSI-II tagged queuing is enabled, we also send a SIMPLE_QUEUE_TAG * message (2 bytes) with a tag ID that we increment with every command * until it wraps back to 0. * * XXX - it turns out that there are some broken SCSI-II devices, * which claim to support tagged queuing but fail when more than * some number of commands are issued at once. */ /* Wait for start of REQ/ACK handshake */ spin_unlock_irq(instance->host_lock); err = NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, SR_REQ, HZ); spin_lock_irq(instance->host_lock); if(err) { printk(KERN_ERR "scsi%d: timeout at NCR5380.c:%d\n", instance->host_no, __LINE__); NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask); goto failed; } dprintk(NDEBUG_SELECTION, "scsi%d : target %d selected, going into MESSAGE OUT phase.\n", instance->host_no, cmd->device->id); tmp[0] = IDENTIFY(((instance->irq == NO_IRQ) ? 0 : 1), cmd->device->lun); len = 1; cmd->tag = 0; /* Send message(s) */ data = tmp; phase = PHASE_MSGOUT; NCR5380_transfer_pio(instance, &phase, &len, &data); dprintk(NDEBUG_SELECTION, "scsi%d : nexus established.\n", instance->host_no); /* XXX need to handle errors here */ hostdata->connected = cmd; hostdata->busy[cmd->device->id] |= (1 << (cmd->device->lun & 0xFF)); initialize_SCp(cmd); return 0; /* Selection failed */ failed: return -1; } /* * Function : int NCR5380_transfer_pio (struct Scsi_Host *instance, * unsigned char *phase, int *count, unsigned char **data) * * Purpose : transfers data in given phase using polled I/O * * Inputs : instance - instance of driver, *phase - pointer to * what phase is expected, *count - pointer to number of * bytes to transfer, **data - pointer to data pointer. * * Returns : -1 when different phase is entered without transferring * maximum number of bytes, 0 if all bytes or transferred or exit * is in same phase. * * Also, *phase, *count, *data are modified in place. * * XXX Note : handling for bus free may be useful. */ /* * Note : this code is not as quick as it could be, however it * IS 100% reliable, and for the actual data transfer where speed * counts, we will always do a pseudo DMA or DMA transfer. */ static int NCR5380_transfer_pio(struct Scsi_Host *instance, unsigned char *phase, int *count, unsigned char **data) { NCR5380_local_declare(); unsigned char p = *phase, tmp; int c = *count; unsigned char *d = *data; /* * RvC: some administrative data to process polling time */ int break_allowed = 0; struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; NCR5380_setup(instance); if (!(p & SR_IO)) dprintk(NDEBUG_PIO, "scsi%d : pio write %d bytes\n", instance->host_no, c); else dprintk(NDEBUG_PIO, "scsi%d : pio read %d bytes\n", instance->host_no, c); /* * The NCR5380 chip will only drive the SCSI bus when the * phase specified in the appropriate bits of the TARGET COMMAND * REGISTER match the STATUS REGISTER */ NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p)); /* RvC: don't know if this is necessary, but other SCSI I/O is short * so breaks are not necessary there */ if ((p == PHASE_DATAIN) || (p == PHASE_DATAOUT)) { break_allowed = 1; } do { /* * Wait for assertion of REQ, after which the phase bits will be * valid */ /* RvC: we simply poll once, after that we stop temporarily * and let the device buffer fill up * if breaking is not allowed, we keep polling as long as needed */ /* FIXME */ while (!((tmp = NCR5380_read(STATUS_REG)) & SR_REQ) && !break_allowed); if (!(tmp & SR_REQ)) { /* timeout condition */ NCR5380_set_timer(hostdata, USLEEP_SLEEP); break; } dprintk(NDEBUG_HANDSHAKE, "scsi%d : REQ detected\n", instance->host_no); /* Check for phase mismatch */ if ((tmp & PHASE_MASK) != p) { dprintk(NDEBUG_HANDSHAKE, "scsi%d : phase mismatch\n", instance->host_no); NCR5380_dprint_phase(NDEBUG_HANDSHAKE, instance); break; } /* Do actual transfer from SCSI bus to / from memory */ if (!(p & SR_IO)) NCR5380_write(OUTPUT_DATA_REG, *d); else *d = NCR5380_read(CURRENT_SCSI_DATA_REG); ++d; /* * The SCSI standard suggests that in MSGOUT phase, the initiator * should drop ATN on the last byte of the message phase * after REQ has been asserted for the handshake but before * the initiator raises ACK. */ if (!(p & SR_IO)) { if (!((p & SR_MSG) && c > 1)) { NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA); NCR5380_dprint(NDEBUG_PIO, instance); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_ACK); } else { NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_ATN); NCR5380_dprint(NDEBUG_PIO, instance); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_ACK); } } else { NCR5380_dprint(NDEBUG_PIO, instance); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ACK); } /* FIXME - if this fails bus reset ?? */ NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, 0, 5*HZ); dprintk(NDEBUG_HANDSHAKE, "scsi%d : req false, handshake complete\n", instance->host_no); /* * We have several special cases to consider during REQ/ACK handshaking : * 1. We were in MSGOUT phase, and we are on the last byte of the * message. ATN must be dropped as ACK is dropped. * * 2. We are in a MSGIN phase, and we are on the last byte of the * message. We must exit with ACK asserted, so that the calling * code may raise ATN before dropping ACK to reject the message. * * 3. ACK and ATN are clear and the target may proceed as normal. */ if (!(p == PHASE_MSGIN && c == 1)) { if (p == PHASE_MSGOUT && c > 1) NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN); else NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); } } while (--c); dprintk(NDEBUG_PIO, "scsi%d : residual %d\n", instance->host_no, c); *count = c; *data = d; tmp = NCR5380_read(STATUS_REG); if (tmp & SR_REQ) *phase = tmp & PHASE_MASK; else *phase = PHASE_UNKNOWN; if (!c || (*phase == p)) return 0; else return -1; } /** * do_reset - issue a reset command * @host: adapter to reset * * Issue a reset sequence to the NCR5380 and try and get the bus * back into sane shape. * * Locks: caller holds queue lock */ static void do_reset(struct Scsi_Host *host) { NCR5380_local_declare(); NCR5380_setup(host); NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(NCR5380_read(STATUS_REG) & PHASE_MASK)); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_RST); udelay(25); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); } /* * Function : do_abort (Scsi_Host *host) * * Purpose : abort the currently established nexus. Should only be * called from a routine which can drop into a * * Returns : 0 on success, -1 on failure. * * Locks: queue lock held by caller * FIXME: sort this out and get new_eh running */ static int do_abort(struct Scsi_Host *host) { NCR5380_local_declare(); unsigned char *msgptr, phase, tmp; int len; int rc; NCR5380_setup(host); /* Request message out phase */ NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN); /* * Wait for the target to indicate a valid phase by asserting * REQ. Once this happens, we'll have either a MSGOUT phase * and can immediately send the ABORT message, or we'll have some * other phase and will have to source/sink data. * * We really don't care what value was on the bus or what value * the target sees, so we just handshake. */ rc = NCR5380_poll_politely(host, STATUS_REG, SR_REQ, SR_REQ, 60 * HZ); if(rc < 0) return -1; tmp = (unsigned char)rc; NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp)); if ((tmp & PHASE_MASK) != PHASE_MSGOUT) { NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN | ICR_ASSERT_ACK); rc = NCR5380_poll_politely(host, STATUS_REG, SR_REQ, 0, 3*HZ); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN); if(rc == -1) return -1; } tmp = ABORT; msgptr = &tmp; len = 1; phase = PHASE_MSGOUT; NCR5380_transfer_pio(host, &phase, &len, &msgptr); /* * If we got here, and the command completed successfully, * we're about to go into bus free state. */ return len ? -1 : 0; } #if defined(REAL_DMA) || defined(PSEUDO_DMA) || defined (REAL_DMA_POLL) /* * Function : int NCR5380_transfer_dma (struct Scsi_Host *instance, * unsigned char *phase, int *count, unsigned char **data) * * Purpose : transfers data in given phase using either real * or pseudo DMA. * * Inputs : instance - instance of driver, *phase - pointer to * what phase is expected, *count - pointer to number of * bytes to transfer, **data - pointer to data pointer. * * Returns : -1 when different phase is entered without transferring * maximum number of bytes, 0 if all bytes or transferred or exit * is in same phase. * * Also, *phase, *count, *data are modified in place. * * Locks: io_request lock held by caller */ static int NCR5380_transfer_dma(struct Scsi_Host *instance, unsigned char *phase, int *count, unsigned char **data) { NCR5380_local_declare(); register int c = *count; register unsigned char p = *phase; register unsigned char *d = *data; unsigned char tmp; int foo; #if defined(REAL_DMA_POLL) int cnt, toPIO; unsigned char saved_data = 0, overrun = 0, residue; #endif struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; NCR5380_setup(instance); if ((tmp = (NCR5380_read(STATUS_REG) & PHASE_MASK)) != p) { *phase = tmp; return -1; } #if defined(REAL_DMA) || defined(REAL_DMA_POLL) #ifdef READ_OVERRUNS if (p & SR_IO) { c -= 2; } #endif dprintk(NDEBUG_DMA, "scsi%d : initializing DMA channel %d for %s, %d bytes %s %0x\n", instance->host_no, instance->dma_channel, (p & SR_IO) ? "reading" : "writing", c, (p & SR_IO) ? "to" : "from", (unsigned) d); hostdata->dma_len = (p & SR_IO) ? NCR5380_dma_read_setup(instance, d, c) : NCR5380_dma_write_setup(instance, d, c); #endif NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p)); #ifdef REAL_DMA NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE | MR_ENABLE_EOP_INTR | MR_MONITOR_BSY); #elif defined(REAL_DMA_POLL) NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE); #else /* * Note : on my sample board, watch-dog timeouts occurred when interrupts * were not disabled for the duration of a single DMA transfer, from * before the setting of DMA mode to after transfer of the last byte. */ #if defined(PSEUDO_DMA) && defined(UNSAFE) spin_unlock_irq(instance->host_lock); #endif /* KLL May need eop and parity in 53c400 */ if (hostdata->flags & FLAG_NCR53C400) NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE | MR_ENABLE_PAR_CHECK | MR_ENABLE_PAR_INTR | MR_ENABLE_EOP_INTR | MR_MONITOR_BSY); else NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE); #endif /* def REAL_DMA */ dprintk(NDEBUG_DMA, "scsi%d : mode reg = 0x%X\n", instance->host_no, NCR5380_read(MODE_REG)); /* * On the PAS16 at least I/O recovery delays are not needed here. * Everyone else seems to want them. */ if (p & SR_IO) { io_recovery_delay(1); NCR5380_write(START_DMA_INITIATOR_RECEIVE_REG, 0); } else { io_recovery_delay(1); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA); io_recovery_delay(1); NCR5380_write(START_DMA_SEND_REG, 0); io_recovery_delay(1); } #if defined(REAL_DMA_POLL) do { tmp = NCR5380_read(BUS_AND_STATUS_REG); } while ((tmp & BASR_PHASE_MATCH) && !(tmp & (BASR_BUSY_ERROR | BASR_END_DMA_TRANSFER))); /* At this point, either we've completed DMA, or we have a phase mismatch, or we've unexpectedly lost BUSY (which is a real error). For write DMAs, we want to wait until the last byte has been transferred out over the bus before we turn off DMA mode. Alas, there seems to be no terribly good way of doing this on a 5380 under all conditions. For non-scatter-gather operations, we can wait until REQ and ACK both go false, or until a phase mismatch occurs. Gather-writes are nastier, since the device will be expecting more data than we are prepared to send it, and REQ will remain asserted. On a 53C8[01] we could test LAST BIT SENT to assure transfer (I imagine this is precisely why this signal was added to the newer chips) but on the older 538[01] this signal does not exist. The workaround for this lack is a watchdog; we bail out of the wait-loop after a modest amount of wait-time if the usual exit conditions are not met. Not a terribly clean or correct solution :-% Reads are equally tricky due to a nasty characteristic of the NCR5380. If the chip is in DMA mode for an READ, it will respond to a target's REQ by latching the SCSI data into the INPUT DATA register and asserting ACK, even if it has _already_ been notified by the DMA controller that the current DMA transfer has completed! If the NCR5380 is then taken out of DMA mode, this already-acknowledged byte is lost. This is not a problem for "one DMA transfer per command" reads, because the situation will never arise... either all of the data is DMA'ed properly, or the target switches to MESSAGE IN phase to signal a disconnection (either operation bringing the DMA to a clean halt). However, in order to handle scatter-reads, we must work around the problem. The chosen fix is to DMA N-2 bytes, then check for the condition before taking the NCR5380 out of DMA mode. One or two extra bytes are transferred via PIO as necessary to fill out the original request. */ if (p & SR_IO) { #ifdef READ_OVERRUNS udelay(10); if (((NCR5380_read(BUS_AND_STATUS_REG) & (BASR_PHASE_MATCH | BASR_ACK)) == (BASR_PHASE_MATCH | BASR_ACK))) { saved_data = NCR5380_read(INPUT_DATA_REGISTER); overrun = 1; } #endif } else { int limit = 100; while (((tmp = NCR5380_read(BUS_AND_STATUS_REG)) & BASR_ACK) || (NCR5380_read(STATUS_REG) & SR_REQ)) { if (!(tmp & BASR_PHASE_MATCH)) break; if (--limit < 0) break; } } dprintk(NDEBUG_DMA, "scsi%d : polled DMA transfer complete, basr 0x%X, sr 0x%X\n", instance->host_no, tmp, NCR5380_read(STATUS_REG)); NCR5380_write(MODE_REG, MR_BASE); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); residue = NCR5380_dma_residual(instance); c -= residue; *count -= c; *data += c; *phase = NCR5380_read(STATUS_REG) & PHASE_MASK; #ifdef READ_OVERRUNS if (*phase == p && (p & SR_IO) && residue == 0) { if (overrun) { dprintk(NDEBUG_DMA, "Got an input overrun, using saved byte\n"); **data = saved_data; *data += 1; *count -= 1; cnt = toPIO = 1; } else { printk("No overrun??\n"); cnt = toPIO = 2; } dprintk(NDEBUG_DMA, "Doing %d-byte PIO to 0x%X\n", cnt, *data); NCR5380_transfer_pio(instance, phase, &cnt, data); *count -= toPIO - cnt; } #endif dprintk(NDEBUG_DMA, "Return with data ptr = 0x%X, count %d, last 0x%X, next 0x%X\n", *data, *count, *(*data + *count - 1), *(*data + *count)); return 0; #elif defined(REAL_DMA) return 0; #else /* defined(REAL_DMA_POLL) */ if (p & SR_IO) { #ifdef DMA_WORKS_RIGHT foo = NCR5380_pread(instance, d, c); #else int diff = 1; if (hostdata->flags & FLAG_NCR53C400) { diff = 0; } if (!(foo = NCR5380_pread(instance, d, c - diff))) { /* * We can't disable DMA mode after successfully transferring * what we plan to be the last byte, since that would open up * a race condition where if the target asserted REQ before * we got the DMA mode reset, the NCR5380 would have latched * an additional byte into the INPUT DATA register and we'd * have dropped it. * * The workaround was to transfer one fewer bytes than we * intended to with the pseudo-DMA read function, wait for * the chip to latch the last byte, read it, and then disable * pseudo-DMA mode. * * After REQ is asserted, the NCR5380 asserts DRQ and ACK. * REQ is deasserted when ACK is asserted, and not reasserted * until ACK goes false. Since the NCR5380 won't lower ACK * until DACK is asserted, which won't happen unless we twiddle * the DMA port or we take the NCR5380 out of DMA mode, we * can guarantee that we won't handshake another extra * byte. */ if (!(hostdata->flags & FLAG_NCR53C400)) { while (!(NCR5380_read(BUS_AND_STATUS_REG) & BASR_DRQ)); /* Wait for clean handshake */ while (NCR5380_read(STATUS_REG) & SR_REQ); d[c - 1] = NCR5380_read(INPUT_DATA_REG); } } #endif } else { #ifdef DMA_WORKS_RIGHT foo = NCR5380_pwrite(instance, d, c); #else int timeout; dprintk(NDEBUG_C400_PWRITE, "About to pwrite %d bytes\n", c); if (!(foo = NCR5380_pwrite(instance, d, c))) { /* * Wait for the last byte to be sent. If REQ is being asserted for * the byte we're interested, we'll ACK it and it will go false. */ if (!(hostdata->flags & FLAG_HAS_LAST_BYTE_SENT)) { timeout = 20000; while (!(NCR5380_read(BUS_AND_STATUS_REG) & BASR_DRQ) && (NCR5380_read(BUS_AND_STATUS_REG) & BASR_PHASE_MATCH)); if (!timeout) dprintk(NDEBUG_LAST_BYTE_SENT, "scsi%d : timed out on last byte\n", instance->host_no); if (hostdata->flags & FLAG_CHECK_LAST_BYTE_SENT) { hostdata->flags &= ~FLAG_CHECK_LAST_BYTE_SENT; if (NCR5380_read(TARGET_COMMAND_REG) & TCR_LAST_BYTE_SENT) { hostdata->flags |= FLAG_HAS_LAST_BYTE_SENT; dprintk(NDEBUG_LAST_BYTE_SENT, "scsi%d : last byte sent works\n", instance->host_no); } } } else { dprintk(NDEBUG_C400_PWRITE, "Waiting for LASTBYTE\n"); while (!(NCR5380_read(TARGET_COMMAND_REG) & TCR_LAST_BYTE_SENT)); dprintk(NDEBUG_C400_PWRITE, "Got LASTBYTE\n"); } } #endif } NCR5380_write(MODE_REG, MR_BASE); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); if ((!(p & SR_IO)) && (hostdata->flags & FLAG_NCR53C400)) { dprintk(NDEBUG_C400_PWRITE, "53C400w: Checking for IRQ\n"); if (NCR5380_read(BUS_AND_STATUS_REG) & BASR_IRQ) { dprintk(NDEBUG_C400_PWRITE, "53C400w: got it, reading reset interrupt reg\n"); NCR5380_read(RESET_PARITY_INTERRUPT_REG); } else { printk("53C400w: IRQ NOT THERE!\n"); } } *data = d + c; *count = 0; *phase = NCR5380_read(STATUS_REG) & PHASE_MASK; #if defined(PSEUDO_DMA) && defined(UNSAFE) spin_lock_irq(instance->host_lock); #endif /* defined(REAL_DMA_POLL) */ return foo; #endif /* def REAL_DMA */ } #endif /* defined(REAL_DMA) | defined(PSEUDO_DMA) */ /* * Function : NCR5380_information_transfer (struct Scsi_Host *instance) * * Purpose : run through the various SCSI phases and do as the target * directs us to. Operates on the currently connected command, * instance->connected. * * Inputs : instance, instance for which we are doing commands * * Side effects : SCSI things happen, the disconnected queue will be * modified if a command disconnects, *instance->connected will * change. * * XXX Note : we need to watch for bus free or a reset condition here * to recover from an unexpected bus free condition. * * Locks: io_request_lock held by caller in IRQ mode */ static void NCR5380_information_transfer(struct Scsi_Host *instance) { NCR5380_local_declare(); struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *)instance->hostdata; unsigned char msgout = NOP; int sink = 0; int len; #if defined(PSEUDO_DMA) || defined(REAL_DMA_POLL) int transfersize; #endif unsigned char *data; unsigned char phase, tmp, extended_msg[10], old_phase = 0xff; struct scsi_cmnd *cmd = (struct scsi_cmnd *) hostdata->connected; /* RvC: we need to set the end of the polling time */ unsigned long poll_time = jiffies + USLEEP_POLL; NCR5380_setup(instance); while (1) { tmp = NCR5380_read(STATUS_REG); /* We only have a valid SCSI phase when REQ is asserted */ if (tmp & SR_REQ) { phase = (tmp & PHASE_MASK); if (phase != old_phase) { old_phase = phase; NCR5380_dprint_phase(NDEBUG_INFORMATION, instance); } if (sink && (phase != PHASE_MSGOUT)) { NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp)); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN | ICR_ASSERT_ACK); while (NCR5380_read(STATUS_REG) & SR_REQ); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN); sink = 0; continue; } switch (phase) { case PHASE_DATAIN: case PHASE_DATAOUT: #if (NDEBUG & NDEBUG_NO_DATAOUT) printk("scsi%d : NDEBUG_NO_DATAOUT set, attempted DATAOUT aborted\n", instance->host_no); sink = 1; do_abort(instance); cmd->result = DID_ERROR << 16; cmd->scsi_done(cmd); return; #endif /* * If there is no room left in the current buffer in the * scatter-gather list, move onto the next one. */ if (!cmd->SCp.this_residual && cmd->SCp.buffers_residual) { ++cmd->SCp.buffer; --cmd->SCp.buffers_residual; cmd->SCp.this_residual = cmd->SCp.buffer->length; cmd->SCp.ptr = sg_virt(cmd->SCp.buffer); dprintk(NDEBUG_INFORMATION, "scsi%d : %d bytes and %d buffers left\n", instance->host_no, cmd->SCp.this_residual, cmd->SCp.buffers_residual); } /* * The preferred transfer method is going to be * PSEUDO-DMA for systems that are strictly PIO, * since we can let the hardware do the handshaking. * * For this to work, we need to know the transfersize * ahead of time, since the pseudo-DMA code will sit * in an unconditional loop. */ #if defined(PSEUDO_DMA) || defined(REAL_DMA_POLL) /* KLL * PSEUDO_DMA is defined here. If this is the g_NCR5380 * driver then it will always be defined, so the * FLAG_NO_PSEUDO_DMA is used to inhibit PDMA in the base * NCR5380 case. I think this is a fairly clean solution. * We supplement these 2 if's with the flag. */ #ifdef NCR5380_dma_xfer_len if (!cmd->device->borken && !(hostdata->flags & FLAG_NO_PSEUDO_DMA) && (transfersize = NCR5380_dma_xfer_len(instance, cmd)) != 0) { #else transfersize = cmd->transfersize; #ifdef LIMIT_TRANSFERSIZE /* If we have problems with interrupt service */ if (transfersize > 512) transfersize = 512; #endif /* LIMIT_TRANSFERSIZE */ if (!cmd->device->borken && transfersize && !(hostdata->flags & FLAG_NO_PSEUDO_DMA) && cmd->SCp.this_residual && !(cmd->SCp.this_residual % transfersize)) { /* Limit transfers to 32K, for xx400 & xx406 * pseudoDMA that transfers in 128 bytes blocks. */ if (transfersize > 32 * 1024) transfersize = 32 * 1024; #endif len = transfersize; if (NCR5380_transfer_dma(instance, &phase, &len, (unsigned char **) &cmd->SCp.ptr)) { /* * If the watchdog timer fires, all future accesses to this * device will use the polled-IO. */ scmd_printk(KERN_INFO, cmd, "switching to slow handshake\n"); cmd->device->borken = 1; NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN); sink = 1; do_abort(instance); cmd->result = DID_ERROR << 16; cmd->scsi_done(cmd); /* XXX - need to source or sink data here, as appropriate */ } else cmd->SCp.this_residual -= transfersize - len; } else #endif /* defined(PSEUDO_DMA) || defined(REAL_DMA_POLL) */ NCR5380_transfer_pio(instance, &phase, (int *) &cmd->SCp.this_residual, (unsigned char **) &cmd->SCp.ptr); break; case PHASE_MSGIN: len = 1; data = &tmp; NCR5380_transfer_pio(instance, &phase, &len, &data); cmd->SCp.Message = tmp; switch (tmp) { /* * Linking lets us reduce the time required to get the * next command out to the device, hopefully this will * mean we don't waste another revolution due to the delays * required by ARBITRATION and another SELECTION. * * In the current implementation proposal, low level drivers * merely have to start the next command, pointed to by * next_link, done() is called as with unlinked commands. */ #ifdef LINKED case LINKED_CMD_COMPLETE: case LINKED_FLG_CMD_COMPLETE: /* Accept message by clearing ACK */ NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); dprintk(NDEBUG_LINKED, "scsi%d : target %d lun %llu linked command complete.\n", instance->host_no, cmd->device->id, cmd->device->lun); /* * Sanity check : A linked command should only terminate with * one of these messages if there are more linked commands * available. */ if (!cmd->next_link) { printk("scsi%d : target %d lun %llu linked command complete, no next_link\n" instance->host_no, cmd->device->id, cmd->device->lun); sink = 1; do_abort(instance); return; } initialize_SCp(cmd->next_link); /* The next command is still part of this process */ cmd->next_link->tag = cmd->tag; cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8); dprintk(NDEBUG_LINKED, "scsi%d : target %d lun %llu linked request done, calling scsi_done().\n", instance->host_no, cmd->device->id, cmd->device->lun); cmd->scsi_done(cmd); cmd = hostdata->connected; break; #endif /* def LINKED */ case ABORT: case COMMAND_COMPLETE: /* Accept message by clearing ACK */ sink = 1; NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); hostdata->connected = NULL; dprintk(NDEBUG_QUEUES, "scsi%d : command for target %d, lun %llu completed\n", instance->host_no, cmd->device->id, cmd->device->lun); hostdata->busy[cmd->device->id] &= ~(1 << (cmd->device->lun & 0xFF)); /* * I'm not sure what the correct thing to do here is : * * If the command that just executed is NOT a request * sense, the obvious thing to do is to set the result * code to the values of the stored parameters. * * If it was a REQUEST SENSE command, we need some way * to differentiate between the failure code of the original * and the failure code of the REQUEST sense - the obvious * case is success, where we fall through and leave the result * code unchanged. * * The non-obvious place is where the REQUEST SENSE failed */ if (cmd->cmnd[0] != REQUEST_SENSE) cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8); else if (status_byte(cmd->SCp.Status) != GOOD) cmd->result = (cmd->result & 0x00ffff) | (DID_ERROR << 16); if ((cmd->cmnd[0] == REQUEST_SENSE) && hostdata->ses.cmd_len) { scsi_eh_restore_cmnd(cmd, &hostdata->ses); hostdata->ses.cmd_len = 0 ; } if ((cmd->cmnd[0] != REQUEST_SENSE) && (status_byte(cmd->SCp.Status) == CHECK_CONDITION)) { scsi_eh_prep_cmnd(cmd, &hostdata->ses, NULL, 0, ~0); dprintk(NDEBUG_AUTOSENSE, "scsi%d : performing request sense\n", instance->host_no); LIST(cmd, hostdata->issue_queue); cmd->host_scribble = (unsigned char *) hostdata->issue_queue; hostdata->issue_queue = (struct scsi_cmnd *) cmd; dprintk(NDEBUG_QUEUES, "scsi%d : REQUEST SENSE added to head of issue queue\n", instance->host_no); } else { cmd->scsi_done(cmd); } NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask); /* * Restore phase bits to 0 so an interrupted selection, * arbitration can resume. */ NCR5380_write(TARGET_COMMAND_REG, 0); while ((NCR5380_read(STATUS_REG) & SR_BSY) && !hostdata->connected) barrier(); return; case MESSAGE_REJECT: /* Accept message by clearing ACK */ NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); switch (hostdata->last_message) { case HEAD_OF_QUEUE_TAG: case ORDERED_QUEUE_TAG: case SIMPLE_QUEUE_TAG: cmd->device->simple_tags = 0; hostdata->busy[cmd->device->id] |= (1 << (cmd->device->lun & 0xFF)); break; default: break; } case DISCONNECT:{ /* Accept message by clearing ACK */ NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); cmd->device->disconnect = 1; LIST(cmd, hostdata->disconnected_queue); cmd->host_scribble = (unsigned char *) hostdata->disconnected_queue; hostdata->connected = NULL; hostdata->disconnected_queue = cmd; dprintk(NDEBUG_QUEUES, "scsi%d : command for target %d lun %llu was moved from connected to" " the disconnected_queue\n", instance->host_no, cmd->device->id, cmd->device->lun); /* * Restore phase bits to 0 so an interrupted selection, * arbitration can resume. */ NCR5380_write(TARGET_COMMAND_REG, 0); /* Enable reselect interrupts */ NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask); /* Wait for bus free to avoid nasty timeouts - FIXME timeout !*/ /* NCR538_poll_politely(instance, STATUS_REG, SR_BSY, 0, 30 * HZ); */ while ((NCR5380_read(STATUS_REG) & SR_BSY) && !hostdata->connected) barrier(); return; } /* * The SCSI data pointer is *IMPLICITLY* saved on a disconnect * operation, in violation of the SCSI spec so we can safely * ignore SAVE/RESTORE pointers calls. * * Unfortunately, some disks violate the SCSI spec and * don't issue the required SAVE_POINTERS message before * disconnecting, and we have to break spec to remain * compatible. */ case SAVE_POINTERS: case RESTORE_POINTERS: /* Accept message by clearing ACK */ NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); break; case EXTENDED_MESSAGE: /* * Extended messages are sent in the following format : * Byte * 0 EXTENDED_MESSAGE == 1 * 1 length (includes one byte for code, doesn't * include first two bytes) * 2 code * 3..length+1 arguments * * Start the extended message buffer with the EXTENDED_MESSAGE * byte, since spi_print_msg() wants the whole thing. */ extended_msg[0] = EXTENDED_MESSAGE; /* Accept first byte by clearing ACK */ NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); dprintk(NDEBUG_EXTENDED, "scsi%d : receiving extended message\n", instance->host_no); len = 2; data = extended_msg + 1; phase = PHASE_MSGIN; NCR5380_transfer_pio(instance, &phase, &len, &data); dprintk(NDEBUG_EXTENDED, "scsi%d : length=%d, code=0x%02x\n", instance->host_no, (int) extended_msg[1], (int) extended_msg[2]); if (!len && extended_msg[1] <= (sizeof(extended_msg) - 1)) { /* Accept third byte by clearing ACK */ NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); len = extended_msg[1] - 1; data = extended_msg + 3; phase = PHASE_MSGIN; NCR5380_transfer_pio(instance, &phase, &len, &data); dprintk(NDEBUG_EXTENDED, "scsi%d : message received, residual %d\n", instance->host_no, len); switch (extended_msg[2]) { case EXTENDED_SDTR: case EXTENDED_WDTR: case EXTENDED_MODIFY_DATA_POINTER: case EXTENDED_EXTENDED_IDENTIFY: tmp = 0; } } else if (len) { printk("scsi%d: error receiving extended message\n", instance->host_no); tmp = 0; } else { printk("scsi%d: extended message code %02x length %d is too long\n", instance->host_no, extended_msg[2], extended_msg[1]); tmp = 0; } /* Fall through to reject message */ /* * If we get something weird that we aren't expecting, * reject it. */ default: if (!tmp) { printk("scsi%d: rejecting message ", instance->host_no); spi_print_msg(extended_msg); printk("\n"); } else if (tmp != EXTENDED_MESSAGE) scmd_printk(KERN_INFO, cmd, "rejecting unknown message %02x\n",tmp); else scmd_printk(KERN_INFO, cmd, "rejecting unknown extended message code %02x, length %d\n", extended_msg[1], extended_msg[0]); msgout = MESSAGE_REJECT; NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN); break; } /* switch (tmp) */ break; case PHASE_MSGOUT: len = 1; data = &msgout; hostdata->last_message = msgout; NCR5380_transfer_pio(instance, &phase, &len, &data); if (msgout == ABORT) { hostdata->busy[cmd->device->id] &= ~(1 << (cmd->device->lun & 0xFF)); hostdata->connected = NULL; cmd->result = DID_ERROR << 16; cmd->scsi_done(cmd); NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask); return; } msgout = NOP; break; case PHASE_CMDOUT: len = cmd->cmd_len; data = cmd->cmnd; /* * XXX for performance reasons, on machines with a * PSEUDO-DMA architecture we should probably * use the dma transfer function. */ NCR5380_transfer_pio(instance, &phase, &len, &data); if (!cmd->device->disconnect && should_disconnect(cmd->cmnd[0])) { NCR5380_set_timer(hostdata, USLEEP_SLEEP); dprintk(NDEBUG_USLEEP, "scsi%d : issued command, sleeping until %lu\n", instance->host_no, hostdata->time_expires); return; } break; case PHASE_STATIN: len = 1; data = &tmp; NCR5380_transfer_pio(instance, &phase, &len, &data); cmd->SCp.Status = tmp; break; default: printk("scsi%d : unknown phase\n", instance->host_no); NCR5380_dprint(NDEBUG_ANY, instance); } /* switch(phase) */ } /* if (tmp * SR_REQ) */ else { /* RvC: go to sleep if polling time expired */ if (!cmd->device->disconnect && time_after_eq(jiffies, poll_time)) { NCR5380_set_timer(hostdata, USLEEP_SLEEP); dprintk(NDEBUG_USLEEP, "scsi%d : poll timed out, sleeping until %lu\n", instance->host_no, hostdata->time_expires); return; } } } /* while (1) */ } /* * Function : void NCR5380_reselect (struct Scsi_Host *instance) * * Purpose : does reselection, initializing the instance->connected * field to point to the scsi_cmnd for which the I_T_L or I_T_L_Q * nexus has been reestablished, * * Inputs : instance - this instance of the NCR5380. * * Locks: io_request_lock held by caller if IRQ driven */ static void NCR5380_reselect(struct Scsi_Host *instance) { NCR5380_local_declare(); struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; unsigned char target_mask; unsigned char lun, phase; int len; unsigned char msg[3]; unsigned char *data; struct scsi_cmnd *tmp = NULL, *prev; int abort = 0; NCR5380_setup(instance); /* * Disable arbitration, etc. since the host adapter obviously * lost, and tell an interrupted NCR5380_select() to restart. */ NCR5380_write(MODE_REG, MR_BASE); hostdata->restart_select = 1; target_mask = NCR5380_read(CURRENT_SCSI_DATA_REG) & ~(hostdata->id_mask); dprintk(NDEBUG_SELECTION, "scsi%d : reselect\n", instance->host_no); /* * At this point, we have detected that our SCSI ID is on the bus, * SEL is true and BSY was false for at least one bus settle delay * (400 ns). * * We must assert BSY ourselves, until the target drops the SEL * signal. */ NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_BSY); /* FIXME: timeout too long, must fail to workqueue */ if(NCR5380_poll_politely(instance, STATUS_REG, SR_SEL, 0, 2*HZ)<0) abort = 1; NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); /* * Wait for target to go into MSGIN. * FIXME: timeout needed and fail to work queeu */ if(NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, SR_REQ, 2*HZ)) abort = 1; len = 1; data = msg; phase = PHASE_MSGIN; NCR5380_transfer_pio(instance, &phase, &len, &data); if (!(msg[0] & 0x80)) { printk(KERN_ERR "scsi%d : expecting IDENTIFY message, got ", instance->host_no); spi_print_msg(msg); abort = 1; } else { /* Accept message by clearing ACK */ NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); lun = (msg[0] & 0x07); /* * We need to add code for SCSI-II to track which devices have * I_T_L_Q nexuses established, and which have simple I_T_L * nexuses so we can chose to do additional data transfer. */ /* * Find the command corresponding to the I_T_L or I_T_L_Q nexus we * just reestablished, and remove it from the disconnected queue. */ for (tmp = (struct scsi_cmnd *) hostdata->disconnected_queue, prev = NULL; tmp; prev = tmp, tmp = (struct scsi_cmnd *) tmp->host_scribble) if ((target_mask == (1 << tmp->device->id)) && (lun == (u8)tmp->device->lun) ) { if (prev) { REMOVE(prev, prev->host_scribble, tmp, tmp->host_scribble); prev->host_scribble = tmp->host_scribble; } else { REMOVE(-1, hostdata->disconnected_queue, tmp, tmp->host_scribble); hostdata->disconnected_queue = (struct scsi_cmnd *) tmp->host_scribble; } tmp->host_scribble = NULL; break; } if (!tmp) { printk(KERN_ERR "scsi%d : warning : target bitmask %02x lun %d not in disconnect_queue.\n", instance->host_no, target_mask, lun); /* * Since we have an established nexus that we can't do anything with, * we must abort it. */ abort = 1; } } if (abort) { do_abort(instance); } else { hostdata->connected = tmp; dprintk(NDEBUG_RESELECTION, "scsi%d : nexus established, target = %d, lun = %llu, tag = %d\n", instance->host_no, tmp->device->id, tmp->device->lun, tmp->tag); } } /* * Function : void NCR5380_dma_complete (struct Scsi_Host *instance) * * Purpose : called by interrupt handler when DMA finishes or a phase * mismatch occurs (which would finish the DMA transfer). * * Inputs : instance - this instance of the NCR5380. * * Returns : pointer to the scsi_cmnd structure for which the I_T_L * nexus has been reestablished, on failure NULL is returned. */ #ifdef REAL_DMA static void NCR5380_dma_complete(NCR5380_instance * instance) { NCR5380_local_declare(); struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; int transferred; NCR5380_setup(instance); /* * XXX this might not be right. * * Wait for final byte to transfer, ie wait for ACK to go false. * * We should use the Last Byte Sent bit, unfortunately this is * not available on the 5380/5381 (only the various CMOS chips) * * FIXME: timeout, and need to handle long timeout/irq case */ NCR5380_poll_politely(instance, BUS_AND_STATUS_REG, BASR_ACK, 0, 5*HZ); NCR5380_write(MODE_REG, MR_BASE); NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE); /* * The only places we should see a phase mismatch and have to send * data from the same set of pointers will be the data transfer * phases. So, residual, requested length are only important here. */ if (!(hostdata->connected->SCp.phase & SR_CD)) { transferred = instance->dmalen - NCR5380_dma_residual(); hostdata->connected->SCp.this_residual -= transferred; hostdata->connected->SCp.ptr += transferred; } } #endif /* def REAL_DMA */ /* * Function : int NCR5380_abort (struct scsi_cmnd *cmd) * * Purpose : abort a command * * Inputs : cmd - the scsi_cmnd to abort, code - code to set the * host byte of the result field to, if zero DID_ABORTED is * used. * * Returns : SUCCESS - success, FAILED on failure. * * XXX - there is no way to abort the command that is currently * connected, you have to wait for it to complete. If this is * a problem, we could implement longjmp() / setjmp(), setjmp() * called where the loop started in NCR5380_main(). * * Locks: host lock taken by caller */ static int NCR5380_abort(struct scsi_cmnd *cmd) { NCR5380_local_declare(); struct Scsi_Host *instance = cmd->device->host; struct NCR5380_hostdata *hostdata = (struct NCR5380_hostdata *) instance->hostdata; struct scsi_cmnd *tmp, **prev; scmd_printk(KERN_WARNING, cmd, "aborting command\n"); NCR5380_print_status(instance); NCR5380_setup(instance); dprintk(NDEBUG_ABORT, "scsi%d : abort called\n", instance->host_no); dprintk(NDEBUG_ABORT, " basr 0x%X, sr 0x%X\n", NCR5380_read(BUS_AND_STATUS_REG), NCR5380_read(STATUS_REG)); #if 0 /* * Case 1 : If the command is the currently executing command, * we'll set the aborted flag and return control so that * information transfer routine can exit cleanly. */ if (hostdata->connected == cmd) { dprintk(NDEBUG_ABORT, "scsi%d : aborting connected command\n", instance->host_no); hostdata->aborted = 1; /* * We should perform BSY checking, and make sure we haven't slipped * into BUS FREE. */ NCR5380_write(INITIATOR_COMMAND_REG, ICR_ASSERT_ATN); /* * Since we can't change phases until we've completed the current * handshake, we have to source or sink a byte of data if the current * phase is not MSGOUT. */ /* * Return control to the executing NCR drive so we can clear the * aborted flag and get back into our main loop. */ return SUCCESS; } #endif /* * Case 2 : If the command hasn't been issued yet, we simply remove it * from the issue queue. */ dprintk(NDEBUG_ABORT, "scsi%d : abort going into loop.\n", instance->host_no); for (prev = (struct scsi_cmnd **) &(hostdata->issue_queue), tmp = (struct scsi_cmnd *) hostdata->issue_queue; tmp; prev = (struct scsi_cmnd **) &(tmp->host_scribble), tmp = (struct scsi_cmnd *) tmp->host_scribble) if (cmd == tmp) { REMOVE(5, *prev, tmp, tmp->host_scribble); (*prev) = (struct scsi_cmnd *) tmp->host_scribble; tmp->host_scribble = NULL; tmp->result = DID_ABORT << 16; dprintk(NDEBUG_ABORT, "scsi%d : abort removed command from issue queue.\n", instance->host_no); tmp->scsi_done(tmp); return SUCCESS; } #if (NDEBUG & NDEBUG_ABORT) /* KLL */ else if (prev == tmp) printk(KERN_ERR "scsi%d : LOOP\n", instance->host_no); #endif /* * Case 3 : If any commands are connected, we're going to fail the abort * and let the high level SCSI driver retry at a later time or * issue a reset. * * Timeouts, and therefore aborted commands, will be highly unlikely * and handling them cleanly in this situation would make the common * case of noresets less efficient, and would pollute our code. So, * we fail. */ if (hostdata->connected) { dprintk(NDEBUG_ABORT, "scsi%d : abort failed, command connected.\n", instance->host_no); return FAILED; } /* * Case 4: If the command is currently disconnected from the bus, and * there are no connected commands, we reconnect the I_T_L or * I_T_L_Q nexus associated with it, go into message out, and send * an abort message. * * This case is especially ugly. In order to reestablish the nexus, we * need to call NCR5380_select(). The easiest way to implement this * function was to abort if the bus was busy, and let the interrupt * handler triggered on the SEL for reselect take care of lost arbitrations * where necessary, meaning interrupts need to be enabled. * * When interrupts are enabled, the queues may change - so we * can't remove it from the disconnected queue before selecting it * because that could cause a failure in hashing the nexus if that * device reselected. * * Since the queues may change, we can't use the pointers from when we * first locate it. * * So, we must first locate the command, and if NCR5380_select() * succeeds, then issue the abort, relocate the command and remove * it from the disconnected queue. */ for (tmp = (struct scsi_cmnd *) hostdata->disconnected_queue; tmp; tmp = (struct scsi_cmnd *) tmp->host_scribble) if (cmd == tmp) { dprintk(NDEBUG_ABORT, "scsi%d : aborting disconnected command.\n", instance->host_no); if (NCR5380_select(instance, cmd)) return FAILED; dprintk(NDEBUG_ABORT, "scsi%d : nexus reestablished.\n", instance->host_no); do_abort(instance); for (prev = (struct scsi_cmnd **) &(hostdata->disconnected_queue), tmp = (struct scsi_cmnd *) hostdata->disconnected_queue; tmp; prev = (struct scsi_cmnd **) &(tmp->host_scribble), tmp = (struct scsi_cmnd *) tmp->host_scribble) if (cmd == tmp) { REMOVE(5, *prev, tmp, tmp->host_scribble); *prev = (struct scsi_cmnd *) tmp->host_scribble; tmp->host_scribble = NULL; tmp->result = DID_ABORT << 16; tmp->scsi_done(tmp); return SUCCESS; } } /* * Case 5 : If we reached this point, the command was not found in any of * the queues. * * We probably reached this point because of an unlikely race condition * between the command completing successfully and the abortion code, * so we won't panic, but we will notify the user in case something really * broke. */ printk(KERN_WARNING "scsi%d : warning : SCSI command probably completed successfully\n" " before abortion\n", instance->host_no); return FAILED; } /* * Function : int NCR5380_bus_reset (struct scsi_cmnd *cmd) * * Purpose : reset the SCSI bus. * * Returns : SUCCESS * * Locks: host lock taken by caller */ static int NCR5380_bus_reset(struct scsi_cmnd *cmd) { struct Scsi_Host *instance = cmd->device->host; NCR5380_local_declare(); NCR5380_setup(instance); NCR5380_print_status(instance); spin_lock_irq(instance->host_lock); do_reset(instance); spin_unlock_irq(instance->host_lock); return SUCCESS; }
mit
dmcoin/diamondcoin
src/qt/bitcoinamountfield.cpp
1
4376
#include "bitcoinamountfield.h" #include "qvaluecombobox.h" #include "bitcoinunits.h" #include "guiconstants.h" #include <QHBoxLayout> #include <QKeyEvent> #include <QDoubleSpinBox> #include <QApplication> #include <qmath.h> // for qPow() BitcoinAmountField::BitcoinAmountField(QWidget *parent): QWidget(parent), amount(0), currentUnit(-1) { amount = new QDoubleSpinBox(this); amount->setLocale(QLocale::c()); amount->setDecimals(8); amount->installEventFilter(this); amount->setMaximumWidth(170); amount->setSingleStep(0.001); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0,0,0,0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void BitcoinAmountField::setText(const QString &text) { if (text.isEmpty()) amount->clear(); else amount->setValue(text.toDouble()); } void BitcoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } bool BitcoinAmountField::validate() { bool valid = true; if (amount->value() == 0.0) valid = false; if (valid && !BitcoinUnits::parse(currentUnit, text(), 0)) valid = false; setValid(valid); return valid; } void BitcoinAmountField::setValid(bool valid) { if (valid) amount->setStyleSheet(""); else amount->setStyleSheet(STYLE_INVALID); } QString BitcoinAmountField::text() const { if (amount->text().isEmpty()) return QString(); else return amount->text(); } bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); QApplication::sendEvent(object, &periodKeyEvent); return true; } } return QWidget::eventFilter(object, event); } QWidget *BitcoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); return amount; } qint64 BitcoinAmountField::value(bool *valid_out) const { qint64 val_out = 0; bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out); if(valid_out) { *valid_out = valid; } return val_out; } void BitcoinAmountField::setValue(qint64 value) { setText(BitcoinUnits::format(currentUnit, value)); } void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); // Parse current value and convert to new unit bool valid = false; qint64 currentValue = value(&valid); currentUnit = newUnit; // Set max length after retrieving the value, to prevent truncation amount->setDecimals(BitcoinUnits::decimals(currentUnit)); amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals())); if(currentUnit == BitcoinUnits::cDMC) amount->setSingleStep(0.01); else amount->setSingleStep(0.001); if(valid) { // If value was valid, re-place it in the widget with the new unit setValue(currentValue); } else { // If current value is invalid, just clear field setText(""); } setValid(true); } void BitcoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); }
mit
jonancm/viennagrid-python
src/segmentations/triangular.cpp
1
6159
/* * Copyright (c) 2013 Jonan Cruz-Martin * * Distributed under the terms of the MIT license, see the accompanying * file COPYING or http://opensource.org/licenses/MIT. */ #include "triangular.hpp" #include "../domains/triangular.hpp" //////////////////////////////////////// // TriangularCartesian2D_Segmentation // //////////////////////////////////////// TriangularCartesian2D_Segmentation::TriangularCartesian2D_Segmentation(TriangularCartesian2D_Domain &dom) : segmentation(dom.get_domain()) { domain = &dom; } unsigned int TriangularCartesian2D_Segmentation::num_segments() { return segmentation.size(); } TriangularCartesian2D_Segment TriangularCartesian2D_Segmentation::make_segment() { TriangularCartesian2D_Segment_t seg = segmentation.make_segment(); TriangularCartesian2D_Segment new_segment(seg, *this); return new_segment; } list TriangularCartesian2D_Segmentation::get_segments() { typedef TriangularCartesian2D_Segmentation_t::iterator iterator; list segment_list; for (iterator it = segmentation.begin(); it != segmentation.end(); ++it) segment_list.append<TriangularCartesian2D_Segment>(TriangularCartesian2D_Segment(*it, *this)); return segment_list; } TriangularCartesian2D_Domain_t & TriangularCartesian2D_Segmentation::get_domain() { return domain->get_domain(); } TriangularCartesian2D_Segmentation_t & TriangularCartesian2D_Segmentation::get_segmentation() { return segmentation; } //////////////////////////////////////// // TriangularCartesian3D_Segmentation // //////////////////////////////////////// TriangularCartesian3D_Segmentation::TriangularCartesian3D_Segmentation(TriangularCartesian3D_Domain &dom) : segmentation(dom.get_domain()) { domain = &dom; } unsigned int TriangularCartesian3D_Segmentation::num_segments() { return segmentation.size(); } TriangularCartesian3D_Segment TriangularCartesian3D_Segmentation::make_segment() { TriangularCartesian3D_Segment_t seg = segmentation.make_segment(); TriangularCartesian3D_Segment new_segment(seg, *this); return new_segment; } list TriangularCartesian3D_Segmentation::get_segments() { typedef TriangularCartesian3D_Segmentation_t::iterator iterator; list segment_list; for (iterator it = segmentation.begin(); it != segmentation.end(); ++it) segment_list.append<TriangularCartesian3D_Segment>(TriangularCartesian3D_Segment(*it, *this)); return segment_list; } TriangularCartesian3D_Domain_t & TriangularCartesian3D_Segmentation::get_domain() { return domain->get_domain(); } TriangularCartesian3D_Segmentation_t & TriangularCartesian3D_Segmentation::get_segmentation() { return segmentation; } ////////////////////////////////////////// // TriangularCylindrical3D_Segmentation // ////////////////////////////////////////// TriangularCylindrical3D_Segmentation::TriangularCylindrical3D_Segmentation(TriangularCylindrical3D_Domain &dom) : segmentation(dom.get_domain()) { domain = &dom; } unsigned int TriangularCylindrical3D_Segmentation::num_segments() { return segmentation.size(); } TriangularCylindrical3D_Segment TriangularCylindrical3D_Segmentation::make_segment() { TriangularCylindrical3D_Segment_t seg = segmentation.make_segment(); TriangularCylindrical3D_Segment new_segment(seg, *this); return new_segment; } list TriangularCylindrical3D_Segmentation::get_segments() { typedef TriangularCylindrical3D_Segmentation_t::iterator iterator; list segment_list; for (iterator it = segmentation.begin(); it != segmentation.end(); ++it) segment_list.append<TriangularCylindrical3D_Segment>(TriangularCylindrical3D_Segment(*it, *this)); return segment_list; } TriangularCylindrical3D_Domain_t & TriangularCylindrical3D_Segmentation::get_domain() { return domain->get_domain(); } TriangularCylindrical3D_Segmentation_t & TriangularCylindrical3D_Segmentation::get_segmentation() { return segmentation; } //////////////////////////////////// // TriangularPolar2D_Segmentation // //////////////////////////////////// TriangularPolar2D_Segmentation::TriangularPolar2D_Segmentation(TriangularPolar2D_Domain &dom) : segmentation(dom.get_domain()) { domain = &dom; } unsigned int TriangularPolar2D_Segmentation::num_segments() { return segmentation.size(); } TriangularPolar2D_Segment TriangularPolar2D_Segmentation::make_segment() { TriangularPolar2D_Segment_t seg = segmentation.make_segment(); TriangularPolar2D_Segment new_segment(seg, *this); return new_segment; } list TriangularPolar2D_Segmentation::get_segments() { typedef TriangularPolar2D_Segmentation_t::iterator iterator; list segment_list; for (iterator it = segmentation.begin(); it != segmentation.end(); ++it) segment_list.append<TriangularPolar2D_Segment>(TriangularPolar2D_Segment(*it, *this)); return segment_list; } TriangularPolar2D_Domain_t & TriangularPolar2D_Segmentation::get_domain() { return domain->get_domain(); } TriangularPolar2D_Segmentation_t & TriangularPolar2D_Segmentation::get_segmentation() { return segmentation; } //////////////////////////////////////// // TriangularSpherical3D_Segmentation // //////////////////////////////////////// TriangularSpherical3D_Segmentation::TriangularSpherical3D_Segmentation(TriangularSpherical3D_Domain &dom) : segmentation(dom.get_domain()) { domain = &dom; } unsigned int TriangularSpherical3D_Segmentation::num_segments() { return segmentation.size(); } TriangularSpherical3D_Segment TriangularSpherical3D_Segmentation::make_segment() { TriangularSpherical3D_Segment_t seg = segmentation.make_segment(); TriangularSpherical3D_Segment new_segment(seg, *this); return new_segment; } list TriangularSpherical3D_Segmentation::get_segments() { typedef TriangularSpherical3D_Segmentation_t::iterator iterator; list segment_list; for (iterator it = segmentation.begin(); it != segmentation.end(); ++it) segment_list.append<TriangularSpherical3D_Segment>(TriangularSpherical3D_Segment(*it, *this)); return segment_list; } TriangularSpherical3D_Domain_t & TriangularSpherical3D_Segmentation::get_domain() { return domain->get_domain(); } TriangularSpherical3D_Segmentation_t & TriangularSpherical3D_Segmentation::get_segmentation() { return segmentation; }
mit
phinze/pianobar
src/libwaitress/waitress.c
1
33385
/* Copyright (c) 2009-2011 Lars-Dominik Braun <lars@6xq.net> 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 __FreeBSD__ #define _POSIX_C_SOURCE 1 /* required by getaddrinfo() */ #define _BSD_SOURCE /* snprintf() */ #define _DARWIN_C_SOURCE /* snprintf() on OS X */ #endif #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <fcntl.h> #include <poll.h> #include <errno.h> #include <assert.h> #include <gnutls/x509.h> #include "config.h" #include "waitress.h" #define strcaseeq(a,b) (strcasecmp(a,b) == 0) #define WAITRESS_HTTP_VERSION "1.1" typedef struct { char *data; size_t pos; } WaitressFetchBufCbBuffer_t; static WaitressReturn_t WaitressReceiveHeaders (WaitressHandle_t *, size_t *); #define READ_RET(buf, count, size) \ if ((wRet = waith->request.read (waith, buf, count, size)) != \ WAITRESS_RET_OK) { \ return wRet; \ } #define WRITE_RET(buf, count) \ if ((wRet = waith->request.write (waith, buf, count)) != WAITRESS_RET_OK) { \ return wRet; \ } void WaitressInit (WaitressHandle_t *waith) { assert (waith != NULL); memset (waith, 0, sizeof (*waith)); waith->timeout = 30000; } void WaitressFree (WaitressHandle_t *waith) { assert (waith != NULL); free (waith->url.url); free (waith->proxy.url); memset (waith, 0, sizeof (*waith)); } /* Proxy set up? * @param Waitress handle * @return true|false */ static bool WaitressProxyEnabled (const WaitressHandle_t *waith) { assert (waith != NULL); return waith->proxy.host != NULL; } /* urlencode post-data * @param encode this * @return malloc'ed encoded string, don't forget to free it */ char *WaitressUrlEncode (const char *in) { assert (in != NULL); size_t inLen = strlen (in); /* worst case: encode all characters */ char *out = calloc (inLen * 3 + 1, sizeof (*in)); const char *inPos = in; char *outPos = out; while (inPos - in < inLen) { if (!isalnum (*inPos) && *inPos != '_' && *inPos != '-' && *inPos != '.') { *outPos++ = '%'; snprintf (outPos, 3, "%02x", *inPos & 0xff); outPos += 2; } else { /* copy character */ *outPos++ = *inPos; } ++inPos; } return out; } /* base64 encode data * @param encode this * @return malloc'ed string */ static char *WaitressBase64Encode (const char *in) { assert (in != NULL); size_t inLen = strlen (in); char *out, *outPos; const char *inPos; static const char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz0123456789+/"; const size_t alphabetLen = strlen (alphabet); /* worst case is 1.333 */ out = malloc ((inLen * 2 + 1) * sizeof (*out)); if (out == NULL) { return NULL; } outPos = out; inPos = in; while (inLen >= 3) { uint8_t idx; idx = ((*inPos) >> 2) & 0x3f; assert (idx < alphabetLen); *outPos = alphabet[idx]; ++outPos; idx = ((*inPos) & 0x3) << 4; ++inPos; idx |= ((*inPos) >> 4) & 0xf; assert (idx < alphabetLen); *outPos = alphabet[idx]; ++outPos; idx = ((*inPos) & 0xf) << 2; ++inPos; idx |= ((*inPos) >> 6) & 0x3; assert (idx < alphabetLen); *outPos = alphabet[idx]; ++outPos; idx = (*inPos) & 0x3f; ++inPos; assert (idx < alphabetLen); *outPos = alphabet[idx]; ++outPos; inLen -= 3; } switch (inLen) { case 2: { uint8_t idx; idx = ((*inPos) >> 2) & 0x3f; assert (idx < alphabetLen); *outPos = alphabet[idx]; ++outPos; idx = ((*inPos) & 0x3) << 4; ++inPos; idx |= ((*inPos) >> 4) & 0xf; assert (idx < alphabetLen); *outPos = alphabet[idx]; ++outPos; idx = ((*inPos) & 0xf) << 2; assert (idx < alphabetLen); *outPos = alphabet[idx]; ++outPos; *outPos = '='; ++outPos; break; } case 1: { uint8_t idx; idx = ((*inPos) >> 2) & 0x3f; assert (idx < alphabetLen); *outPos = alphabet[idx]; ++outPos; idx = ((*inPos) & 0x3) << 4; assert (idx < alphabetLen); *outPos = alphabet[idx]; ++outPos; *outPos = '='; ++outPos; *outPos = '='; ++outPos; break; } } *outPos = '\0'; return out; } /* Split http url into host, port and path * @param url * @param returned url struct * @return url is a http url? does not say anything about its validity! */ static bool WaitressSplitUrl (const char *inurl, WaitressUrl_t *retUrl) { assert (inurl != NULL); assert (retUrl != NULL); static const char *httpPrefix = "http://"; /* is http url? */ if (strncmp (httpPrefix, inurl, strlen (httpPrefix)) == 0) { enum {FIND_USER, FIND_PASS, FIND_HOST, FIND_PORT, FIND_PATH, DONE} state = FIND_USER, newState = FIND_USER; char *url, *urlPos, *assignStart; const char **assign = NULL; url = strdup (inurl); retUrl->url = url; urlPos = url + strlen (httpPrefix); assignStart = urlPos; if (*urlPos == '\0') { state = DONE; } while (state != DONE) { const char c = *urlPos; switch (state) { case FIND_USER: { if (c == ':') { assign = &retUrl->user; newState = FIND_PASS; } else if (c == '@') { assign = &retUrl->user; newState = FIND_HOST; } else if (c == '/') { /* not a user */ assign = &retUrl->host; newState = FIND_PATH; } else if (c == '\0') { assign = &retUrl->host; newState = DONE; } break; } case FIND_PASS: { if (c == '@') { assign = &retUrl->password; newState = FIND_HOST; } else if (c == '/') { /* not a password */ assign = &retUrl->port; newState = FIND_PATH; } else if (c == '\0') { assign = &retUrl->port; newState = DONE; } break; } case FIND_HOST: { if (c == ':') { assign = &retUrl->host; newState = FIND_PORT; } else if (c == '/') { assign = &retUrl->host; newState = FIND_PATH; } else if (c == '\0') { assign = &retUrl->host; newState = DONE; } break; } case FIND_PORT: { if (c == '/') { assign = &retUrl->port; newState = FIND_PATH; } else if (c == '\0') { assign = &retUrl->port; newState = DONE; } break; } case FIND_PATH: { if (c == '\0') { assign = &retUrl->path; newState = DONE; } break; } case DONE: break; } /* end switch */ if (assign != NULL) { *assign = assignStart; *urlPos = '\0'; assignStart = urlPos+1; state = newState; assign = NULL; } ++urlPos; } /* end while */ /* fixes for our state machine logic */ if (retUrl->user != NULL && retUrl->host == NULL && retUrl->port != NULL) { retUrl->host = retUrl->user; retUrl->user = NULL; } return true; } /* end if strncmp */ return false; } /* Parse url and set host, port, path * @param Waitress handle * @param url: protocol://host:port/path */ bool WaitressSetUrl (WaitressHandle_t *waith, const char *url) { return WaitressSplitUrl (url, &waith->url); } /* Set http proxy * @param waitress handle * @param url, e.g. http://proxy:80/ */ bool WaitressSetProxy (WaitressHandle_t *waith, const char *url) { return WaitressSplitUrl (url, &waith->proxy); } /* Callback for WaitressFetchBuf, appends received data to \0-terminated * buffer * @param received data * @param data size * @param buffer structure */ static WaitressCbReturn_t WaitressFetchBufCb (void *recvData, size_t recvDataSize, void *extraData) { char *recvBytes = recvData; WaitressFetchBufCbBuffer_t *buffer = extraData; if (buffer->data == NULL) { if ((buffer->data = malloc (sizeof (*buffer->data) * (recvDataSize + 1))) == NULL) { return WAITRESS_CB_RET_ERR; } } else { char *newbuf; if ((newbuf = realloc (buffer->data, sizeof (*buffer->data) * (buffer->pos + recvDataSize + 1))) == NULL) { free (buffer->data); return WAITRESS_CB_RET_ERR; } buffer->data = newbuf; } memcpy (buffer->data + buffer->pos, recvBytes, recvDataSize); buffer->pos += recvDataSize; buffer->data[buffer->pos] = '\0'; return WAITRESS_CB_RET_OK; } /* Fetch string. Beware! This overwrites your waith->data pointer * @param waitress handle * @param \0-terminated result buffer, malloced (don't forget to free it * yourself) */ WaitressReturn_t WaitressFetchBuf (WaitressHandle_t *waith, char **retBuffer) { WaitressFetchBufCbBuffer_t buffer; WaitressReturn_t wRet; assert (waith != NULL); assert (retBuffer != NULL); memset (&buffer, 0, sizeof (buffer)); waith->data = &buffer; waith->callback = WaitressFetchBufCb; wRet = WaitressFetchCall (waith); *retBuffer = buffer.data; return wRet; } /* poll wrapper that retries after signal interrupts, required for socksify * wrapper */ static int WaitressPollLoop (int fd, short events, int timeout) { int pollres = -1; struct pollfd sockpoll = {fd, events, 0}; assert (fd != -1); do { errno = 0; pollres = poll (&sockpoll, 1, timeout); } while (errno == EINTR || errno == EINPROGRESS || errno == EAGAIN); return pollres; } /* write () wrapper with poll () timeout * @param waitress handle * @param write buffer * @param write count bytes * @return number of written bytes or -1 on error */ static ssize_t WaitressPollWrite (void *data, const void *buf, size_t count) { int pollres = -1; ssize_t retSize; WaitressHandle_t *waith = data; assert (waith != NULL); assert (buf != NULL); /* FIXME: simplify logic */ pollres = WaitressPollLoop (waith->request.sockfd, POLLOUT, waith->timeout); if (pollres == 0) { waith->request.readWriteRet = WAITRESS_RET_TIMEOUT; return -1; } else if (pollres == -1) { waith->request.readWriteRet = WAITRESS_RET_ERR; return -1; } if ((retSize = write (waith->request.sockfd, buf, count)) == -1) { waith->request.readWriteRet = WAITRESS_RET_ERR; return -1; } waith->request.readWriteRet = WAITRESS_RET_OK; return retSize; } static WaitressReturn_t WaitressOrdinaryWrite (void *data, const char *buf, const size_t size) { WaitressHandle_t *waith = data; WaitressPollWrite (waith, buf, size); return waith->request.readWriteRet; } static WaitressReturn_t WaitressGnutlsWrite (void *data, const char *buf, const size_t size) { WaitressHandle_t *waith = data; if (gnutls_record_send (waith->request.tlsSession, buf, size) < 0) { return WAITRESS_RET_TLS_WRITE_ERR; } return waith->request.readWriteRet; } /* read () wrapper with poll () timeout * @param waitress handle * @param write to this buf, not NULL terminated * @param buffer size * @return number of read bytes or -1 on error */ static ssize_t WaitressPollRead (void *data, void *buf, size_t count) { int pollres = -1; ssize_t retSize; WaitressHandle_t *waith = data; assert (waith != NULL); assert (buf != NULL); /* FIXME: simplify logic */ pollres = WaitressPollLoop (waith->request.sockfd, POLLIN, waith->timeout); if (pollres == 0) { waith->request.readWriteRet = WAITRESS_RET_TIMEOUT; return -1; } else if (pollres == -1) { waith->request.readWriteRet = WAITRESS_RET_ERR; return -1; } if ((retSize = read (waith->request.sockfd, buf, count)) == -1) { waith->request.readWriteRet = WAITRESS_RET_READ_ERR; return -1; } waith->request.readWriteRet = WAITRESS_RET_OK; return retSize; } static WaitressReturn_t WaitressOrdinaryRead (void *data, char *buf, const size_t size, size_t *retSize) { WaitressHandle_t *waith = data; const ssize_t ret = WaitressPollRead (waith, buf, size); if (ret != -1) { assert (ret >= 0); *retSize = (size_t) ret; } return waith->request.readWriteRet; } static WaitressReturn_t WaitressGnutlsRead (void *data, char *buf, const size_t size, size_t *retSize) { WaitressHandle_t *waith = data; ssize_t ret = gnutls_record_recv (waith->request.tlsSession, buf, size); if (ret < 0) { return WAITRESS_RET_TLS_READ_ERR; } else { *retSize = ret; } return waith->request.readWriteRet; } /* send basic http authorization * @param waitress handle * @param url containing user/password * @param header name prefix */ static bool WaitressFormatAuthorization (WaitressHandle_t *waith, WaitressUrl_t *url, const char *prefix, char *writeBuf, const size_t writeBufSize) { assert (waith != NULL); assert (url != NULL); assert (prefix != NULL); assert (writeBuf != NULL); assert (writeBufSize > 0); if (url->user != NULL) { char userPass[1024], *encodedUserPass; snprintf (userPass, sizeof (userPass), "%s:%s", url->user, (url->password != NULL) ? url->password : ""); encodedUserPass = WaitressBase64Encode (userPass); assert (encodedUserPass != NULL); snprintf (writeBuf, writeBufSize, "%sAuthorization: Basic %s\r\n", prefix, encodedUserPass); free (encodedUserPass); return true; } return false; } /* get default http port if none was given */ static const char *WaitressDefaultPort (const WaitressUrl_t * const url) { assert (url != NULL); return url->port == NULL ? (url->tls ? "443" : "80") : url->port; } /* get line from string * @param string beginning/return value of last call * @return start of _next_ line or NULL if there is no next line */ static char *WaitressGetline (char * const str) { char *eol; assert (str != NULL); eol = strchr (str, '\n'); if (eol == NULL) { return NULL; } /* make lines parseable by string routines */ *eol = '\0'; if (eol-1 >= str && *(eol-1) == '\r') { *(eol-1) = '\0'; } /* skip \0 */ ++eol; assert (eol >= str); return eol; } /* identity encoding handler */ static WaitressHandlerReturn_t WaitressHandleIdentity (void *data, char *buf, const size_t size) { assert (data != NULL); assert (buf != NULL); WaitressHandle_t *waith = data; waith->request.contentReceived += size; if (waith->callback (buf, size, waith->data) == WAITRESS_CB_RET_ERR) { return WAITRESS_HANDLER_ABORTED; } else { return WAITRESS_HANDLER_CONTINUE; } } /* chunked encoding handler. buf must be \0-terminated, size does not include * trailing \0. */ static WaitressHandlerReturn_t WaitressHandleChunked (void *data, char *buf, const size_t size) { assert (data != NULL); assert (buf != NULL); WaitressHandle_t *waith = data; char *content = buf, *nextContent; assert (waith != NULL); assert (buf != NULL); while (1) { if (waith->request.chunkSize > 0) { const size_t remaining = size-(content-buf); if (remaining >= waith->request.chunkSize) { if (WaitressHandleIdentity (waith, content, waith->request.chunkSize) == WAITRESS_HANDLER_ABORTED) { return WAITRESS_HANDLER_ABORTED; } content += waith->request.chunkSize; if (content[0] == '\r' && content[1] == '\n') { content += 2; } else { return WAITRESS_HANDLER_ERR; } waith->request.chunkSize = 0; } else { if (WaitressHandleIdentity (waith, content, remaining) == WAITRESS_HANDLER_ABORTED) { return WAITRESS_HANDLER_ABORTED; } waith->request.chunkSize -= remaining; return WAITRESS_HANDLER_CONTINUE; } } if ((nextContent = WaitressGetline (content)) != NULL) { const long int chunkSize = strtol (content, NULL, 16); if (chunkSize == 0) { return WAITRESS_HANDLER_DONE; } else if (chunkSize < 0) { return WAITRESS_HANDLER_ERR; } else { waith->request.chunkSize = chunkSize; content = nextContent; } } else { return WAITRESS_HANDLER_ERR; } } assert (0); return WAITRESS_HANDLER_ERR; } /* handle http header */ static void WaitressHandleHeader (WaitressHandle_t *waith, const char * const key, const char * const value) { assert (waith != NULL); assert (key != NULL); assert (value != NULL); if (strcaseeq (key, "Content-Length")) { waith->request.contentLength = atol (value); } else if (strcaseeq (key, "Transfer-Encoding")) { if (strcaseeq (value, "chunked")) { waith->request.dataHandler = WaitressHandleChunked; } } } /* parse http status line and return status code */ static int WaitressParseStatusline (const char * const line) { char status[4] = "000"; assert (line != NULL); if (sscanf (line, "HTTP/1.%*1[0-9] %3[0-9] ", status) == 1) { return atoi (status); } return -1; } /* verify server certificate */ static int WaitressTlsVerify (const WaitressHandle_t *waith) { gnutls_session_t session = waith->request.tlsSession; unsigned int certListSize; const gnutls_datum_t *certList; gnutls_x509_crt_t cert; if (gnutls_certificate_type_get (session) != GNUTLS_CRT_X509) { return GNUTLS_E_CERTIFICATE_ERROR; } if ((certList = gnutls_certificate_get_peers (session, &certListSize)) == NULL) { return GNUTLS_E_CERTIFICATE_ERROR; } if (gnutls_x509_crt_init (&cert) != GNUTLS_E_SUCCESS) { return GNUTLS_E_CERTIFICATE_ERROR; } if (gnutls_x509_crt_import (cert, &certList[0], GNUTLS_X509_FMT_DER) != GNUTLS_E_SUCCESS) { return GNUTLS_E_CERTIFICATE_ERROR; } char fingerprint[20]; size_t fingerprintSize = sizeof (fingerprint); if (gnutls_x509_crt_get_fingerprint (cert, GNUTLS_DIG_SHA1, fingerprint, &fingerprintSize) != 0) { return GNUTLS_E_CERTIFICATE_ERROR; } if (memcmp (fingerprint, waith->tlsFingerprint, sizeof (fingerprint)) != 0) { return GNUTLS_E_CERTIFICATE_ERROR; } gnutls_x509_crt_deinit (cert); return 0; } /* Connect to server */ static WaitressReturn_t WaitressConnect (WaitressHandle_t *waith) { struct addrinfo hints, *res; int pollres; memset (&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; /* Use proxy? */ if (WaitressProxyEnabled (waith)) { if (getaddrinfo (waith->proxy.host, WaitressDefaultPort (&waith->proxy), &hints, &res) != 0) { return WAITRESS_RET_GETADDR_ERR; } } else { if (getaddrinfo (waith->url.host, WaitressDefaultPort (&waith->url), &hints, &res) != 0) { return WAITRESS_RET_GETADDR_ERR; } } if ((waith->request.sockfd = socket (res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) { freeaddrinfo (res); return WAITRESS_RET_SOCK_ERR; } /* we need shorter timeouts for connect() */ fcntl (waith->request.sockfd, F_SETFL, O_NONBLOCK); /* increase socket receive buffer */ const int sockopt = 256*1024; setsockopt (waith->request.sockfd, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof (sockopt)); /* non-blocking connect will return immediately */ connect (waith->request.sockfd, res->ai_addr, res->ai_addrlen); pollres = WaitressPollLoop (waith->request.sockfd, POLLOUT, waith->timeout); freeaddrinfo (res); if (pollres == 0) { return WAITRESS_RET_TIMEOUT; } else if (pollres == -1) { return WAITRESS_RET_ERR; } /* check connect () return value */ socklen_t pollresSize = sizeof (pollres); getsockopt (waith->request.sockfd, SOL_SOCKET, SO_ERROR, &pollres, &pollresSize); if (pollres != 0) { return WAITRESS_RET_CONNECT_REFUSED; } if (waith->url.tls) { /* set up proxy tunnel */ if (WaitressProxyEnabled (waith)) { char buf[256]; size_t size; WaitressReturn_t wRet; snprintf (buf, sizeof (buf), "CONNECT %s:%s HTTP/" WAITRESS_HTTP_VERSION "\r\n" "Host: %s:%s\r\n" "Proxy-Connection: close\r\n", waith->url.host, WaitressDefaultPort (&waith->url), waith->url.host, WaitressDefaultPort (&waith->url)); WRITE_RET (buf, strlen (buf)); /* write authorization headers */ if (WaitressFormatAuthorization (waith, &waith->proxy, "Proxy-", buf, WAITRESS_BUFFER_SIZE)) { WRITE_RET (buf, strlen (buf)); } WRITE_RET ("\r\n", 2); if ((wRet = WaitressReceiveHeaders (waith, &size)) != WAITRESS_RET_OK) { return wRet; } } if (gnutls_handshake (waith->request.tlsSession) != GNUTLS_E_SUCCESS) { return WAITRESS_RET_TLS_HANDSHAKE_ERR; } if (WaitressTlsVerify (waith) != 0) { return WAITRESS_RET_TLS_HANDSHAKE_ERR; } /* now we can talk encrypted */ waith->request.read = WaitressGnutlsRead; waith->request.write = WaitressGnutlsWrite; } return WAITRESS_RET_OK; } /* Write http header/post data to socket */ static WaitressReturn_t WaitressSendRequest (WaitressHandle_t *waith) { assert (waith != NULL); assert (waith->request.buf != NULL); const char *path = waith->url.path; char * const buf = waith->request.buf; WaitressReturn_t wRet = WAITRESS_RET_OK; if (waith->url.path == NULL) { /* avoid NULL pointer deref */ path = ""; } else if (waith->url.path[0] == '/') { /* most servers don't like "//" */ ++path; } /* send request */ if (WaitressProxyEnabled (waith) && !waith->url.tls) { snprintf (buf, WAITRESS_BUFFER_SIZE, "%s http://%s:%s/%s HTTP/" WAITRESS_HTTP_VERSION "\r\n", (waith->method == WAITRESS_METHOD_GET ? "GET" : "POST"), waith->url.host, WaitressDefaultPort (&waith->url), path); } else { snprintf (buf, WAITRESS_BUFFER_SIZE, "%s /%s HTTP/" WAITRESS_HTTP_VERSION "\r\n", (waith->method == WAITRESS_METHOD_GET ? "GET" : "POST"), path); } WRITE_RET (buf, strlen (buf)); snprintf (buf, WAITRESS_BUFFER_SIZE, "Host: %s\r\nUser-Agent: " PACKAGE "\r\nConnection: Close\r\n", waith->url.host); WRITE_RET (buf, strlen (buf)); if (waith->method == WAITRESS_METHOD_POST && waith->postData != NULL) { snprintf (buf, WAITRESS_BUFFER_SIZE, "Content-Length: %zu\r\n", strlen (waith->postData)); WRITE_RET (buf, strlen (buf)); } /* write authorization headers */ if (WaitressFormatAuthorization (waith, &waith->url, "", buf, WAITRESS_BUFFER_SIZE)) { WRITE_RET (buf, strlen (buf)); } /* don't leak proxy credentials to destination server if tls is used */ if (!waith->url.tls && WaitressFormatAuthorization (waith, &waith->proxy, "Proxy-", buf, WAITRESS_BUFFER_SIZE)) { WRITE_RET (buf, strlen (buf)); } if (waith->extraHeaders != NULL) { WRITE_RET (waith->extraHeaders, strlen (waith->extraHeaders)); } WRITE_RET ("\r\n", 2); if (waith->method == WAITRESS_METHOD_POST && waith->postData != NULL) { WRITE_RET (waith->postData, strlen (waith->postData)); } return WAITRESS_RET_OK; } /* receive response headers * @param Waitress handle * @param return unhandled bytes count in buf */ static WaitressReturn_t WaitressReceiveHeaders (WaitressHandle_t *waith, size_t *retRemaining) { char * const buf = waith->request.buf; size_t bufFilled = 0, recvSize = 0; char *nextLine = NULL, *thisLine = NULL; enum {HDRM_HEAD, HDRM_LINES, HDRM_FINISHED} hdrParseMode = HDRM_HEAD; WaitressReturn_t wRet = WAITRESS_RET_OK; /* receive answer */ nextLine = buf; while (hdrParseMode != HDRM_FINISHED) { READ_RET (buf+bufFilled, WAITRESS_BUFFER_SIZE-1 - bufFilled, &recvSize); if (recvSize == 0) { /* connection closed too early */ return WAITRESS_RET_CONNECTION_CLOSED; } bufFilled += recvSize; buf[bufFilled] = '\0'; thisLine = buf; /* split */ while (hdrParseMode != HDRM_FINISHED && (nextLine = WaitressGetline (thisLine)) != NULL) { switch (hdrParseMode) { /* Status code */ case HDRM_HEAD: switch (WaitressParseStatusline (thisLine)) { case 200: case 206: hdrParseMode = HDRM_LINES; break; case 403: return WAITRESS_RET_FORBIDDEN; break; case 404: return WAITRESS_RET_NOTFOUND; break; case -1: /* ignore invalid line */ break; default: return WAITRESS_RET_STATUS_UNKNOWN; break; } break; /* Everything else, except status code */ case HDRM_LINES: /* empty line => content starts here */ if (*thisLine == '\0') { hdrParseMode = HDRM_FINISHED; } else { /* parse header: "key: value", ignore invalid lines */ char *key = thisLine, *val; val = strchr (thisLine, ':'); if (val != NULL) { *val++ = '\0'; while (*val != '\0' && isspace ((unsigned char) *val)) { ++val; } WaitressHandleHeader (waith, key, val); } } break; default: break; } /* end switch */ thisLine = nextLine; } /* end while strchr */ memmove (buf, thisLine, bufFilled-(thisLine-buf)); bufFilled -= (thisLine-buf); } /* end while hdrParseMode */ *retRemaining = bufFilled; return wRet; } /* read response header and data */ static WaitressReturn_t WaitressReceiveResponse (WaitressHandle_t *waith) { assert (waith != NULL); assert (waith->request.buf != NULL); char * const buf = waith->request.buf; size_t recvSize = 0; WaitressReturn_t wRet = WAITRESS_RET_OK; if ((wRet = WaitressReceiveHeaders (waith, &recvSize)) != WAITRESS_RET_OK) { return wRet; } do { /* data must be \0-terminated for chunked handler */ buf[recvSize] = '\0'; switch (waith->request.dataHandler (waith, buf, recvSize)) { case WAITRESS_HANDLER_DONE: return WAITRESS_RET_OK; break; case WAITRESS_HANDLER_ERR: return WAITRESS_RET_DECODING_ERR; break; case WAITRESS_HANDLER_ABORTED: return WAITRESS_RET_CB_ABORT; break; case WAITRESS_HANDLER_CONTINUE: /* go on */ break; } READ_RET (buf, WAITRESS_BUFFER_SIZE-1, &recvSize); } while (recvSize > 0); return WAITRESS_RET_OK; } /* Receive data from host and call *callback () * @param waitress handle * @return WaitressReturn_t */ WaitressReturn_t WaitressFetchCall (WaitressHandle_t *waith) { WaitressReturn_t wRet = WAITRESS_RET_OK; /* initialize */ memset (&waith->request, 0, sizeof (waith->request)); waith->request.dataHandler = WaitressHandleIdentity; waith->request.read = WaitressOrdinaryRead; waith->request.write = WaitressOrdinaryWrite; if (waith->url.tls) { gnutls_init (&waith->request.tlsSession, GNUTLS_CLIENT); gnutls_set_default_priority (waith->request.tlsSession); gnutls_certificate_allocate_credentials (&waith->tlsCred); if (gnutls_credentials_set (waith->request.tlsSession, GNUTLS_CRD_CERTIFICATE, waith->tlsCred) != GNUTLS_E_SUCCESS) { return WAITRESS_RET_ERR; } /* set up custom read/write functions */ gnutls_transport_set_ptr (waith->request.tlsSession, (gnutls_transport_ptr_t) waith); gnutls_transport_set_pull_function (waith->request.tlsSession, WaitressPollRead); gnutls_transport_set_push_function (waith->request.tlsSession, WaitressPollWrite); } /* buffer is required for connect already */ waith->request.buf = malloc (WAITRESS_BUFFER_SIZE * sizeof (*waith->request.buf)); /* request */ if ((wRet = WaitressConnect (waith)) == WAITRESS_RET_OK) { if ((wRet = WaitressSendRequest (waith)) == WAITRESS_RET_OK) { wRet = WaitressReceiveResponse (waith); } } /* cleanup */ if (waith->url.tls) { gnutls_bye (waith->request.tlsSession, GNUTLS_SHUT_RDWR); gnutls_deinit (waith->request.tlsSession); gnutls_certificate_free_credentials (waith->tlsCred); } close (waith->request.sockfd); free (waith->request.buf); if (wRet == WAITRESS_RET_OK && waith->request.contentReceived < waith->request.contentLength) { return WAITRESS_RET_PARTIAL_FILE; } return wRet; } const char *WaitressErrorToStr (WaitressReturn_t wRet) { switch (wRet) { case WAITRESS_RET_OK: return "Everything's fine :)"; break; case WAITRESS_RET_ERR: return "Unknown."; break; case WAITRESS_RET_STATUS_UNKNOWN: return "Unknown HTTP status code."; break; case WAITRESS_RET_NOTFOUND: return "File not found."; break; case WAITRESS_RET_FORBIDDEN: return "Forbidden."; break; case WAITRESS_RET_CONNECT_REFUSED: return "Connection refused."; break; case WAITRESS_RET_SOCK_ERR: return "Socket error."; break; case WAITRESS_RET_GETADDR_ERR: return "getaddr failed."; break; case WAITRESS_RET_CB_ABORT: return "Callback aborted request."; break; case WAITRESS_RET_PARTIAL_FILE: return "Partial file."; break; case WAITRESS_RET_TIMEOUT: return "Timeout."; break; case WAITRESS_RET_READ_ERR: return "Read error."; break; case WAITRESS_RET_CONNECTION_CLOSED: return "Connection closed by remote host."; break; case WAITRESS_RET_DECODING_ERR: return "Invalid encoded data."; break; case WAITRESS_RET_TLS_WRITE_ERR: return "TLS write failed."; break; case WAITRESS_RET_TLS_READ_ERR: return "TLS read failed."; break; case WAITRESS_RET_TLS_HANDSHAKE_ERR: return "TLS handshake failed."; break; case WAITRESS_RET_TLS_TRUSTFILE_ERR: return "Loading root certificates failed."; break; default: return "No error message available."; break; } } #ifdef TEST /* test cases for libwaitress */ #include <stdio.h> #include <stdbool.h> #include <string.h> #include "waitress.h" #define streq(a,b) (strcmp(a,b) == 0) /* string equality test (memory location or content) */ static bool streqtest (const char *x, const char *y) { return (x == y) || (x != NULL && y != NULL && streq (x, y)); } /* test WaitressSplitUrl * @param tested url * @param expected user * @param expected password * @param expected host * @param expected port * @param expected path */ static void compareUrl (const char *url, const char *user, const char *password, const char *host, const char *port, const char *path) { WaitressUrl_t splitUrl; memset (&splitUrl, 0, sizeof (splitUrl)); WaitressSplitUrl (url, &splitUrl); bool userTest, passwordTest, hostTest, portTest, pathTest, overallTest; userTest = streqtest (splitUrl.user, user); passwordTest = streqtest (splitUrl.password, password); hostTest = streqtest (splitUrl.host, host); portTest = streqtest (splitUrl.port, port); pathTest = streqtest (splitUrl.path, path); overallTest = userTest && passwordTest && hostTest && portTest && pathTest; if (!overallTest) { printf ("FAILED test(s) for %s\n", url); if (!userTest) { printf ("user: %s vs %s\n", splitUrl.user, user); } if (!passwordTest) { printf ("password: %s vs %s\n", splitUrl.password, password); } if (!hostTest) { printf ("host: %s vs %s\n", splitUrl.host, host); } if (!portTest) { printf ("port: %s vs %s\n", splitUrl.port, port); } if (!pathTest) { printf ("path: %s vs %s\n", splitUrl.path, path); } } else { printf ("OK for %s\n", url); } } /* compare two strings */ void compareStr (const char *result, const char *expected) { if (!streq (result, expected)) { printf ("FAIL for %s, result was %s\n", expected, result); } else { printf ("OK for %s\n", expected); } } /* test entry point */ int main () { /* WaitressSplitUrl tests */ compareUrl ("http://www.example.com/", NULL, NULL, "www.example.com", NULL, ""); compareUrl ("http://www.example.com", NULL, NULL, "www.example.com", NULL, NULL); compareUrl ("http://www.example.com:80/", NULL, NULL, "www.example.com", "80", ""); compareUrl ("http://www.example.com:/", NULL, NULL, "www.example.com", "", ""); compareUrl ("http://:80/", NULL, NULL, "", "80", ""); compareUrl ("http://www.example.com/foobar/barbaz", NULL, NULL, "www.example.com", NULL, "foobar/barbaz"); compareUrl ("http://www.example.com:80/foobar/barbaz", NULL, NULL, "www.example.com", "80", "foobar/barbaz"); compareUrl ("http://foo:bar@www.example.com:80/foobar/barbaz", "foo", "bar", "www.example.com", "80", "foobar/barbaz"); compareUrl ("http://foo:@www.example.com:80/foobar/barbaz", "foo", "", "www.example.com", "80", "foobar/barbaz"); compareUrl ("http://foo@www.example.com:80/foobar/barbaz", "foo", NULL, "www.example.com", "80", "foobar/barbaz"); compareUrl ("http://:foo@www.example.com:80/foobar/barbaz", "", "foo", "www.example.com", "80", "foobar/barbaz"); compareUrl ("http://:@:80", "", "", "", "80", NULL); compareUrl ("http://", NULL, NULL, NULL, NULL, NULL); compareUrl ("http:///", NULL, NULL, "", NULL, ""); compareUrl ("http://foo:bar@", "foo", "bar", "", NULL, NULL); /* WaitressBase64Encode tests */ compareStr (WaitressBase64Encode ("M"), "TQ=="); compareStr (WaitressBase64Encode ("Ma"), "TWE="); compareStr (WaitressBase64Encode ("Man"), "TWFu"); compareStr (WaitressBase64Encode ("The quick brown fox jumped over the lazy dog."), "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"); compareStr (WaitressBase64Encode ("The quick brown fox jumped over the lazy dog"), "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2c="); compareStr (WaitressBase64Encode ("The quick brown fox jumped over the lazy do"), "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkbw=="); return EXIT_SUCCESS; } #endif /* TEST */
mit
arvestad/FastPhylo
src/c++/arg_utils_ext.cpp
1
1764
//-------------------------------------------------- // // File: argsutil_ext.cpp // // Author: Isaac Elias // e-mail: isaac@nada.kth.se // // cvs: $Id: arg_utils_ext.cpp,v 1.3 2006/08/23 07:40:08 isaac Exp $ // //-------------------------------------------------- #include "arg_utils_ext.hpp" #include <cstdlib> bool get_boolean_option_value(int argc, char **argv, char *option_id){ int i; i = has_option(argc,argv,option_id); if ( i ){ return true; } return false; } bool get_list_of_args(int argc, char **argv, char *option_id, std::vector<char*> &vec){ int i = HAS_OPTION(option_id); if ( i <= 0 ) return false; i++; //read all file names that come after option_id until next option. for ( ; i < argc ; i++ ){ if ( argv[i][0] != '-' ){ vec.push_back(argv[i]); } else break; } return true; } bool get_list_of_ints(int argc, char **argv, char *option_id, std::vector<int> &vec){ int i = HAS_OPTION(option_id); if ( i <= 0 ) return false; i++; //read all file names that come after option_id until next option. for ( ; i < argc ; i++ ){ if ( argv[i][0] != '-' ){ vec.push_back(atoi(argv[i])); } else break; } return true; } bool get_list_of_floats(int argc, char **argv, char *option_id, std::vector<float> &vec){ int i = HAS_OPTION(option_id); if ( i <= 0 ) return false; i++; //read all file names that come after option_id until next option. for ( ; i < argc ; i++ ){ if ( argv[i][0] != '-' ){ vec.push_back(atof(argv[i])); } else break; } return true; }
mit
SnowOnion/CodeForcesLee
thisAndThat/1c.cpp
1
4136
/** AC i've learned sth. today… 1. fmod 2. fmod 是很严格的... fmod(1.256637056,1.256637061) 返回 1.256637061 于是为了能用fmod, 窝把两个数*1e6再/1e6... 可能这导致了后面很大的浮点误差... 3. 控制浮点误差的方法 不是可以拍脑袋想的... 窝根据四五次WA的test case把判断x和y相等的函数从fabs(x-y)<1e-6改成1e-5, 2e-5,4e-5… 太胡闹了... 你萌有没有比较系统的控制浮点误差的方法... 4. 如果非要调参数 (导致总是要看中间结果), 就用IDE调试罢, 别printf注释来注释去的了- - http://codeforces.com/contest/1/submission/17893605 仆 02:19:12 板栗要是做了的话求share一发( */ #include<cstdio> #include<cmath> #define PI (4*atan(1)) bool eq_strict(double x,double y){ return fabs(x-y)<=1e-6; } bool eq(double x,double y){ return fabs(x-y)<4e-5; //// 第三次WA(case5):1:砍成6位小数再喂fmod 似乎导致eq时精度不够了... 放宽相等判定到1e-5... 害怕 // 第四次WA: 为了case20 (0.000011) 再放宽到2e-5... // 第五次WA: case40 0.000036 那就4e-5吧... 感到了调参的魅力... } bool eq0(double x){ // printf("eq0!! %lf\n",x); return eq(x,0); } // square double sq(double x){ return x*x; } // square, sum double sqs(double x,double y){ return sq(x)+sq(y); } // euclidean double dist(double x1,double y1,double x2,double y2){ return sqrt(sqs(x1-x2,y1-y2)); } double det3( double a11,double a12,double a13, double a21,double a22,double a23, double a31,double a32,double a33){ return a11*(a22*a33-a23*a32) + a21*(a32*a13-a33*a12) + a31*(a12*a23-a13*a22); } //[0,2pi) double theta(double ox,double oy,double px,double py){ if(eq_strict(ox,px)){ // 第四次WA放宽后: 窝觉得这里可以用严格版本的eq... 如果再出诡异错误就这么改 // case 40: expected: '5669.9944428', found: '5670.8426010', error = '0.0001496' // 果断改用 strict... 不对, 没有影响答案... if(py>=0) return PI/2; else return 3*PI/2; } else{ double dx=px-ox,dy=py-oy; double k=dy/dx; if(dx<=0) { return atan(k)+PI; } else { if(dy>=0){ return atan(k); } else{ return atan(k)+2*PI; // 第一次WA(case3) :1: 这里写成 +PI/2 } } } } double cut6fmod(double numer,double denom){ return fmod(((int)(numer*1e6))/1e6,((int)(denom*1e6))/1e6); } int main(){ // printf("%lf\n",fmod(1.256637,1.256637)); // printf("%lf\n",fmod(1.256637056,1.256637061)); double x1,y1,x2,y2,x3,y3; scanf("%lf%lf%lf%lf%lf%lf",&x1,&y1,&x2,&y2,&x3,&y3); // calc O and r double z1=sqs(x1,y1), z2=sqs(x2,y2), z3=sqs(x3,y3); double denominator=2*det3( x1,y1,1, x2,y2,1, x3,y3,1); double ox=det3( z1,y1,1, z2,y2,1, z3,y3,1)/denominator, oy=det3( x1,z1,1, x2,z2,1, x3,z3,1)/denominator; double r=dist(x1,y1,ox,oy); // printf("x,y,r %lf,%lf;%lf\n",ox,oy,r); // printf("theta %lf,%lf,%lf\n", // theta(ox,oy,x1,y1), // theta(ox,oy,x2,y2), // theta(ox,oy,x3,y3) // ); // printf("{{%lf,%lf},{%lf,%lf},{%lf,%lf},{%lf,%lf}}\n",x1,y1,x2,y2,x3,y3,ox,oy); double theta1=theta(ox,oy,x1,y1), theta2=theta(ox,oy,x2,y2), theta3=theta(ox,oy,x3,y3); //关心两个夹角就可以了 // 第一次WA:2:不能随便两个! 要<=PI的两个... double a=fabs(theta1-theta2), b=fabs(theta1-theta3); // printf("a,b %lf,%lf\n",a,b); if(a>PI) a=2*PI-a; if(b>PI) b=2*PI-b; // printf("a,b %.9f,%.9f\n",a,b); int i; // It's guaranteed that the number of angles in the optimal polygon is not larger than 100. for(i=3;i<=100;i++){ // printf("i %d\n",i); // printf("2*PI/i %.9f\n",2*PI/i); if(eq0(cut6fmod(a,2*PI/i)) && eq0(cut6fmod(b,2*PI/i))){ // 第二次WA(case4):1:计算精度不够, 喂进fmod会出问题... 砍成6位小数再喂 break; } } // printf("%d\n",i); // double area=i*(r*r*sin(PI/i)*cos(PI/i)); // WA5:case40:输出精度不够:边数应该数对了(吧), 尝试瞎优化一下area的精度... 不攒很多个连乘, 而是早做除法?(no) // 不! 边数数错了! case40 应该91边形. 所以继续放宽eq就好了!((( double area=i*r*r*sin(2*PI/i)/2; printf("%lf\n",area); return 0; }
mit
i3lome/failfial
src/qt/transactionrecord.cpp
1
7782
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactionrecord.h" #include "base58.h" #include "wallet.h" #include <stdint.h> /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction(const CWalletTx &wtx) { if (wtx.IsCoinBase()) { // Ensures we show generated coins / mined transactions at depth 1 if (!wtx.IsInMainChain()) { return false; } } return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx) { QList<TransactionRecord> parts; int64_t nTime = wtx.GetTxTime(); int64_t nCredit = wtx.GetCredit(true); int64_t nDebit = wtx.GetDebit(); int64_t nNet = nCredit - nDebit; uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; if (nNet > 0 || wtx.IsCoinBase()) { // // Credit // BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if(wallet->IsMine(txout)) { TransactionRecord sub(hash, nTime); CTxDestination address; sub.idx = parts.size(); // sequence number sub.credit = txout.nValue; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) { // Received by Vikingcoin Address sub.type = TransactionRecord::RecvWithAddress; sub.address = CVikingcoinAddress(address).ToString(); } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } if (wtx.IsCoinBase()) { // Generated sub.type = TransactionRecord::Generated; } parts.append(sub); } } } else { bool fAllFromMe = true; BOOST_FOREACH(const CTxIn& txin, wtx.vin) fAllFromMe = fAllFromMe && wallet->IsMine(txin); bool fAllToMe = true; BOOST_FOREACH(const CTxOut& txout, wtx.vout) fAllToMe = fAllToMe && wallet->IsMine(txout); if (fAllFromMe && fAllToMe) { // Payment to self int64_t nChange = wtx.GetChange(); parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "", -(nDebit - nChange), nCredit - nChange)); } else if (fAllFromMe) { // // Debit // int64_t nTxFee = nDebit - wtx.GetValueOut(); for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; TransactionRecord sub(hash, nTime); sub.idx = parts.size(); if(wallet->IsMine(txout)) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { // Sent to Vikingcoin Address sub.type = TransactionRecord::SendToAddress; sub.address = CVikingcoinAddress(address).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } int64_t nValue = txout.nValue; /* Add fee to first output */ if (nTxFee > 0) { nValue += nTxFee; nTxFee = 0; } sub.debit = -nValue; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0)); } } return parts; } void TransactionRecord::updateStatus(const CWalletTx &wtx) { AssertLockHeld(cs_main); // Determine transaction status // Find the block the tx is in CBlockIndex* pindex = NULL; std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock); if (mi != mapBlockIndex.end()) pindex = (*mi).second; // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()), (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx); status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0); status.depth = wtx.GetDepthInMainChain(); status.cur_num_blocks = chainActive.Height(); if (!IsFinalTx(wtx, chainActive.Height() + 1)) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = wtx.nLockTime - chainActive.Height(); } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.nLockTime; } } // For generated transactions, determine maturity else if(type == TransactionRecord::Generated) { if (wtx.GetBlocksToMaturity() > 0) { status.status = TransactionStatus::Immature; if (wtx.IsInMainChain()) { status.matures_in = wtx.GetBlocksToMaturity(); // Check if the block was requested by anyone if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) status.status = TransactionStatus::MaturesWarning; } else { status.status = TransactionStatus::NotAccepted; } } else { status.status = TransactionStatus::Confirmed; } } else { if (status.depth < 0) { status.status = TransactionStatus::Conflicted; } else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) { status.status = TransactionStatus::Offline; } else if (status.depth == 0) { status.status = TransactionStatus::Unconfirmed; } else if (status.depth < RecommendedNumConfirmations) { status.status = TransactionStatus::Confirming; } else { status.status = TransactionStatus::Confirmed; } } } bool TransactionRecord::statusUpdateNeeded() { AssertLockHeld(cs_main); return status.cur_num_blocks != chainActive.Height(); } QString TransactionRecord::getTxID() const { return formatSubTxId(hash, idx); } QString TransactionRecord::formatSubTxId(const uint256 &hash, int vout) { return QString::fromStdString(hash.ToString() + strprintf("-%03d", vout)); }
mit
MoltenPlastic/nersis
nersis/graphics/love/opengl/Mesh.cpp
1
19457
/** * Copyright (c) 2006-2015 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ // LOVE #include "Mesh.h" #include "common/Matrix.h" #include "common/Exception.h" #include "Shader.h" // C++ #include <algorithm> #include <limits> namespace love { namespace graphics { namespace opengl { static const char *getBuiltinAttribName(VertexAttribID attribid) { const char *name = ""; Shader::getConstant(attribid, name); return name; } static_assert(offsetof(Vertex, x) == sizeof(float) * 0, "Incorrect position offset in Vertex struct"); static_assert(offsetof(Vertex, s) == sizeof(float) * 2, "Incorrect texture coordinate offset in Vertex struct"); static_assert(offsetof(Vertex, r) == sizeof(float) * 4, "Incorrect color offset in Vertex struct"); static std::vector<Mesh::AttribFormat> getDefaultVertexFormat() { // Corresponds to the love::Vertex struct. std::vector<Mesh::AttribFormat> vertexformat = { {getBuiltinAttribName(ATTRIB_POS), Mesh::DATA_FLOAT, 2}, {getBuiltinAttribName(ATTRIB_TEXCOORD), Mesh::DATA_FLOAT, 2}, {getBuiltinAttribName(ATTRIB_COLOR), Mesh::DATA_BYTE, 4}, }; return vertexformat; } Mesh::Mesh(const std::vector<AttribFormat> &vertexformat, const void *data, size_t datasize, DrawMode drawmode, Usage usage) : vertexFormat(vertexformat) , vbo(nullptr) , vertexCount(0) , vertexStride(0) , vboUsedOffset(0) , vboUsedSize(0) , ibo(nullptr) , elementCount(0) , elementDataType(0) , drawMode(drawmode) , rangeMin(-1) , rangeMax(-1) { setupAttachedAttributes(); calculateAttributeSizes(); vertexCount = datasize / vertexStride; elementDataType = getGLDataTypeFromMax(vertexCount); if (vertexCount == 0) throw love::Exception("Data size is too small for specified vertex attribute formats."); vbo = new GLBuffer(datasize, data, GL_ARRAY_BUFFER, getGLBufferUsage(usage)); vertexScratchBuffer = new char[vertexStride]; } Mesh::Mesh(const std::vector<AttribFormat> &vertexformat, int vertexcount, DrawMode drawmode, Usage usage) : vertexFormat(vertexformat) , vbo(nullptr) , vertexCount((size_t) vertexcount) , vertexStride(0) , vboUsedOffset(0) , vboUsedSize(0) , ibo(nullptr) , elementCount(0) , elementDataType(getGLDataTypeFromMax(vertexcount)) , drawMode(drawmode) , rangeMin(-1) , rangeMax(-1) { if (vertexcount <= 0) throw love::Exception("Invalid number of vertices (%d).", vertexcount); setupAttachedAttributes(); calculateAttributeSizes(); size_t buffersize = vertexCount * vertexStride; vbo = new GLBuffer(buffersize, nullptr, GL_ARRAY_BUFFER, getGLBufferUsage(usage)); // Initialize the buffer's contents to 0. GLBuffer::Bind bind(*vbo); memset(vbo->map(), 0, buffersize); vbo->unmap(); vertexScratchBuffer = new char[vertexStride]; } Mesh::Mesh(const std::vector<Vertex> &vertices, DrawMode drawmode, Usage usage) : Mesh(getDefaultVertexFormat(), &vertices[0], vertices.size() * sizeof(Vertex), drawmode, usage) { } Mesh::Mesh(int vertexcount, DrawMode drawmode, Usage usage) : Mesh(getDefaultVertexFormat(), vertexcount, drawmode, usage) { } Mesh::~Mesh() { delete vbo; delete ibo; delete vertexScratchBuffer; for (const auto attrib : attachedAttributes) { if (attrib.second.mesh != this) attrib.second.mesh->release(); } } void Mesh::setupAttachedAttributes() { for (size_t i = 0; i < vertexFormat.size(); i++) { const std::string &name = vertexFormat[i].name; if (attachedAttributes.find(name) != attachedAttributes.end()) throw love::Exception("Duplicate vertex attribute name: %s", name.c_str()); attachedAttributes[name] = {this, i, true}; } } void Mesh::calculateAttributeSizes() { size_t stride = 0; for (const AttribFormat &format : vertexFormat) { // Hardware really doesn't like attributes that aren't 32 bit-aligned. if (format.type == DATA_BYTE && format.components != 4) throw love::Exception("byte vertex attributes must have 4 components."); if (format.components <= 0 || format.components > 4) throw love::Exception("Vertex attributes must have between 1 and 4 components."); // Total size in bytes of each attribute in a single vertex. attributeSizes.push_back(getAttribFormatSize(format)); stride += attributeSizes.back(); } vertexStride = stride; } size_t Mesh::getAttributeOffset(size_t attribindex) const { size_t offset = 0; for (size_t i = 0; i < attribindex; i++) offset += attributeSizes[i]; return offset; } void Mesh::setVertex(size_t vertindex, const void *data, size_t datasize) { if (vertindex >= vertexCount) throw love::Exception("Invalid vertex index: %ld", vertindex + 1); size_t offset = vertindex * vertexStride; size_t size = std::min(datasize, vertexStride); GLBuffer::Bind bind(*vbo); uint8 *bufferdata = (uint8 *) vbo->map(); memcpy(bufferdata + offset, data, size); vboUsedOffset = std::min(vboUsedOffset, offset); vboUsedSize = std::max(vboUsedSize, (offset + size) - vboUsedOffset); } size_t Mesh::getVertex(size_t vertindex, void *data, size_t datasize) { if (vertindex >= vertexCount) throw love::Exception("Invalid vertex index: %ld", vertindex + 1); size_t offset = vertindex * vertexStride; size_t size = std::min(datasize, vertexStride); // We're relying on vbo->map() returning read/write data... ew. GLBuffer::Bind bind(*vbo); const uint8 *bufferdata = (const uint8 *) vbo->map(); memcpy(data, bufferdata + offset, size); if (vboUsedSize == 0) { vboUsedOffset = std::min(vboUsedOffset, offset); vboUsedSize = std::max(vboUsedSize, (offset + size) - vboUsedOffset); } return size; } void *Mesh::getVertexScratchBuffer() { return vertexScratchBuffer; } void Mesh::setVertexAttribute(size_t vertindex, int attribindex, const void *data, size_t datasize) { if (vertindex >= vertexCount) throw love::Exception("Invalid vertex index: %ld", vertindex + 1); if (attribindex >= (int) vertexFormat.size()) throw love::Exception("Invalid vertex attribute index: %d", attribindex + 1); size_t offset = vertindex * vertexStride + getAttributeOffset(attribindex); size_t size = std::min(datasize, attributeSizes[attribindex]); GLBuffer::Bind bind(*vbo); uint8 *bufferdata = (uint8 *) vbo->map(); memcpy(bufferdata + offset, data, size); vboUsedOffset = std::min(vboUsedOffset, offset); vboUsedSize = std::max(vboUsedSize, (offset + size) - vboUsedOffset); } size_t Mesh::getVertexAttribute(size_t vertindex, int attribindex, void *data, size_t datasize) { if (vertindex >= vertexCount) throw love::Exception("Invalid vertex index: %ld", vertindex + 1); if (attribindex >= (int) vertexFormat.size()) throw love::Exception("Invalid vertex attribute index: %d", attribindex + 1); size_t offset = vertindex * vertexStride + getAttributeOffset(attribindex); size_t size = std::min(datasize, attributeSizes[attribindex]); // We're relying on vbo->map() returning read/write data... ew. GLBuffer::Bind bind(*vbo); const uint8 *bufferdata = (const uint8 *) vbo->map(); memcpy(data, bufferdata + offset, size); if (vboUsedSize == 0) { vboUsedOffset = std::min(vboUsedOffset, offset); vboUsedSize = std::max(vboUsedSize, (offset + size) - vboUsedOffset); } return size; } size_t Mesh::getVertexCount() const { return vertexCount; } size_t Mesh::getVertexStride() const { return vertexStride; } const std::vector<Mesh::AttribFormat> &Mesh::getVertexFormat() const { return vertexFormat; } Mesh::DataType Mesh::getAttributeInfo(int attribindex, int &components) const { if (attribindex < 0 || attribindex >= (int) vertexFormat.size()) throw love::Exception("Invalid vertex attribute index: %d", attribindex + 1); DataType type = vertexFormat[attribindex].type; components = vertexFormat[attribindex].components; return type; } void Mesh::setAttributeEnabled(const std::string &name, bool enable) { auto it = attachedAttributes.find(name); if (it == attachedAttributes.end()) throw love::Exception("Mesh does not have an attached vertex attribute named '%s'", name.c_str()); it->second.enabled = enable; } bool Mesh::isAttributeEnabled(const std::string &name) const { const auto it = attachedAttributes.find(name); if (it == attachedAttributes.end()) throw love::Exception("Mesh does not have an attached vertex attribute named '%s'", name.c_str()); return it->second.enabled; } void Mesh::attachAttribute(const std::string &name, Mesh *mesh) { if (mesh != this) { for (const auto &it : mesh->attachedAttributes) { // If the supplied Mesh has attached attributes of its own, then we // prevent it from being attached to avoid reference cycles. if (it.second.mesh != mesh) throw love::Exception("Cannot attach a Mesh which has attached Meshes of its own."); } } AttachedAttribute oldattrib = {}; AttachedAttribute newattrib = {}; auto it = attachedAttributes.find(name); if (it != attachedAttributes.end()) oldattrib = it->second; newattrib.mesh = mesh; newattrib.index = std::numeric_limits<size_t>::max(); newattrib.enabled = oldattrib.mesh ? oldattrib.enabled : true; // Find the index of the attribute in the mesh. for (size_t i = 0; i < mesh->vertexFormat.size(); i++) { if (mesh->vertexFormat[i].name == name) { newattrib.index = i; break; } } if (newattrib.index == std::numeric_limits<size_t>::max()) throw love::Exception("The specified mesh does not have a vertex attribute named '%s'", name.c_str()); if (newattrib.mesh != this) newattrib.mesh->retain(); attachedAttributes[name] = newattrib; if (oldattrib.mesh && oldattrib.mesh != this) oldattrib.mesh->release(); } void Mesh::flush() { { GLBuffer::Bind vbobind(*vbo); vbo->unmap(vboUsedOffset, vboUsedSize); vboUsedOffset = vboUsedSize = 0; } if (ibo != nullptr) { GLBuffer::Bind ibobind(*ibo); ibo->unmap(); } } /** * Copies index data from a vector to a mapped index buffer. **/ template <typename T> static void copyToIndexBuffer(const std::vector<uint32> &indices, GLBuffer::Mapper &buffermap, size_t maxval) { T *elems = (T *) buffermap.get(); for (size_t i = 0; i < indices.size(); i++) { if (indices[i] >= maxval) throw love::Exception("Invalid vertex map value: %d", indices[i] + 1); elems[i] = (T) indices[i]; } } void Mesh::setVertexMap(const std::vector<uint32> &map) { size_t maxval = getVertexCount(); GLenum datatype = getGLDataTypeFromMax(maxval); // Calculate the size in bytes of the index buffer data. size_t size = map.size() * getGLDataTypeSize(datatype); if (ibo && size > ibo->getSize()) { delete ibo; ibo = nullptr; } if (!ibo && size > 0) ibo = new GLBuffer(size, nullptr, GL_ELEMENT_ARRAY_BUFFER, vbo->getUsage()); elementCount = map.size(); if (!ibo || elementCount == 0) return; GLBuffer::Bind ibobind(*ibo); GLBuffer::Mapper ibomap(*ibo); // Fill the buffer with the index values from the vector. switch (datatype) { case GL_UNSIGNED_SHORT: copyToIndexBuffer<uint16>(map, ibomap, maxval); break; case GL_UNSIGNED_INT: default: copyToIndexBuffer<uint32>(map, ibomap, maxval); break; } elementDataType = datatype; } /** * Copies index data from a mapped buffer to a vector. **/ template <typename T> static void copyFromIndexBuffer(void *buffer, size_t count, std::vector<uint32> &indices) { T *elems = (T *) buffer; for (size_t i = 0; i < count; i++) indices.push_back((uint32) elems[i]); } void Mesh::getVertexMap(std::vector<uint32> &map) const { if (!ibo || elementCount == 0) return; map.clear(); map.reserve(elementCount); GLBuffer::Bind ibobind(*ibo); // We unmap the buffer in Mesh::draw, Mesh::setVertexMap, and Mesh::flush. void *buffer = ibo->map(); // Fill the vector from the buffer. switch (elementDataType) { case GL_UNSIGNED_SHORT: copyFromIndexBuffer<uint16>(buffer, elementCount, map); break; case GL_UNSIGNED_INT: default: copyFromIndexBuffer<uint32>(buffer, elementCount, map); break; } } size_t Mesh::getVertexMapCount() const { return elementCount; } void Mesh::setTexture(Texture *tex) { texture.set(tex); } void Mesh::setTexture() { texture.set(nullptr); } Texture *Mesh::getTexture() const { return texture.get(); } void Mesh::setDrawMode(DrawMode mode) { drawMode = mode; } Mesh::DrawMode Mesh::getDrawMode() const { return drawMode; } void Mesh::setDrawRange(int min, int max) { if (min < 0 || max < 0 || min > max) throw love::Exception("Invalid draw range."); rangeMin = min; rangeMax = max; } void Mesh::setDrawRange() { rangeMin = rangeMax = -1; } void Mesh::getDrawRange(int &min, int &max) const { min = rangeMin; max = rangeMax; } void Mesh::draw(float x, float y, float angle, float sx, float sy, float ox, float oy, float kx, float ky) { OpenGL::TempDebugGroup debuggroup("Mesh draw"); std::vector<GLint> attriblocations; attriblocations.reserve(attachedAttributes.size()); bool hasposattrib = false; for (const auto &attrib : attachedAttributes) { if (!attrib.second.enabled) continue; Mesh *mesh = attrib.second.mesh; const AttribFormat &format = mesh->vertexFormat[attrib.second.index]; GLint attriblocation = -1; // If the attribute is one of the LOVE-defined ones, use the constant // attribute index for it, otherwise query the index from the shader. VertexAttribID builtinattrib; if (Shader::getConstant(format.name.c_str(), builtinattrib)) attriblocation = (GLint) builtinattrib; else if (Shader::current) attriblocation = Shader::current->getAttribLocation(format.name); // The active shader might not use this vertex attribute name. if (attriblocation < 0) continue; // Needed for unmap and glVertexAttribPointer. GLBuffer::Bind vbobind(*mesh->vbo); // Make sure the buffer isn't mapped (sends data to GPU if needed.) mesh->vbo->unmap(mesh->vboUsedOffset, mesh->vboUsedSize); mesh->vboUsedOffset = mesh->vboUsedSize = 0; size_t offset = mesh->getAttributeOffset(attrib.second.index); const void *gloffset = mesh->vbo->getPointer(offset); GLenum datatype = getGLDataType(format.type); GLboolean normalized = (datatype == GL_UNSIGNED_BYTE); glEnableVertexAttribArray(attriblocation); glVertexAttribPointer(attriblocation, format.components, datatype, normalized, mesh->vertexStride, gloffset); attriblocations.push_back(attriblocation); if (attriblocation == ATTRIB_POS) hasposattrib = true; } if (!hasposattrib) { for (GLint attrib : attriblocations) glDisableVertexAttribArray(attrib); // Not supported on all platforms or GL versions at least, I believe. throw love::Exception("Mesh must have an enabled VertexPosition attribute to be drawn."); } if (texture.get()) gl.bindTexture(*(GLuint *) texture->getHandle()); else gl.bindTexture(gl.getDefaultTexture()); Matrix m(x, y, angle, sx, sy, ox, oy, kx, ky); OpenGL::TempTransform transform(gl); transform.get() *= m; gl.prepareDraw(); if (ibo && elementCount > 0) { // Use the custom vertex map (index buffer) to draw the vertices. GLBuffer::Bind ibo_bind(*ibo); // Make sure the index buffer isn't mapped (sends data to GPU if needed.) ibo->unmap(); int max = (int) elementCount - 1; if (rangeMax >= 0) max = std::min(rangeMax, max); int min = 0; if (rangeMin >= 0) min = std::min(rangeMin, max); GLenum type = elementDataType; const void *indices = ibo->getPointer(min * getGLDataTypeSize(type)); gl.drawElements(getGLDrawMode(drawMode), max - min + 1, type, indices); } else { int max = (int) vertexCount - 1; if (rangeMax >= 0) max = std::min(rangeMax, max); int min = 0; if (rangeMin >= 0) min = std::min(rangeMin, max); // Normal non-indexed drawing (no custom vertex map.) gl.drawArrays(getGLDrawMode(drawMode), min, max - min + 1); } for (GLint attrib : attriblocations) { glDisableVertexAttribArray(attrib); if (attrib == ATTRIB_COLOR) gl.setColor(gl.getColor()); } } size_t Mesh::getAttribFormatSize(const AttribFormat &format) { switch (format.type) { case DATA_BYTE: return format.components * sizeof(uint8); case DATA_FLOAT: return format.components * sizeof(float); default: return 0; } } GLenum Mesh::getGLDrawMode(DrawMode mode) { switch (mode) { case DRAWMODE_FAN: return GL_TRIANGLE_FAN; case DRAWMODE_STRIP: return GL_TRIANGLE_STRIP; case DRAWMODE_TRIANGLES: default: return GL_TRIANGLES; case DRAWMODE_POINTS: return GL_POINTS; } } GLenum Mesh::getGLDataType(DataType type) { switch (type) { case DATA_BYTE: return GL_UNSIGNED_BYTE; case DATA_FLOAT: return GL_FLOAT; default: return 0; } } GLenum Mesh::getGLDataTypeFromMax(size_t maxvalue) { if (maxvalue > LOVE_UINT16_MAX) return GL_UNSIGNED_INT; else return GL_UNSIGNED_SHORT; } size_t Mesh::getGLDataTypeSize(GLenum datatype) { switch (datatype) { case GL_UNSIGNED_BYTE: return sizeof(uint8); case GL_UNSIGNED_SHORT: return sizeof(uint16); case GL_UNSIGNED_INT: return sizeof(uint32); default: return 0; } } GLenum Mesh::getGLBufferUsage(Usage usage) { switch (usage) { case USAGE_STREAM: return GL_STREAM_DRAW; case USAGE_DYNAMIC: return GL_DYNAMIC_DRAW; case USAGE_STATIC: return GL_STATIC_DRAW; default: return 0; } } bool Mesh::getConstant(const char *in, Usage &out) { return usages.find(in, out); } bool Mesh::getConstant(Usage in, const char *&out) { return usages.find(in, out); } bool Mesh::getConstant(const char *in, Mesh::DrawMode &out) { return drawModes.find(in, out); } bool Mesh::getConstant(Mesh::DrawMode in, const char *&out) { return drawModes.find(in, out); } bool Mesh::getConstant(const char *in, DataType &out) { return dataTypes.find(in, out); } bool Mesh::getConstant(DataType in, const char *&out) { return dataTypes.find(in, out); } StringMap<Mesh::Usage, Mesh::USAGE_MAX_ENUM>::Entry Mesh::usageEntries[] = { {"stream", USAGE_STREAM}, {"dynamic", USAGE_DYNAMIC}, {"static", USAGE_STATIC}, }; StringMap<Mesh::Usage, Mesh::USAGE_MAX_ENUM> Mesh::usages(Mesh::usageEntries, sizeof(Mesh::usageEntries)); StringMap<Mesh::DrawMode, Mesh::DRAWMODE_MAX_ENUM>::Entry Mesh::drawModeEntries[] = { {"fan", DRAWMODE_FAN}, {"strip", DRAWMODE_STRIP}, {"triangles", DRAWMODE_TRIANGLES}, {"points", DRAWMODE_POINTS}, }; StringMap<Mesh::DrawMode, Mesh::DRAWMODE_MAX_ENUM> Mesh::drawModes(Mesh::drawModeEntries, sizeof(Mesh::drawModeEntries)); StringMap<Mesh::DataType, Mesh::DATA_MAX_ENUM>::Entry Mesh::dataTypeEntries[] = { {"byte", DATA_BYTE}, {"float", DATA_FLOAT}, }; StringMap<Mesh::DataType, Mesh::DATA_MAX_ENUM> Mesh::dataTypes(Mesh::dataTypeEntries, sizeof(Mesh::dataTypeEntries)); } // opengl } // graphics } // love
mit
OpenPTV/openptv-python
src_c/corresp.c
1
13394
/* Finding correspondences between particles in a set of images. References: [1] http://en.wikipedia.org/wiki/Tree_traversal#Depth-first */ #include <stdlib.h> #include <stdio.h> #include "typedefs.h" #include "globals.h" #include "epi.h" #include "btree.h" #include <optv/calibration.h> #include <optv/parameters.h> #include <optv/trafo.h> /* advance_nd_iterator() increments by 1 an iterator over n dimensions. The iterator is an array of counters, one for each dimension. Least significant dimension is on the left. Arguments: int nd - number of dimensions for this iterator. int *current - pointer to the iterator. int *count - pointer to array of the same size holding the maximal value for each dimension. Returns: 1 if the iterator has finished and was reset to zeroes, 0 otherwise. */ int advance_nd_iterator(int nd, int *current, int *count) { int d, carry = 1; for (d = 0; d < nd; d++) { current[d] += carry; if (current[d] >= count[d]) { current[d] = 0; carry = 1; } else { carry = 0; break; } } return carry; } /* correspondences() generates a list of correspondence groups. Each correspondence group is the set of target numbers identifying each one target in one image from the set, such that each target in the cgroup is an image of the same 3D particle. Arguments: frame *frm - holds all needed image data. calibration **calib - holds camera calibration information needed for getting real metric target coordinates corrected from those identified in image. Array of num_cams pointers to calibration objects. volume_par *vpar - search volume parameters, contains the search volume for epipolar lines and the measure of correspondence needed for a candidate target. Returns: n_tupel **corres_lists - a num_cams list of corres-lists, each is a list of 4-item arrays containing the index of target for each particle in the list in each of up to 4 images, in order. Each list is terminated by an n_tupel with negative .corr and garbage p[]. The top-level array is by number of particles in correspondence, so that the first element is always NULL and is there for convenience only. */ n_tupel **correspondences(frame *frm, Calibration **calib, volume_par *vpar) { int chfield = 0; /* temporary replacement of obsolete global */ int cam, part; /* loop counters */ double img_x, img_y; /* image center */ coord_2d **corrected; int part_img, epi_img; double epi_start[2], epi_end[2]; /* each for x,y coordinates of a point */ target *targ; /* shortcut to working target. */ candidate cand[maxcand]; int num_cands, cix, adj_row, adj_ix; int *accum_parts; /* accumulated number of particles through each image */ int *cam_set, *cam_subset, *subset_count, *subset_iter; candidate *adjacency; /* Adjacency matrix. */ int subset, subset_size, pow_set_size; double corr, dist; /* accumulators for set correspondences calculation. */ int is_clique, *num_matches; btree_node **match_trees; n_tupel *match; int stack_top = 0; /* For iterative tree traversal. */ btree_node *node; btree_node **stack = NULL; n_tupel **corres_lists, *flat_top; int **part_used, use_corres; int list_len; /* Hidden first element stores 0, to save some branches below. */ accum_parts = (int *) malloc(frm->num_cams * sizeof(int) + 1); accum_parts[0] = 0; accum_parts++; cam_set = (int *) malloc(frm->num_cams * sizeof(int)); /* We work on distortion-corrected image coordinates of particles. This loop does the correction. It also recycles the iteration on frm->num_cams to allocate some arrays needed later and do some related preparation. */ corrected = (coord_2d **) malloc(frm->num_cams * sizeof(coord_2d *)); for (cam = 0; cam < frm->num_cams; cam++) { corrected[cam] = (coord_2d *) malloc( frm->num_targets[cam] * sizeof(coord_2d)); accum_parts[cam] = frm->num_targets[cam]; if (cam > 0) accum_parts[cam] += accum_parts[cam - 1]; cam_set[cam] = 1 << cam; for (part = 0; part < frm->num_targets[cam]; part++) { pixel_to_metric(&corrected[cam][part].x, &corrected[cam][part].y, frm->targets[cam][part].x, frm->targets[cam][part].y, cpar); img_x = corrected[cam][part].x - calib[cam]->int_par.xh; img_y = corrected[cam][part].y - calib[cam]->int_par.yh; correct_brown_affin (img_x, img_y, calib[cam]->added_par, &corrected[cam][part].x, &corrected[cam][part].y); corrected[cam][part].pnr = frm->targets[cam][part].pnr; } /* This is expected by find_candidate_plus() */ quicksort_coord2d_x(corrected[cam], frm->num_targets[cam]); } /* Build adjacency matrix of particles in all images to each-other, using a list of candidates on the epipolar line from particle in one image to a paired image. A link exists if a cell's .corr attribute != 0. */ adjacency = (candidate *) calloc( /* calloc() zeroes memory in advance */ accum_parts[frm->num_cams - 1] * accum_parts[frm->num_cams - 1], sizeof(candidate)); for (part_img = 0; part_img < frm->num_cams - 1; part_img++) { for (epi_img = part_img + 1; epi_img < frm->num_cams; epi_img++) { /* Note that we always take the particle from the first image and candidates from the second. The reverse may give slightly different results. A better algorithm would check both, but ambition must wait for now. */ for (part = 0; part < frm->num_targets[part_img]; part++) { /* Find epipolar line on corrected image */ epi_mm(epi_img, corrected[part_img][part].x, corrected[part_img][part].y, calib[part_img]->ext_par, calib[part_img]->int_par, calib[part_img]->glass_par, calib[epi_img]->ext_par, calib[epi_img]->int_par, calib[epi_img]->glass_par, *(cpar->mm), vpar, &(epi_start[0]), &(epi_start[1]), &(epi_end[0]), &(epi_end[1])); /* Find candidates close to epipolar line */ targ = &(frm->targets[part_img][corrected[part_img][part].pnr]); find_candidate_plus (corrected[epi_img], frm->targets[epi_img], frm->num_targets[epi_img], epi_start[0], epi_start[1], epi_end[0], epi_end[1], targ->n, targ->nx, targ->ny, targ->sumg, cand, &num_cands, epi_img, vpar, cpar); /* Copy candidate information to the adjacency matrix. */ if (num_cands > maxcand) num_cands = maxcand; adj_row = (accum_parts[part_img - 1] + corrected[part_img][part].pnr) * accum_parts[frm->num_cams - 1]; for (cix = 0; cix < num_cands; cix++) { adj_ix = adj_row + accum_parts[epi_img - 1] + cand[cix].pnr; adjacency[adj_ix].pnr = cand[cix].pnr; adjacency[adj_ix].corr = cand[cix].corr; adjacency[adj_ix].tol = cand[cix].tol; } } } } /* Image coordinates not needed beyond this point. */ for (cam = 0; cam < frm->num_cams; cam++) { free(corrected[cam]); } free(corrected); /* Match candidates between sets of (n > 1) images. Iteration is over the subset of the power-set of 0 .. num_cams - 1, i.e. all combinations of 2, ..., num_cams members of the camera indices set (unordered combinations). */ match_trees = (btree_node **) calloc(frm->num_cams, sizeof(btree_node *)); num_matches = (int *) calloc(frm->num_cams, sizeof(int)); cam_subset = (int *) malloc(frm->num_cams * sizeof(int)); subset_count = (int *) malloc(frm->num_cams * sizeof(int)); subset_iter = (int *) malloc(frm->num_cams * sizeof(int)); pow_set_size = (1 << frm->num_cams) - 1; for (subset = 1; subset <= pow_set_size; subset++) { /* Prepare the subset for iterating over its particle groups. */ subset_size = 0; for (cam = 0; cam < frm->num_cams; cam++) { if (subset & cam_set[cam]) { cam_subset[subset_size] = cam; subset_iter[subset_size] = 0; subset_count[subset_size] = frm->num_targets[cam]; subset_size++; } } if (subset_size < 2) continue; do { /* For each combination of particles, one from each image in set */ is_clique = 1; corr = dist = 0; /* Check that the adjacency matrix of the subset represents a complete subgraph by checking that the upper triangle is all ones. */ for (part_img = 0; part_img < subset_size - 1; part_img++) { adj_row = (accum_parts[cam_subset[part_img] - 1] + \ subset_iter[part_img]) * accum_parts[frm->num_cams - 1]; for (epi_img = part_img + 1; epi_img < subset_size; epi_img++) { adj_ix = adj_row + accum_parts[cam_subset[epi_img] - 1] + \ subset_iter[epi_img]; if (adjacency[adj_ix].corr == 0) { is_clique = 0; break; } corr += adjacency[adj_ix].corr; dist += adjacency[adj_ix].tol; } if (!is_clique) break; } if ((!is_clique) || (corr/dist < vpar->corrmin)) continue; corr /= dist; /* record a match */ match = (n_tupel *) malloc(sizeof(n_tupel)); for (cam = 0; cam < 4; cam++) match->p[cam] = -2; /* n_tupel is hard-coded to max. 4 cameras for now. */ match->corr = corr; for (cam = 0; cam < subset_size; cam++) { match->p[cam_subset[cam]] = subset_iter[cam]; } btree_insert(&match_trees[subset_size - 1], (void *) match, corr); num_matches[subset_size - 1]++; } while (!advance_nd_iterator(subset_size, subset_iter, subset_count)); } free(adjacency); free(--accum_parts); /* Flatten trees while filtering already-used particles. Using in-order iterative btree traversal. [1] */ corres_lists = (n_tupel **) calloc(frm->num_cams, sizeof(n_tupel *)); part_used = (int **) malloc(frm->num_cams * sizeof(int *)); for (cam = 0; cam < frm->num_cams; cam++) { part_used[cam] = (int *) calloc(frm->num_targets[cam], sizeof(int)); } for (subset_size = frm->num_cams; subset_size > 1; subset_size--) { corres_lists[subset_size - 1] = (n_tupel *) calloc( num_matches[subset_size - 1] + 1, sizeof(n_tupel)); stack = (btree_node **) realloc(stack, num_matches[subset_size - 1] * sizeof(btree_node *)); flat_top = corres_lists[subset_size - 1]; corres_lists[subset_size - 1][0].corr = -1; stack_top = 0; node = match_trees[subset_size - 1]; /* Reverse in-order btree traversal [1] */ while ((stack_top != 0) || (node != NULL)) { if (node != NULL) { stack[stack_top++] = node; node = node->right; } else { node = stack[--stack_top]; /* Insert to output array only if particle wasn't taken already */ match = (n_tupel *)(node->val); use_corres = 1; for (cam = 0; cam < frm->num_cams; cam++) { if ((match->p[cam] >= 0) && part_used[cam][match->p[cam]]) { use_corres = 0; break; } } if (use_corres) { for (cam = 0; cam < 4; cam++) if (match->p[cam] >= 0) part_used[cam][match->p[cam]] = 1; *flat_top = *((n_tupel *) (node->val)); flat_top++; } node = node->left; } } /* Release unused memory and terminate lists properly */ btree_free(match_trees[subset_size - 1]); list_len = flat_top - corres_lists[subset_size - 1]; corres_lists[subset_size - 1] = (n_tupel *) realloc( corres_lists[subset_size - 1], (list_len + 1) * sizeof(n_tupel)); corres_lists[subset_size - 1][list_len].corr = -1; } free(match_trees); free(stack); free(num_matches); free(cam_set); free(cam_subset); free(subset_count); free(subset_iter); return corres_lists; }
mit
remi-daigle/invert_lobster_biophysical_particle_tracking
track/read_track.f
1
1986
include 'parameter.h' character*80 titre,colormap,anumb character*25 file,nom PARAMETER(MPART=150000) PARAMETER(MSTEP=1000) INTEGER IPOINT(MPART) REAL XP(MPART,MSTEP) REAL YP(MPART,MSTEP),ZP(MPART,MSTEP) REAL xmean,ymean,zmean,x,y,z,stage INTEGER icount,i,id real depth(m,n) character*180 filenom,clon,archive,filepath character*180 bp CALL get_command_argument(1,bp) open(98,file='../Run/bp/2_'//bp) read(98,*)filepath filepath=TRIM('tmp/'//filepath) c c--------------------------------------------------------------------- c call getarg(1,archive) print*,'archive=',archive c----------------------------------------------------------------------- !filenom=archive(1:lenstr(archive))//'.output_particles' filenom='../Run/OUT/'//bp OPEN(10,FILE=filenom,form='unformatted',status='old') do ii = 1, mpart ipoint(ii) = 0 enddo imax=0 Do read(10,end=20) i,ibid1,ibid2,ibid3,ibid4,ibid5,ibid6,x,y,z c print*,i,ipoint(i) c print*, i,ibid1,ibid2,ibid3,ibid4,ibid5,ibid6,x,y,z if(i.eq.105) print*,ibid1,ibid2,ibid3,ibid4,ibid5,ibid6 if(i.gt.imax)imax=i ipoint(i) = ipoint(i) + 1 if(ipoint(i).gt.mstep) stop 'Probleme: mstep' xp(i,ipoint(i)) = x yp(i,ipoint(i)) = y zp(i,ipoint(i)) = z endDO c----------------------------------------------------------------------- 20 continue print*,'imax=',imax print*,'ipoint(1)=',ipoint(1) c Do i=1,imax,1 call nb_char(i,anumb) open(11,file=TRIM(filepath)//'/track'//anumb(1:lenstr(anumb))) do iout=1,ipoint(i),1 call xy_to_ll_NEMO(xp(i,iout),yp(i,iout),rlon,rlat) write(11,*)rlon,rlat,zp(i,iout) enddo close(11) endDO close(98) close(10) 542 continue * end c c
mit
tanxunrong/shield
mrb/lib.c
1
1250
#include <stdlib.h> #include <stdio.h> #include <setjmp.h> #include <mruby.h> #include <mruby/irep.h> #include <mruby/error.h> #include <mruby/debug.h> #include <mruby/variable.h> mrb_value wrap_mrb_obj_value(void *p) { return mrb_obj_value(p); } mrb_value wrap_mrb_fixnum_value(mrb_int i) { return mrb_fixnum_value(i); } mrb_value wrap_mrb_float_value(mrb_state *m,mrb_float f) { return mrb_float_value(m,f); } mrb_value wrap_mrb_true_value() { return mrb_true_value(); } mrb_value wrap_mrb_false_value() { return mrb_false_value(); } mrb_value wrap_mrb_symbol_value(mrb_sym i) { return mrb_symbol_value(i); } mrb_value wrap_mrb_nil_value() { return mrb_nil_value(); } mrb_value wrap_mrb_undef_value() { return mrb_undef_value(); } mrb_value wrap_mrb_cptr_value(mrb_state *m,void *p) { return mrb_cptr_value(m,p); } void * wrap_mrb_ptr (mrb_value o) { return (o).value.p;} void *wrap_mrb_cptr (mrb_value o) { return wrap_mrb_ptr(o); } mrb_float wrap_mrb_float (mrb_value o) { return o.value.f; } mrb_int wrap_mrb_fixnum (mrb_value o) { return (o).value.i; } mrb_sym wrap_mrb_symbol (mrb_value o) { return (o).value.sym; } int wrap_mrb_type (mrb_value o) { return (o).tt; }
mit
Oxygencoin/oxygen
src/qt/addressbookpage.cpp
1
10176
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017 The OXYGEN developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/oxygen-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "bitcoingui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget* parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); #endif switch (mode) { case ForSelection: switch (tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch (tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch (tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your OXYGEN addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your OXYGEN addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction* copyAddressAction = new QAction(tr("&Copy Address"), this); QAction* copyLabelAction = new QAction(tr("Copy &Label"), this); QAction* editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if (tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel* model) { this->model = model; if (!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch (tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(selectNewAddress(QModelIndex, int, int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if (!model) return; if (!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if (indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if (!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if (dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView* table = ui->tableView; if (!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if (!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView* table = ui->tableView; if (!table->selectionModel()) return; if (table->selectionModel()->hasSelection()) { switch (tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView* table = ui->tableView; if (!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if (returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if (!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint& point) { QModelIndex index = ui->tableView->indexAt(point); if (index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex& parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if (idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
mit
Tecprog-voID/voID
src/Customs/FirstBossCentralEffectScript.cpp
1
3772
/** @file FirstBossLifeScript.cpp @brief Manage the animations for the first boss central effect. @copyright MIT License. */ #include "Customs/FirstBossCentralEffectScript.hpp" #include <cassert> const int centralImageheight = 70; const int centralImageWidth = 700; const int animationPosition = 70; const int frameCounter = 10; const int bossXPosition = 5.575263158; const int bossYPosition = 7.566428571; /** @brief Constructor for the FirstBossCentralEffectScript class. */ FirstBossCentralEffectScript::FirstBossCentralEffectScript(GameObject *owner) : Script(owner) { assert((owner != NULL) and "the owner must be equal to NULL"); } /** @brief Start the animation for the first boss central effect. */ void FirstBossCentralEffectScript::Start() { /* Creates the animations defining position the place to insert and the scene that will be inserted. */ CreateAnimations(); m_position = GetOwner()->GetPosition(); m_animator = (Animator *)GetOwner() -> GetComponent("Animator"); m_input = InputSystem::GetInstance(); auto map = SceneManager::GetInstance() -> GetScene("Gameplay") -> GetGameObject("Map"); // Checks for the map, and sets its properties. if (map) { GetOwner()->SetZoomProportion(Vector(map -> originalWidth / GetOwner() -> originalWidth, map -> originalHeight / GetOwner() -> originalHeight)); } } /** @brief Create the first boss central effect animations. */ void FirstBossCentralEffectScript::CreateAnimations() { // Image Attacks. auto firstBossCentralImage1 = new Image("assets/image/centerBoss11.png", 0, 0, centralImageWidth, centralImageheight); // Surge Animation. auto firstBossCentralAnimation1 = new Animation(GetOwner(), firstBossCentralImage1); for (int counter = 0; counter < frameCounter; counter++) { firstBossCentralAnimation1->AddFrame(new Frame(counter * animationPosition, 0, animationPosition, centralImageheight)); // Animator. auto firstBossAnimator = new Animator(GetOwner()); firstBossAnimator->AddAnimation("firstBossCentralAnimation1", firstBossCentralAnimation1); } } /** @brief Start a boss animation if he is in the scene. */ void FirstBossCentralEffectScript::ComponentUpdate() { m_boss = SceneManager::GetInstance()->GetCurrentScene()-> GetGameObject("FirstBoss"); // Checks the boss state. if (m_boss) { m_animator->PlayAnimation("firstBossCentralAnimation1"); } else { // Do nothing } } /** @brief Determine the boss position horizontally and vertically. */ void FirstBossCentralEffectScript::FixedComponentUpdate() { /* If the boss is initialized arrow to a new position for it         according to the player's position. */ // Checks the boss state. if (m_boss) { m_position->m_x = m_boss->GetPosition()->m_x + m_boss->GetWidth() / 2 - GetOwner()->GetWidth() / 2 + GetOwner()->GetWidth() / bossXPosition; m_position->m_y = m_boss->GetPosition()->m_y + m_boss->GetHeight() / 2 - GetOwner()->GetHeight() / 2 + GetOwner()->GetHeight() / bossYPosition; } else { // Do nothing } }
mit
MarkZH/Genetic_Chess
src/Genes/Gene_Pool.cpp
1
23384
#include "Genes/Gene_Pool.h" #include <vector> #include <iostream> #include <map> #include <iomanip> #include <csignal> #include <fstream> #include <cmath> #include <algorithm> #include <future> #include <thread> #include <chrono> using namespace std::chrono_literals; #include <array> #include <cstdio> #include <filesystem> #include <string> #include <numeric> #include <sstream> #include <mutex> #include "Players/Minimax_AI.h" #include "Game/Game.h" #include "Game/Board.h" #include "Game/Clock.h" #include "Game/Game_Result.h" #include "Utility/String.h" #include "Utility/Configuration.h" #include "Utility/Random.h" #include "Utility/Exceptions.h" #include "Utility/Thread_Limiter.h" namespace { const std::string stop_key = "Ctrl-c"; #ifdef _WIN32 const auto PAUSE_SIGNAL = SIGINT; #else const auto PAUSE_SIGNAL = SIGTSTP; const std::string pause_key = "Ctrl-z"; #endif // _WIN32 std::mutex pause_mutex; bool keep_going(); std::vector<Minimax_AI> load_gene_pool_file(const std::string& load_file); [[noreturn]] void throw_on_bad_still_alive_line(size_t line_number, const std::string& line); void pause_gene_pool(int); void record_the_living(const std::vector<Minimax_AI>& pool, const std::string& genome_file_name); size_t count_still_alive_lines(const std::string& genome_file_name) noexcept; int count_wins(const std::string& file_name, int id); std::vector<Minimax_AI> fill_pool(const std::string& genome_file_name, size_t gene_pool_population, const std::string& seed_ai_specification, size_t mutation_rate); void load_previous_game_stats(const std::string& game_record_file, Clock::seconds& game_time, std::array<size_t, 3>& color_wins); struct best_ai_stats { int id = 0; int wins = 0; double wins_to_beat = 0.0; }; best_ai_stats recall_previous_best_stats(const std::string& best_file_name, const std::string& game_record_file) noexcept; void update_best_stats(best_ai_stats& best_stats, const std::vector<Minimax_AI>& pool, const std::string& best_file_name) noexcept; void print_round_header(const std::vector<Minimax_AI>& pool, const std::string& genome_file_name, const std::array<size_t, 3>& color_wins, size_t round_count, size_t first_mutation_interval, size_t second_mutation_interval, size_t mutation_rate, Clock::seconds game_time, best_ai_stats best_stats) noexcept; void print_verbose_output(const std::stringstream& result_printer, const std::vector<Minimax_AI>& pool); } void gene_pool(const std::string& config_file) { signal(PAUSE_SIGNAL, pause_gene_pool); const auto config = Configuration(config_file); const auto maximum_simultaneous_games = config.as_positive_number<int>("maximum simultaneous games"); const auto gene_pool_population = config.as_positive_number<size_t>("gene pool population"); const auto roaming_distance = config.as_positive_number<double>("roaming distance"); const auto genome_file_name = config.as_text("gene pool file"); if(genome_file_name.empty()) { throw std::invalid_argument("Gene pool file name cannot be blank."); } const auto first_mutation_rate = config.as_positive_number<size_t>("first mutation rate"); const auto first_mutation_interval = config.as_positive_number<size_t>("first mutation interval"); const auto second_mutation_rate = config.as_positive_number<size_t>("second mutation rate"); const auto second_mutation_interval = config.as_positive_number<size_t>("second mutation interval"); const auto minimum_game_time = config.as_positive_time_duration<Clock::seconds>("minimum game time"); const auto maximum_game_time = config.as_positive_time_duration<Clock::seconds>("maximum game time"); if(maximum_game_time < minimum_game_time) { std::cerr << "Minimum game time = " << minimum_game_time.count() << "\n"; std::cerr << "Maximum game time = " << maximum_game_time.count() << "\n"; throw std::invalid_argument("Maximum game time must be greater than the minimum game time."); } const auto game_time_increment = config.as_time_duration<Clock::seconds>("game time increment"); const auto board = Board{config.as_text_or_default("FEN", Board().fen())}; const auto seed_ai_specification = config.as_text_or_default("seed", ""); const auto verbose_output = config.as_boolean("output volume", "verbose", "quiet"); if(config.any_unused_parameters()) { std::cout << "There were unused parameters in the file: " << config_file << '\n'; config.print_unused_parameters(); std::cout << "\nPress enter to continue or " << stop_key << " to quit ...\n"; std::cin.get(); } auto round_count = count_still_alive_lines(genome_file_name); auto pool = fill_pool(genome_file_name, gene_pool_population, seed_ai_specification, first_mutation_rate); const auto game_record_file = genome_file_name + "_games.pgn"; auto game_time = game_time_increment > 0.0s ? minimum_game_time : maximum_game_time; std::array<size_t, 3> color_wins{}; // indexed with [Winner_Color] load_previous_game_stats(game_record_file, game_time, color_wins); game_time = std::clamp(game_time, minimum_game_time, maximum_game_time); const auto best_file_name = genome_file_name + "_best_genome.txt"; auto best_stats = recall_previous_best_stats(best_file_name, game_record_file); while(keep_going()) { const auto mutation_phase = round_count++ % (first_mutation_interval + second_mutation_interval); const auto mutation_rate = mutation_phase < first_mutation_interval ? first_mutation_rate : second_mutation_rate; print_round_header(pool, genome_file_name, color_wins, round_count, first_mutation_interval, second_mutation_interval, mutation_rate, game_time, best_stats); // The shuffled pool list determines the match-ups. After shuffling the list, // adjacent AIs are matched as opponents. Random::stir_order(pool, roaming_distance); std::vector<std::future<Game_Result>> results; auto limiter = Thread_Limiter(maximum_simultaneous_games); for(size_t index = 0; index < gene_pool_population; index += 2) { limiter.ask(); const auto& white = pool[index]; const auto& black = pool[index + 1]; results.emplace_back(std::async(std::launch::async, [&]() { const auto result = play_game(board, Clock{game_time}, std::cref(white), std::cref(black), "Gene pool", "Local computer", game_record_file, false); limiter.done(); return result; })); } std::stringstream result_printer; for(size_t index = 0; index < gene_pool_population; index += 2) { auto& white = pool[index]; auto& black = pool[index + 1]; const auto result = results[index/2].get(); const auto winner = result.winner(); result_printer << white.id() << " vs " << black.id() << ": " << color_text(winner) << " (" << result.ending_reason() << ")\n"; const auto mating_winner = (winner == Winner_Color::NONE ? (Random::coin_flip() ? Winner_Color::WHITE : Winner_Color::BLACK) : winner); auto& winning_player = (mating_winner == Winner_Color::WHITE ? white : black); auto& losing_player = (winning_player.id() == white.id() ? black : white); auto offspring = Minimax_AI(white, black); offspring.mutate(mutation_rate); offspring.print(genome_file_name); losing_player = offspring; ++color_wins[static_cast<int>(winner)]; if(winner == Winner_Color::NONE) { winning_player.add_draw(); } else { winning_player.add_win(); } } record_the_living(pool, genome_file_name); update_best_stats(best_stats, pool, best_file_name); if(verbose_output) { print_verbose_output(result_printer, pool); } game_time = std::clamp(game_time + game_time_increment, minimum_game_time, maximum_game_time); } std::cout << "Done.\n"; } namespace { bool keep_going() { if(auto pause_lock = std::unique_lock(pause_mutex, std::try_to_lock); ! pause_lock.owns_lock()) { #ifdef _WIN32 return false; #else std::cout << "\nGene pool paused. Press " << pause_key << " to continue "; std::cout << "or " << stop_key << " to quit.\n"; pause_lock.lock(); #endif // _WIN32 } return true; } void pause_gene_pool(int) { static auto pause_lock = std::unique_lock(pause_mutex, std::defer_lock); if(pause_lock.owns_lock()) { pause_lock.unlock(); std::cout << "\nResuming ...\n"; } else { pause_lock.lock(); std::cout << "\nGetting to a good stopping point ...\n"; } } std::vector<Minimax_AI> fill_pool(const std::string& genome_file_name, size_t gene_pool_population, const std::string& seed_ai_specification, size_t mutation_rate) { auto pool = load_gene_pool_file(genome_file_name); if(pool.empty() && ! seed_ai_specification.empty()) { const auto seed_split = String::split(seed_ai_specification, "/"); if(seed_split.size() > 2) { throw std::runtime_error("Too many parameters in the seed configuration\nseed = " + seed_ai_specification); } const auto file_name = String::trim_outer_whitespace(seed_split.front()); const auto seed_id = seed_split.size() == 2 ? String::to_number<int>(seed_split.back()) : find_last_id(file_name); const auto seed_ai = Minimax_AI(file_name, seed_id); std::cout << "Seeding with #" << seed_ai.id() << " from file " << file_name << '\n'; pool = {seed_ai}; } const auto old_pool_size = pool.size(); pool.resize(gene_pool_population); for(auto i = old_pool_size; i < pool.size(); ++i) { pool[i].mutate(mutation_rate); pool[i].print(genome_file_name); } return pool; } void record_the_living(const std::vector<Minimax_AI>& pool, const std::string& genome_file_name) { auto ofs = std::ofstream(genome_file_name, std::ios::app); if( ! ofs) { throw std::runtime_error("Could not open gene pool file for writing: " + genome_file_name); } ofs << "\nStill Alive: "; for(const auto& ai : pool) { ofs << ai.id() << " "; } ofs << "\n\n" << std::flush; } void print_round_header(const std::vector<Minimax_AI>& pool, const std::string& genome_file_name, const std::array<size_t, 3>& color_wins, const size_t round_count, const size_t first_mutation_interval, const size_t second_mutation_interval, const size_t mutation_rate, const Clock::seconds game_time, const best_ai_stats best_stats) noexcept { std::cout << "\n=======================\n\n" << "Gene pool size: " << pool.size() << " Gene pool file name: " << genome_file_name << "\nGames: " << std::accumulate(color_wins.begin(), color_wins.end(), size_t{0}) << " White wins: " << color_wins[static_cast<int>(Winner_Color::WHITE)] << " Black wins: " << color_wins[static_cast<int>(Winner_Color::BLACK)] << " Draws: " << color_wins[static_cast<int>(Winner_Color::NONE)] << "\nRounds: " << round_count << " Mutation rate phase: " << round_count % (first_mutation_interval + second_mutation_interval) << " (" << first_mutation_interval << "/" << second_mutation_interval << ")" << "\nMutation rate: " << mutation_rate << " Game time: " << game_time.count() << " sec\n\n"; std::cout << "Wins to be recorded as best: " << best_stats.wins_to_beat << "\nBest ID : " << best_stats.id << " with " << String::pluralize(best_stats.wins, "win") << "\n"; const auto best_living = std::max_element(pool.begin(), pool.end(), [](const auto& a, const auto& b) { return a.wins() < b.wins(); }); std::cout << "Best living ID : " << best_living->id() << " with " << String::pluralize(best_living->wins(), "win") + "\n\n"; #ifdef _WIN32 std::cout << "Quit after this round: " << stop_key << " Abort: " << stop_key << " " << stop_key << "\n\n"; #else std::cout << "Pause: " << pause_key << " Abort: " << stop_key << "\n\n"; #endif // _WIN32 } void print_verbose_output(const std::stringstream& result_printer, const std::vector<Minimax_AI>& pool) { std::cout << result_printer.str(); // widths of columns for stats printout const auto largest_id = std::max_element(pool.begin(), pool.end())->id(); const auto id_column_width = int(std::to_string(largest_id).size() + 1); const auto win_column_width = 7; const auto draw_column_width = 7; // Write stat headers std::cout << "\n" << std::setw(id_column_width) << "ID" << std::setw(win_column_width) << "Wins" << std::setw(draw_column_width) << "Draws" << "\n"; // Write stats for each specimen for(const auto& ai : pool) { std::cout << std::setw(id_column_width) << ai.id() << std::setw(win_column_width) << ai.wins() << std::setw(draw_column_width) << ai.draws() << "\n"; } } void load_previous_game_stats(const std::string& game_record_file, Clock::seconds& game_time, std::array<size_t, 3>& color_wins) { auto ifs = std::ifstream(game_record_file); if( ! ifs) { return; } // Use game time from last run of this gene pool std::cout << "Searching " << game_record_file << " for last game time and stats ...\n"; for(std::string line; std::getline(ifs, line);) { line = String::trim_outer_whitespace(line); if(String::starts_with(line, "[TimeControl")) { game_time = String::to_duration<Clock::seconds>(String::extract_delimited_text(line, "\"", "\"")); } else if(String::starts_with(line, "[Result")) { auto result = String::extract_delimited_text(line, "\"", "\""); if(result == "1-0") { color_wins[static_cast<int>(Winner_Color::WHITE)]++; } else if(result == "0-1") { color_wins[static_cast<int>(Winner_Color::BLACK)]++; } else if(result == "1/2-1/2") { color_wins[static_cast<int>(Winner_Color::NONE)]++; } else { throw std::invalid_argument("Bad PGN Result line: " + line); } } } } best_ai_stats recall_previous_best_stats(const std::string& best_file_name, const std::string& game_record_file) noexcept { try { const auto best_id = find_last_id(best_file_name); std::cout << "Searching for previous best AI win counts ...\n"; auto wins = count_wins(game_record_file, best_id); return {best_id, wins, double(wins)}; } catch(...) { return {}; } } void update_best_stats(best_ai_stats& best_stats, const std::vector<Minimax_AI>& pool, const std::string& best_file_name) noexcept { // Slowly reduce the wins required to be recorded as best to allow // later AIs that are playing against a better field to be recorded. const double decay_constant = 0.99; best_stats.wins_to_beat *= decay_constant; const auto& winningest_live_ai = *std::max_element(pool.begin(), pool.end(), [](const auto& a, const auto& b) { return a.wins() < b.wins(); }); const auto win_count = winningest_live_ai.wins(); if(win_count > best_stats.wins_to_beat) { best_stats.wins_to_beat = win_count; best_stats.id = winningest_live_ai.id(); best_stats.wins = win_count; const auto temp_best_file_name = best_file_name + ".tmp"; winningest_live_ai.print(temp_best_file_name); std::filesystem::rename(temp_best_file_name, best_file_name); } } std::vector<Minimax_AI> load_gene_pool_file(const std::string& load_file) { std::ifstream ifs(load_file); if( ! ifs) { std::cout << "Starting new gene pool and writing to: " << load_file << '\n'; return {}; } std::cout << "Loading gene pool file: " << load_file << " ...\n"; std::string still_alive; size_t pool_line_number = 0; std::string pool_line; size_t line_number = 0; for(std::string line; std::getline(ifs, line);) { ++line_number; if(String::contains(line, "Still Alive")) { try { auto parse = String::split(line, ":", 1); still_alive = parse.at(1); pool_line_number = line_number; pool_line = line; } catch(...) { throw_on_bad_still_alive_line(line_number, line); } } } if(pool_line.empty()) { std::cout << "No \"Still Alive\" lines found. Starting with empty gene pool."; return {}; } const auto id_strings = String::split(still_alive); std::vector<int> ids; try { std::transform(id_strings.begin(), id_strings.end(), std::back_inserter(ids), String::to_number<int>); } catch(...) { throw_on_bad_still_alive_line(pool_line_number, pool_line); } auto sorted_ids = ids; std::sort(sorted_ids.begin(), sorted_ids.end()); std::map<int, Minimax_AI> loaded_ais; for(auto id : sorted_ids) { while(true) { const auto search_started_from_beginning_of_file = ifs.tellg() == 0; try { loaded_ais.insert_or_assign(id, Minimax_AI{ifs, id}); break; } catch(const Genome_Creation_Error& e) { if(search_started_from_beginning_of_file) { std::cerr << e.what() << load_file << "\n"; throw_on_bad_still_alive_line(pool_line_number, pool_line); } else { ifs = std::ifstream(load_file); } } } } std::vector<Minimax_AI> result; std::transform(ids.begin(), ids.end(), std::back_inserter(result), [&loaded_ais](const auto id) { return loaded_ais.at(id); }); return result; } void throw_on_bad_still_alive_line(size_t line_number, const std::string& line) { throw std::runtime_error("Invalid \"Still Alive\" line (line# " + std::to_string(line_number) + "): " + line); } size_t count_still_alive_lines(const std::string& genome_file_name) noexcept { auto genome_file = std::ifstream(genome_file_name); if( ! genome_file) { return 0; } std::cout << "Counting number of previous rounds...\n"; size_t round_count = 0; for(std::string line; std::getline(genome_file, line);) { line = String::trim_outer_whitespace(line); if(String::starts_with(line, "Still Alive")) { ++round_count; } } return round_count; } int count_wins(const std::string& file_name, int id) { auto input = std::ifstream(file_name); if( ! input) { return 0; } auto win_count = 0; for(std::string line; std::getline(input, line);) { line = String::remove_extra_whitespace(line); const auto is_white_player = String::starts_with(line, "[White"); const auto is_black_player = String::starts_with(line, "[Black"); if(is_white_player || is_black_player) { const auto number_begin = std::find_if(line.begin(), line.end(), String::isdigit); const auto number_end = std::find_if_not(std::next(number_begin), line.end(), String::isdigit); const auto player_id = String::to_number<int>({number_begin, number_end}); if(player_id == id) { while(std::getline(input, line)) { line = String::remove_extra_whitespace(line); if(String::starts_with(line, "[Result")) { if((is_white_player && String::contains(line, "1-0")) || (is_black_player && String::contains(line, "0-1"))) { ++win_count; } break; } } } } } return win_count; } }
mit
vovkos/jancy
src/jnc_ct/jnc_ct_TypeMgr/jnc_ct_Type.cpp
1
26820
//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #include "pch.h" #include "jnc_ct_Type.h" #include "jnc_ct_Decl.h" #include "jnc_ct_Module.h" #include "jnc_Variant.h" #include "jnc_rt_GcHeap.h" namespace jnc { namespace ct { //.............................................................................. TypeKind getInt32TypeKind(int32_t integer) { return integer >= INT8_MIN && integer <= INT8_MAX ? TypeKind_Int8 : (uint32_t)integer <= UINT8_MAX ? TypeKind_Int8_u : integer >= INT16_MIN && integer <= INT16_MAX ? TypeKind_Int16 : (uint32_t)integer <= UINT16_MAX ? TypeKind_Int16_u : TypeKind_Int32; } TypeKind getInt32TypeKind_u(uint32_t integer) { return integer <= INT8_MAX ? TypeKind_Int8 : integer <= UINT8_MAX ? TypeKind_Int8_u : integer <= INT16_MAX ? TypeKind_Int16 : integer <= UINT16_MAX ? TypeKind_Int16_u : integer <= INT32_MAX ? TypeKind_Int32 : TypeKind_Int32_u; } TypeKind getInt64TypeKind(int64_t integer) { return integer >= INT8_MIN && integer <= INT8_MAX ? TypeKind_Int8 : (uint64_t)integer <= UINT8_MAX ? TypeKind_Int8_u : integer >= INT16_MIN && integer <= INT16_MAX ? TypeKind_Int16 : (uint64_t)integer <= UINT16_MAX ? TypeKind_Int16_u : integer >= INT32_MIN && integer <= INT32_MAX ? TypeKind_Int32 : (uint64_t)integer <= UINT32_MAX ? TypeKind_Int32_u : TypeKind_Int64; } TypeKind getInt64TypeKind_u(uint64_t integer) { return integer <= INT8_MAX ? TypeKind_Int8 : integer <= UINT8_MAX ? TypeKind_Int8_u : integer <= INT16_MAX ? TypeKind_Int16 : integer <= UINT16_MAX ? TypeKind_Int16_u : integer <= INT32_MAX ? TypeKind_Int32 : integer <= UINT32_MAX ? TypeKind_Int32_u : integer <= INT64_MAX ? TypeKind_Int64 : TypeKind_Int64_u; } //.............................................................................. sl::String getLlvmTypeString(llvm::Type* llvmType) { std::string s; llvm::raw_string_ostream stream(s); llvmType->print(stream); return stream.str().c_str(); } //.............................................................................. const char* getPtrTypeFlagString(PtrTypeFlag flag) { static const char* stringTable[] = { "safe", // PtrTypeFlag_Safe = 0x0010000 "const", // PtrTypeFlag_Const = 0x0020000 "readonly", // PtrTypeFlag_ReadOnly = 0x0040000 "cmut", // PtrTypeFlag_CMut = 0x0080000 "volatile", // PtrTypeFlag_Volatile = 0x0100000 "event", // PtrTypeFlag_Event = 0x0200000 "dualevent", // PtrTypeFlag_DualEvent = 0x0400000 "bindable", // PtrTypeFlag_Bindable = 0x0800000 "autoget", // PtrTypeFlag_AutoGet = 0x1000000 }; size_t i = sl::getLoBitIdx32(flag >> 12); return i < countof(stringTable) ? stringTable[i] : "undefined-ptr-type-flag"; } sl::String getPtrTypeFlagString(uint_t flags) { sl::String string; if (flags & PtrTypeFlag_Safe) string = "safe "; if (flags & PtrTypeFlag_Const) string += "const "; else if (flags & PtrTypeFlag_ReadOnly) string += "readonly "; else if (flags & PtrTypeFlag_CMut) string += "cmut "; if (flags & PtrTypeFlag_Volatile) string += "volatile "; if (flags & PtrTypeFlag_Event) string += "event "; else if (flags & PtrTypeFlag_DualEvent) string += "dualevent "; if (flags & PtrTypeFlag_Bindable) string += "bindable "; if (flags & PtrTypeFlag_AutoGet) string += "autoget "; if (!string.isEmpty()) string.chop(1); return string; } sl::String getPtrTypeFlagSignature(uint_t flags) { sl::String signature; if (flags & PtrTypeFlag_Safe) signature += 's'; if (flags & PtrTypeFlag_Const) signature += 'c'; else if (flags & PtrTypeFlag_ReadOnly) signature += 'r'; else if (flags & PtrTypeFlag_CMut) signature += 'm'; if (flags & PtrTypeFlag_Volatile) signature += 'v'; if (flags & PtrTypeFlag_Event) signature += 'e'; else if (flags & PtrTypeFlag_DualEvent) signature += 'd'; return signature; } uint_t getPtrTypeFlagsFromModifiers(uint_t modifiers) { uint_t flags = 0; if (modifiers & TypeModifier_Safe) flags |= PtrTypeFlag_Safe; if (modifiers & TypeModifier_Volatile) flags |= PtrTypeFlag_Volatile; if (modifiers & TypeModifier_Const) flags |= PtrTypeFlag_Const; else if (modifiers & TypeModifier_ReadOnly) flags |= PtrTypeFlag_ReadOnly; else if (modifiers & TypeModifier_CMut) flags |= PtrTypeFlag_CMut; if (modifiers & TypeModifier_Event) flags |= PtrTypeFlag_Event; return flags; } //.............................................................................. Type::Type() { m_itemKind = ModuleItemKind_Type; m_typeKind = TypeKind_Void; m_stdType = (StdType)-1; m_size = 0; m_alignment = 0; m_llvmType = NULL; m_typeVariable = NULL; m_typeStringTuple = NULL; m_simplePropertyTypeTuple = NULL; m_functionArgTuple = NULL; m_dataPtrTypeTuple = NULL; m_dualTypeTuple = NULL; } Type::~Type() { if (m_typeStringTuple) AXL_MEM_DELETE(m_typeStringTuple); } TypeStringTuple* Type::getTypeStringTuple() { if (!m_typeStringTuple) m_typeStringTuple = AXL_MEM_NEW(TypeStringTuple); return m_typeStringTuple; } const sl::String& Type::getTypeString() { TypeStringTuple* tuple = getTypeStringTuple(); if (!tuple->m_typeString.isEmpty()) return tuple->m_typeString; prepareTypeString(); ASSERT(!tuple->m_typeStringPrefix.isEmpty()); tuple->m_typeString = tuple->m_typeStringPrefix; if (!tuple->m_typeStringSuffix.isEmpty()) { tuple->m_typeString += ' '; tuple->m_typeString += tuple->m_typeStringSuffix; } return tuple->m_typeString; } const sl::String& Type::getTypeStringPrefix() { TypeStringTuple* tuple = getTypeStringTuple(); if (tuple->m_typeStringPrefix.isEmpty()) { prepareTypeString(); ASSERT(!tuple->m_typeStringPrefix.isEmpty()); } return tuple->m_typeStringPrefix; } const sl::String& Type::getTypeStringSuffix() { TypeStringTuple* tuple = getTypeStringTuple(); if (tuple->m_typeStringPrefix.isEmpty()) { // this is not a typo, we still need to check prefix string! prepareTypeString(); ASSERT(!tuple->m_typeStringPrefix.isEmpty()); } return tuple->m_typeStringSuffix; } const sl::String& Type::getDoxyTypeString() { TypeStringTuple* tuple = getTypeStringTuple(); if (tuple->m_doxyTypeString.isEmpty()) { prepareDoxyTypeString(); ASSERT(!tuple->m_doxyTypeString.isEmpty()); } return tuple->m_doxyTypeString; } const sl::String& Type::getDoxyLinkedTextPrefix() { TypeStringTuple* tuple = getTypeStringTuple(); if (tuple->m_doxyLinkedTextPrefix.isEmpty()) { prepareDoxyLinkedText(); ASSERT(!tuple->m_doxyLinkedTextPrefix.isEmpty()); } return tuple->m_doxyLinkedTextPrefix; } const sl::String& Type::getDoxyLinkedTextSuffix() { TypeStringTuple* tuple = getTypeStringTuple(); if (tuple->m_doxyLinkedTextPrefix.isEmpty()) { // this is not a typo, we still need to check prefix string! prepareDoxyLinkedText(); ASSERT(!tuple->m_doxyLinkedTextPrefix.isEmpty()); } return tuple->m_doxyLinkedTextSuffix; } Value Type::getUndefValue() { llvm::Value* llvmValue = llvm::UndefValue::get(getLlvmType()); return Value(llvmValue, this); } Value Type::getZeroValue() { AXL_TODO("Type::getZeroValue () probably should return ValueKind_Const") if (!m_module->hasCodeGen()) { Value value; value.createConst(NULL, this); return value; } llvm::Value* llvmValue = llvm::Constant::getNullValue(getLlvmType()); return Value(llvmValue, this); } Value Type::getErrorCodeValue() { uint_t typeKindFlags = getTypeKindFlags(); ASSERT(typeKindFlags & TypeKindFlag_ErrorCode); if (m_typeKind == TypeKind_Bool || !(typeKindFlags & TypeKindFlag_Integer)) return getZeroValue(); Value errorCodeValue; uint64_t minusOne = -1; errorCodeValue.createConst(&minusOne, this); return errorCodeValue; } ArrayType* Type::getArrayType(size_t elementCount) { return m_module->m_typeMgr.getArrayType(this, elementCount); } DataPtrType* Type::getDataPtrType( TypeKind typeKind, DataPtrTypeKind ptrTypeKind, uint_t flags ) { return m_module->m_typeMgr.getDataPtrType(this, typeKind, ptrTypeKind, flags); } FunctionArg* Type::getSimpleFunctionArg(uint_t ptrTypeFlags) { return m_module->m_typeMgr.getSimpleFunctionArg(this, ptrTypeFlags); } bool Type::prepareImports() { ASSERT(!(m_flags & (ModuleItemFlag_LayoutReady | TypeFlag_NoImports))); bool result = resolveImports(); if (!result) return false; m_flags |= TypeFlag_NoImports; return true; } bool Type::prepareLayout() { ASSERT(!(m_flags & ModuleItemFlag_LayoutReady)); if (m_flags & ModuleItemFlag_InCalcLayout) { ModuleItemDecl* decl = getDecl(); ASSERT(decl); // recursion is only possible with named types err::setFormatStringError("can't calculate layout of '%s' due to recursion", decl->getQualifiedName().sz()); return false; } m_flags |= ModuleItemFlag_InCalcLayout; bool result = calcLayout(); if (!result) { m_flags &= ~ModuleItemFlag_InCalcLayout; return false; } m_flags |= ModuleItemFlag_LayoutReady; // no need to clear ModuleItemFlag_InCalcLayout return true; } void Type::prepareTypeString() { static const char* stringTable[TypeKind__PrimitiveTypeCount] = { "void", "variant", "bool", "char", "unsigned char", "short", "unsigned short", "int", "unsigned int", "long", "unsigned long", "bigendian short", "bigendian unsigned short", "bigendian int", "bigendian unsigned int", "bigendian long", "bigendian unsigned long", "float", "double", }; ASSERT(m_typeKind < TypeKind__PrimitiveTypeCount); getTypeStringTuple()->m_typeStringPrefix = stringTable[m_typeKind]; } void Type::prepareDoxyLinkedText() { TypeStringTuple* tuple = getTypeStringTuple(); tuple->m_doxyLinkedTextPrefix = getTypeStringPrefix(); tuple->m_doxyLinkedTextSuffix = getTypeStringSuffix(); } void Type::prepareDoxyTypeString() { TypeStringTuple* tuple = getTypeStringTuple(); tuple->m_doxyTypeString = "<type>"; tuple->m_doxyTypeString += getDoxyLinkedTextPrefix(); tuple->m_doxyTypeString += "</type>\n"; AXL_TODO("add compile-option for whether to use doxy-linked-text instead of plain-text") sl::String suffix = getTypeStringSuffix(); if (!suffix.isEmpty()) { // suffix should be ready by now tuple->m_doxyTypeString += "<argsstring>"; tuple->m_doxyTypeString += suffix; tuple->m_doxyTypeString += "</argsstring>\n"; } } void Type::prepareSignature() { static const char* primitiveTypeSignatureTable[TypeKind_Double + 1] = { "v", // TypeKind_Void, "z", // TypeKind_Variant, "b", // TypeKind_Bool, "is1", // TypeKind_Int8, "iu1", // TypeKind_Int8_u, "is2", // TypeKind_Int16, "iu2", // TypeKind_Int16_u, "is4", // TypeKind_Int32, "iu4", // TypeKind_Int32_u, "is8", // TypeKind_Int64, "iu8", // TypeKind_Int64_u, "ibs2", // TypeKind_Int16_be, "ibu2", // TypeKind_Int16_beu, "ibs4", // TypeKind_Int32_be, "ibu4", // TypeKind_Int32_beu, "ibs8", // TypeKind_Int64_be, "ibu8", // TypeKind_Int64_beu, "f4", // TypeKind_Float, "f8", // TypeKind_Double, }; if ((size_t)m_typeKind <= countof(primitiveTypeSignatureTable)) m_signature = primitiveTypeSignatureTable[m_typeKind]; else ASSERT(false); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . llvm::Type* getLlvmType_void(Module* module) { return llvm::Type::getVoidTy(*module->getLlvmContext()); } llvm::Type* getLlvmType_variant(Module* module) { return module->m_typeMgr.getStdType(StdType_VariantStruct)->getLlvmType(); } llvm::Type* getLlvmType_bool(Module* module) { return llvm::Type::getInt1Ty(*module->getLlvmContext()); } llvm::Type* getLlvmType_int8(Module* module) { return llvm::Type::getInt8Ty(*module->getLlvmContext()); } llvm::Type* getLlvmType_int16(Module* module) { return llvm::Type::getInt16Ty(*module->getLlvmContext()); } llvm::Type* getLlvmType_int32(Module* module) { return llvm::Type::getInt32Ty(*module->getLlvmContext()); } llvm::Type* getLlvmType_int64(Module* module) { return llvm::Type::getInt64Ty(*module->getLlvmContext()); } llvm::Type* getLlvmType_float(Module* module) { return llvm::Type::getFloatTy(*module->getLlvmContext()); } llvm::Type* getLlvmType_double(Module* module) { return llvm::Type::getDoubleTy(*module->getLlvmContext()); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . void Type::prepareLlvmType() { ASSERT(!m_llvmType && (size_t)m_typeKind < TypeKind__PrimitiveTypeCount); typedef llvm::Type* GetLlvmTypeFunc(Module* module); GetLlvmTypeFunc* getLlvmTypeFuncTable[TypeKind__PrimitiveTypeCount] = { getLlvmType_void, // TypeKind_Void getLlvmType_variant, // TypeKind_Variant getLlvmType_bool, // TypeKind_Bool getLlvmType_int8, // TypeKind_Int8 getLlvmType_int8, // TypeKind_Int8_u getLlvmType_int16, // TypeKind_Int16 getLlvmType_int16, // TypeKind_Int16_u getLlvmType_int32, // TypeKind_Int32 getLlvmType_int32, // TypeKind_Int32_u getLlvmType_int64, // TypeKind_Int64 getLlvmType_int64, // TypeKind_Int64_u getLlvmType_int16, // TypeKind_Int16_be getLlvmType_int16, // TypeKind_Int16_beu getLlvmType_int32, // TypeKind_Int32_be getLlvmType_int32, // TypeKind_Int32_beu getLlvmType_int64, // TypeKind_Int64_be getLlvmType_int64, // TypeKind_Int64_beu getLlvmType_float, // TypeKind_Float getLlvmType_double, // TypeKind_Double }; m_llvmType = getLlvmTypeFuncTable[(size_t)m_typeKind](m_module); } void Type::prepareLlvmDiType() { ASSERT(m_typeKind && m_typeKind < TypeKind__PrimitiveTypeCount); if (m_typeKind == TypeKind_Variant) { m_llvmDiType = m_module->m_typeMgr.getStdType(StdType_VariantStruct)->getLlvmDiType(); return; } struct LlvmDiType { const char* m_name; uint_t m_code; size_t m_size; }; LlvmDiType llvmDiTypeTable[TypeKind__PrimitiveTypeCount] = { { 0 }, // TypeKind_Void, { 0 }, // TypeKind_Variant, // TypeKind_Bool, { "bool", llvm::dwarf::DW_ATE_boolean, 1, }, // TypeKind_Int8, { "char", llvm::dwarf::DW_ATE_signed_char, 1, }, // TypeKind_Int8_u, { "unsigned char", llvm::dwarf::DW_ATE_unsigned_char, 1, }, // TypeKind_Int16, { "int16", llvm::dwarf::DW_ATE_signed, 2, }, // TypeKind_Int16_u, { "unsigned int16", llvm::dwarf::DW_ATE_unsigned, 2, }, // TypeKind_Int32, { "int", llvm::dwarf::DW_ATE_signed, 4, }, // TypeKind_Int32_u, { "unsigned int", llvm::dwarf::DW_ATE_unsigned, 4, }, // TypeKind_Int64, { "unsigned int64", llvm::dwarf::DW_ATE_signed, 8, }, // TypeKind_Int64_u, { "unsigned int64", llvm::dwarf::DW_ATE_unsigned, 8, }, // TypeKind_Int16_be, { "bigendian int16", llvm::dwarf::DW_ATE_signed, 2, }, // TypeKind_Int16_beu, { "unsigned bigendian int16", llvm::dwarf::DW_ATE_unsigned, 2, }, // TypeKind_Int32_be, { "bigendian int16", llvm::dwarf::DW_ATE_signed, 4, }, // TypeKind_Int32_beu, { "unsigned bigendian int16", llvm::dwarf::DW_ATE_unsigned, 4, }, // TypeKind_Int64_be, { "bigendian int16", llvm::dwarf::DW_ATE_signed, 8, }, // TypeKind_Int64_beu, { "unsigned bigendian int64", llvm::dwarf::DW_ATE_unsigned, 8, }, // TypeKind_Float, { "float", llvm::dwarf::DW_ATE_float, 4, }, // TypeKind_Double, { "double", llvm::dwarf::DW_ATE_float, 8, }, }; LlvmDiType* diType = &llvmDiTypeTable[m_typeKind]; ASSERT(diType->m_size); m_llvmDiType = m_module->m_llvmDiBuilder.createBasicType( diType->m_name, diType->m_size, diType->m_size, diType->m_code ); } void Type::prepareSimpleTypeVariable(StdType stdType) { ASSERT(!m_typeVariable && m_module->getCompileState() < ModuleCompileState_Compiled); sl::String qualifiedName = "jnc.g_type_" + getSignature(); Type* type = m_module->m_typeMgr.getStdType(stdType); sl::BoxList<Token> constructor; Token* token = constructor.insertTail().p(); token->m_token = TokenKind_Integer; token->m_data.m_int64_u = (intptr_t)this; m_typeVariable = m_module->m_variableMgr.createVariable( StorageKind_Static, sl::String(), qualifiedName, type, 0, &constructor ); m_typeVariable->m_parentNamespace = m_module->m_namespaceMgr.getStdNamespace(StdNamespace_Jnc); m_typeVariable->m_flags |= VariableFlag_Type; bool result = m_module->m_variableMgr.allocateVariable(m_typeVariable); ASSERT(result); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sl::String getValueString_void( const void* p, const char* formatSpec ) { return "void"; } sl::String getValueString_variant( const void* p, const char* formatSpec ) { return ((Variant*)p)->m_type ? ((Variant*)p)->m_type->getValueString(p, formatSpec) : "<empty-variant>"; } sl::String getValueString_bool( const void* p, const char* formatSpec ) { return formatSpec ? sl::formatString(formatSpec, *(bool*)p) : *(bool*)p ? sl::String("true") : sl::String("false"); } sl::String getValueString_int8( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%d", *(int8_t*)p); } sl::String getValueString_int8_u( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%u", *(uint8_t*)p); } sl::String getValueString_int16( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%d", *(int16_t*)p); } sl::String getValueString_int16_u( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%u", *(uint16_t*)p); } sl::String getValueString_int32( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%d", *(int32_t*)p); } sl::String getValueString_int32_u( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%u", *(uint32_t*)p); } sl::String getValueString_int64( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%lld", *(int64_t*)p); } sl::String getValueString_int64_u( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%llu", *(uint64_t*)p); } sl::String getValueString_int16_be( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%d", (int16_t)sl::swapByteOrder16(*(uint16_t*)p)); } sl::String getValueString_int16_beu( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%u", (uint16_t)sl::swapByteOrder16(*(uint16_t*)p)); } sl::String getValueString_int32_be( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%d", (int32_t)sl::swapByteOrder32(*(uint32_t*)p)); } sl::String getValueString_int32_beu( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%u", (uint32_t)sl::swapByteOrder32(*(uint32_t*)p)); } sl::String getValueString_int64_be( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%lld", (int64_t)sl::swapByteOrder64(*(uint64_t*)p)); } sl::String getValueString_int64_beu( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%llu", (uint64_t)sl::swapByteOrder64(*(uint64_t*)p)); } sl::String getValueString_float( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%f", *(float*)p); } sl::String getValueString_double( const void* p, const char* formatSpec ) { return sl::formatString(formatSpec ? formatSpec : "%f", *(double*)p); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sl::String Type::getValueString( const void* p, const char* formatSpec ) { typedef sl::String GetValueStringFunc( const void* p, const char* formatSpec ); GetValueStringFunc* getValueStringFuncTable[TypeKind__PrimitiveTypeCount] = { getValueString_void, // TypeKind_Void getValueString_variant, // TypeKind_Variant getValueString_bool, // TypeKind_Bool getValueString_int8, // TypeKind_Int8 getValueString_int8_u, // TypeKind_Int8_u getValueString_int16, // TypeKind_Int16 getValueString_int16_u, // TypeKind_Int16_u getValueString_int32, // TypeKind_Int32 getValueString_int32_u, // TypeKind_Int32_u getValueString_int64, // TypeKind_Int64 getValueString_int64_u, // TypeKind_Int64_u getValueString_int16_be, // TypeKind_Int16_be getValueString_int16_beu, // TypeKind_Int16_beu getValueString_int32_be, // TypeKind_Int32_be getValueString_int32_beu, // TypeKind_Int32_beu getValueString_int64_be, // TypeKind_Int64_be getValueString_int64_beu, // TypeKind_Int64_beu getValueString_float, // TypeKind_Float getValueString_double, // TypeKind_Double }; return (size_t)m_typeKind < TypeKind__PrimitiveTypeCount ? getValueStringFuncTable[(size_t)m_typeKind](p, formatSpec) : "<unsupported-type>"; } void Type::markGcRoots( const void* p, rt::GcHeap* gcHeap ) { ASSERT(m_typeKind == TypeKind_Variant); gcHeap->markVariant(*(Variant*)p); } //.............................................................................. void NamedType::prepareDoxyLinkedText() { if (!m_parentUnit || m_parentUnit->getLib()) { // don't reference imported libraries Type::prepareDoxyLinkedText(); return; } dox::Block* doxyBlock = m_module->m_doxyHost.getItemBlock(this); sl::String refId = doxyBlock->getRefId(); getTypeStringTuple()->m_doxyLinkedTextPrefix.format( "<ref refid=\"%s\">%s</ref>", refId.sz(), getQualifiedName().sz() ); } //.............................................................................. Typedef::Typedef() { m_itemKind = ModuleItemKind_Typedef; m_type = NULL; m_shadowType = NULL; } TypedefShadowType* Typedef::getShadowType() { if (!m_shadowType) m_shadowType = m_module->m_typeMgr.createTypedefShadowType(this); return m_shadowType; } bool Typedef::generateDocumentation( const sl::StringRef& outputDir, sl::String* itemXml, sl::String* indexXml ) { bool result = m_type->ensureNoImports(); if (!result) return false; dox::Block* doxyBlock = m_module->m_doxyHost.getItemBlock(this); itemXml->format( "<memberdef kind='typedef' id='%s'>\n" "<name>%s</name>\n", doxyBlock->getRefId().sz(), m_name.sz() ); itemXml->append(m_type->getDoxyTypeString()); itemXml->append(doxyBlock->getImportString()); itemXml->append(doxyBlock->getDescriptionString()); itemXml->append(getDoxyLocationString()); itemXml->append("</memberdef>\n"); return true; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bool TypedefShadowType::calcLayout() { Type* type = m_typedef->getType(); bool result = type->ensureLayout(); if (!result) return false; m_flags |= (type->getFlags() & TypeFlag_Pod); m_size = type->getSize(); m_alignment = type->getAlignment(); return true; } void TypedefShadowType::prepareDoxyLinkedText() { Unit* unit = m_typedef->getParentUnit(); if (!unit || unit->getLib()) { // don't reference imported libraries Type::prepareDoxyLinkedText(); return; } dox::Block* doxyBlock = m_module->m_doxyHost.getItemBlock(m_typedef); sl::String refId = doxyBlock->getRefId(); getTypeStringTuple()->m_doxyLinkedTextPrefix.format( "<ref refid=\"%s\">%s</ref>", refId.sz(), getQualifiedName().sz() ); } //.............................................................................. Type* getSimpleType( TypeKind typeKind, Module* module ) { return module->m_typeMgr.getPrimitiveType(typeKind); } Type* getSimpleType( StdType stdType, Module* module ) { return module->m_typeMgr.getStdType(stdType); } Type* getDirectRefType( Type* type, uint_t ptrTypeFlags ) { return type->getTypeKind() == TypeKind_Class ? (Type*)((ClassType*)type)->getClassPtrType( TypeKind_ClassRef, ClassPtrTypeKind_Normal, ptrTypeFlags ) : (Type*)type->getDataPtrType( TypeKind_DataRef, DataPtrTypeKind_Lean, ptrTypeFlags ); } //.............................................................................. bool isDisposableType(Type* type) { if (type->getTypeKindFlags() & TypeKindFlag_ClassPtr) type = ((ClassPtrType*)type)->getTargetType(); else if (type->getTypeKindFlags() & TypeKindFlag_DataPtr) type = ((DataPtrType*)type)->getTargetType(); if (!(type->getTypeKindFlags() & TypeKindFlag_Derivable)) return false; DerivableType* derivableType = (DerivableType*)type; FindModuleItemResult findResult = derivableType->findItem("dispose"); if (!findResult.m_item) return false; FunctionType* functionType; ModuleItem* item = findResult.m_item; ModuleItemKind itemKind = item->getItemKind(); switch (itemKind) { case ModuleItemKind_Function: functionType = ((Function*)item)->getType(); break; case ModuleItemKind_Alias: functionType = (FunctionType*)((Alias*)item)->getType(); if (functionType->getTypeKind() != TypeKind_Function) { if (functionType->getTypeKind() == TypeKind_Void) { // alias was declared like this: alias dispose = close; // since we don't do strict checks now anyway, let it go break; } return false; } break; default: return false; } AXL_TODO("double-check function type - must be thiscall, no arguments") return true; } bool isSafePtrType(Type* type) { return (type->getTypeKindFlags() & TypeKindFlag_Ptr) && (type->getFlags() & PtrTypeFlag_Safe); } bool isWeakPtrType(Type* type) { TypeKind typeKind = type->getTypeKind(); switch (typeKind) { case TypeKind_ClassPtr: return ((ClassPtrType*)type)->getPtrTypeKind() == ClassPtrTypeKind_Weak; case TypeKind_FunctionPtr: return ((FunctionPtrType*)type)->getPtrTypeKind() == FunctionPtrTypeKind_Weak; case TypeKind_PropertyPtr: return ((PropertyPtrType*)type)->getPtrTypeKind() == PropertyPtrTypeKind_Weak; default: return false; } } Type* getWeakPtrType(Type* type) { TypeKind typeKind = type->getTypeKind(); switch (typeKind) { case TypeKind_ClassPtr: return ((ClassPtrType*)type)->getWeakPtrType(); case TypeKind_FunctionPtr: return ((FunctionPtrType*)type)->getWeakPtrType(); case TypeKind_PropertyPtr: return ((PropertyPtrType*)type)->getWeakPtrType(); default: return type; } } //.............................................................................. } // namespace ct } // namespace jnc
mit
elsys/po-homework
V/04/11/task2.c
1
1625
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef enum { button_clicked = 0, cycle_complete = 1 } commands; typedef enum { CLOSED, OPENING, OPEN, CLOSING, STOPPED_WHILE_CLOSING, STOPPED_WHILE_OPENING } sust; int main(){ unsigned short cm[1000] = {0}, cmd = 0; char duma[14] = {0}; int i, sust = CLOSED; while(scanf("%s", duma) != EOF){ if(strcmp(duma, "button_clicked") == 0) cm[cmd++] = button_clicked; else if(strcmp(duma, "cycle_complete") == 0) cm[cmd++] = cycle_complete; } for(i = 0; i < cmd+1; i++){ switch(sust){ case CLOSED: printf("Door: CLOSED\n"); break; case OPENING: printf("Door: OPENING\n"); break; case OPEN: printf("Door: OPEN\n"); break; case CLOSING: printf("Door: CLOSING\n"); break; case STOPPED_WHILE_CLOSING: printf("Door: STOPPED_WHILE_CLOSING\n"); break; case STOPPED_WHILE_OPENING: printf("Door: STOPPED_WHILE_OPENING\n"); break; default: printf("UNDEFINED\n"); break; } if(cm[i] == button_clicked && sust == CLOSED) sust = OPENING; else if(cm[i] == button_clicked && sust == OPEN) sust = CLOSING; else if(cm[i] == button_clicked && sust == OPENING) sust = STOPPED_WHILE_OPENING; else if(cm[i] == button_clicked && sust == CLOSING) sust = STOPPED_WHILE_CLOSING; else if(cm[i] == cycle_complete && sust == CLOSING) sust = CLOSED; else if(cm[i] == cycle_complete && sust == OPENING) sust = OPEN; else if(cm[i] == button_clicked && sust == STOPPED_WHILE_CLOSING) sust = OPENING; else if(cm[i] == button_clicked && sust == STOPPED_WHILE_OPENING) sust = CLOSING; } return 0; }
mit
lcs2/carpg
project/source/game/panels/Options.cpp
1
14734
#include "Pch.h" #include "GameCore.h" #include "Options.h" #include "Language.h" #include "KeyStates.h" #include "GlobalGui.h" #include "Game.h" #include "MenuList.h" #include "SoundManager.h" #include "Render.h" //----------------------------------------------------------------------------- cstring txQuality, txMsNone; //----------------------------------------------------------------------------- class Res : public GuiElement { public: Int2 size; int hz; Res(const Int2& size, int hz) : size(size), hz(hz) { } cstring ToString() { return Format("%dx%d (%d Hz)", size.x, size.y, hz); } }; //----------------------------------------------------------------------------- inline bool ResPred(const Res* r1, const Res* r2) { if(r1->size.x > r2->size.x) return false; else if(r1->size.x < r2->size.x) return true; else if(r1->size.y > r2->size.y) return false; else if(r1->size.y < r2->size.y) return true; else if(r1->hz > r2->hz) return false; else if(r1->hz < r2->hz) return true; else return false; } //----------------------------------------------------------------------------- class MultisamplingItem : public GuiElement { public: int level, quality; MultisamplingItem(int level, int quality) : level(level), quality(quality) { } cstring ToString() { if(level == 0) return txMsNone; else return Format("x%d (%s %d)", level, txQuality, quality); } }; //----------------------------------------------------------------------------- class LanguageItem : public GuiElement { public: string text, id; LanguageItem(const string& id, const string& text) : id(id), text(text) { } cstring ToString() { return text.c_str(); } }; //================================================================================================= Options::Options(const DialogInfo& info) : GameDialogBox(info) { size = Int2(570, 460); bts.resize(2); Int2 offset(290, 60); for(int i = 0; i < 5; ++i) { check[i].id = IdFullscreen + i; check[i].parent = this; check[i].size = Int2(size.x - 44, 32); check[i].pos = offset; offset.y += 32 + 10; } scroll[0].pos = Int2(290, 290); scroll[0].size = Int2(250, 16); scroll[0].total = 100; scroll[0].part = 10; scroll[0].offset = 0; scroll[0].hscrollbar = true; scroll[1].pos = Int2(290, 330); scroll[1].size = Int2(250, 16); scroll[1].total = 100; scroll[1].part = 10; scroll[1].offset = 0; scroll[1].hscrollbar = true; scroll[2].pos = Int2(290, 370); scroll[2].size = Int2(250, 16); scroll[2].total = 100; scroll[2].part = 10; scroll[2].offset = 0; scroll[2].hscrollbar = true; scroll[3].pos = Int2(290, 410); scroll[3].size = Int2(250, 16); scroll[3].total = 100; scroll[3].part = 10; scroll[3].offset = 0; scroll[3].hscrollbar = true; language.SetCollapsed(true); language.parent = this; language.pos = Int2(20, 383); language.size = Int2(250, 25); language.event_handler = DialogEvent(this, &Options::OnChangeLanguage); int index = 0; for(Language::Map* p_lmap : Language::GetLanguages()) { Language::Map& lmap = *p_lmap; string& dir = lmap["dir"]; language.Add(new LanguageItem(dir, Format("%s, %s, %s", dir.c_str(), lmap["englishName"].c_str(), lmap["localName"].c_str()))); if(dir == Language::prefix) language.SetIndex(index); ++index; } language.Initialize(); visible = false; } //================================================================================================= void Options::LoadLanguage() { Language::Section s = Language::GetSection("Options"); txOPTIONS = s.Get("OPTIONS"); txResolution = s.Get("resolution"); txMultisampling = s.Get("multisampling"); txLanguage = s.Get("language"); txMultisamplingError = s.Get("multisamplingError"); txNeedRestart = s.Get("needRestart"); txSoundVolume = s.Get("soundVolume"); txMusicVolume = s.Get("musicVolume"); txMouseSensitivity = s.Get("mouseSensitivity"); txGrassRange = s.Get("grassRange"); txQuality = s.Get("quality"); txMsNone = s.Get("msNone"); check[0].text = s.Get("fullscreenMode"); check[1].text = s.Get("glow"); check[2].text = s.Get("normalMap"); check[3].text = s.Get("specularMap"); check[4].text = s.Get("vsync"); bts[0].id = IdOk; bts[0].parent = this; bts[0].text = Str("ok"); bts[0].size = GUI.default_font->CalculateSize(bts[0].text) + Int2(24, 24); bts[1].id = IdControls; bts[1].parent = this; bts[1].text = s.Get("controls"); bts[1].size = GUI.default_font->CalculateSize(bts[1].text) + Int2(24, 24); bts[0].size.x = bts[1].size.x = max(bts[0].size.x, bts[1].size.x); bts[0].pos = Int2(20, 410); bts[1].pos = Int2(bts[0].size.x + 40, 410); // lista rozdzielczoœci Render* render = game->GetRender(); int refresh_hz = render->GetRefreshRate(); res.parent = this; res.pos = Int2(20, 80); res.size = Int2(250, 200); res.event_handler = DialogEvent(this, &Options::OnChangeRes); vector<Resolution> resolutions; render->GetResolutions(resolutions); LocalVector<Res*> vres; for(Resolution& r : resolutions) vres->push_back(new Res(r.size, r.hz)); std::sort(vres->begin(), vres->end(), ResPred); int index = 0; for(auto r : vres) { res.Add(r); if(r->size == game->GetWindowSize() && r->hz == refresh_hz) res.SetIndex(index); ++index; } res.Initialize(); res.ScrollTo(res.GetIndex(), true); // multisampling multisampling.SetCollapsed(true); multisampling.parent = this; multisampling.pos = Int2(20, 327); multisampling.size = Int2(250, 25); multisampling.event_handler = DialogEvent(this, &Options::OnChangeMultisampling); multisampling.Add(new MultisamplingItem(0, 0)); int ms, msq; render->GetMultisampling(ms, msq); if(ms == 0) multisampling.SetIndex(0); vector<Int2> ms_modes; render->GetMultisamplingModes(ms_modes); index = 1; for(Int2& mode : ms_modes) { multisampling.Add(new MultisamplingItem(mode.x, mode.y)); if(ms == mode.x && msq == mode.y) multisampling.SetIndex(index); ++index; } multisampling.Initialize(); } //================================================================================================= void Options::Draw(ControlDrawData* /*cdd*/) { // t³o GUI.DrawSpriteFull(tBackground, Color::Alpha(128)); // panel GUI.DrawItem(tDialog, global_pos, size, Color::Alpha(222), 16); // checkboxy for(int i = 0; i < 5; ++i) check[i].Draw(); // scrollbary for(int i = 0; i < 4; ++i) scroll[i].Draw(); // przyciski for(int i = 0; i < 2; ++i) bts[i].Draw(); // tekst OPCJE Rect r = { global_pos.x, global_pos.y + 8, global_pos.x + size.x, global_pos.y + size.y }; GUI.DrawText(GUI.fBig, txOPTIONS, DTF_TOP | DTF_CENTER, Color::Black, r); // tekst Rozdzielczoœæ: Rect r2 = { global_pos.x + 10, global_pos.y + 50, global_pos.x + size.x, global_pos.y + 75 }; GUI.DrawText(GUI.default_font, txResolution, DTF_SINGLELINE, Color::Black, r2); // Multisampling: r2.Top() = global_pos.y + 300; r2.Bottom() = r2.Top() + 20; GUI.DrawText(GUI.default_font, txMultisampling, DTF_SINGLELINE, Color::Black, r2); // Jêzyk: r2.Top() = global_pos.y + 360; r2.Bottom() = r2.Top() + 20; GUI.DrawText(GUI.default_font, txLanguage, DTF_SINGLELINE, Color::Black, r2); // G³oœnoœæ dŸwiêku (0) r2.Left() = global_pos.x + 290; r2.Top() = global_pos.y + 270; r2.Bottom() = r2.Top() + 20; GUI.DrawText(GUI.default_font, Format("%s (%d)", txSoundVolume, sound_volume), DTF_SINGLELINE, Color::Black, r2); // G³oœnoœæ muzyki (0) r2.Top() = global_pos.y + 310; r2.Bottom() = r2.Top() + 20; GUI.DrawText(GUI.default_font, Format("%s (%d)", txMusicVolume, music_volume), DTF_SINGLELINE, Color::Black, r2); // Czu³oœæ myszki (0) r2.Top() = global_pos.y + 350; r2.Bottom() = r2.Top() + 20; GUI.DrawText(GUI.default_font, Format("%s (%d)", txMouseSensitivity, mouse_sensitivity), DTF_SINGLELINE, Color::Black, r2); // Zasiêg trawy (0) r2.Top() = global_pos.y + 390; r2.Bottom() = r2.Top() + 20; GUI.DrawText(GUI.default_font, Format("%s (%d)", txGrassRange, grass_range), DTF_SINGLELINE, Color::Black, r2); // listbox z rozdzielczoœciami res.Draw(); multisampling.Draw(); language.Draw(); if(multisampling.menu->visible) multisampling.menu->Draw(); if(language.menu->visible) language.menu->Draw(); } //================================================================================================= void Options::Update(float dt) { SetOptions(); // aktualizuj kontrolki if(multisampling.menu->visible) multisampling.menu->Update(dt); if(language.menu->visible) language.menu->Update(dt); for(int i = 0; i < 5; ++i) { check[i].mouse_focus = focus; check[i].Update(dt); } for(int i = 0; i < 4; ++i) { scroll[i].mouse_focus = focus; float prev_offset = scroll[i].offset; scroll[i].Update(dt); if(prev_offset != scroll[i].offset) { int value = int(scroll[i].GetValue() * 100); if(i == 0) sound_volume = value; else if(i == 1) music_volume = value; else if(i == 2) mouse_sensitivity = value; else grass_range = value; Event((GuiEvent)(IdSoundVolume + i)); } } for(int i = 0; i < 2; ++i) { bts[i].mouse_focus = focus; bts[i].Update(dt); } res.mouse_focus = focus; res.Update(dt); multisampling.mouse_focus = focus; multisampling.Update(dt); language.mouse_focus = focus; language.Update(dt); if(focus && Key.Focus() && Key.PressedRelease(VK_ESCAPE)) Event((GuiEvent)IdOk); } //================================================================================================= void Options::Event(GuiEvent e) { if(e == GuiEvent_Show || e == GuiEvent_WindowResize) { if(e == GuiEvent_Show) { visible = true; SetOptions(); } pos = global_pos = (GUI.wnd_size - size) / 2; for(int i = 0; i < 5; ++i) check[i].global_pos = global_pos + check[i].pos; for(int i = 0; i < 4; ++i) scroll[i].global_pos = global_pos + scroll[i].pos; for(int i = 0; i < 2; ++i) bts[i].global_pos = global_pos + bts[i].pos; res.Event(GuiEvent_Moved); multisampling.Event(GuiEvent_Moved); language.Event(GuiEvent_Moved); } else if(e == GuiEvent_Close) { res.Event(GuiEvent_LostFocus); visible = false; } else if(e == GuiEvent_LostFocus) res.Event(GuiEvent_LostFocus); else if(e >= GuiEvent_Custom) { switch((Id)e) { case IdOk: CloseDialog(); game->SaveOptions(); break; case IdFullscreen: game->ChangeMode(check[0].checked); break; case IdChangeRes: break; case IdSoundVolume: game->sound_mgr->SetSoundVolume(sound_volume); break; case IdMusicVolume: game->sound_mgr->SetMusicVolume(music_volume); break; case IdMouseSensitivity: game->settings.mouse_sensitivity = mouse_sensitivity; game->settings.mouse_sensitivity_f = Lerp(0.5f, 1.5f, float(game->settings.mouse_sensitivity) / 100); break; case IdGrassRange: game->settings.grass_range = (float)grass_range; break; case IdControls: GUI.ShowDialog((DialogBox*)game->gui->controls); break; case IdGlow: game->cl_glow = check[1].checked; break; case IdNormal: game->cl_normalmap = check[2].checked; break; case IdSpecular: game->cl_specularmap = check[3].checked; break; case IdVsync: { Render* render = game->GetRender(); render->SetVsync(!render->IsVsyncEnabled()); } break; } } } //================================================================================================= void Options::SetOptions() { Render* render = game->GetRender(); check[0].checked = game->IsFullscreen(); check[1].checked = game->cl_glow; check[2].checked = game->cl_normalmap; check[3].checked = game->cl_specularmap; check[4].checked = render->IsVsyncEnabled(); Res& re = *res.GetItemCast<Res>(); int refresh_hz = render->GetRefreshRate(); if(re.size != game->GetWindowSize() || re.hz != refresh_hz) { auto& ress = res.GetItemsCast<Res>(); int index = 0; for(auto r : ress) { if(r->size == game->GetWindowSize() && r->hz == refresh_hz) { res.SetIndex(index); break; } ++index; } } MultisamplingItem& mi = *multisampling.GetItemCast<MultisamplingItem>(); int ms, msq; render->GetMultisampling(ms, msq); if(mi.level != ms || mi.quality != msq) { auto& multis = multisampling.GetItemsCast<MultisamplingItem>(); int index = 0; for(vector<MultisamplingItem*>::iterator it = multis.begin(), end = multis.end(); it != end; ++it, ++index) { if((*it)->level == ms && (*it)->quality == msq) { multisampling.SetIndex(index); break; } } } SoundManager* sound_mgr = game->sound_mgr.get(); if(sound_volume != sound_mgr->GetSoundVolume()) { sound_volume = sound_mgr->GetSoundVolume(); scroll[0].SetValue(float(sound_volume) / 100.f); } if(music_volume != sound_mgr->GetMusicVolume()) { music_volume = sound_mgr->GetMusicVolume(); scroll[1].SetValue(float(music_volume) / 100.f); } if(mouse_sensitivity != game->settings.mouse_sensitivity) { mouse_sensitivity = game->settings.mouse_sensitivity; scroll[2].SetValue(float(mouse_sensitivity) / 100.f); } if(grass_range != game->settings.grass_range) { grass_range = (int)game->settings.grass_range; scroll[3].SetValue(float(grass_range) / 100.f); } } //================================================================================================= void Options::OnChangeRes(int) { Res& r = *res.GetItemCast<Res>(); game->ChangeMode(r.size, game->IsFullscreen(), r.hz); Event((GuiEvent)IdChangeRes); } //================================================================================================= void Options::OnChangeMultisampling(int id) { MultisamplingItem& multi = *multisampling.GetItemCast<MultisamplingItem>(); if(game->GetRender()->SetMultisampling(multi.level, multi.quality) == 0) GUI.SimpleDialog(txMultisamplingError, this); } //================================================================================================= void Options::OnChangeLanguage(int id) { language_id = language.GetItemCast<LanguageItem>()->id; DialogInfo info; info.event = DialogEvent(this, &Options::ChangeLanguage); info.order = ORDER_TOP; info.parent = this; info.pause = false; info.text = txNeedRestart; info.type = DIALOG_YESNO; GUI.ShowDialog(info); } //================================================================================================= void Options::ChangeLanguage(int id) { if(id == BUTTON_YES) { Language::prefix = language_id; game->SaveOptions(); game->RestartGame(); } else { // przywróc zaznaczenie vector<LanguageItem*>& langs = language.GetItemsCast<LanguageItem>(); int index = 0; for(vector<LanguageItem*>::iterator it = langs.begin(), end = langs.end(); it != end; ++it, ++index) { if((*it)->id == Language::prefix) { language.SetIndex(index); break; } } } }
mit
inertialsense/InertialSenseSDK
src/DeviceLogSerial.cpp
1
4660
/* MIT LICENSE Copyright (c) 2014-2020 Inertial Sense, Inc. - http://inertialsense.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <ctime> #include <string> #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <iomanip> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include "DeviceLogSerial.h" #include "ISLogger.h" #include "ISLogFileFactory.h" using namespace std; void cDeviceLogSerial::InitDeviceForWriting(int pHandle, std::string timestamp, std::string directory, uint64_t maxDiskSpace, uint32_t maxFileSize) { // m_chunk.Init(chunkSize); m_chunk.m_hdr.pHandle = pHandle; cDeviceLog::InitDeviceForWriting(pHandle, timestamp, directory, maxDiskSpace, maxFileSize); } bool cDeviceLogSerial::CloseAllFiles() { cDeviceLog::CloseAllFiles(); // Write any remaining chunk data to file WriteChunkToFile(); // Close file CloseISLogFile(m_pFile); return true; } bool cDeviceLogSerial::SaveData(p_data_hdr_t* dataHdr, const uint8_t* dataBuf) { cDeviceLog::SaveData(dataHdr, dataBuf); // Add serial number if available if (dataHdr->id == DID_DEV_INFO && !copyDataPToStructP2(&m_devInfo, dataHdr, dataBuf, sizeof(dev_info_t))) { int start = dataHdr->offset; int end = dataHdr->offset + dataHdr->size; int snOffset = offsetof(dev_info_t, serialNumber); // Did we really get the serial number? if (start <= snOffset && (int)(snOffset + sizeof(uint32_t)) <= end) { m_chunk.m_hdr.devSerialNum = m_devInfo.serialNumber; } } // Ensure data will fit in chunk. If not, create new chunk uint32_t dataBytes = sizeof(p_data_hdr_t) + dataHdr->size; if (dataBytes > m_chunk.GetBuffFree()) { // Save chunk to file and clear if (!WriteChunkToFile()) { return false; } else if (m_fileSize >= m_maxFileSize) { // Close existing file CloseAllFiles(); } } // Add data header and data buffer to chunk if (!m_chunk.PushBack((unsigned char*)dataHdr, sizeof(p_data_hdr_t), (unsigned char*)dataBuf, dataHdr->size)) { return false; } return true; } bool cDeviceLogSerial::WriteChunkToFile() { // Make sure we have data to write if (m_chunk.GetDataSize() == 0) { return false; } // Create first file if it doesn't exist if (m_pFile == NULLPTR) { OpenNewSaveFile(); } // Validate file pointer if (m_pFile == NULLPTR) { return false; } // Write chunk to file int fileBytes = m_chunk.WriteToFile(m_pFile, 0); if (!m_pFile->good()) { return false; } // File byte size m_fileSize += fileBytes; m_logSize += fileBytes; return true; } p_data_t* cDeviceLogSerial::ReadData() { p_data_t* data = NULL; // Read data from chunk while (!(data = ReadDataFromChunk())) { // Read next chunk from file if (!ReadChunkFromFile()) { return NULL; } } // Read is good cDeviceLog::OnReadData(data); return data; } p_data_t* cDeviceLogSerial::ReadDataFromChunk() { // Ensure chunk has data if (m_chunk.GetDataSize() <= 0) { return NULL; } p_data_t* data = (p_data_t*)m_chunk.GetDataPtr(); int size = data->hdr.size + sizeof(p_data_hdr_t); if (m_chunk.PopFront(size)) { return data; } else { return NULL; } } bool cDeviceLogSerial::ReadChunkFromFile() { // Read next chunk from file while (m_chunk.ReadFromFile(m_pFile) < 0) { if (!OpenNextReadFile()) { // No more data or error opening next file return false; } } return true; } void cDeviceLogSerial::SetSerialNumber(uint32_t serialNumber) { m_devInfo.serialNumber = serialNumber; m_chunk.m_hdr.devSerialNum = serialNumber; } void cDeviceLogSerial::Flush() { if (WriteChunkToFile()) { m_pFile->flush(); } }
mit
wjingzhe/OpenGL_SB5_static
Sb5Codes/Chapter04/SphereWorld3/SphereWorld3.cpp
2
5956
// SphereWorld.cpp // OpenGL SuperBible // New and improved (performance) sphere world // Program by Richard S. Wright Jr. #include <GLTools.h> #include <GLShaderManager.h> #include <GLFrustum.h> #include <GLBatch.h> #include <GLFrame.h> #include <GLMatrixStack.h> #include <GLGeometryTransform.h> #include <StopWatch.h> #include <math.h> #include <stdio.h> #ifdef __APPLE__ #include <glut/glut.h> #else #define FREEGLUT_STATIC #include <GL/glut.h> #endif #define NUM_SPHERES 50 GLFrame spheres[NUM_SPHERES]; GLShaderManager shaderManager; // Shader Manager GLMatrixStack modelViewMatrix; // Modelview Matrix GLMatrixStack projectionMatrix; // Projection Matrix GLFrustum viewFrustum; // View Frustum GLGeometryTransform transformPipeline; // Geometry Transform Pipeline GLTriangleBatch torusBatch; GLBatch floorBatch; GLTriangleBatch sphereBatch; GLFrame cameraFrame; ////////////////////////////////////////////////////////////////// // This function does any needed initialization on the rendering // context. void SetupRC() { // Initialze Shader Manager shaderManager.InitializeStockShaders(); glEnable(GL_DEPTH_TEST); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // This makes a torus gltMakeTorus(torusBatch, 0.4f, 0.15f, 30, 30); // This make a sphere gltMakeSphere(sphereBatch, 0.1f, 26, 13); floorBatch.Begin(GL_LINES, 324); for(GLfloat x = -20.0; x <= 20.0f; x+= 0.5) { floorBatch.Vertex3f(x, -0.55f, 20.0f); floorBatch.Vertex3f(x, -0.55f, -20.0f); floorBatch.Vertex3f(20.0f, -0.55f, x); floorBatch.Vertex3f(-20.0f, -0.55f, x); } floorBatch.End(); // Randomly place the spheres for(int i = 0; i < NUM_SPHERES; i++) { GLfloat x = ((GLfloat)((rand() % 400) - 200) * 0.1f); GLfloat z = ((GLfloat)((rand() % 400) - 200) * 0.1f); spheres[i].SetOrigin(x, 0.0f, z); } } /////////////////////////////////////////////////// // Screen changes size or is initialized void ChangeSize(int nWidth, int nHeight) { glViewport(0, 0, nWidth, nHeight); // Create the projection matrix, and load it on the projection matrix stack viewFrustum.SetPerspective(35.0f, float(nWidth)/float(nHeight), 1.0f, 100.0f); projectionMatrix.LoadMatrix(viewFrustum.GetProjectionMatrix()); // Set the transformation pipeline to use the two matrix stacks transformPipeline.SetMatrixStacks(modelViewMatrix, projectionMatrix); } // Called to draw scene void RenderScene(void) { // Color values static GLfloat vFloorColor[] = { 0.0f, 1.0f, 0.0f, 1.0f}; static GLfloat vTorusColor[] = { 1.0f, 0.0f, 0.0f, 1.0f }; static GLfloat vSphereColor[] = { 0.0f, 0.0f, 1.0f, 1.0f }; // Time Based animation static CStopWatch rotTimer; float yRot = rotTimer.GetElapsedSeconds() * 60.0f; // Clear the color and depth buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Save the current modelview matrix (the identity matrix) modelViewMatrix.PushMatrix(); M3DMatrix44f mCamera; cameraFrame.GetCameraMatrix(mCamera); modelViewMatrix.PushMatrix(mCamera); // Draw the ground shaderManager.UseStockShader(GLT_SHADER_FLAT, transformPipeline.GetModelViewProjectionMatrix(), vFloorColor); floorBatch.Draw(); for(int i = 0; i < NUM_SPHERES; i++) { modelViewMatrix.PushMatrix(); modelViewMatrix.MultMatrix(spheres[i]); shaderManager.UseStockShader(GLT_SHADER_FLAT, transformPipeline.GetModelViewProjectionMatrix(), vSphereColor); sphereBatch.Draw(); modelViewMatrix.PopMatrix(); } // Draw the spinning Torus modelViewMatrix.Translate(0.0f, 0.0f, -2.5f); // Save the Translation modelViewMatrix.PushMatrix(); // Apply a rotation and draw the torus modelViewMatrix.Rotate(yRot, 0.0f, 1.0f, 0.0f); shaderManager.UseStockShader(GLT_SHADER_FLAT, transformPipeline.GetModelViewProjectionMatrix(), vTorusColor); torusBatch.Draw(); modelViewMatrix.PopMatrix(); // "Erase" the Rotation from before // Apply another rotation, followed by a translation, then draw the sphere modelViewMatrix.Rotate(yRot * -2.0f, 0.0f, 1.0f, 0.0f); modelViewMatrix.Translate(0.8f, 0.0f, 0.0f); shaderManager.UseStockShader(GLT_SHADER_FLAT, transformPipeline.GetModelViewProjectionMatrix(), vSphereColor); sphereBatch.Draw(); // Restore the previous modleview matrix (the identity matrix) modelViewMatrix.PopMatrix(); modelViewMatrix.PopMatrix(); // Do the buffer Swap glutSwapBuffers(); // Tell GLUT to do it again glutPostRedisplay(); } // Respond to arrow keys by moving the camera frame of reference void SpecialKeys(int key, int x, int y) { float linear = 0.1f; float angular = float(m3dDegToRad(5.0f)); if(key == GLUT_KEY_UP) cameraFrame.MoveForward(linear); if(key == GLUT_KEY_DOWN) cameraFrame.MoveForward(-linear); if(key == GLUT_KEY_LEFT) cameraFrame.RotateWorld(angular, 0.0f, 1.0f, 0.0f); if(key == GLUT_KEY_RIGHT) cameraFrame.RotateWorld(-angular, 0.0f, 1.0f, 0.0f); } int main(int argc, char* argv[]) { gltSetWorkingDirectory(argv[0]); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800,600); glutCreateWindow("OpenGL SphereWorld"); glutSpecialFunc(SpecialKeys); glutReshapeFunc(ChangeSize); glutDisplayFunc(RenderScene); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); return 1; } SetupRC(); glutMainLoop(); return 0; }
mit
cislaa/prophy
prophy_cpp/test/test_generated_dynfields.cpp
2
3822
#include <vector> #include <gtest/gtest.h> #include "Dynfields.ppf.hpp" #include "util.hpp" using namespace testing; using namespace prophy::generated; TEST(generated_dynfields, Dynfields) { std::vector<char> data(1024); Dynfields x{{2}, {3}, 4}; size_t size = x.encode(data.data()); EXPECT_EQ(24, size); EXPECT_EQ(size, x.get_byte_size()); EXPECT_EQ(bytes( "\x01\x00\x00\x00" "\x02\x00\x00\x00" "\x01\x00\x00\x00" "\x03\x00\x00\x00" "\x04\x00\x00\x00\x00\x00\x00\x00"), bytes(data.data(), size)); EXPECT_TRUE(x.decode(bytes( "\x03\x00\x00\x00" "\x02" "\x02" "\x02" "\x00" "\x02\x00\x00\x00" "\x03\x00" "\x03\x00" "\x05\x00\x00\x00\x00\x00\x00\x00"))); EXPECT_EQ(3, x.x.size()); EXPECT_EQ(2, x.x[0]); EXPECT_EQ(2, x.x[1]); EXPECT_EQ(2, x.x[2]); EXPECT_EQ(2, x.y.size()); EXPECT_EQ(3, x.y[0]); EXPECT_EQ(3, x.y[1]); EXPECT_EQ(5, x.z); } TEST(generated_dynfields, DynfieldsMixed) { std::vector<char> data(1024); DynfieldsMixed x{{3}, {4, 5}, {2}}; size_t size = x.encode(data.data()); EXPECT_EQ(24, size); EXPECT_EQ(size, x.get_byte_size()); EXPECT_EQ(bytes( "\x02\x00" "\x01\x00" "\x03\x00" "\x00\x00" "\x01\x00\x00\x00" "\x04\x05" "\x00\x00" "\x02\x00\x00\x00\x00\x00\x00\x00"), bytes(data.data(), size)); DynfieldsMixed y; EXPECT_TRUE(y.decode(bytes(data.data(), size))); EXPECT_TRUE(x.decode(bytes( "\x01\x00" "\x03\xFF" "\x01\x00\x02\x00" "\x03\x00\xFF\xFF" "\x02\x00\x00\x00" "\x04\xFF\xFF\xFF\xFF\xFF\xFF\xFF" "\x05\x00\x00\x00\x00\x00\x00\x00" "\x06\x00\x00\x00\x00\x00\x00\x00"))); EXPECT_EQ(3, x.a.size()); EXPECT_EQ(1, x.a[0]); EXPECT_EQ(2, x.a[1]); EXPECT_EQ(3, x.a[2]); EXPECT_EQ(1, x.b.size()); EXPECT_EQ(4, x.b[0]); EXPECT_EQ(2, x.c.size()); EXPECT_EQ(5, x.c[0]); EXPECT_EQ(6, x.c[1]); } TEST(generated_dynfields, DynfieldsPartialpad) { std::vector<char> data(1024); DynfieldsPartialpad x{1, {{2}, 3, 4}}; size_t size = x.encode(data.data()); EXPECT_EQ(32, size); EXPECT_EQ(size, x.get_byte_size()); EXPECT_EQ(bytes( "\x01" "\x00\x00\x00" "\x00\x00\x00\x00" "\x01\x00\x00\x00" "\x02" "\x00\x00\x00" "\x03" "\x00\x00\x00" "\x00\x00\x00\x00" "\x04\x00\x00\x00\x00\x00\x00\x00"), bytes(data.data(), size)); EXPECT_TRUE(x.decode(bytes( "\x05" "\xFF\xFF\xFF" "\xFF\xFF\xFF\xFF" "\x01\x00\x00\x00" "\x04" "\xFF\xFF\xFF" "\x03" "\xFF\xFF\xFF" "\xFF\xFF\xFF\xFF" "\x02\x00\x00\x00\x00\x00\x00\x00"))); EXPECT_EQ(5, x.x); EXPECT_EQ(1, x.y.x.size()); EXPECT_EQ(4, x.y.x[0]); EXPECT_EQ(3, x.y.y); EXPECT_EQ(2, x.y.z); } TEST(generated_dynfields, DynfieldsScalarpartialpad) { std::vector<char> data(1024); DynfieldsScalarpartialpad x{{{2}}, {{3, 4, 5, 6, 7, 8}}, {{9, 10, 11}}}; size_t size = x.encode(data.data()); EXPECT_EQ(28, size); EXPECT_EQ(size, x.get_byte_size()); EXPECT_EQ(bytes( "\x01\x00\x00\x00\x02" "\x00\x00\x00" "\x06\x00\x00\x00\x03\x04\x05\x06\x07\x08" "\x00\x00" "\x03\x00\x00\x00\x09\x0a\x0b" "\x00"), bytes(data.data(), size)); EXPECT_TRUE(x.decode(bytes( "\x02\x00\x00\x00" "\x02\x03" "\x00\x00" "\x02\x00\x00\x00" "\x04\x05" "\x00\x00" "\x05\x00\x00\x00" "abcde" "\x00\x00\x00"))); EXPECT_EQ(bytes("\x02\x03"), x.x.x); EXPECT_EQ(bytes("\x04\x05"), x.y.x); EXPECT_EQ(bytes("abcde"), x.z.x); }
mit
maurer/tiamat
samples/Juliet/testcases/CWE190_Integer_Overflow/s05/CWE190_Integer_Overflow__unsigned_int_rand_square_81_bad.cpp
2
1145
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__unsigned_int_rand_square_81_bad.cpp Label Definition File: CWE190_Integer_Overflow.label.xml Template File: sources-sinks-81_bad.tmpl.cpp */ /* * @description * CWE: 190 Integer Overflow * BadSource: rand Set data to result of rand() * GoodSource: Set data to a small, non-zero number (two) * Sinks: square * GoodSink: Ensure there will not be an overflow before squaring data * BadSink : Square data, which can lead to overflow * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE190_Integer_Overflow__unsigned_int_rand_square_81.h" #include <math.h> namespace CWE190_Integer_Overflow__unsigned_int_rand_square_81 { void CWE190_Integer_Overflow__unsigned_int_rand_square_81_bad::action(unsigned int data) const { { /* POTENTIAL FLAW: if (data*data) > UINT_MAX, this will overflow */ unsigned int result = data * data; printUnsignedLine(result); } } } #endif /* OMITBAD */
mit
maurer/tiamat
samples/Juliet/testcases/CWE121_Stack_Based_Buffer_Overflow/s02/CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_64b.c
2
2127
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_64b.c Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE193.label.xml Template File: sources-sink-64b.tmpl.c */ /* * @description * CWE: 121 Stack Based Buffer Overflow * BadSource: Point data to a buffer that does not have space for a NULL terminator * GoodSource: Point data to a buffer that includes space for a NULL terminator * Sinks: ncpy * BadSink : Copy string to data using strncpy() * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif /* MAINTENANCE NOTE: The length of this string should equal the 10 */ #define SRC_STRING "AAAAAAAAAA" #ifndef OMITBAD void CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_64b_badSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); { char source[10+1] = SRC_STRING; /* Copy length + 1 to include NUL terminator from source */ /* POTENTIAL FLAW: data may not have enough space to hold source */ strncpy(data, source, strlen(source) + 1); printLine(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_64b_goodG2BSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); { char source[10+1] = SRC_STRING; /* Copy length + 1 to include NUL terminator from source */ /* POTENTIAL FLAW: data may not have enough space to hold source */ strncpy(data, source, strlen(source) + 1); printLine(data); } } #endif /* OMITGOOD */
mit
tihovinc/SuperLU_w64_mkl
SuperLU_5.2.1/TESTING/MATGEN/clacgv.c
2
1670
#include "f2c.h" /* Subroutine */ int clacgv_slu(integer *n, complex *x, integer *incx) { /* -- LAPACK auxiliary routine (version 2.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= CLACGV conjugates a complex vector of length N. Arguments ========= N (input) INTEGER The length of the vector X. N >= 0. X (input/output) COMPLEX array, dimension (1+(N-1)*abs(INCX)) On entry, the vector of length N to be conjugated. On exit, X is overwritten with conjg(X). INCX (input) INTEGER The spacing between successive elements of X. ===================================================================== Parameter adjustments Function Body */ /* System generated locals */ integer i__1, i__2; complex q__1; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer ioff, i; #define X(I) x[(I)-1] if (*incx == 1) { i__1 = *n; for (i = 1; i <= *n; ++i) { i__2 = i; r_cnjg(&q__1, &X(i)); X(i).r = q__1.r, X(i).i = q__1.i; /* L10: */ } } else { ioff = 1; if (*incx < 0) { ioff = 1 - (*n - 1) * *incx; } i__1 = *n; for (i = 1; i <= *n; ++i) { i__2 = ioff; r_cnjg(&q__1, &X(ioff)); X(ioff).r = q__1.r, X(ioff).i = q__1.i; ioff += *incx; /* L20: */ } } return 0; /* End of CLACGV */ } /* clacgv_slu */
mit
4981boomerang/commaudio
BoomerangCommAudio/BoomerangCommAudio/Packetizer.cpp
2
7611
#include "stdafx.h" #include "Packetizer.h" #include <windows.h> #include <iostream> #include <memory> using namespace std; /*-------------------------------------------------------------------------- -- FUNCTION: SoundFilePacketizer -- -- DATE: Mar. 29, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/Mar/29 - Comment Added -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: SoundFilePacketizer (int size) -- int size -- size of each packet, defaults to 1024 -- -- NOTES: -- ctor --------------------------------------------------------------------------*/ SoundFilePacketizer::SoundFilePacketizer(int size) :filesize(-1), fp(nullptr), packsize(size), packindex(0) { } /*-------------------------------------------------------------------------- -- FUNCTION: ~SoundFilePacketizer -- -- DATE: Mar. 29, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/Mar/29 - Comment aded -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: ~SoundFilePacketizer () -- -- NOTES: -- dtor --------------------------------------------------------------------------*/ SoundFilePacketizer::~SoundFilePacketizer() { if (fp) // closes file if is is open { closeFile(); } } /*-------------------------------------------------------------------------- -- FUNCTION: SoundFilePacketizer -- -- DATE: Mar. 29, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/Mar/29 - Comment added -- Version 1.0 - [EY] - 2016/Apr/09 - updated for audio file sending -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: getNextPacket () -- -- NOTES: -- reutrns a pointer to the next packet (char * ) -- In order to not loose the data after you call makePacketsFromFile -- you must do a memset on the data --------------------------------------------------------------------------*/ char * SoundFilePacketizer::getNextPacket() { if (static_cast<unsigned int>(packindex) < vPack.size()) { return vPack[packindex++]; } else return nullptr; } /*-------------------------------------------------------------------------- -- FUNCTION: getTotalPackets -- -- DATE: Feb. 06, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/Feb/06 - Created Functions -- Version 1.1 - [EY] - 2016/Feb/06 - Turned into class funtion -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: long getTotalPackets (functionParams) -- -- RETURNS: -- long that represents the number of packets to send -- -- NOTES: -- calcs the number of packets to send when a file is broken down -- to a specific byte suize per packet --------------------------------------------------------------------------*/ long SoundFilePacketizer::getTotalPackets() { return (filesize / packsize + (filesize % packsize != 0)); } /*-------------------------------------------------------------------------- -- FUNCTION: getlastPackSize -- -- DATE: Feb. 06, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/Feb/06 - Created Functions -- Version 1.1 - [EY] - 2016/Feb/06 - Turned into class funtion -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: long getTotalPackets () -- -- RETURNS: -- long that represents the number of packets to send -- -- NOTES: -- calcs the number of packets to send when a file is broken down -- to a specific byte size per packet --------------------------------------------------------------------------*/ int SoundFilePacketizer::getLastPackSize() { return static_cast<int>(filesize - ((getTotalPackets() - 1) * packsize)); } /*-------------------------------------------------------------------------- -- FUNCTION: clearVector -- -- DATE: Apr. 4, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/Feb/06 - Clears out the vector by deleting all elements -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: void clearVector() -- -- NOTES: -- clears out the vector. be warned! this is called every time you make -- a new file! --------------------------------------------------------------------------*/ void SoundFilePacketizer::clearVector() { for (size_t i = 0; i < vPack.size(); ++i) { free(vPack[i]); vPack[i] = NULL; } filesize = 0; packindex = 0; vPack.clear(); } /*-------------------------------------------------------------------------- -- FUNCTION: makePacketsFromFile(File* pfile, int packsize) -- -- DATE: Feb. 06, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/Feb/06 - Created Function -- Version 2.0 - [EY] - 2016/Feb/06 - Changed to be more compatible with current project -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: void makePacketsFromFile(fpath) -- const char * fpath -- the files path -- -- RETURNS: -- a vector of pointers to packets -- -- NOTES: -- creates packets of *packsize* bytes for the entire files -- and stores it into a vector of the class --------------------------------------------------------------------------*/ void SoundFilePacketizer::makePacketsFromFile(const char * fpath) { size_t read; //empty a vector that may hold something else if (!vPack.empty()) { clearVector(); } openFile(fpath); if (!fp) { return; } calcFileSize(); while (!feof(fp)) { char * buff = static_cast<char *>(malloc(DEFAULT_PACKSIZE)); read = fread(static_cast<void *>(buff), sizeof(char), packsize, fp); if (ferror(fp)) { cout << "Error on file read. " << GetLastError(); fclose(fp); } vPack.push_back(buff); buff = nullptr; } closeFile(); } /*-------------------------------------------------------------------------- -- FUNCTION: openFile -- -- DATE: FEB. 06, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/FEB/06 - Created Function -- Version 2.0 - [EY] - 2016/FEB/06 - Changed to class; made safe with fopen_s -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: itn openFile (FILE * pfile) -- FILE * pfile T-- file pointer -- -- RETURNS: -- int representing state ( 0 is file opened , -1 unsuccessful) -- -- NOTES: -- wrapper function to open a file --------------------------------------------------------------------------*/ void SoundFilePacketizer::openFile(const char * fpath) { if ((fopen_s(&fp, fpath, "rb")) != 0) { cerr << "fopen Failed Error: " << GetLastError() << endl; } } /*-------------------------------------------------------------------------- -- FUNCTION: closeFile -- -- DATE: FEB. 06, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/FEB/06 - Created Function -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: itn closeFile (FILE * pfile) -- FILE * pfile T-- file pointer -- -- RETURNS: -- int representing state ( 0 is file opened , -1 unsuccessful) -- -- NOTES: -- wrapper function to close a file --------------------------------------------------------------------------*/ void SoundFilePacketizer::closeFile() { if (fclose(fp) != 0) { std::cerr << "fclose Failed Error: " << GetLastError() << endl; return; } fp = NULL; } /*-------------------------------------------------------------------------- -- FUNCTION: calcFileSize -- -- DATE: Feb. 06, 2017 -- -- REVISIONS: -- Version 1.0 - [EY] - 2016/Feb/06 - created function -- -- DESIGNER: Eva Yu -- -- PROGRAMMER: Eva Yu -- -- INTERFACE: logn calcFileSize () -- -- -- NOTES: -- gets the size of the file and stores it in class member "filesize" --------------------------------------------------------------------------*/ void SoundFilePacketizer::calcFileSize() { if (fseek(fp, 0, SEEK_END) != 0) { cerr << "Error on fseek. " << GetLastError() << endl; return; } if ((filesize = ftell(fp)) < 0) { cerr << "Error on ftell. " << GetLastError() << endl; rewind(fp); return; } rewind(fp); }
mit
guileschool/BEAGLEBONE-tutorials
BBB-firmware/starterwarefree-code/grlib/fonts/fontcmss22b.c
2
15742
//***************************************************************************** // // fontcmss22b.c - Font definition for the 22 point Cmss bold font. // // Copyright (c) 2008-2010 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 6288 of the Stellaris Graphics Library. // //***************************************************************************** //***************************************************************************** // // This file is generated by ftrasterize; DO NOT EDIT BY HAND! // //***************************************************************************** #include "grlib.h" //***************************************************************************** // // Details of this font: // Style: cmss // Size: 22 point // Bold: yes // Italic: no // Memory usage: 2536 bytes // //***************************************************************************** //***************************************************************************** // // The compressed data for the 22 point Cmss bold font. // //***************************************************************************** static const unsigned char g_pucCmss22bData[2334] = { 5, 9, 0, 24, 96, 17, 5, 163, 35, 35, 35, 35, 35, 35, 35, 35, 35, 195, 35, 35, 240, 192, 16, 10, 240, 83, 35, 35, 35, 35, 35, 49, 65, 50, 50, 0, 19, 16, 44, 19, 0, 5, 97, 65, 194, 50, 194, 50, 194, 50, 178, 50, 194, 50, 111, 2, 47, 2, 114, 50, 194, 50, 194, 50, 127, 2, 47, 2, 98, 50, 194, 50, 178, 50, 194, 50, 194, 50, 193, 65, 240, 224, 33, 12, 66, 162, 135, 73, 35, 18, 34, 35, 18, 99, 18, 102, 119, 103, 103, 98, 19, 98, 19, 33, 50, 19, 34, 34, 19, 41, 86, 130, 0, 6, 96, 53, 22, 37, 130, 103, 99, 83, 36, 82, 99, 51, 66, 115, 51, 51, 115, 51, 50, 131, 51, 34, 162, 35, 34, 183, 19, 240, 66, 240, 66, 54, 163, 35, 35, 131, 51, 35, 130, 67, 35, 114, 83, 35, 99, 83, 35, 98, 118, 113, 148, 0, 11, 64, 36, 19, 240, 240, 212, 215, 180, 35, 163, 51, 163, 51, 163, 35, 183, 82, 100, 98, 101, 98, 87, 66, 83, 36, 35, 83, 55, 99, 69, 127, 2, 70, 54, 0, 12, 16, 10, 5, 163, 35, 35, 49, 50, 0, 9, 96, 25, 8, 66, 82, 83, 82, 83, 83, 82, 83, 83, 83, 83, 83, 83, 83, 83, 98, 99, 83, 98, 99, 98, 114, 32, 25, 8, 2, 114, 99, 98, 99, 83, 98, 99, 83, 83, 83, 83, 83, 83, 83, 82, 83, 83, 82, 83, 82, 82, 96, 19, 10, 50, 130, 82, 18, 18, 40, 68, 100, 72, 34, 18, 18, 82, 130, 0, 15, 80, 37, 18, 0, 7, 82, 240, 18, 240, 18, 240, 18, 240, 18, 240, 18, 240, 18, 159, 1, 47, 1, 146, 240, 18, 240, 18, 240, 18, 240, 18, 240, 18, 240, 18, 0, 7, 112, 11, 5, 0, 8, 99, 35, 35, 49, 50, 240, 48, 9, 8, 0, 11, 6, 38, 0, 9, 32, 9, 5, 0, 8, 99, 35, 35, 240, 192, 25, 11, 114, 146, 145, 146, 146, 145, 146, 146, 130, 146, 146, 130, 146, 146, 130, 146, 145, 146, 146, 145, 146, 146, 144, 32, 12, 240, 196, 104, 67, 35, 51, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 51, 35, 72, 100, 0, 8, 16, 21, 10, 240, 146, 70, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 72, 40, 0, 6, 64, 24, 11, 240, 148, 88, 50, 51, 49, 83, 33, 83, 131, 131, 115, 115, 115, 130, 130, 130, 137, 41, 0, 7, 16, 22, 12, 240, 197, 88, 66, 51, 147, 147, 147, 101, 117, 163, 163, 147, 147, 34, 68, 56, 86, 0, 8, 28, 13, 240, 240, 20, 148, 133, 133, 114, 19, 99, 19, 98, 35, 83, 35, 82, 51, 67, 51, 75, 43, 131, 163, 163, 0, 8, 80, 25, 11, 240, 135, 71, 67, 131, 131, 134, 87, 67, 35, 50, 51, 131, 131, 49, 67, 34, 52, 55, 85, 0, 7, 48, 28, 12, 240, 212, 102, 83, 146, 147, 20, 73, 52, 36, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 51, 36, 56, 101, 0, 8, 21, 12, 240, 154, 42, 131, 146, 147, 131, 147, 131, 147, 147, 131, 147, 147, 147, 147, 0, 8, 48, 29, 12, 240, 182, 88, 51, 67, 35, 67, 35, 67, 35, 67, 56, 86, 82, 66, 51, 67, 35, 67, 35, 67, 35, 67, 56, 86, 0, 8, 29, 12, 240, 181, 104, 52, 35, 51, 67, 35, 67, 35, 67, 35, 67, 35, 52, 57, 68, 19, 147, 146, 65, 67, 71, 101, 0, 8, 16, 13, 5, 240, 240, 83, 35, 35, 240, 115, 35, 35, 240, 192, 15, 5, 240, 240, 83, 35, 35, 240, 115, 35, 35, 49, 50, 240, 48, 18, 5, 240, 243, 35, 35, 115, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 112, 16, 18, 0, 18, 15, 1, 47, 1, 0, 7, 15, 1, 47, 1, 0, 16, 21, 10, 0, 7, 114, 130, 130, 240, 50, 130, 130, 115, 114, 115, 114, 115, 130, 50, 55, 68, 224, 21, 10, 240, 101, 71, 49, 67, 115, 115, 99, 99, 99, 115, 115, 240, 195, 115, 115, 0, 6, 112, 39, 16, 240, 240, 103, 123, 68, 23, 67, 25, 35, 20, 36, 35, 19, 67, 35, 19, 67, 35, 19, 67, 35, 19, 67, 35, 20, 36, 51, 24, 67, 38, 100, 83, 90, 134, 0, 10, 80, 31, 16, 240, 240, 116, 181, 182, 166, 147, 19, 147, 35, 131, 35, 115, 52, 99, 67, 99, 67, 92, 76, 67, 99, 51, 116, 35, 131, 0, 10, 32, 30, 14, 240, 217, 91, 51, 83, 51, 83, 51, 83, 51, 83, 58, 74, 67, 83, 51, 99, 35, 99, 35, 99, 35, 84, 43, 58, 0, 9, 32, 24, 14, 240, 240, 39, 90, 52, 82, 51, 163, 179, 179, 179, 179, 179, 179, 195, 180, 97, 74, 103, 0, 9, 16, 33, 16, 240, 240, 42, 108, 67, 100, 51, 115, 51, 131, 35, 131, 35, 131, 35, 131, 35, 131, 35, 131, 35, 131, 35, 115, 51, 100, 60, 74, 0, 10, 96, 21, 13, 240, 186, 58, 51, 163, 163, 163, 170, 58, 51, 163, 163, 163, 163, 171, 43, 0, 8, 48, 21, 12, 240, 154, 42, 35, 147, 147, 147, 153, 57, 51, 147, 147, 147, 147, 147, 147, 0, 8, 80, 29, 15, 240, 240, 72, 91, 52, 98, 51, 129, 36, 179, 195, 195, 195, 85, 35, 85, 36, 99, 51, 99, 52, 83, 75, 104, 0, 9, 96, 34, 15, 240, 243, 115, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 45, 45, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 0, 9, 80, 19, 5, 163, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 240, 192, 22, 10, 240, 163, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 33, 67, 39, 69, 0, 6, 96, 35, 15, 240, 243, 115, 35, 99, 51, 83, 67, 67, 83, 51, 99, 35, 115, 19, 136, 117, 19, 100, 36, 83, 67, 83, 83, 67, 99, 51, 100, 35, 115, 0, 9, 80, 21, 11, 240, 115, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 137, 41, 0, 7, 16, 56, 19, 240, 240, 132, 148, 37, 117, 37, 117, 37, 117, 35, 18, 82, 19, 35, 18, 82, 19, 35, 19, 51, 19, 35, 34, 50, 35, 35, 34, 50, 35, 35, 35, 19, 35, 35, 50, 18, 51, 35, 50, 18, 51, 35, 53, 51, 35, 67, 67, 35, 67, 67, 0, 12, 16, 43, 15, 240, 245, 83, 37, 83, 37, 83, 38, 67, 35, 18, 67, 35, 19, 51, 35, 34, 51, 35, 35, 35, 35, 50, 35, 35, 51, 19, 35, 66, 19, 35, 70, 35, 85, 35, 85, 35, 85, 0, 9, 80, 33, 17, 240, 240, 135, 139, 84, 84, 67, 115, 51, 147, 35, 147, 35, 147, 35, 147, 35, 147, 35, 147, 35, 147, 51, 115, 68, 84, 91, 135, 0, 11, 48, 26, 14, 240, 217, 91, 51, 84, 35, 99, 35, 99, 35, 99, 35, 84, 43, 57, 83, 179, 179, 179, 179, 179, 0, 10, 16, 37, 17, 240, 240, 135, 139, 84, 84, 67, 115, 51, 147, 35, 147, 35, 147, 35, 147, 35, 147, 35, 147, 35, 51, 51, 51, 51, 19, 68, 54, 91, 137, 227, 228, 0, 6, 96, 31, 14, 240, 218, 75, 51, 84, 35, 99, 35, 99, 35, 84, 43, 57, 83, 51, 83, 51, 83, 67, 67, 68, 51, 83, 51, 99, 35, 99, 0, 9, 25, 13, 240, 215, 89, 52, 66, 51, 97, 51, 165, 151, 120, 118, 164, 163, 33, 115, 35, 68, 42, 87, 0, 8, 80, 21, 15, 240, 253, 45, 115, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 195, 0, 10, 32, 33, 15, 240, 243, 115, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 35, 115, 51, 83, 89, 119, 0, 10, 33, 16, 240, 240, 35, 131, 35, 131, 36, 115, 51, 99, 67, 99, 68, 67, 99, 67, 99, 67, 100, 35, 131, 35, 131, 35, 150, 166, 165, 196, 0, 10, 112, 56, 23, 0, 5, 98, 100, 99, 35, 84, 99, 35, 85, 82, 51, 85, 82, 66, 67, 18, 67, 67, 50, 34, 67, 67, 50, 35, 50, 83, 50, 35, 35, 98, 35, 50, 35, 99, 18, 67, 18, 115, 18, 67, 18, 115, 18, 70, 133, 85, 132, 100, 148, 100, 0, 15, 16, 31, 16, 240, 240, 36, 99, 68, 67, 99, 52, 100, 35, 135, 166, 180, 196, 182, 166, 147, 35, 115, 52, 84, 68, 67, 99, 51, 116, 0, 10, 32, 28, 17, 240, 240, 68, 131, 52, 99, 68, 84, 84, 52, 116, 35, 147, 19, 167, 181, 211, 227, 227, 227, 227, 227, 227, 0, 11, 80, 20, 14, 240, 220, 44, 163, 164, 148, 163, 163, 164, 148, 163, 164, 148, 163, 172, 44, 0, 9, 25, 7, 5, 37, 35, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 69, 37, 32, 16, 9, 240, 66, 34, 49, 49, 51, 19, 35, 19, 35, 19, 0, 17, 16, 25, 7, 5, 37, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 37, 37, 32, 10, 8, 240, 35, 69, 50, 34, 0, 17, 32, 8, 5, 163, 35, 35, 0, 10, 112, 10, 5, 178, 49, 51, 35, 35, 0, 9, 80, 22, 11, 0, 9, 102, 82, 51, 131, 131, 56, 35, 51, 35, 51, 35, 51, 56, 67, 19, 0, 7, 16, 28, 12, 240, 147, 147, 147, 147, 147, 147, 20, 73, 51, 52, 35, 67, 35, 67, 35, 67, 35, 67, 35, 52, 41, 51, 20, 0, 8, 19, 11, 0, 9, 118, 72, 36, 50, 35, 131, 131, 131, 132, 50, 56, 70, 0, 7, 32, 30, 12, 240, 240, 19, 147, 147, 147, 147, 68, 19, 57, 36, 51, 35, 67, 35, 67, 35, 67, 35, 67, 36, 51, 57, 68, 19, 0, 7, 96, 19, 12, 0, 10, 102, 88, 52, 51, 35, 67, 42, 35, 147, 163, 66, 57, 85, 0, 8, 20, 10, 240, 132, 71, 51, 115, 115, 102, 70, 83, 115, 115, 115, 115, 115, 115, 115, 0, 7, 26, 12, 0, 10, 101, 18, 57, 35, 50, 67, 50, 67, 50, 87, 71, 82, 169, 73, 34, 98, 34, 98, 57, 70, 240, 16, 31, 12, 240, 147, 147, 147, 147, 147, 147, 36, 51, 22, 36, 51, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 0, 7, 96, 17, 5, 163, 35, 35, 195, 35, 35, 35, 35, 35, 35, 35, 35, 35, 240, 192, 22, 8, 240, 67, 83, 83, 240, 99, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 38, 52, 176, 28, 12, 240, 147, 147, 147, 147, 147, 147, 51, 51, 35, 67, 19, 86, 102, 103, 83, 35, 67, 35, 67, 51, 51, 67, 0, 7, 96, 19, 5, 163, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 240, 192, 37, 18, 0, 15, 99, 21, 36, 52, 52, 35, 35, 67, 51, 35, 67, 51, 35, 67, 51, 35, 67, 51, 35, 67, 51, 35, 67, 51, 35, 67, 51, 35, 67, 51, 0, 11, 64, 27, 12, 0, 10, 67, 36, 51, 22, 36, 51, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 0, 7, 96, 22, 12, 0, 10, 102, 88, 52, 36, 35, 67, 35, 67, 35, 67, 35, 67, 36, 36, 56, 86, 0, 8, 28, 12, 0, 10, 67, 20, 73, 51, 52, 35, 67, 35, 67, 35, 67, 35, 67, 35, 52, 41, 51, 20, 67, 147, 147, 147, 240, 96, 27, 12, 0, 10, 100, 19, 57, 36, 51, 35, 67, 35, 67, 35, 67, 35, 67, 36, 51, 57, 68, 19, 147, 147, 147, 147, 224, 18, 9, 0, 7, 115, 19, 39, 36, 83, 99, 99, 99, 99, 99, 99, 0, 6, 48, 18, 9, 0, 8, 5, 55, 34, 50, 34, 132, 101, 114, 34, 50, 39, 53, 0, 6, 20, 9, 240, 211, 99, 99, 99, 87, 39, 51, 99, 99, 99, 99, 99, 33, 54, 68, 0, 6, 27, 12, 0, 10, 67, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 52, 53, 19, 0, 7, 96, 23, 12, 0, 10, 67, 67, 35, 67, 50, 66, 67, 35, 67, 35, 82, 34, 102, 102, 116, 132, 0, 8, 16, 36, 17, 0, 14, 115, 51, 66, 35, 51, 51, 50, 51, 50, 66, 36, 50, 67, 21, 19, 67, 18, 18, 19, 82, 17, 34, 18, 100, 37, 100, 37, 99, 67, 0, 11, 32, 22, 12, 0, 10, 67, 67, 51, 35, 86, 116, 131, 148, 118, 98, 34, 83, 50, 51, 67, 0, 7, 96, 25, 11, 0, 9, 82, 82, 35, 51, 50, 50, 67, 34, 82, 19, 85, 116, 116, 115, 146, 146, 130, 101, 100, 240, 48, 17, 11, 0, 9, 89, 41, 115, 115, 115, 130, 131, 115, 121, 41, 0, 7, 16, 9, 14, 0, 17, 76, 44, 0, 17, 96, 11, 26, 0, 32, 79, 9, 47, 9, 0, 32, 96, 12, 9, 240, 51, 19, 34, 34, 50, 33, 0, 19, 80, 11, 10, 240, 99, 34, 40, 34, 35, 0, 21, 80, }; //***************************************************************************** // // The font definition for the 22 point Cmss bold font. // //***************************************************************************** const tFont g_sFontCmss22b = { // // The format of the font. // FONT_FMT_PIXEL_RLE, // // The maximum width of the font. // 23, // // The height of the font. // 22, // // The baseline of the font. // 17, // // The offset to each character in the font. // { 0, 5, 22, 38, 82, 115, 168, 204, 214, 239, 264, 283, 320, 331, 340, 349, 374, 406, 427, 451, 473, 501, 526, 554, 575, 604, 633, 646, 661, 679, 695, 716, 737, 776, 807, 837, 861, 894, 915, 936, 965, 999, 1018, 1040, 1075, 1096, 1152, 1195, 1228, 1254, 1291, 1322, 1347, 1368, 1401, 1434, 1490, 1521, 1549, 1569, 1594, 1610, 1635, 1645, 1653, 1663, 1685, 1713, 1732, 1762, 1781, 1801, 1827, 1858, 1875, 1897, 1925, 1944, 1981, 2008, 2030, 2058, 2085, 2103, 2121, 2141, 2168, 2191, 2227, 2249, 2274, 2291, 2300, 2311, 2323, }, // // A pointer to the actual font data // g_pucCmss22bData };
mit
GOMC-WSU/GOMC
lib/cereal-1.3.0/unittests/stack.cpp
2
2107
/* Copyright (c) 2014, Randolph Voorhies, Shane Grant 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 cereal 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 RANDOLPH VOORHIES AND SHANE GRANT 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. */ #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "stack.hpp" TEST_SUITE_BEGIN("stack"); TEST_CASE("binary_stack") { test_stack<cereal::BinaryInputArchive, cereal::BinaryOutputArchive>(); } TEST_CASE("portable_binary_stack") { test_stack<cereal::PortableBinaryInputArchive, cereal::PortableBinaryOutputArchive>(); } TEST_CASE("xml_stack") { test_stack<cereal::XMLInputArchive, cereal::XMLOutputArchive>(); } TEST_CASE("json_stack") { test_stack<cereal::JSONInputArchive, cereal::JSONOutputArchive>(); } TEST_SUITE_END();
mit
benvenutti/hasmTest
tests/SymbolTable.test.cpp
2
1382
#include "SymbolTable.hpp" #include <catch2/catch.hpp> #include <boost/optional/optional_io.hpp> #include <boost/range/algorithm.hpp> namespace { struct FixtureSymbolTable { FixtureSymbolTable() { symbolTable.addEntry( "s1", 0x1010 ); symbolTable.addEntry( "s2", 0x2020 ); symbolTable.addEntry( "s3", 0x3030 ); } Hasm::SymbolTable symbolTable; }; } // anonymous namespace SCENARIO_METHOD( FixtureSymbolTable, "contains symbol", "[SymbolTable]" ) { REQUIRE( symbolTable.contains( "s1" ) ); REQUIRE( symbolTable.contains( "s2" ) ); REQUIRE( symbolTable.contains( "s3" ) ); REQUIRE_FALSE( symbolTable.contains( "s4" ) ); } SCENARIO_METHOD( FixtureSymbolTable, "symbol refers address", "[SymbolTable]" ) { REQUIRE( symbolTable.getAddress( "s1" ).get() == 0x1010 ); REQUIRE( symbolTable.getAddress( "s2" ).get() == 0x2020 ); REQUIRE( symbolTable.getAddress( "s3" ).get() == 0x3030 ); REQUIRE( symbolTable.getAddress( "s4" ) == boost::none ); } SCENARIO_METHOD( FixtureSymbolTable, "all symbols", "[SymbolTable]" ) { const auto symbols = symbolTable.getSymbols(); REQUIRE( boost::range::count( symbols, "s1" ) == 1u ); REQUIRE( boost::range::count( symbols, "s2" ) == 1u ); REQUIRE( boost::range::count( symbols, "s3" ) == 1u ); REQUIRE( boost::range::count( symbols, "s4" ) == 0u ); }
mit
andyLaurito92/haikunet
debug/atomics/continuous/integrador.cpp
2
14148
#include "integrador.h" void integrador::init(double t, ...){ //The 'parameters' variable contains the parameters transferred from the editor. va_list parameters; va_start(parameters,t); //To get a parameter: %Name% = va_arg(parameters,%Type%) //where: // %Name% is the parameter name // %Type% is the parameter type Method=va_arg(parameters,char*); dQ=va_arg(parameters,double); X=va_arg(parameters,double); pidiv3=1.047197551; u=0; mu=0; pu=0; if (strcmp(Method,"QSS")==0) { met=1; q=floor(X/dQ)*dQ; }; if(strcmp(Method,"QSS2")==0) { met=2; q=X; }; if (strcmp(Method,"QSS3")==0){ q=X; met=3; }; if ((strcmp(Method,"BQSS")==0)||(strcmp(Method,"CQSS")==0)){ met=4; if(strcmp(Method,"CQSS")==0){met=5;}; ep=dQ/100; //ep=0; qs=floor(X/dQ)*dQ+dQ; qi=floor(X/dQ-ep)*dQ; q=qi; eps=1e-20; band=1; }; mq=0; pq=0; sigma=0; for (int i=0;i<10;i++) {y[i]=0;}; } double integrador::ta(double t){ //This function return a double. return sigma; } void integrador::dint(double t){ double s; switch(met) { case 1: // QSS X=X+sigma*u; q=X; if (u==0) { sigma=INF; } else { sigma=dQ/fabs(u); }; break; case 2: // QSS2 X=X+u*sigma+mu/2*sigma*sigma; q=X; u=u+mu*sigma; mq=u; if (mu==0){ sigma=INF; } else { sigma=sqrt(2*dQ/fabs(mu)); }; break; case 3: // QSS3 X=X+u*sigma+(mu*pow(sigma,2))/2 + (pu*pow(sigma,3))/3; q=X; u=u + mu * sigma + pu * pow(sigma,2); mq=u; mu=mu+2*pu*sigma; pq=mu/2; //pu=2*pu; if (pu==0){ sigma=INF; } else{ sigma=pow(fabs(3*dQ/pu), 1.0/3); }; break; case 4: //BQSS and CQSS case 5: X=X+sigma*u; if (sigma>eps) { // X arrives to a new level (q) if(u>0) { qs=qs+dQ; q=qs; qi=q-2*dQ; }else{ qi=qi-dQ; q=qi; qs=q+2*dQ; }; } else { // slope change if(u>0) { q=qs; }else{ q=qi; }; }; // if(fabs(q/dQ)<1){q=0;}; //Corrige error numérico en torno a cero if (u!=0) { sigma=(q-X)/u+2*eps; } else { sigma=INF; }; band=0; break; } } void integrador::dext(Event x, double t){ //The input event is in the 'x' variable. //where: // 'x.value' is the value // 'x.port' is the port number double *Aux; Aux=(double*)x.value; double a,b,c,s; // Modificated by Mario switch(met) { case 1: //QSS X=X+e*u; u=Aux[0]; if (sigma!=0){ if (u==0) { sigma=INF; }else { if (u>0) { sigma=(q+dQ-X)/u; } else { sigma=(q-dQ-X)/u; } }; }; break; case 2: // QSS2 // double a,b,c,s; X=X+u*e+mu/2*e*e; u=Aux[0]; //input value mu=Aux[1]; //input slope if (sigma!=0){ //1 q=q+mq*e; a=mu/2; b=u-mq; c=X-q+dQ; sigma=INF; if (a==0) { if (b!=0) { s=-c/b; if (s>0) {sigma=s;}; c=X-q-dQ; s=-c/b; if ((s>0)&&(s<sigma)) {sigma=s;}; }; } else { s=(-b+sqrt(b*b-4*a*c))/2/a; if (s>0) {sigma=s;}; s=(-b-sqrt(b*b-4*a*c))/2/a; if ((s>0)&&(s<sigma)) {sigma=s;}; c=X-q-dQ; s=(-b+sqrt(b*b-4*a*c))/2/a; if ((s>0)&&(s<sigma)) {sigma=s;}; s=(-b-sqrt(b*b-4*a*c))/2/a; if ((s>0)&&(s<sigma)) {sigma=s;}; }; if (((X-q)>dQ) || ((q-X)>dQ)){sigma=0;}; }; break; case 3: // QSS3 //double a,b,c,s; X=X +u*e+(mu*e*e)/2+(pu*e*e*e)/3; u=Aux[0]; //input value mu=Aux[1]; //input slope pu=Aux[2]; //input derivative if(sigma!=0) { double a,b,c,v,w,A,B, i1,i2, s; q=q+mq*e+pq*e*e; mq=mq+2*pq*e; a=mu/2-pq; b=u-mq; c=X-q-dQ; if(pu!=0) { a=3*a/pu; b=3*b/pu; c=3*c/pu; v=b-a*a/3; w=c-b*a/3+2*a*a*a/27; i1=-w/2; i2=i1*i1+v*v*v/27; if(i2>0) { i2=sqrt(i2); A=i1+i2; B=i1-i2; if(A>0) A=pow(A,1.0/3); else A=-pow(fabs(A),1.0/3); if(B>0) B=pow(B,1.0/3); else B=-pow(fabs(B),1.0/3); s=A+B-a/3; //esta raiz es la unica real pero puede ser negativa if(s<0){ s=INF;} } else if (i2==0) { double x1, x2; A=i1; if(A>0) A=pow(A, 1.0/3); else A=-pow(fabs(A),1.0/3); x1=2*A-a/3; x2=-(A+a/3); if (x1<0) { if(x2<0){s=INF;} else {s=x2;} } else if(x2<0){ s=x1;} else if (x1<x2) {s=x1;} else {s=x2;} } else { double y1, y2, y3, arg; arg=w*sqrt(27/(-v))/(2*v); arg=acos(arg)/3; y1=2*sqrt(-v/3); y2=-y1*cos(pidiv3-arg)-a/3; y3=-y1*cos(pidiv3+arg)-a/3; y1=y1*cos(arg)-a/3; if( y1<0){ s=INF;} else if (y3<0){ s=y1;} else if(y2<0) {s=y3;} else { s=y2;} } c=c+6*dQ/pu; w=c-b*a/3+2*a*a*a/27; i1=-w/2; i2=i1*i1+v*v*v/27; if(i2>0) { i2=sqrt(i2); A=i1+i2; B=i1-i2; if(A>0) A=pow(A,1.0/3); else A=-pow(fabs(A),1.0/3); if(B>0) B=pow(B,1.0/3); else B=-pow(fabs(B),1.0/3); sigma=A+B-a/3; //esta raiz es la unica real pero puede ser negativa if(s<sigma || sigma<0){ sigma=s;} } else if (i2==0) { double x1, x2; A=i1; if(A>0) A=pow(A, 1.0/3); else A=-pow(fabs(A),1.0/3); x1=2*A-a/3; x2=-(A+a/3); if (x1<0) { if(x2<0){sigma=INF;} else {sigma=x2;} } else if(x2<0){ sigma=x1;} else if (x1<x2) {sigma=x1;} else {sigma=x2;} if(s<sigma){ sigma=s;} } else { double y1, y2, y3, arg; arg=w*sqrt(27/(-v))/(2*v); arg=acos(arg)/3; y1=2*sqrt(-v/3); y2=-y1*cos(pidiv3-arg)-a/3; y3=-y1*cos(pidiv3+arg)-a/3; y1=y1*cos(arg)-a/3; if( y1<0){ sigma=INF;} else if (y3<0){ sigma=y1;} else if(y2<0) {sigma=y3;} else { sigma=y2;} if(s<sigma){ sigma=s;} } } else { double x1, x2; if(a!=0) { x1=b*b-4*a*c; if (x1<0){ s=INF;} else { x1=sqrt(x1); x2=(-b-x1)/2/a; x1=(-b+x1)/2/a; if(x1<0) { if(x2<0){s=INF;} else {s=x2;} } else if(x2<0){s=x1;} else if(x1<x2){ s=x1;} else {s=x2;} } c=c+2*dQ; x1=b*b-4*a*c; if (x1<0){ sigma=INF;} else { x1=sqrt(x1); x2=(-b-x1)/2/a; x1=(-b+x1)/2/a; if(x1<0) { if(x2<0){sigma=INF;} else {sigma=x2;} } else if(x2<0){sigma=x1;} else if(x1<x2){ sigma=x1;} else {sigma=x2;} } if(s<sigma) sigma=s; } else { if(b!=0) { x1=-c/b; x2=x1-2*dQ/b; if(x1<0) x1=INF; if(x2<0) x2=INF; if(x1<x2){sigma=x1;}else{sigma=x2;} } } } if ((fabs(X-q))>dQ){sigma=0;}; }; break; case 4: //BQSS and CQSS case 5: if (e*u!=0) { X=X+e*u; if (u>0) { // we check the correct value of qi; if (X-qi>=dQ+ep) qi=qi+dQ; } else { //we check the correct value of qs; if (qs-X>=dQ+ep) qs=qs-dQ; }; }; u=Aux[0]; if (t==0) {// initialization if (band==1) { //we need to send the output sigma=0; } else { //the output was already sent and there was a change in u if (u*(q-X)>=0) { //q is still ok if (u!=0) { sigma=(q-X)/u+eps; } else { sigma=INF; }; } else { // q is wrong, but we wait an infinitesimal until changing it sigma=eps; }; }; } else { if((sigma-e)<eps){ sigma=2*eps; }else{ if (e>0) { //derivative change if (u*(q-X)>=0) { // q was ok if (u!=0) { sigma=(q-X)/u+2*eps; }else{ sigma=INF; }; } else { //we need to change q if(met==4){ sigma=0; }else{ if(u>0){ sigma=(qs-X)/u+2*eps; q=qs; }else{ sigma=(qi-X)/u+2*eps; q=qi; }; }; }; }else { //we had already sent the value q if (u*(q-X)>=0) { // q is still ok if (u!=0) { sigma=(q-X)/u+eps; } else { sigma=INF; }; } else { // q is wrong, but we are close to u=0, so we set u=0. u=0; sigma=INF; }; }; }; }; break; } } Event integrador::lambda(double t){ //This function return an event: // Event(%&Value%, %NroPort%) //where: // %&Value% is a direction to the variable that contain the value. // %NroPort% is the port number (from 0 to n-1) y[3]=0; switch(met) { case 1: // QSS if (u==0) { y[0]=q; } else { y[0]=q+dQ*u/fabs(u); }; break; case 2: // QSS2 y[0]=X+u*sigma+mu*sigma*sigma/2; y[1]=u+mu*sigma; break; case 3: // QSS3 y[0]=X+u*sigma+(mu*pow(sigma,2))/2 + (pu*pow(sigma,3))/3; y[1]=u + mu * sigma + pu * pow(sigma,2); y[2]=mu/2.0+ pu*sigma; break; case 4: //BQSS and CQSS case 5: if (sigma<=eps) { //derivative change if(u>0){ y[0]=qs;y[3]=1; }else{ y[0]=qi;y[3]=2; }; } else { // X arrives to a new level (q) if(u>0){ y[0]=q+dQ;y[3]=3; }else{ y[0]=q-dQ;y[3]=4; }; }; // if(fabs(y[0]/dQ)<1){y[0]=0;}; //Corrige error numérico en torno a cero if(met==5){y[0]=(y[0]+X+sigma*u)/2;}; break; }; return Event(&y,0); }
mit
shoshanatech/Dolphin
Core/DolphinVM/Compiler/disasm.cpp
2
2674
#include "stdafx.h" #include "Compiler.h" #include <minmax.h> #pragma warning(disable:4786) // Browser identifier truncated to 255 characters #pragma warning(push,3) #pragma warning(disable:4530) #include <iostream> #include <iomanip> #include <sstream> #pragma warning(pop) using namespace std; #include "..\tracestream.h" tracestream debugStream; void Compiler::disassemble() { tracelock lock(debugStream); debugStream << noshowbase << nouppercase << setfill(L' '); disassemble(debugStream); } void Compiler::disassemble(wostream& stream) { unsigned maxDepth = 0; for (size_t i = 0; i < m_allScopes.size(); i++) { unsigned depth = m_allScopes[i]->GetLogicalDepth(); if (depth > maxDepth) maxDepth = depth; } LexicalScope* currentScope = m_allScopes[0]; unsigned currentDepth = 0; stream << std::endl; ip_t ip=ip_t::zero; const ip_t last = LastIp; BytecodeDisassembler<Compiler, ip_t> disassembler(*this); while (ip <= LastIp) { disassembler.EmitIp(ip, stream); size_t len = disassembler.EmitRawBytes(ip, stream); // Scope changing, and getting deeper? LexicalScope* newScope = m_bytecodes[ip].pScope; stream << newScope << L' '; char padChar = ' '; // If new nested scope, want to print opening bracket if (currentScope != newScope) { unsigned newDepth = newScope->GetLogicalDepth(); if (!(newDepth < currentDepth)) { padChar = '-'; } currentScope = m_bytecodes[ip].pScope; currentDepth = newDepth; } // If next is in outer scope, want to print closing bracket now bool lastInstr = ip + len > last; unsigned nextDepth = lastInstr ? 0 : m_bytecodes[ip + len].pScope->GetLogicalDepth(); // If not on last bytecode, and scope will change, close the bracket if (nextDepth < currentDepth) { padChar = '-'; } unsigned j; for (j = 0; j < currentDepth; j++) { stream<< L"|"; } for (; j <= maxDepth; j++) { stream << padChar; } const TEXTMAPLIST::iterator it = FindTextMapEntry(ip); if (it != m_textMaps.end()) stream << L'`'; else stream << L' '; disassembler.EmitDecodedInstructionAt(ip, stream); ip += len; } stream << std::endl; } Str Compiler::GetSpecialSelector(size_t index) { const POTE* pSpecialSelectors = GetVMPointers().specialSelectors; return GetString(pSpecialSelectors[index]); } std::wstring Compiler::DebugPrintString(Oop oop) { BSTR bstr = m_piVM->DebugPrintString(oop); std::wstring result(bstr, ::SysStringLen(bstr)); ::SysFreeString(bstr); return result; } std::wostream& __stdcall operator<<(std::wostream& stream, const std::string& str) { USES_CONVERSION; return stream << static_cast<LPCWSTR>(A2W(str.c_str())); }
mit
expertsnipo/xv6
urandom.c
3
4083
// urandom.c // linear congruential random number generator in python /*a = 3 c = 9 m = 16 xi = 0 def seed(x): global xi xi = x def rng(): global xi xi = (a*xi + c)%m return xi % 256 for i in range(10): print rng() */ #include "types.h" #include "defs.h" #include "param.h" #include "traps.h" #include "spinlock.h" #include "fs.h" #include "file.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" #include "x86.h" //////////////////////////////////////////////////////////////// static void zconsputc(int); static int panicked = 0; static struct { struct spinlock lock; int locking; } cons; static void zprintint(int xx, int base, int sign) { static char digits[] = "0123456789abcdef"; char buf[16]; int i; uint x; if(sign && (sign = xx < 0)) x = -xx; else x = xx; i = 0; do{ buf[i++] = digits[x % base]; }while((x /= base) != 0); if(sign) buf[i++] = '-'; while(--i >= 0) zconsputc(buf[i]); } //PAGEBREAK: 50 // Print to the console. only understands %d, %x, %p, %s. void zcprintf(char *fmt, ...) { int i, c, locking; uint *argp; char *s; locking = cons.locking; if(locking) acquire(&cons.lock); if (fmt == 0) panic("null fmt"); argp = (uint*)(void*)(&fmt + 1); for(i = 0; (c = fmt[i] & 0xff) != 0; i++){ if(c != '%'){ zconsputc(c); continue; } c = fmt[++i] & 0xff; if(c == 0) break; switch(c){ case 'd': zprintint(*argp++, 10, 1); break; case 'x': case 'p': zprintint(*argp++, 16, 0); break; case 's': if((s = (char*)*argp++) == 0) s = "(null)"; for(; *s; s++) zconsputc(*s); break; case '%': zconsputc('%'); break; default: // Print unknown % sequence to draw attention. zconsputc('%'); zconsputc(c); break; } } if(locking) release(&cons.lock); } void zpanic(char *s) { int i; uint pcs[10]; cli(); cons.locking = 0; zcprintf("cpu%d: panic: ", cpu->id); zcprintf(s); zcprintf("\n"); getcallerpcs(&s, pcs); for(i=0; i<10; i++) zcprintf(" %p", pcs[i]); panicked = 1; // freeze other CPU for(;;) ; } //PAGEBREAK: 50 #define BACKSPACE 0x100 #define CRTPORT 0x3d4 static ushort *crt = (ushort*)P2V(0xb8000); // CGA memory static void cgaputc(int c) { int pos; // Cursor position: col + 80*row. outb(CRTPORT, 14); pos = inb(CRTPORT+1) << 8; outb(CRTPORT, 15); pos |= inb(CRTPORT+1); if(c == '\n') pos += 80 - pos%80; else if(c == BACKSPACE){ if(pos > 0) --pos; } else crt[pos++] = (c&0xff) | 0x0700; // black on white if((pos/80) >= 24){ // Scroll up. memmove(crt, crt+80, sizeof(crt[0])*23*80); pos -= 80; memset(crt+pos, 0, sizeof(crt[0])*(24*80 - pos)); } outb(CRTPORT, 14); outb(CRTPORT+1, pos>>8); outb(CRTPORT, 15); outb(CRTPORT+1, pos); crt[pos] = ' ' | 0x0700; } void zconsputc(int c) { if(panicked){ cli(); for(;;) ; } if(c == BACKSPACE){ uartputc('\b'); uartputc(' '); uartputc('\b'); } else uartputc(c); cgaputc(c); } #define INPUT_BUF 128 struct { struct spinlock lock; char buf[INPUT_BUF]; uint r; // Read index uint w; // Write index uint e; // Edit index } input; //////////////////////////////////////////////////////////////// uint a = 114071485; uint c = 128201163; uint m = 16777216; uint xi; struct spinlock lock; uint rng(void) { uint tempxi; acquire(&lock); tempxi = xi = (a*xi + c)%m; release(&lock); return tempxi; } int urandomread(struct inode *ip, char *dst, int n) { int i = 0; uint localxi; for (; i < n; ++i) { localxi = rng(); //zcprintf("Original: %d Mod: %d", localxi, localxi % 256); dst[i] = localxi % 256; } return i; } int urandomwrite(struct inode *ip, char *buf, int n) { return 0; } void urandominit(void) { // seed here? xi = 3; initlock(&lock, "urandom"); devsw[DEV_URANDOM].write = urandomwrite; devsw[DEV_URANDOM].read = urandomread; }
mit
oposs/dovecot-extensions
src/lib-master/master-auth.c
3
5703
/* Copyright (c) 2005-2014 Dovecot authors, see the included COPYING file */ #include "lib.h" #include "ioloop.h" #include "fdpass.h" #include "buffer.h" #include "hash.h" #include "master-service-private.h" #include "master-auth.h" #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #define SOCKET_CONNECT_RETRY_MSECS 500 #define MASTER_AUTH_REQUEST_TIMEOUT_MSECS (MASTER_LOGIN_TIMEOUT_SECS/2*1000) struct master_auth_connection { struct master_auth *auth; unsigned int tag; int fd; struct io *io; struct timeout *to; char buf[sizeof(struct master_auth_reply)]; unsigned int buf_pos; master_auth_callback_t *callback; void *context; }; struct master_auth { struct master_service *service; pool_t pool; const char *path; unsigned int tag_counter; HASH_TABLE(void *, struct master_auth_connection *) connections; }; struct master_auth * master_auth_init(struct master_service *service, const char *path) { struct master_auth *auth; pool_t pool; pool = pool_alloconly_create("master auth", 1024); auth = p_new(pool, struct master_auth, 1); auth->pool = pool; auth->service = service; auth->path = p_strdup(pool, path); hash_table_create_direct(&auth->connections, pool, 0); return auth; } static void master_auth_connection_deinit(struct master_auth_connection **_conn) { struct master_auth_connection *conn = *_conn; *_conn = NULL; if (conn->tag != 0) hash_table_remove(conn->auth->connections, POINTER_CAST(conn->tag)); if (conn->callback != NULL) conn->callback(NULL, conn->context); if (conn->to != NULL) timeout_remove(&conn->to); if (conn->io != NULL) io_remove(&conn->io); if (conn->fd != -1) { if (close(conn->fd) < 0) i_fatal("close(%s) failed: %m", conn->auth->path); conn->fd = -1; } i_free(conn); } void master_auth_deinit(struct master_auth **_auth) { struct master_auth *auth = *_auth; struct hash_iterate_context *iter; void *key; struct master_auth_connection *conn; *_auth = NULL; iter = hash_table_iterate_init(auth->connections); while (hash_table_iterate(iter, auth->connections, &key, &conn)) { conn->tag = 0; master_auth_connection_deinit(&conn); } hash_table_iterate_deinit(&iter); hash_table_destroy(&auth->connections); pool_unref(&auth->pool); } static void master_auth_connection_input(struct master_auth_connection *conn) { const struct master_auth_reply *reply; int ret; ret = read(conn->fd, conn->buf + conn->buf_pos, sizeof(conn->buf) - conn->buf_pos); if (ret <= 0) { if (ret == 0 || errno == ECONNRESET) { i_error("read(%s) failed: Remote closed connection " "(service's process_limit reached?)", conn->auth->path); } else { if (errno == EAGAIN) return; i_error("read(%s) failed: %m", conn->auth->path); } master_auth_connection_deinit(&conn); return; } conn->buf_pos += ret; if (conn->buf_pos < sizeof(conn->buf)) return; /* reply is now read */ reply = (const void *)conn->buf; conn->buf_pos = 0; if (conn->tag != reply->tag) i_error("master(%s): Received reply with unknown tag %u", conn->auth->path, reply->tag); else if (conn->callback == NULL) { /* request aborted */ } else { conn->callback(reply, conn->context); conn->callback = NULL; } master_auth_connection_deinit(&conn); } static void master_auth_connection_timeout(struct master_auth_connection *conn) { i_error("master(%s): Auth request timed out (received %u/%u bytes)", conn->auth->path, conn->buf_pos, (unsigned int)sizeof(conn->buf)); master_auth_connection_deinit(&conn); } void master_auth_request(struct master_auth *auth, int fd, const struct master_auth_request *request, const unsigned char *data, master_auth_callback_t *callback, void *context, unsigned int *tag_r) { struct master_auth_connection *conn; struct master_auth_request req; buffer_t *buf; struct stat st; ssize_t ret; i_assert(request->client_pid != 0); i_assert(request->auth_pid != 0); conn = i_new(struct master_auth_connection, 1); conn->auth = auth; conn->callback = callback; conn->context = context; req = *request; req.tag = ++auth->tag_counter; if (req.tag == 0) req.tag = ++auth->tag_counter; if (fstat(fd, &st) < 0) i_fatal("fstat(auth dest fd) failed: %m"); req.ino = st.st_ino; buf = buffer_create_dynamic(pool_datastack_create(), sizeof(req) + req.data_size); buffer_append(buf, &req, sizeof(req)); buffer_append(buf, data, req.data_size); conn->fd = net_connect_unix_with_retries(auth->path, SOCKET_CONNECT_RETRY_MSECS); if (conn->fd == -1) { i_error("net_connect_unix(%s) failed: %m%s", auth->path, errno != EAGAIN ? "" : " - http://wiki2.dovecot.org/SocketUnavailable"); master_auth_connection_deinit(&conn); return; } ret = fd_send(conn->fd, fd, buf->data, buf->used); if (ret < 0) i_error("fd_send(%s, %d) failed: %m", auth->path, fd); else if ((size_t)ret != buf->used) { i_error("fd_send(%s) sent only %d of %d bytes", auth->path, (int)ret, (int)buf->used); ret = -1; } if (ret < 0) { master_auth_connection_deinit(&conn); return; } conn->tag = req.tag; conn->to = timeout_add(MASTER_AUTH_REQUEST_TIMEOUT_MSECS, master_auth_connection_timeout, conn); conn->io = io_add(conn->fd, IO_READ, master_auth_connection_input, conn); hash_table_insert(auth->connections, POINTER_CAST(req.tag), conn); *tag_r = req.tag; } void master_auth_request_abort(struct master_auth *auth, unsigned int tag) { struct master_auth_connection *conn; conn = hash_table_lookup(auth->connections, POINTER_CAST(tag)); if (conn == NULL) i_panic("master_auth_request_abort(): tag %u not found", tag); conn->callback = NULL; }
mit
ehsan/ogre
RenderSystems/GL/src/GLSL/src/OgreGLSLPreprocessor.cpp
3
35398
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2011 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreGLSLPreprocessor.h" #include "OgreLogManager.h" #include <ctype.h> #include <stdio.h> #include <assert.h> namespace Ogre { // Limit max number of macro arguments to this #define MAX_MACRO_ARGS 16 #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 && !defined( __MINGW32__ ) #define snprintf _snprintf #endif //---------------------------------------------------------------------------// /// Return closest power of two not smaller than given number static size_t ClosestPow2 (size_t x) { if (!(x & (x - 1))) return x; while (x & (x + 1)) x |= (x + 1); return x + 1; } void CPreprocessor::Token::Append (const char *iString, size_t iLength) { Token t (Token::TK_TEXT, iString, iLength); Append (t); } void CPreprocessor::Token::Append (const Token &iOther) { if (!iOther.String) return; if (!String) { String = iOther.String; Length = iOther.Length; Allocated = iOther.Allocated; iOther.Allocated = 0; // !!! not quite correct but effective return; } if (Allocated) { size_t new_alloc = ClosestPow2 (Length + iOther.Length); if (new_alloc < 64) new_alloc = 64; if (new_alloc != Allocated) { Allocated = new_alloc; Buffer = (char *)realloc (Buffer, Allocated); } } else if (String + Length != iOther.String) { Allocated = ClosestPow2 (Length + iOther.Length); if (Allocated < 64) Allocated = 64; char *newstr = (char *)malloc (Allocated); memcpy (newstr, String, Length); Buffer = newstr; } if (Allocated) memcpy (Buffer + Length, iOther.String, iOther.Length); Length += iOther.Length; } bool CPreprocessor::Token::GetValue (long &oValue) const { long val = 0; size_t i = 0; while (isspace (String [i])) i++; long base = 10; if (String [i] == '0') if (Length > i + 1 && String [i + 1] == 'x') base = 16, i += 2; else base = 8; for (; i < Length; i++) { long c = long (String [i]); if (isspace (c)) // Possible end of number break; if (c >= 'a' && c <= 'z') c -= ('a' - 'A'); c -= '0'; if (c < 0) return false; if (c > 9) c -= ('A' - '9' - 1); if (c >= base) return false; val = (val * base) + c; } // Check that all other characters are just spaces for (; i < Length; i++) if (!isspace (String [i])) return false; oValue = val; return true; } void CPreprocessor::Token::SetValue (long iValue) { char tmp [21]; int len = snprintf (tmp, sizeof (tmp), "%ld", iValue); Length = 0; Append (tmp, len); Type = TK_NUMBER; } void CPreprocessor::Token::AppendNL (int iCount) { static const char newlines [8] = { '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n' }; while (iCount > 8) { Append (newlines, 8); iCount -= 8; } if (iCount > 0) Append (newlines, iCount); } int CPreprocessor::Token::CountNL () { if (Type == TK_EOS || Type == TK_ERROR) return 0; const char *s = String; int l = Length; int c = 0; while (l > 0) { const char *n = (const char *)memchr (s, '\n', l); if (!n) return c; c++; l -= (n - s + 1); s = n + 1; } return c; } //---------------------------------------------------------------------------// CPreprocessor::Token CPreprocessor::Macro::Expand ( int iNumArgs, CPreprocessor::Token *iArgs, Macro *iMacros) { Expanding = true; CPreprocessor cpp; cpp.MacroList = iMacros; // Define a new macro for every argument int i; for (i = 0; i < iNumArgs; i++) cpp.Define (Args [i].String, Args [i].Length, iArgs [i].String, iArgs [i].Length); // The rest arguments are empty for (; i < NumArgs; i++) cpp.Define (Args [i].String, Args [i].Length, "", 0); // Now run the macro expansion through the supplimentary preprocessor Token xt = cpp.Parse (Value); Expanding = false; // Remove the extra macros we have defined for (int j = NumArgs - 1; j >= 0; j--) cpp.Undef (Args [j].String, Args [j].Length); cpp.MacroList = NULL; return xt; } //---------------------------------------------------------------------------// static void DefaultError (void *iData, int iLine, const char *iError, const char *iToken, size_t iTokenLen) { (void)iData; char line [1000]; if (iToken) snprintf (line, sizeof (line), "line %d: %s: `%.*s'\n", iLine, iError, int (iTokenLen), iToken); else snprintf (line, sizeof (line), "line %d: %s\n", iLine, iError); LogManager::getSingleton ().logMessage (line); } //---------------------------------------------------------------------------// CPreprocessor::ErrorHandlerFunc CPreprocessor::ErrorHandler = DefaultError; CPreprocessor::CPreprocessor (const Token &iToken, int iLine) : MacroList (NULL) { Source = iToken.String; SourceEnd = iToken.String + iToken.Length; EnableOutput = 1; Line = iLine; BOL = true; } CPreprocessor::~CPreprocessor () { delete MacroList; } void CPreprocessor::Error (int iLine, const char *iError, const Token *iToken) { if (iToken) ErrorHandler (ErrorData, iLine, iError, iToken->String, iToken->Length); else ErrorHandler (ErrorData, iLine, iError, NULL, 0); } CPreprocessor::Token CPreprocessor::GetToken (bool iExpand) { if (Source >= SourceEnd) return Token (Token::TK_EOS); const char *begin = Source; char c = *Source++; if (c == '\n' || (c == '\r' && *Source == '\n')) { Line++; BOL = true; if (c == '\r') Source++; return Token (Token::TK_NEWLINE, begin, Source - begin); } else if (isspace (c)) { while (Source < SourceEnd && *Source != '\r' && *Source != '\n' && isspace (*Source)) Source++; return Token (Token::TK_WHITESPACE, begin, Source - begin); } else if (isdigit (c)) { BOL = false; if (c == '0' && Source < SourceEnd && Source [0] == 'x') // hex numbers { Source++; while (Source < SourceEnd && isxdigit (*Source)) Source++; } else while (Source < SourceEnd && isdigit (*Source)) Source++; return Token (Token::TK_NUMBER, begin, Source - begin); } else if (c == '_' || isalnum (c)) { BOL = false; while (Source < SourceEnd && (*Source == '_' || isalnum (*Source))) Source++; Token t (Token::TK_KEYWORD, begin, Source - begin); if (iExpand) t = ExpandMacro (t); return t; } else if (c == '"' || c == '\'') { BOL = false; while (Source < SourceEnd && *Source != c) { if (*Source == '\\') { Source++; if (Source >= SourceEnd) break; } if (*Source == '\n') Line++; Source++; } if (Source < SourceEnd) Source++; return Token (Token::TK_STRING, begin, Source - begin); } else if (c == '/' && *Source == '/') { BOL = false; Source++; while (Source < SourceEnd && *Source != '\r' && *Source != '\n') Source++; return Token (Token::TK_LINECOMMENT, begin, Source - begin); } else if (c == '/' && *Source == '*') { BOL = false; Source++; while (Source < SourceEnd && (Source [0] != '*' || Source [1] != '/')) { if (*Source == '\n') Line++; Source++; } if (Source < SourceEnd && *Source == '*') Source++; if (Source < SourceEnd && *Source == '/') Source++; return Token (Token::TK_COMMENT, begin, Source - begin); } else if (c == '#' && BOL) { // Skip all whitespaces after '#' while (Source < SourceEnd && isspace (*Source)) Source++; while (Source < SourceEnd && !isspace (*Source)) Source++; return Token (Token::TK_DIRECTIVE, begin, Source - begin); } else if (c == '\\' && Source < SourceEnd && (*Source == '\r' || *Source == '\n')) { // Treat backslash-newline as a whole token if (*Source == '\r') Source++; if (*Source == '\n') Source++; Line++; BOL = true; return Token (Token::TK_LINECONT, begin, Source - begin); } else { BOL = false; // Handle double-char operators here if (c == '>' && (*Source == '>' || *Source == '=')) Source++; else if (c == '<' && (*Source == '<' || *Source == '=')) Source++; else if (c == '!' && *Source == '=') Source++; else if (c == '=' && *Source == '=') Source++; else if ((c == '|' || c == '&' || c == '^') && *Source == c) Source++; return Token (Token::TK_PUNCTUATION, begin, Source - begin); } } CPreprocessor::Macro *CPreprocessor::IsDefined (const Token &iToken) { for (Macro *cur = MacroList; cur; cur = cur->Next) if (cur->Name == iToken) return cur; return NULL; } CPreprocessor::Token CPreprocessor::ExpandMacro (const Token &iToken) { Macro *cur = IsDefined (iToken); if (cur && !cur->Expanding) { Token *args = NULL; int nargs = 0; int old_line = Line; if (cur->NumArgs != 0) { Token t = GetArguments (nargs, args, cur->ExpandFunc ? false : true); if (t.Type == Token::TK_ERROR) { delete [] args; return t; } // Put the token back into the source pool; we'll handle it later if (t.String) { // Returned token should never be allocated on heap assert (t.Allocated == 0); Source = t.String; Line -= t.CountNL (); } } if (nargs > cur->NumArgs) { char tmp [60]; snprintf (tmp, sizeof (tmp), "Macro `%.*s' passed %d arguments, but takes just %d", int (cur->Name.Length), cur->Name.String, nargs, cur->NumArgs); Error (old_line, tmp); return Token (Token::TK_ERROR); } Token t = cur->ExpandFunc ? cur->ExpandFunc (this, nargs, args) : cur->Expand (nargs, args, MacroList); t.AppendNL (Line - old_line); delete [] args; return t; } return iToken; } /** * Operator priority: * 0: Whole expression * 1: '(' ')' * 2: || * 3: && * 4: | * 5: ^ * 6: & * 7: '==' '!=' * 8: '<' '<=' '>' '>=' * 9: '<<' '>>' * 10: '+' '-' * 11: '*' '/' '%' * 12: unary '+' '-' '!' '~' */ CPreprocessor::Token CPreprocessor::GetExpression ( Token &oResult, int iLine, int iOpPriority) { char tmp [40]; do { oResult = GetToken (true); } while (oResult.Type == Token::TK_WHITESPACE || oResult.Type == Token::TK_NEWLINE || oResult.Type == Token::TK_COMMENT || oResult.Type == Token::TK_LINECOMMENT || oResult.Type == Token::TK_LINECONT); Token op (Token::TK_WHITESPACE, "", 0); // Handle unary operators here if (oResult.Type == Token::TK_PUNCTUATION && oResult.Length == 1) if (strchr ("+-!~", oResult.String [0])) { char uop = oResult.String [0]; op = GetExpression (oResult, iLine, 12); long val; if (!GetValue (oResult, val, iLine)) { snprintf (tmp, sizeof (tmp), "Unary '%c' not applicable", uop); Error (iLine, tmp, &oResult); return Token (Token::TK_ERROR); } if (uop == '-') oResult.SetValue (-val); else if (uop == '!') oResult.SetValue (!val); else if (uop == '~') oResult.SetValue (~val); } else if (oResult.String [0] == '(') { op = GetExpression (oResult, iLine, 1); if (op.Type == Token::TK_ERROR) return op; if (op.Type == Token::TK_EOS) { Error (iLine, "Unclosed parenthesis in #if expression"); return Token (Token::TK_ERROR); } assert (op.Type == Token::TK_PUNCTUATION && op.Length == 1 && op.String [0] == ')'); op = GetToken (true); } while (op.Type == Token::TK_WHITESPACE || op.Type == Token::TK_NEWLINE || op.Type == Token::TK_COMMENT || op.Type == Token::TK_LINECOMMENT || op.Type == Token::TK_LINECONT) op = GetToken (true); while (true) { if (op.Type != Token::TK_PUNCTUATION) return op; int prio = 0; if (op.Length == 1) switch (op.String [0]) { case ')': return op; case '|': prio = 4; break; case '^': prio = 5; break; case '&': prio = 6; break; case '<': case '>': prio = 8; break; case '+': case '-': prio = 10; break; case '*': case '/': case '%': prio = 11; break; } else if (op.Length == 2) switch (op.String [0]) { case '|': if (op.String [1] == '|') prio = 2; break; case '&': if (op.String [1] == '&') prio = 3; break; case '=': if (op.String [1] == '=') prio = 7; break; case '!': if (op.String [1] == '=') prio = 7; break; case '<': if (op.String [1] == '=') prio = 8; else if (op.String [1] == '<') prio = 9; break; case '>': if (op.String [1] == '=') prio = 8; else if (op.String [1] == '>') prio = 9; break; } if (!prio) { Error (iLine, "Expecting operator, got", &op); return Token (Token::TK_ERROR); } if (iOpPriority >= prio) return op; Token rop; Token nextop = GetExpression (rop, iLine, prio); long vlop, vrop; if (!GetValue (oResult, vlop, iLine)) { snprintf (tmp, sizeof (tmp), "Left operand of '%.*s' is not a number", int (op.Length), op.String); Error (iLine, tmp, &oResult); return Token (Token::TK_ERROR); } if (!GetValue (rop, vrop, iLine)) { snprintf (tmp, sizeof (tmp), "Right operand of '%.*s' is not a number", int (op.Length), op.String); Error (iLine, tmp, &rop); return Token (Token::TK_ERROR); } switch (op.String [0]) { case '|': if (prio == 2) oResult.SetValue (vlop || vrop); else oResult.SetValue (vlop | vrop); break; case '&': if (prio == 3) oResult.SetValue (vlop && vrop); else oResult.SetValue (vlop & vrop); break; case '<': if (op.Length == 1) oResult.SetValue (vlop < vrop); else if (prio == 8) oResult.SetValue (vlop <= vrop); else if (prio == 9) oResult.SetValue (vlop << vrop); break; case '>': if (op.Length == 1) oResult.SetValue (vlop > vrop); else if (prio == 8) oResult.SetValue (vlop >= vrop); else if (prio == 9) oResult.SetValue (vlop >> vrop); break; case '^': oResult.SetValue (vlop ^ vrop); break; case '!': oResult.SetValue (vlop != vrop); break; case '=': oResult.SetValue (vlop == vrop); break; case '+': oResult.SetValue (vlop + vrop); break; case '-': oResult.SetValue (vlop - vrop); break; case '*': oResult.SetValue (vlop * vrop); break; case '/': case '%': if (vrop == 0) { Error (iLine, "Division by zero"); return Token (Token::TK_ERROR); } if (op.String [0] == '/') oResult.SetValue (vlop / vrop); else oResult.SetValue (vlop % vrop); break; } op = nextop; } } bool CPreprocessor::GetValue (const Token &iToken, long &oValue, int iLine) { Token r; const Token *vt = &iToken; if ((vt->Type == Token::TK_KEYWORD || vt->Type == Token::TK_TEXT || vt->Type == Token::TK_NUMBER) && !vt->String) { Error (iLine, "Trying to evaluate an empty expression"); return false; } if (vt->Type == Token::TK_TEXT) { CPreprocessor cpp (iToken, iLine); cpp.MacroList = MacroList; Token t; t = cpp.GetExpression (r, iLine); cpp.MacroList = NULL; if (t.Type == Token::TK_ERROR) return false; if (t.Type != Token::TK_EOS) { Error (iLine, "Garbage after expression", &t); return false; } vt = &r; } Macro *m; switch (vt->Type) { case Token::TK_EOS: case Token::TK_ERROR: return false; case Token::TK_KEYWORD: // Try to expand the macro if ((m = IsDefined (*vt)) && !m->Expanding) { Token x = ExpandMacro (*vt); m->Expanding = true; bool rc = GetValue (x, oValue, iLine); m->Expanding = false; return rc; } // Undefined macro, "expand" to 0 (mimic cpp behaviour) oValue = 0; break; case Token::TK_TEXT: case Token::TK_NUMBER: if (!vt->GetValue (oValue)) { Error (iLine, "Not a numeric expression", vt); return false; } break; default: Error (iLine, "Unexpected token", vt); return false; } return true; } CPreprocessor::Token CPreprocessor::GetArgument (Token &oArg, bool iExpand) { do { oArg = GetToken (iExpand); } while (oArg.Type == Token::TK_WHITESPACE || oArg.Type == Token::TK_NEWLINE || oArg.Type == Token::TK_COMMENT || oArg.Type == Token::TK_LINECOMMENT || oArg.Type == Token::TK_LINECONT); if (!iExpand) if (oArg.Type == Token::TK_EOS) return oArg; else if (oArg.Type == Token::TK_PUNCTUATION && (oArg.String [0] == ',' || oArg.String [0] == ')')) { Token t = oArg; oArg = Token (Token::TK_TEXT, "", 0); return t; } else if (oArg.Type != Token::TK_KEYWORD) { Error (Line, "Unexpected token", &oArg); return Token (Token::TK_ERROR); } uint len = oArg.Length; while (true) { Token t = GetToken (iExpand); switch (t.Type) { case Token::TK_EOS: Error (Line, "Unfinished list of arguments"); case Token::TK_ERROR: return Token (Token::TK_ERROR); case Token::TK_PUNCTUATION: if (t.String [0] == ',' || t.String [0] == ')') { // Trim whitespaces at the end oArg.Length = len; return t; } break; case Token::TK_LINECONT: case Token::TK_COMMENT: case Token::TK_LINECOMMENT: case Token::TK_NEWLINE: // ignore these tokens continue; default: break; } if (!iExpand && t.Type != Token::TK_WHITESPACE) { Error (Line, "Unexpected token", &oArg); return Token (Token::TK_ERROR); } oArg.Append (t); if (t.Type != Token::TK_WHITESPACE) len = oArg.Length; } } CPreprocessor::Token CPreprocessor::GetArguments (int &oNumArgs, Token *&oArgs, bool iExpand) { Token args [MAX_MACRO_ARGS]; int nargs = 0; // Suppose we'll leave by the wrong path oNumArgs = 0; oArgs = NULL; Token t; do { t = GetToken (iExpand); } while (t.Type == Token::TK_WHITESPACE || t.Type == Token::TK_COMMENT || t.Type == Token::TK_LINECOMMENT); if (t.Type != Token::TK_PUNCTUATION || t.String [0] != '(') { oNumArgs = 0; oArgs = NULL; return t; } while (true) { if (nargs == MAX_MACRO_ARGS) { Error (Line, "Too many arguments to macro"); return Token (Token::TK_ERROR); } t = GetArgument (args [nargs++], iExpand); switch (t.Type) { case Token::TK_EOS: Error (Line, "Unfinished list of arguments"); case Token::TK_ERROR: return Token (Token::TK_ERROR); case Token::TK_PUNCTUATION: if (t.String [0] == ')') { t = GetToken (iExpand); goto Done; } // otherwise we've got a ',' break; default: Error (Line, "Unexpected token", &t); break; } } Done: oNumArgs = nargs; oArgs = new Token [nargs]; for (int i = 0; i < nargs; i++) oArgs [i] = args [i]; return t; } bool CPreprocessor::HandleDefine (Token &iBody, int iLine) { // Create an additional preprocessor to process macro body CPreprocessor cpp (iBody, iLine); Token t = cpp.GetToken (false); if (t.Type != Token::TK_KEYWORD) { Error (iLine, "Macro name expected after #define"); return false; } Macro *m = new Macro (t); m->Body = iBody; t = cpp.GetArguments (m->NumArgs, m->Args, false); while (t.Type == Token::TK_WHITESPACE) t = cpp.GetToken (false); switch (t.Type) { case Token::TK_NEWLINE: case Token::TK_EOS: // Assign "" to token t = Token (Token::TK_TEXT, "", 0); break; case Token::TK_ERROR: delete m; return false; default: t.Type = Token::TK_TEXT; assert (t.String + t.Length == cpp.Source); t.Length = cpp.SourceEnd - t.String; break; } m->Value = t; m->Next = MacroList; MacroList = m; return true; } bool CPreprocessor::HandleUnDef (Token &iBody, int iLine) { CPreprocessor cpp (iBody, iLine); Token t = cpp.GetToken (false); if (t.Type != Token::TK_KEYWORD) { Error (iLine, "Expecting a macro name after #undef, got", &t); return false; } // Don't barf if macro does not exist - standard C behaviour Undef (t.String, t.Length); do { t = cpp.GetToken (false); } while (t.Type == Token::TK_WHITESPACE || t.Type == Token::TK_COMMENT || t.Type == Token::TK_LINECOMMENT); if (t.Type != Token::TK_EOS) Error (iLine, "Warning: Ignoring garbage after directive", &t); return true; } bool CPreprocessor::HandleIfDef (Token &iBody, int iLine) { if (EnableOutput & (1 << 31)) { Error (iLine, "Too many embedded #if directives"); return false; } CPreprocessor cpp (iBody, iLine); Token t = cpp.GetToken (false); if (t.Type != Token::TK_KEYWORD) { Error (iLine, "Expecting a macro name after #ifdef, got", &t); return false; } EnableOutput <<= 1; if (IsDefined (t)) EnableOutput |= 1; do { t = cpp.GetToken (false); } while (t.Type == Token::TK_WHITESPACE || t.Type == Token::TK_COMMENT || t.Type == Token::TK_LINECOMMENT); if (t.Type != Token::TK_EOS) Error (iLine, "Warning: Ignoring garbage after directive", &t); return true; } CPreprocessor::Token CPreprocessor::ExpandDefined (CPreprocessor *iParent, int iNumArgs, Token *iArgs) { if (iNumArgs != 1) { iParent->Error (iParent->Line, "The defined() function takes exactly one argument"); return Token (Token::TK_ERROR); } const char *v = iParent->IsDefined (iArgs [0]) ? "1" : "0"; return Token (Token::TK_NUMBER, v, 1); } bool CPreprocessor::HandleIf (Token &iBody, int iLine) { Macro defined (Token (Token::TK_KEYWORD, "defined", 7)); defined.Next = MacroList; defined.ExpandFunc = ExpandDefined; defined.NumArgs = 1; // Temporary add the defined() function to the macro list MacroList = &defined; long val; bool rc = GetValue (iBody, val, iLine); // Restore the macro list MacroList = defined.Next; defined.Next = NULL; if (!rc) return false; EnableOutput <<= 1; if (val) EnableOutput |= 1; return true; } bool CPreprocessor::HandleElse (Token &iBody, int iLine) { if (EnableOutput == 1) { Error (iLine, "#else without #if"); return false; } // Negate the result of last #if EnableOutput ^= 1; if (iBody.Length) Error (iLine, "Warning: Ignoring garbage after #else", &iBody); return true; } bool CPreprocessor::HandleEndIf (Token &iBody, int iLine) { EnableOutput >>= 1; if (EnableOutput == 0) { Error (iLine, "#endif without #if"); return false; } if (iBody.Length) Error (iLine, "Warning: Ignoring garbage after #endif", &iBody); return true; } CPreprocessor::Token CPreprocessor::HandleDirective (Token &iToken, int iLine) { // Analyze preprocessor directive const char *directive = iToken.String + 1; size_t dirlen = iToken.Length - 1; while (dirlen && isspace (*directive)) dirlen--, directive++; int old_line = Line; // Collect the remaining part of the directive until EOL Token t, last; do { t = GetToken (false); if (t.Type == Token::TK_NEWLINE) { // No directive arguments last = t; t.Length = 0; goto Done; } } while (t.Type == Token::TK_WHITESPACE || t.Type == Token::TK_LINECONT || t.Type == Token::TK_COMMENT || t.Type == Token::TK_LINECOMMENT); for (;;) { last = GetToken (false); switch (last.Type) { case Token::TK_EOS: // Can happen and is not an error goto Done; case Token::TK_LINECOMMENT: case Token::TK_COMMENT: // Skip comments in macros continue; case Token::TK_ERROR: return last; case Token::TK_LINECONT: continue; case Token::TK_NEWLINE: goto Done; default: break; } t.Append (last); t.Type = Token::TK_TEXT; } Done: #define IS_DIRECTIVE(s) \ (dirlen == strlen(s) && (strncmp (directive, s, strlen(s)) == 0)) bool outputEnabled = ((EnableOutput & (EnableOutput + 1)) == 0); bool rc; if (IS_DIRECTIVE ("define") && outputEnabled) rc = HandleDefine (t, iLine); else if (IS_DIRECTIVE ("undef") && outputEnabled) rc = HandleUnDef (t, iLine); else if (IS_DIRECTIVE ("ifdef")) rc = HandleIfDef (t, iLine); else if (IS_DIRECTIVE ("ifndef")) { rc = HandleIfDef (t, iLine); if (rc) EnableOutput ^= 1; } else if (IS_DIRECTIVE ("if")) rc = HandleIf (t, iLine); else if (IS_DIRECTIVE ("else")) rc = HandleElse (t, iLine); else if (IS_DIRECTIVE ("endif")) rc = HandleEndIf (t, iLine); else { //Error (iLine, "Unknown preprocessor directive", &iToken); //return Token (Token::TK_ERROR); // Unknown preprocessor directive, roll back and pass through Line = old_line; Source = iToken.String + iToken.Length; iToken.Type = Token::TK_TEXT; return iToken; } #undef IS_DIRECTIVE if (!rc) return Token (Token::TK_ERROR); return last; } void CPreprocessor::Define (const char *iMacroName, size_t iMacroNameLen, const char *iMacroValue, size_t iMacroValueLen) { Macro *m = new Macro (Token (Token::TK_KEYWORD, iMacroName, iMacroNameLen)); m->Value = Token (Token::TK_TEXT, iMacroValue, iMacroValueLen); m->Next = MacroList; MacroList = m; } void CPreprocessor::Define (const char *iMacroName, size_t iMacroNameLen, long iMacroValue) { Macro *m = new Macro (Token (Token::TK_KEYWORD, iMacroName, iMacroNameLen)); m->Value.SetValue (iMacroValue); m->Next = MacroList; MacroList = m; } bool CPreprocessor::Undef (const char *iMacroName, size_t iMacroNameLen) { Macro **cur = &MacroList; Token name (Token::TK_KEYWORD, iMacroName, iMacroNameLen); while (*cur) { if ((*cur)->Name == name) { Macro *next = (*cur)->Next; (*cur)->Next = NULL; delete (*cur); *cur = next; return true; } cur = &(*cur)->Next; } return false; } CPreprocessor::Token CPreprocessor::Parse (const Token &iSource) { Source = iSource.String; SourceEnd = Source + iSource.Length; Line = 1; BOL = true; EnableOutput = 1; // Accumulate output into this token Token output (Token::TK_TEXT); int empty_lines = 0; // Enable output only if all embedded #if's were true bool old_output_enabled = true; bool output_enabled = true; int output_disabled_line = 0; while (Source < SourceEnd) { int old_line = Line; Token t = GetToken (true); NextToken: switch (t.Type) { case Token::TK_ERROR: return t; case Token::TK_EOS: return output; // Force termination case Token::TK_COMMENT: // C comments are replaced with single spaces. if (output_enabled) { output.Append (" ", 1); output.AppendNL (Line - old_line); } break; case Token::TK_LINECOMMENT: // C++ comments are ignored continue; case Token::TK_DIRECTIVE: // Handle preprocessor directives t = HandleDirective (t, old_line); output_enabled = ((EnableOutput & (EnableOutput + 1)) == 0); if (output_enabled != old_output_enabled) { if (output_enabled) output.AppendNL (old_line - output_disabled_line); else output_disabled_line = old_line; old_output_enabled = output_enabled; } if (output_enabled) output.AppendNL (Line - old_line - t.CountNL ()); goto NextToken; case Token::TK_LINECONT: // Backslash-Newline sequences are deleted, no matter where. empty_lines++; break; case Token::TK_NEWLINE: if (empty_lines) { // Compensate for the backslash-newline combinations // we have encountered, otherwise line numeration is broken if (output_enabled) output.AppendNL (empty_lines); empty_lines = 0; } // Fallthrough to default case Token::TK_WHITESPACE: // Fallthrough to default default: // Passthrough all other tokens if (output_enabled) output.Append (t); break; } } if (EnableOutput != 1) { Error (Line, "Unclosed #if at end of source"); return Token (Token::TK_ERROR); } return output; } char *CPreprocessor::Parse (const char *iSource, size_t iLength, size_t &oLength) { Token retval = Parse (Token (Token::TK_TEXT, iSource, iLength)); if (retval.Type == Token::TK_ERROR) return NULL; oLength = retval.Length; retval.Allocated = 0; return retval.Buffer; } } // namespace Ogre
mit
abdllhbyrktr/Urho3D
Source/Urho3D/Graphics/OpenGL/OGLTextureCube.cpp
3
16074
// // Copyright (c) 2008-2017 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../../Precompiled.h" #include "../../Core/Context.h" #include "../../Core/Profiler.h" #include "../../Graphics/Graphics.h" #include "../../Graphics/GraphicsEvents.h" #include "../../Graphics/GraphicsImpl.h" #include "../../Graphics/Renderer.h" #include "../../Graphics/TextureCube.h" #include "../../IO/FileSystem.h" #include "../../IO/Log.h" #include "../../Resource/ResourceCache.h" #include "../../Resource/XMLFile.h" #include "../../DebugNew.h" #ifdef _MSC_VER #pragma warning(disable:4355) #endif namespace Urho3D { void TextureCube::OnDeviceLost() { GPUObject::OnDeviceLost(); for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i) { if (renderSurfaces_[i]) renderSurfaces_[i]->OnDeviceLost(); } } void TextureCube::OnDeviceReset() { if (!object_.name_ || dataPending_) { // If has a resource file, reload through the resource cache. Otherwise just recreate. ResourceCache* cache = GetSubsystem<ResourceCache>(); if (cache->Exists(GetName())) dataLost_ = !cache->ReloadResource(this); if (!object_.name_) { Create(); dataLost_ = true; } } dataPending_ = false; } void TextureCube::Release() { if (object_.name_) { if (!graphics_) return; if (!graphics_->IsDeviceLost()) { for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i) { if (graphics_->GetTexture(i) == this) graphics_->SetTexture(i, 0); } glDeleteTextures(1, &object_.name_); } for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i) { if (renderSurfaces_[i]) renderSurfaces_[i]->Release(); } object_.name_ = 0; } resolveDirty_ = false; levelsDirty_ = false; } bool TextureCube::SetData(CubeMapFace face, unsigned level, int x, int y, int width, int height, const void* data) { URHO3D_PROFILE(SetTextureData); if (!object_.name_ || !graphics_) { URHO3D_LOGERROR("No texture created, can not set data"); return false; } if (!data) { URHO3D_LOGERROR("Null source for setting data"); return false; } if (level >= levels_) { URHO3D_LOGERROR("Illegal mip level for setting data"); return false; } if (graphics_->IsDeviceLost()) { URHO3D_LOGWARNING("Texture data assignment while device is lost"); dataPending_ = true; return true; } if (IsCompressed()) { x &= ~3; y &= ~3; } int levelWidth = GetLevelWidth(level); int levelHeight = GetLevelHeight(level); if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0) { URHO3D_LOGERROR("Illegal dimensions for setting data"); return false; } graphics_->SetTextureForUpdate(this); bool wholeLevel = x == 0 && y == 0 && width == levelWidth && height == levelHeight; unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_; if (!IsCompressed()) { if (wholeLevel) glTexImage2D((GLenum)(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face), level, format, width, height, 0, GetExternalFormat(format_), GetDataType(format_), data); else glTexSubImage2D((GLenum)(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face), level, x, y, width, height, GetExternalFormat(format_), GetDataType(format_), data); } else { if (wholeLevel) glCompressedTexImage2D((GLenum)(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face), level, format, width, height, 0, GetDataSize(width, height), data); else glCompressedTexSubImage2D((GLenum)(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face), level, x, y, width, height, format, GetDataSize(width, height), data); } graphics_->SetTexture(0, 0); return true; } bool TextureCube::SetData(CubeMapFace face, Deserializer& source) { SharedPtr<Image> image(new Image(context_)); if (!image->Load(source)) return false; return SetData(face, image); } bool TextureCube::SetData(CubeMapFace face, Image* image, bool useAlpha) { if (!image) { URHO3D_LOGERROR("Null image, can not set face data"); return false; } // Use a shared ptr for managing the temporary mip images created during this function SharedPtr<Image> mipImage; unsigned memoryUse = 0; int quality = QUALITY_HIGH; Renderer* renderer = GetSubsystem<Renderer>(); if (renderer) quality = renderer->GetTextureQuality(); if (!image->IsCompressed()) { // Convert unsuitable formats to RGBA unsigned components = image->GetComponents(); if (Graphics::GetGL3Support() && ((components == 1 && !useAlpha) || components == 2)) { mipImage = image->ConvertToRGBA(); image = mipImage; if (!image) return false; components = image->GetComponents(); } unsigned char* levelData = image->GetData(); int levelWidth = image->GetWidth(); int levelHeight = image->GetHeight(); unsigned format = 0; if (levelWidth != levelHeight) { URHO3D_LOGERROR("Cube texture width not equal to height"); return false; } // Discard unnecessary mip levels for (unsigned i = 0; i < mipsToSkip_[quality]; ++i) { mipImage = image->GetNextLevel(); image = mipImage; levelData = image->GetData(); levelWidth = image->GetWidth(); levelHeight = image->GetHeight(); } switch (components) { case 1: format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat(); break; case 2: format = Graphics::GetLuminanceAlphaFormat(); break; case 3: format = Graphics::GetRGBFormat(); break; case 4: format = Graphics::GetRGBAFormat(); break; default: assert(false); // Should not reach here break; } // Create the texture when face 0 is being loaded, check that rest of the faces are same size & format if (!face) { // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size if (IsCompressed() && requestedLevels_ > 1) requestedLevels_ = 0; SetSize(levelWidth, format); } else { if (!object_.name_) { URHO3D_LOGERROR("Cube texture face 0 must be loaded first"); return false; } if (levelWidth != width_ || format != format_) { URHO3D_LOGERROR("Cube texture face does not match size or format of face 0"); return false; } } for (unsigned i = 0; i < levels_; ++i) { SetData(face, i, 0, 0, levelWidth, levelHeight, levelData); memoryUse += levelWidth * levelHeight * components; if (i < levels_ - 1) { mipImage = image->GetNextLevel(); image = mipImage; levelData = image->GetData(); levelWidth = image->GetWidth(); levelHeight = image->GetHeight(); } } } else { int width = image->GetWidth(); int height = image->GetHeight(); unsigned levels = image->GetNumCompressedLevels(); unsigned format = graphics_->GetFormat(image->GetCompressedFormat()); bool needDecompress = false; if (width != height) { URHO3D_LOGERROR("Cube texture width not equal to height"); return false; } if (!format) { format = Graphics::GetRGBAFormat(); needDecompress = true; } unsigned mipsToSkip = mipsToSkip_[quality]; if (mipsToSkip >= levels) mipsToSkip = levels - 1; while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4)) --mipsToSkip; width /= (1 << mipsToSkip); height /= (1 << mipsToSkip); // Create the texture when face 0 is being loaded, assume rest of the faces are same size & format if (!face) { SetNumLevels(Max((levels - mipsToSkip), 1U)); SetSize(width, format); } else { if (!object_.name_) { URHO3D_LOGERROR("Cube texture face 0 must be loaded first"); return false; } if (width != width_ || format != format_) { URHO3D_LOGERROR("Cube texture face does not match size or format of face 0"); return false; } } for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i) { CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip); if (!needDecompress) { SetData(face, i, 0, 0, level.width_, level.height_, level.data_); memoryUse += level.rows_ * level.rowSize_; } else { unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4]; level.Decompress(rgbaData); SetData(face, i, 0, 0, level.width_, level.height_, rgbaData); memoryUse += level.width_ * level.height_ * 4; delete[] rgbaData; } } } faceMemoryUse_[face] = memoryUse; unsigned totalMemoryUse = sizeof(TextureCube); for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i) totalMemoryUse += faceMemoryUse_[i]; SetMemoryUse(totalMemoryUse); return true; } bool TextureCube::GetData(CubeMapFace face, unsigned level, void* dest) const { if (!object_.name_ || !graphics_) { URHO3D_LOGERROR("No texture created, can not get data"); return false; } #ifndef GL_ES_VERSION_2_0 if (!dest) { URHO3D_LOGERROR("Null destination for getting data"); return false; } if (level >= levels_) { URHO3D_LOGERROR("Illegal mip level for getting data"); return false; } if (graphics_->IsDeviceLost()) { URHO3D_LOGWARNING("Getting texture data while device is lost"); return false; } if (multiSample_ > 1 && !autoResolve_) { URHO3D_LOGERROR("Can not get data from multisampled texture without autoresolve"); return false; } if (resolveDirty_) graphics_->ResolveToTexture(const_cast<TextureCube*>(this)); graphics_->SetTextureForUpdate(const_cast<TextureCube*>(this)); if (!IsCompressed()) glGetTexImage((GLenum)(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face), level, GetExternalFormat(format_), GetDataType(format_), dest); else glGetCompressedTexImage((GLenum)(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face), level, dest); graphics_->SetTexture(0, 0); return true; #else // Special case on GLES: if the texture is a rendertarget, can make it current and use glReadPixels() if (usage_ == TEXTURE_RENDERTARGET) { graphics_->SetRenderTarget(0, renderSurfaces_[face]); // Ensure the FBO is current; this viewport is actually never rendered to graphics_->SetViewport(IntRect(0, 0, width_, height_)); glReadPixels(0, 0, width_, height_, GetExternalFormat(format_), GetDataType(format_), dest); return true; } URHO3D_LOGERROR("Getting texture data not supported"); return false; #endif } bool TextureCube::Create() { Release(); if (!graphics_ || !width_ || !height_) return false; if (graphics_->IsDeviceLost()) { URHO3D_LOGWARNING("Texture creation while device is lost"); return true; } #ifdef GL_ES_VERSION_2_0 if (multiSample_ > 1) { URHO3D_LOGWARNING("Multisampled texture is not supported on OpenGL ES"); multiSample_ = 1; autoResolve_ = false; } #endif glGenTextures(1, &object_.name_); // Ensure that our texture is bound to OpenGL texture unit 0 graphics_->SetTextureForUpdate(this); // If not compressed, create the initial level 0 texture with null data unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_; unsigned externalFormat = GetExternalFormat(format_); unsigned dataType = GetDataType(format_); // If multisample, create renderbuffers for each face if (multiSample_ > 1) { for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i) renderSurfaces_[i]->CreateRenderBuffer(width_, height_, format, multiSample_); } bool success = true; if (!IsCompressed()) { glGetError(); for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format, width_, height_, 0, externalFormat, dataType, 0); if (glGetError()) success = false; } } if (!success) URHO3D_LOGERROR("Failed to create texture"); // Set mipmapping if (usage_ == TEXTURE_DEPTHSTENCIL) requestedLevels_ = 1; else if (usage_ == TEXTURE_RENDERTARGET) { #if defined(__EMSCRIPTEN__) || defined(IOS) // glGenerateMipmap appears to not be working on WebGL or iOS, disable rendertarget mipmaps for now requestedLevels_ = 1; #else if (requestedLevels_ != 1) { // Generate levels for the first time now RegenerateLevels(); // Determine max. levels automatically requestedLevels_ = 0; } #endif } levels_ = CheckMaxLevels(width_, height_, requestedLevels_); #ifndef GL_ES_VERSION_2_0 glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1); #endif // Set initial parameters, then unbind the texture UpdateParameters(); graphics_->SetTexture(0, 0); return success; } }
mit
eyolfson/weston
src/rpi-renderer.c
3
49145
/* * Copyright © 2012-2013 Raspberry Pi Foundation * * 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 (including the * next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "config.h" #include <stdlib.h> #include <assert.h> #include <string.h> #ifdef HAVE_BCM_HOST # include <bcm_host.h> #else # include "rpi-bcm-stubs.h" #endif #include "compositor.h" #include "rpi-renderer.h" #include "shared/helpers.h" #ifdef ENABLE_EGL #include <EGL/egl.h> #include <EGL/eglext.h> #include "weston-egl-ext.h" #endif /* * Dispmanx API offers alpha-blended overlays for hardware compositing. * The final composite consists of dispmanx elements, and their contents: * the dispmanx resource assigned to the element. The elements may be * scanned out directly, or composited to a temporary surface, depending on * how the firmware decides to handle the scene. Updates to multiple elements * may be queued in a single dispmanx update object, resulting in atomic and * vblank synchronized display updates. * * To avoid tearing and display artifacts, the current dispmanx resource in a * dispmanx element must not be touched. Therefore each element must be * double-buffered, using two resources, the front and the back. While a * dispmanx update is running, the both resources must be considered in use. * * A resource may be destroyed only, when the update removing the element has * completed. Otherwise you risk showing an incomplete composition. */ #ifndef ELEMENT_CHANGE_LAYER /* copied from interface/vmcs_host/vc_vchi_dispmanx.h of userland.git */ #define ELEMENT_CHANGE_LAYER (1<<0) #define ELEMENT_CHANGE_OPACITY (1<<1) #define ELEMENT_CHANGE_DEST_RECT (1<<2) #define ELEMENT_CHANGE_SRC_RECT (1<<3) #define ELEMENT_CHANGE_MASK_RESOURCE (1<<4) #define ELEMENT_CHANGE_TRANSFORM (1<<5) #endif #if 0 #define DBG(...) \ weston_log(__VA_ARGS__) #else #define DBG(...) do {} while (0) #endif /* If we had a fully featured vc_dispmanx_resource_write_data()... */ /*#define HAVE_RESOURCE_WRITE_DATA_RECT 1*/ /* If we had a vc_dispmanx_element_set_opaque_rect()... */ /*#define HAVE_ELEMENT_SET_OPAQUE_RECT 1*/ struct rpi_resource { DISPMANX_RESOURCE_HANDLE_T handle; int width; int height; /* height of the image (valid pixel data) */ int stride; /* bytes */ int buffer_height; /* height of the buffer */ int enable_opaque_regions; VC_IMAGE_TYPE_T ifmt; }; struct rpir_output; struct rpir_egl_buffer { struct weston_buffer_reference buffer_ref; DISPMANX_RESOURCE_HANDLE_T resource_handle; }; enum buffer_type { BUFFER_TYPE_NULL, BUFFER_TYPE_SHM, BUFFER_TYPE_EGL }; struct rpir_surface { struct weston_surface *surface; struct wl_list views; int visible_views; int need_swap; int single_buffer; int enable_opaque_regions; struct rpi_resource resources[2]; struct rpi_resource *front; struct rpi_resource *back; pixman_region32_t prev_damage; struct rpir_egl_buffer *egl_front; struct rpir_egl_buffer *egl_back; struct rpir_egl_buffer *egl_old_front; struct weston_buffer_reference buffer_ref; enum buffer_type buffer_type; struct wl_listener surface_destroy_listener; }; struct rpir_view { struct rpir_surface *surface; struct wl_list surface_link; struct weston_view *view; /* If link is empty, the view is guaranteed to not be on screen, * i.e. updates removing Elements have completed. */ struct wl_list link; DISPMANX_ELEMENT_HANDLE_T handle; int layer; struct wl_listener view_destroy_listener; }; struct rpir_output { DISPMANX_DISPLAY_HANDLE_T display; DISPMANX_UPDATE_HANDLE_T update; struct weston_matrix matrix; /* all Elements currently on screen */ struct wl_list view_list; /* struct rpir_surface::link */ /* Elements just removed, waiting for update completion */ struct wl_list view_cleanup_list; /* struct rpir_surface::link */ struct rpi_resource capture_buffer; uint8_t *capture_data; }; struct rpi_renderer { struct weston_renderer base; int single_buffer; int enable_opaque_regions; #ifdef ENABLE_EGL EGLDisplay egl_display; PFNEGLBINDWAYLANDDISPLAYWL bind_display; PFNEGLUNBINDWAYLANDDISPLAYWL unbind_display; PFNEGLQUERYWAYLANDBUFFERWL query_buffer; #endif int has_bind_display; }; static int rpi_renderer_create_surface(struct weston_surface *base); static int rpi_renderer_create_view(struct weston_view *base); static void rpir_view_handle_view_destroy(struct wl_listener *listener, void *data); static inline struct rpir_surface * to_rpir_surface(struct weston_surface *surface) { if (!surface->renderer_state) rpi_renderer_create_surface(surface); return surface->renderer_state; } static inline struct rpir_view * to_rpir_view(struct weston_view *view) { if (!view->renderer_state) rpi_renderer_create_view(view); return view->renderer_state; } static inline struct rpir_output * to_rpir_output(struct weston_output *output) { return output->renderer_state; } static inline struct rpi_renderer * to_rpi_renderer(struct weston_compositor *compositor) { return container_of(compositor->renderer, struct rpi_renderer, base); } static inline int int_max(int a, int b) { return a > b ? a : b; } static inline void int_swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } static uint8_t float2uint8(float f) { int v = roundf(f * 255.0f); return v < 0 ? 0 : (v > 255 ? 255 : v); } static void rpi_resource_init(struct rpi_resource *resource) { resource->handle = DISPMANX_NO_HANDLE; } static void rpi_resource_release(struct rpi_resource *resource) { if (resource->handle == DISPMANX_NO_HANDLE) return; vc_dispmanx_resource_delete(resource->handle); DBG("resource %p release\n", resource); resource->handle = DISPMANX_NO_HANDLE; } static int rpi_resource_realloc(struct rpi_resource *resource, VC_IMAGE_TYPE_T ifmt, int width, int height, int stride, int buffer_height) { uint32_t dummy; if (resource->handle != DISPMANX_NO_HANDLE && resource->width == width && resource->height == height && resource->stride == stride && resource->buffer_height == buffer_height && resource->ifmt == ifmt) return 0; rpi_resource_release(resource); /* NOTE: if stride is not a multiple of 16 pixels in bytes, * the vc_image_* functions may break. Dispmanx elements * should be fine, though. Buffer_height probably has similar * constraints, too. */ resource->handle = vc_dispmanx_resource_create(ifmt, width | (stride << 16), height | (buffer_height << 16), &dummy); if (resource->handle == DISPMANX_NO_HANDLE) return -1; resource->width = width; resource->height = height; resource->stride = stride; resource->buffer_height = buffer_height; resource->ifmt = ifmt; DBG("resource %p alloc\n", resource); return 1; } /* A firmware workaround for broken ALPHA_PREMULT + ALPHA_MIX hardware. */ #define PREMULT_ALPHA_FLAG (1 << 31) static VC_IMAGE_TYPE_T shm_buffer_get_vc_format(struct wl_shm_buffer *buffer) { switch (wl_shm_buffer_get_format(buffer)) { case WL_SHM_FORMAT_XRGB8888: return VC_IMAGE_XRGB8888; case WL_SHM_FORMAT_ARGB8888: return VC_IMAGE_ARGB8888 | PREMULT_ALPHA_FLAG; case WL_SHM_FORMAT_RGB565: return VC_IMAGE_RGB565; default: /* invalid format */ return VC_IMAGE_MIN; } } #ifndef HAVE_ELEMENT_SET_OPAQUE_RECT static uint32_t * apply_opaque_region(struct wl_shm_buffer *buffer, pixman_region32_t *opaque_region) { uint32_t *src, *dst; int width; int height; int stride; int x, y; width = wl_shm_buffer_get_width(buffer); height = wl_shm_buffer_get_height(buffer); stride = wl_shm_buffer_get_stride(buffer); src = wl_shm_buffer_get_data(buffer); dst = malloc(height * stride); if (dst == NULL) { weston_log("rpi-renderer error: out of memory\n"); return NULL; } for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { int i = y * stride / 4 + x; if (pixman_region32_contains_point (opaque_region, x, y, NULL)) { dst[i] = src[i] | 0xff000000; } else { dst[i] = src[i]; } } } return dst; } #endif static int rpi_resource_update(struct rpi_resource *resource, struct weston_buffer *buffer, pixman_region32_t *region, pixman_region32_t *opaque_region) { pixman_region32_t write_region; pixman_box32_t *r; VC_RECT_T rect; VC_IMAGE_TYPE_T ifmt; uint32_t *pixels; int width; int height; int stride; int ret; int applied_opaque_region = 0; #ifdef HAVE_RESOURCE_WRITE_DATA_RECT int n; #endif if (!buffer) return -1; ifmt = shm_buffer_get_vc_format(buffer->shm_buffer); width = wl_shm_buffer_get_width(buffer->shm_buffer); height = wl_shm_buffer_get_height(buffer->shm_buffer); stride = wl_shm_buffer_get_stride(buffer->shm_buffer); pixels = wl_shm_buffer_get_data(buffer->shm_buffer); #ifndef HAVE_ELEMENT_SET_OPAQUE_RECT if (pixman_region32_not_empty(opaque_region) && wl_shm_buffer_get_format(buffer->shm_buffer) == WL_SHM_FORMAT_ARGB8888 && resource->enable_opaque_regions) { pixels = apply_opaque_region(buffer->shm_buffer, opaque_region); if (!pixels) return -1; applied_opaque_region = 1; } #endif ret = rpi_resource_realloc(resource, ifmt & ~PREMULT_ALPHA_FLAG, width, height, stride, height); if (ret < 0) { if (applied_opaque_region) free(pixels); return -1; } pixman_region32_init_rect(&write_region, 0, 0, width, height); if (ret == 0) pixman_region32_intersect(&write_region, &write_region, region); wl_shm_buffer_begin_access(buffer->shm_buffer); #ifdef HAVE_RESOURCE_WRITE_DATA_RECT /* XXX: Can this do a format conversion, so that scanout does not have to? */ r = pixman_region32_rectangles(&write_region, &n); while (n--) { vc_dispmanx_rect_set(&rect, r[n].x1, r[n].y1, r[n].x2 - r[n].x1, r[n].y2 - r[n].y1); ret = vc_dispmanx_resource_write_data_rect(resource->handle, ifmt, stride, pixels, &rect, rect.x, rect.y); DBG("%s: %p %ux%u@%u,%u, ret %d\n", __func__, resource, rect.width, rect.height, rect.x, rect.y, ret); if (ret) break; } #else /* vc_dispmanx_resource_write_data() ignores ifmt, * rect.x, rect.width, and uses stride only for computing * the size of the transfer as rect.height * stride. * Therefore we can only write rows starting at x=0. * To be able to write more than one scanline at a time, * the resource must have been created with the same stride * as used here, and we must write full scanlines. */ r = pixman_region32_extents(&write_region); vc_dispmanx_rect_set(&rect, 0, r->y1, width, r->y2 - r->y1); ret = vc_dispmanx_resource_write_data(resource->handle, ifmt, stride, pixels, &rect); DBG("%s: %p %ux%u@%u,%u, ret %d\n", __func__, resource, width, r->y2 - r->y1, 0, r->y1, ret); #endif wl_shm_buffer_end_access(buffer->shm_buffer); pixman_region32_fini(&write_region); if (applied_opaque_region) free(pixels); return ret ? -1 : 0; } static inline void rpi_buffer_egl_lock(struct weston_buffer *buffer) { #ifdef ENABLE_EGL vc_dispmanx_set_wl_buffer_in_use(buffer->resource, 1); #endif } static inline void rpi_buffer_egl_unlock(struct weston_buffer *buffer) { #ifdef ENABLE_EGL vc_dispmanx_set_wl_buffer_in_use(buffer->resource, 0); #endif } static void rpir_egl_buffer_destroy(struct rpir_egl_buffer *egl_buffer) { struct weston_buffer *buffer; if (egl_buffer == NULL) return; buffer = egl_buffer->buffer_ref.buffer; if (buffer == NULL) { /* The client has already destroyed the wl_buffer, the * compositor has the responsibility to delete the resource. */ vc_dispmanx_resource_delete(egl_buffer->resource_handle); } else { rpi_buffer_egl_unlock(buffer); weston_buffer_reference(&egl_buffer->buffer_ref, NULL); } free(egl_buffer); } static struct rpir_surface * rpir_surface_create(struct rpi_renderer *renderer) { struct rpir_surface *surface; surface = zalloc(sizeof *surface); if (surface == NULL) return NULL; wl_list_init(&surface->views); surface->single_buffer = renderer->single_buffer; surface->enable_opaque_regions = renderer->enable_opaque_regions; rpi_resource_init(&surface->resources[0]); rpi_resource_init(&surface->resources[1]); surface->front = &surface->resources[0]; if (surface->single_buffer) surface->back = &surface->resources[0]; else surface->back = &surface->resources[1]; surface->front->enable_opaque_regions = renderer->enable_opaque_regions; surface->back->enable_opaque_regions = renderer->enable_opaque_regions; surface->buffer_type = BUFFER_TYPE_NULL; pixman_region32_init(&surface->prev_damage); return surface; } static void rpir_surface_destroy(struct rpir_surface *surface) { if (surface->visible_views) weston_log("ERROR rpi: destroying on-screen element\n"); assert(wl_list_empty(&surface->views)); if (surface->surface) surface->surface->renderer_state = NULL; pixman_region32_fini(&surface->prev_damage); rpi_resource_release(&surface->resources[0]); rpi_resource_release(&surface->resources[1]); DBG("rpir_surface %p destroyed (%u)\n", surface, surface->visible_views); rpir_egl_buffer_destroy(surface->egl_back); rpir_egl_buffer_destroy(surface->egl_front); rpir_egl_buffer_destroy(surface->egl_old_front); free(surface); } static int rpir_surface_damage(struct rpir_surface *surface, struct weston_buffer *buffer, pixman_region32_t *damage) { pixman_region32_t upload; int ret; if (!pixman_region32_not_empty(damage)) return 0; DBG("rpir_surface %p update resource %p\n", surface, surface->back); /* XXX: todo: if no surface->handle, update front buffer directly * to avoid creating a new back buffer */ if (surface->single_buffer) { ret = rpi_resource_update(surface->front, buffer, damage, &surface->surface->opaque); } else { pixman_region32_init(&upload); pixman_region32_union(&upload, &surface->prev_damage, damage); ret = rpi_resource_update(surface->back, buffer, &upload, &surface->surface->opaque); pixman_region32_fini(&upload); } pixman_region32_copy(&surface->prev_damage, damage); surface->need_swap = 1; return ret; } static struct rpir_view * rpir_view_create(struct rpir_surface *surface) { struct rpir_view *view; view = zalloc(sizeof *view); if (view == NULL) return NULL; view->surface = surface; wl_list_insert(&surface->views, &view->surface_link); wl_list_init(&view->link); view->handle = DISPMANX_NO_HANDLE; return view; } static void rpir_view_destroy(struct rpir_view *view) { wl_list_remove(&view->link); if (view->handle != DISPMANX_NO_HANDLE) { view->surface->visible_views--; weston_log("ERROR rpi: destroying on-screen element\n"); } if (view->view) view->view->renderer_state = NULL; wl_list_remove(&view->surface_link); if (wl_list_empty(&view->surface->views) && view->surface->surface == NULL) rpir_surface_destroy(view->surface); DBG("rpir_view %p destroyed (%d)\n", view, view->handle); free(view); } static void matrix_type_str(struct weston_matrix *matrix, char *buf, int len) { static const char types[33] = "TSRO"; unsigned mask = matrix->type; int i = 0; while (mask && i < len - 1) { if (mask & (1u << i)) *buf++ = types[i]; mask &= ~(1u << i); i++; } *buf = '\0'; } static void log_print_matrix(struct weston_matrix *matrix) { char typestr[6]; float *d = matrix->d; matrix_type_str(matrix, typestr, sizeof typestr); weston_log_continue("%14.6e %14.6e %14.6e %14.6e\n", d[0], d[4], d[8], d[12]); weston_log_continue("%14.6e %14.6e %14.6e %14.6e\n", d[1], d[5], d[9], d[13]); weston_log_continue("%14.6e %14.6e %14.6e %14.6e\n", d[2], d[6], d[10], d[14]); weston_log_continue("%14.6e %14.6e %14.6e %14.6e type: %s\n", d[3], d[7], d[11], d[15], typestr); } static void warn_bad_matrix(struct weston_matrix *total, struct weston_matrix *output, struct weston_matrix *surface) { static int n_warn; char typestr[6]; if (n_warn++ == 10) weston_log("%s: not showing more warnings\n", __func__); if (n_warn > 10) return; weston_log("%s: warning: total transformation is not renderable:\n", __func__); log_print_matrix(total); matrix_type_str(surface, typestr, sizeof typestr); weston_log_continue("surface matrix type: %s\n", typestr); matrix_type_str(output, typestr, sizeof typestr); weston_log_continue("output matrix type: %s\n", typestr); } /*#define SURFACE_TRANSFORM */ static int rpir_view_compute_rects(struct rpir_view *view, VC_RECT_T *src_rect, VC_RECT_T *dst_rect, VC_IMAGE_TRANSFORM_T *flipmask) { struct weston_output *output_base = view->view->surface->output; struct rpir_output *output = to_rpir_output(output_base); struct weston_matrix matrix = view->view->transform.matrix; VC_IMAGE_TRANSFORM_T flipt = 0; int src_x, src_y; int dst_x, dst_y; int src_width, src_height; int dst_width, dst_height; struct weston_vector p1 = {{ 0.0f, 0.0f, 0.0f, 1.0f }}; struct weston_vector p2 = {{ 0.0f, 0.0f, 0.0f, 1.0f }}; int t; int over; /* XXX: take buffer transform into account */ /* src is in 16.16, dst is in 32.0 fixed point. * Negative values are not allowed in VC_RECT_T. * Clip size to output boundaries, firmware ignores * huge elements like 8192x8192. */ src_x = 0 << 16; src_y = 0 << 16; if (view->surface->buffer_type == BUFFER_TYPE_EGL) { struct weston_buffer *buffer = view->surface->egl_front->buffer_ref.buffer; src_width = buffer->width << 16; src_height = buffer->height << 16; } else { src_width = view->surface->front->width << 16; src_height = view->surface->front->height << 16; } weston_matrix_multiply(&matrix, &output->matrix); #ifdef SURFACE_TRANSFORM if (matrix.type >= WESTON_MATRIX_TRANSFORM_OTHER) { #else if (matrix.type >= WESTON_MATRIX_TRANSFORM_ROTATE) { #endif warn_bad_matrix(&matrix, &output->matrix, &view->view->transform.matrix); } else { if (matrix.type & WESTON_MATRIX_TRANSFORM_ROTATE) { if (fabsf(matrix.d[0]) < 1e-4f && fabsf(matrix.d[5]) < 1e-4f) { flipt |= TRANSFORM_TRANSPOSE; } else if (fabsf(matrix.d[1]) < 1e-4 && fabsf(matrix.d[4]) < 1e-4) { /* no transpose */ } else { warn_bad_matrix(&matrix, &output->matrix, &view->view->transform.matrix); } } } p2.f[0] = view->view->surface->width; p2.f[1] = view->view->surface->height; /* transform top-left and bot-right corner into screen coordinates */ weston_matrix_transform(&matrix, &p1); weston_matrix_transform(&matrix, &p2); /* Compute the destination rectangle on screen, converting * negative dimensions to flips. */ dst_width = round(p2.f[0] - p1.f[0]); if (dst_width < 0) { dst_x = round(p2.f[0]); dst_width = -dst_width; if (!(flipt & TRANSFORM_TRANSPOSE)) flipt |= TRANSFORM_HFLIP; else flipt |= TRANSFORM_VFLIP; } else { dst_x = round(p1.f[0]); } dst_height = round(p2.f[1] - p1.f[1]); if (dst_height < 0) { dst_y = round(p2.f[1]); dst_height = -dst_height; if (!(flipt & TRANSFORM_TRANSPOSE)) flipt |= TRANSFORM_VFLIP; else flipt |= TRANSFORM_HFLIP; } else { dst_y = round(p1.f[1]); } if (dst_width == 0 || dst_height == 0) { DBG("ignored, zero surface area before clipping\n"); return -1; } #ifdef SURFACE_TRANSFORM /* Dispmanx works as if you flipped the whole screen, when * you flip an element. But, we want to flip an element in place. * XXX: fixme */ if (flipt & TRANSFORM_HFLIP) dst_x = output_base->width - dst_x; if (flipt & TRANSFORM_VFLIP) dst_y = output_base->height - dst_y; if (flipt & TRANSFORM_TRANSPOSE) { int_swap(&dst_x, &dst_y); int_swap(&dst_width, &dst_height); } #else switch (output_base->transform) { case WL_OUTPUT_TRANSFORM_FLIPPED: flipt = TRANSFORM_HFLIP; break; case WL_OUTPUT_TRANSFORM_NORMAL: flipt = 0; break; case WL_OUTPUT_TRANSFORM_FLIPPED_90: flipt = TRANSFORM_HFLIP | TRANSFORM_VFLIP | TRANSFORM_TRANSPOSE; break; case WL_OUTPUT_TRANSFORM_90: flipt = TRANSFORM_VFLIP | TRANSFORM_TRANSPOSE; break; case WL_OUTPUT_TRANSFORM_FLIPPED_180: flipt = TRANSFORM_VFLIP; break; case WL_OUTPUT_TRANSFORM_180: flipt = TRANSFORM_HFLIP | TRANSFORM_VFLIP; break; case WL_OUTPUT_TRANSFORM_FLIPPED_270: flipt = TRANSFORM_TRANSPOSE; break; case WL_OUTPUT_TRANSFORM_270: flipt = TRANSFORM_HFLIP | TRANSFORM_TRANSPOSE; break; default: break; } #endif /* clip destination rectangle to screen dimensions */ if (dst_x < 0) { t = (int64_t)dst_x * src_width / dst_width; src_width += t; dst_width += dst_x; src_x -= t; dst_x = 0; } if (dst_y < 0) { t = (int64_t)dst_y * src_height / dst_height; src_height += t; dst_height += dst_y; src_y -= t; dst_y = 0; } over = dst_x + dst_width - output_base->width; if (over > 0) { t = (int64_t)over * src_width / dst_width; src_width -= t; dst_width -= over; } over = dst_y + dst_height - output_base->height; if (over > 0) { t = (int64_t)over * src_height / dst_height; src_height -= t; dst_height -= over; } src_width = int_max(src_width, 0); src_height = int_max(src_height, 0); DBG("rpir_view %p %dx%d: p1 %f, %f; p2 %f, %f\n", view, view->view->surface->width, view->view->surface->height, p1.f[0], p1.f[1], p2.f[0], p2.f[1]); DBG("src rect %d;%d, %d;%d, %d;%dx%d;%d\n", src_x >> 16, src_x & 0xffff, src_y >> 16, src_y & 0xffff, src_width >> 16, src_width & 0xffff, src_height >> 16, src_height & 0xffff); DBG("dest rect %d, %d, %dx%d%s%s%s\n", dst_x, dst_y, dst_width, dst_height, (flipt & TRANSFORM_HFLIP) ? " hflip" : "", (flipt & TRANSFORM_VFLIP) ? " vflip" : "", (flipt & TRANSFORM_TRANSPOSE) ? " transp" : ""); assert(src_x >= 0); assert(src_y >= 0); assert(dst_x >= 0); assert(dst_y >= 0); if (dst_width < 1 || dst_height < 1) { DBG("ignored, zero surface area after clipping\n"); return -1; } /* EGL buffers will be upside-down related to what DispmanX expects */ if (view->surface->buffer_type == BUFFER_TYPE_EGL) flipt ^= TRANSFORM_VFLIP; vc_dispmanx_rect_set(src_rect, src_x, src_y, src_width, src_height); vc_dispmanx_rect_set(dst_rect, dst_x, dst_y, dst_width, dst_height); *flipmask = flipt; return 0; } static DISPMANX_TRANSFORM_T vc_image2dispmanx_transform(VC_IMAGE_TRANSFORM_T t) { /* XXX: uhh, are these right? */ switch (t) { case VC_IMAGE_ROT0: return DISPMANX_NO_ROTATE; case VC_IMAGE_MIRROR_ROT0: return DISPMANX_FLIP_HRIZ; case VC_IMAGE_MIRROR_ROT180: return DISPMANX_FLIP_VERT; case VC_IMAGE_ROT180: return DISPMANX_ROTATE_180; case VC_IMAGE_MIRROR_ROT90: return DISPMANX_ROTATE_90 | DISPMANX_FLIP_HRIZ; case VC_IMAGE_ROT270: return DISPMANX_ROTATE_270; case VC_IMAGE_ROT90: return DISPMANX_ROTATE_90; case VC_IMAGE_MIRROR_ROT270: return DISPMANX_ROTATE_270 | DISPMANX_FLIP_VERT; default: assert(0 && "bad VC_IMAGE_TRANSFORM_T"); return DISPMANX_NO_ROTATE; } } static DISPMANX_RESOURCE_HANDLE_T rpir_surface_get_resource(struct rpir_surface *surface) { switch (surface->buffer_type) { case BUFFER_TYPE_SHM: case BUFFER_TYPE_NULL: return surface->front->handle; case BUFFER_TYPE_EGL: if (surface->egl_front != NULL) return surface->egl_front->resource_handle; default: return DISPMANX_NO_HANDLE; } } #ifdef HAVE_ELEMENT_SET_OPAQUE_RECT static int rpir_surface_set_opaque_rect(struct rpir_surface *surface, DISPMANX_UPDATE_HANDLE_T update) { int ret; if (pixman_region32_not_empty(&surface->surface->opaque) && surface->opaque_regions) { pixman_box32_t *box; VC_RECT_T opaque_rect; box = pixman_region32_extents(&surface->surface->opaque); opaque_rect.x = box->x1; opaque_rect.y = box->y1; opaque_rect.width = box->x2 - box->x1; opaque_rect.height = box->y2 - box->y1; ret = vc_dispmanx_element_set_opaque_rect(update, surface->handle, &opaque_rect); if (ret) { weston_log("vc_dispmanx_element_set_opaque_rect failed\n"); return -1; } } return 0; } #endif static int rpir_view_dmx_add(struct rpir_view *view, struct rpir_output *output, DISPMANX_UPDATE_HANDLE_T update, int layer) { /* Do not use DISPMANX_FLAGS_ALPHA_PREMULT here. * If you define PREMULT and ALPHA_MIX, the hardware will not * multiply the source color with the element alpha, leading to * bad colors. Instead, we define PREMULT during pixel data upload. */ VC_DISPMANX_ALPHA_T alphasetup = { DISPMANX_FLAGS_ALPHA_FROM_SOURCE | DISPMANX_FLAGS_ALPHA_MIX, float2uint8(view->view->alpha), /* opacity 0-255 */ 0 /* mask resource handle */ }; VC_RECT_T dst_rect; VC_RECT_T src_rect; VC_IMAGE_TRANSFORM_T flipmask; int ret; DISPMANX_RESOURCE_HANDLE_T resource_handle; resource_handle = rpir_surface_get_resource(view->surface); if (resource_handle == DISPMANX_NO_HANDLE) { weston_log("%s: no buffer yet, aborting\n", __func__); return 0; } ret = rpir_view_compute_rects(view, &src_rect, &dst_rect, &flipmask); if (ret < 0) return 0; view->handle = vc_dispmanx_element_add( update, output->display, layer, &dst_rect, resource_handle, &src_rect, DISPMANX_PROTECTION_NONE, &alphasetup, NULL /* clamp */, vc_image2dispmanx_transform(flipmask)); DBG("rpir_surface %p add %u, alpha %f resource %d\n", view, view->handle, view->view->alpha, resource_handle); if (view->handle == DISPMANX_NO_HANDLE) return -1; #ifdef HAVE_ELEMENT_SET_OPAQUE_RECT ret = rpir_surface_set_opaque_rect(surface, update); if (ret < 0) return -1; #endif view->surface->visible_views++; return 1; } static void rpir_view_dmx_swap(struct rpir_view *view, DISPMANX_UPDATE_HANDLE_T update) { VC_RECT_T rect; pixman_box32_t *r; /* XXX: skip, iff resource was not reallocated, and single-buffering */ vc_dispmanx_element_change_source(update, view->handle, view->surface->front->handle); /* This is current damage now, after rpir_surface_damage() */ r = pixman_region32_extents(&view->surface->prev_damage); vc_dispmanx_rect_set(&rect, r->x1, r->y1, r->x2 - r->x1, r->y2 - r->y1); vc_dispmanx_element_modified(update, view->handle, &rect); DBG("rpir_view %p swap\n", view); } static int rpir_view_dmx_move(struct rpir_view *view, DISPMANX_UPDATE_HANDLE_T update, int layer) { uint8_t alpha = float2uint8(view->view->alpha); VC_RECT_T dst_rect; VC_RECT_T src_rect; VC_IMAGE_TRANSFORM_T flipmask; int ret; /* XXX: return early, if all attributes stay the same */ if (view->surface->buffer_type == BUFFER_TYPE_EGL) { DISPMANX_RESOURCE_HANDLE_T resource_handle; resource_handle = rpir_surface_get_resource(view->surface); if (resource_handle == DISPMANX_NO_HANDLE) { weston_log("%s: no buffer yet, aborting\n", __func__); return 0; } vc_dispmanx_element_change_source(update, view->handle, resource_handle); } ret = rpir_view_compute_rects(view, &src_rect, &dst_rect, &flipmask); if (ret < 0) return 0; ret = vc_dispmanx_element_change_attributes( update, view->handle, ELEMENT_CHANGE_LAYER | ELEMENT_CHANGE_OPACITY | ELEMENT_CHANGE_TRANSFORM | ELEMENT_CHANGE_DEST_RECT | ELEMENT_CHANGE_SRC_RECT, layer, alpha, &dst_rect, &src_rect, DISPMANX_NO_HANDLE, /* This really is DISPMANX_TRANSFORM_T, no matter * what the header says. */ vc_image2dispmanx_transform(flipmask)); DBG("rpir_view %p move\n", view); if (ret) return -1; #ifdef HAVE_ELEMENT_SET_OPAQUE_RECT ret = rpir_surface_set_opaque_rect(surface, update); if (ret < 0) return -1; #endif return 1; } static void rpir_view_dmx_remove(struct rpir_view *view, DISPMANX_UPDATE_HANDLE_T update) { if (view->handle == DISPMANX_NO_HANDLE) return; vc_dispmanx_element_remove(update, view->handle); DBG("rpir_view %p remove %u\n", view, view->handle); view->handle = DISPMANX_NO_HANDLE; view->surface->visible_views--; } static void rpir_surface_swap_pointers(struct rpir_surface *surface) { struct rpi_resource *tmp; if (surface->buffer_type == BUFFER_TYPE_EGL) { if (surface->egl_back != NULL) { assert(surface->egl_old_front == NULL); surface->egl_old_front = surface->egl_front; surface->egl_front = surface->egl_back; surface->egl_back = NULL; DBG("new front %d\n", surface->egl_front->resource_handle); } } else { tmp = surface->front; surface->front = surface->back; surface->back = tmp; DBG("new back %p, new front %p\n", surface->back, surface->front); } } static int is_view_not_visible(struct weston_view *view) { /* Return true, if surface is guaranteed to be totally obscured. */ int ret; pixman_region32_t unocc; pixman_region32_init(&unocc); pixman_region32_subtract(&unocc, &view->transform.boundingbox, &view->clip); ret = !pixman_region32_not_empty(&unocc); pixman_region32_fini(&unocc); return ret; } static void rpir_view_update(struct rpir_view *view, struct rpir_output *output, DISPMANX_UPDATE_HANDLE_T update, int layer) { int ret; int obscured; obscured = is_view_not_visible(view->view); if (obscured) { DBG("rpir_view %p totally obscured.\n", view); wl_list_remove(&view->link); if (view->handle == DISPMANX_NO_HANDLE) { wl_list_init(&view->link); } else { rpir_view_dmx_remove(view, update); wl_list_insert(&output->view_cleanup_list, &view->link); } goto out; } if (view->handle == DISPMANX_NO_HANDLE) { ret = rpir_view_dmx_add(view, output, update, layer); if (ret == 0) { wl_list_remove(&view->link); wl_list_init(&view->link); } else if (ret < 0) { weston_log("ERROR rpir_view_dmx_add() failed.\n"); } } else { if (view->surface->need_swap) rpir_view_dmx_swap(view, update); ret = rpir_view_dmx_move(view, update, layer); if (ret == 0) { rpir_view_dmx_remove(view, update); wl_list_remove(&view->link); wl_list_insert(&output->view_cleanup_list, &view->link); } else if (ret < 0) { weston_log("ERROR rpir_view_dmx_move() failed.\n"); } } out: view->layer = layer; } static int rpi_renderer_read_pixels(struct weston_output *base, pixman_format_code_t format, void *pixels, uint32_t x, uint32_t y, uint32_t width, uint32_t height) { struct rpir_output *output = to_rpir_output(base); struct rpi_resource *buffer = &output->capture_buffer; VC_RECT_T rect; uint32_t fb_width, fb_height; uint32_t dst_pitch; uint32_t i; int ret; fb_width = base->current_mode->width; fb_height = base->current_mode->height; DBG("%s(%u, %u, %u, %u), resource %p\n", __func__, x, y, width, height, buffer); if (format != PIXMAN_a8r8g8b8) { weston_log("rpi-renderer error: bad read_format\n"); return -1; } dst_pitch = fb_width * 4; if (buffer->handle == DISPMANX_NO_HANDLE) { free(output->capture_data); output->capture_data = NULL; ret = rpi_resource_realloc(buffer, VC_IMAGE_ARGB8888, fb_width, fb_height, dst_pitch, fb_height); if (ret < 0) { weston_log("rpi-renderer error: " "allocating read buffer failed\n"); return -1; } ret = vc_dispmanx_snapshot(output->display, buffer->handle, VC_IMAGE_ROT0); if (ret) { weston_log("rpi-renderer error: " "vc_dispmanx_snapshot returned %d\n", ret); return -1; } DBG("%s: snapshot done.\n", __func__); } /* * If vc_dispmanx_resource_read_data was able to read sub-rectangles, * we could read directly into 'pixels'. But it cannot, it does not * use rect.x or rect.width, and does this: * host_start = (uint8_t *)dst_address + (dst_pitch * p_rect->y); * In other words, it is only good for reading the full buffer in * one go. */ vc_dispmanx_rect_set(&rect, 0, 0, fb_width, fb_height); if (x == 0 && y == 0 && width == fb_width && height == fb_height) { ret = vc_dispmanx_resource_read_data(buffer->handle, &rect, pixels, dst_pitch); if (ret) { weston_log("rpi-renderer error: " "resource_read_data returned %d\n", ret); return -1; } DBG("%s: full frame done.\n", __func__); return 0; } if (!output->capture_data) { output->capture_data = malloc(fb_height * dst_pitch); if (!output->capture_data) { weston_log("rpi-renderer error: " "out of memory\n"); return -1; } ret = vc_dispmanx_resource_read_data(buffer->handle, &rect, output->capture_data, dst_pitch); if (ret) { weston_log("rpi-renderer error: " "resource_read_data returned %d\n", ret); return -1; } } for (i = 0; i < height; i++) { uint8_t *src = output->capture_data + (y + i) * dst_pitch + x * 4; uint8_t *dst = (uint8_t *)pixels + i * width * 4; memcpy(dst, src, width * 4); } return 0; } static void rpir_output_dmx_remove_all(struct rpir_output *output, DISPMANX_UPDATE_HANDLE_T update) { struct rpir_view *view; while (!wl_list_empty(&output->view_list)) { view = container_of(output->view_list.next, struct rpir_view, link); rpir_view_dmx_remove(view, update); wl_list_remove(&view->link); wl_list_insert(&output->view_cleanup_list, &view->link); } } static void output_compute_matrix(struct weston_output *base) { struct rpir_output *output = to_rpir_output(base); struct weston_matrix *matrix = &output->matrix; #ifdef SURFACE_TRANSFORM const float half_w = 0.5f * base->width; const float half_h = 0.5f * base->height; #endif float mag; weston_matrix_init(matrix); weston_matrix_translate(matrix, -base->x, -base->y, 0.0f); #ifdef SURFACE_TRANSFORM weston_matrix_translate(matrix, -half_w, -half_h, 0.0f); switch (base->transform) { case WL_OUTPUT_TRANSFORM_FLIPPED: weston_matrix_scale(matrix, -1.0f, 1.0f, 1.0f); case WL_OUTPUT_TRANSFORM_NORMAL: /* weston_matrix_rotate_xy(matrix, 1.0f, 0.0f); no-op */ weston_matrix_translate(matrix, half_w, half_h, 0.0f); break; case WL_OUTPUT_TRANSFORM_FLIPPED_90: weston_matrix_scale(matrix, -1.0f, 1.0f, 1.0f); case WL_OUTPUT_TRANSFORM_90: weston_matrix_rotate_xy(matrix, 0.0f, 1.0f); weston_matrix_translate(matrix, half_h, half_w, 0.0f); break; case WL_OUTPUT_TRANSFORM_FLIPPED_180: weston_matrix_scale(matrix, -1.0f, 1.0f, 1.0f); case WL_OUTPUT_TRANSFORM_180: weston_matrix_rotate_xy(matrix, -1.0f, 0.0f); weston_matrix_translate(matrix, half_w, half_h, 0.0f); break; case WL_OUTPUT_TRANSFORM_FLIPPED_270: weston_matrix_scale(matrix, -1.0f, 1.0f, 1.0f); case WL_OUTPUT_TRANSFORM_270: weston_matrix_rotate_xy(matrix, 0.0f, -1.0f); weston_matrix_translate(matrix, half_h, half_w, 0.0f); break; default: break; } #endif if (base->zoom.active) { mag = 1.0f / (1.0f - base->zoom.spring_z.current); weston_matrix_translate(matrix, base->zoom.trans_x, base->zoom.trans_y, 0.0f); weston_matrix_scale(matrix, mag, mag, 1.0f); } } /* Note: this won't work right for multiple outputs. A DispmanX Element * is tied to one DispmanX Display, i.e. output. */ static void rpi_renderer_repaint_output(struct weston_output *base, pixman_region32_t *output_damage) { struct weston_compositor *compositor = base->compositor; struct rpir_output *output = to_rpir_output(base); struct weston_view *wv; struct rpir_view *view; struct wl_list done_list; int layer = 1; assert(output->update != DISPMANX_NO_HANDLE); output_compute_matrix(base); rpi_resource_release(&output->capture_buffer); free(output->capture_data); output->capture_data = NULL; /* Swap resources on surfaces as needed */ wl_list_for_each_reverse(wv, &compositor->view_list, link) wv->surface->touched = 0; wl_list_for_each_reverse(wv, &compositor->view_list, link) { view = to_rpir_view(wv); if (!wv->surface->touched) { wv->surface->touched = 1; if (view->surface->buffer_type == BUFFER_TYPE_EGL || view->surface->need_swap) rpir_surface_swap_pointers(view->surface); } if (view->surface->buffer_type == BUFFER_TYPE_EGL) { struct weston_buffer *buffer; buffer = view->surface->egl_front->buffer_ref.buffer; if (buffer != NULL) { rpi_buffer_egl_lock(buffer); } else { weston_log("warning: client destroyed current front buffer\n"); wl_list_remove(&view->link); if (view->handle == DISPMANX_NO_HANDLE) { wl_list_init(&view->link); } else { rpir_view_dmx_remove(view, output->update); wl_list_insert(&output->view_cleanup_list, &view->link); } } } } /* update all renderable surfaces */ wl_list_init(&done_list); wl_list_for_each_reverse(wv, &compositor->view_list, link) { if (wv->plane != &compositor->primary_plane) continue; view = to_rpir_view(wv); assert(!wl_list_empty(&view->link) || view->handle == DISPMANX_NO_HANDLE); wl_list_remove(&view->link); wl_list_insert(&done_list, &view->link); rpir_view_update(view, output, output->update, layer++); } /* Mark all surfaces as swapped */ wl_list_for_each_reverse(wv, &compositor->view_list, link) to_rpir_surface(wv->surface)->need_swap = 0; /* Remove all surfaces that are still on screen, but were * not rendered this time. */ rpir_output_dmx_remove_all(output, output->update); wl_list_insert_list(&output->view_list, &done_list); output->update = DISPMANX_NO_HANDLE; /* The frame_signal is emitted in rpi_renderer_finish_frame(), * so that the firmware can capture the up-to-date contents. */ } static void rpi_renderer_flush_damage(struct weston_surface *base) { /* Called for every surface just before repainting it, if * having an shm buffer. */ struct rpir_surface *surface = to_rpir_surface(base); struct weston_buffer *buffer = surface->buffer_ref.buffer; int ret; assert(buffer); assert(wl_shm_buffer_get(buffer->resource)); ret = rpir_surface_damage(surface, buffer, &base->damage); if (ret) weston_log("%s error: updating Dispmanx resource failed.\n", __func__); weston_buffer_reference(&surface->buffer_ref, NULL); } static void rpi_renderer_attach(struct weston_surface *base, struct weston_buffer *buffer) { /* Called every time a client commits an attach. */ struct rpir_surface *surface = to_rpir_surface(base); assert(surface); if (!surface) return; if (surface->buffer_type == BUFFER_TYPE_SHM) { if (!surface->single_buffer) /* XXX: need to check if in middle of update */ rpi_resource_release(surface->back); if (!surface->visible_views) /* XXX: cannot do this, if middle of an update */ rpi_resource_release(surface->front); weston_buffer_reference(&surface->buffer_ref, NULL); } /* If buffer is NULL, Weston core unmaps the surface, the surface * will not appear in repaint list, and so rpi_renderer_repaint_output * will remove the DispmanX element. Later, for SHM, also the front * buffer will be released in the cleanup_list processing. */ if (!buffer) return; if (wl_shm_buffer_get(buffer->resource)) { surface->buffer_type = BUFFER_TYPE_SHM; buffer->shm_buffer = wl_shm_buffer_get(buffer->resource); buffer->width = wl_shm_buffer_get_width(buffer->shm_buffer); buffer->height = wl_shm_buffer_get_height(buffer->shm_buffer); weston_buffer_reference(&surface->buffer_ref, buffer); } else { #if ENABLE_EGL struct rpi_renderer *renderer = to_rpi_renderer(base->compositor); struct wl_resource *wl_resource = buffer->resource; if (!renderer->has_bind_display || !renderer->query_buffer(renderer->egl_display, wl_resource, EGL_WIDTH, &buffer->width)) { weston_log("unhandled buffer type!\n"); weston_buffer_reference(&surface->buffer_ref, NULL); surface->buffer_type = BUFFER_TYPE_NULL; } renderer->query_buffer(renderer->egl_display, wl_resource, EGL_HEIGHT, &buffer->height); surface->buffer_type = BUFFER_TYPE_EGL; if(surface->egl_back == NULL) surface->egl_back = zalloc(sizeof *surface->egl_back); weston_buffer_reference(&surface->egl_back->buffer_ref, buffer); surface->egl_back->resource_handle = vc_dispmanx_get_handle_from_wl_buffer(wl_resource); #else weston_log("unhandled buffer type!\n"); weston_buffer_reference(&surface->buffer_ref, NULL); surface->buffer_type = BUFFER_TYPE_NULL; #endif } } static void rpir_surface_handle_surface_destroy(struct wl_listener *listener, void *data) { struct rpir_surface *surface; struct weston_surface *base = data; surface = container_of(listener, struct rpir_surface, surface_destroy_listener); assert(surface); assert(surface->surface == base); if (!surface) return; surface->surface = NULL; base->renderer_state = NULL; if (wl_list_empty(&surface->views)) rpir_surface_destroy(surface); } static int rpi_renderer_create_surface(struct weston_surface *base) { struct rpi_renderer *renderer = to_rpi_renderer(base->compositor); struct rpir_surface *surface; assert(base->renderer_state == NULL); surface = rpir_surface_create(renderer); if (!surface) return -1; surface->surface = base; base->renderer_state = surface; surface->surface_destroy_listener.notify = rpir_surface_handle_surface_destroy; wl_signal_add(&base->destroy_signal, &surface->surface_destroy_listener); return 0; } static int rpi_renderer_create_view(struct weston_view *base) { struct rpir_surface *surface = to_rpir_surface(base->surface); struct rpir_view *view; assert(base->renderer_state == NULL); view = rpir_view_create(surface); if (!view) return -1; view->view = base; base->renderer_state = view; view->view_destroy_listener.notify = rpir_view_handle_view_destroy; wl_signal_add(&base->destroy_signal, &view->view_destroy_listener); return 0; } static void rpi_renderer_surface_set_color(struct weston_surface *base, float red, float green, float blue, float alpha) { struct rpir_surface *surface = to_rpir_surface(base); uint8_t color[4]; VC_RECT_T rect; int ret; assert(surface); ret = rpi_resource_realloc(surface->back, VC_IMAGE_ARGB8888, 1, 1, 4, 1); if (ret < 0) { weston_log("Error: %s: rpi_resource_realloc failed.\n", __func__); return; } color[0] = float2uint8(blue); color[1] = float2uint8(green); color[2] = float2uint8(red); color[3] = float2uint8(alpha); vc_dispmanx_rect_set(&rect, 0, 0, 1, 1); ret = vc_dispmanx_resource_write_data(surface->back->handle, VC_IMAGE_ARGB8888, 4, color, &rect); if (ret) { weston_log("Error: %s: resource_write_data failed.\n", __func__); return; } DBG("%s: resource %p solid color BGRA %u,%u,%u,%u\n", __func__, surface->back, color[0], color[1], color[2], color[3]); /*pixman_region32_copy(&surface->prev_damage, damage);*/ surface->need_swap = 1; } static void rpir_view_handle_view_destroy(struct wl_listener *listener, void *data) { struct rpir_view *view; struct weston_view *base = data; view = container_of(listener, struct rpir_view, view_destroy_listener); assert(view); assert(view->view == base); if (!view) return; view->view = NULL; base->renderer_state = NULL; /* If guaranteed to not be on screen, just destroy it. */ if (wl_list_empty(&view->link)) rpir_view_destroy(view); /* Otherwise, the view is either on screen and needs * to be removed by a repaint update, or it is in the * view_cleanup_list, and will be destroyed by * rpi_renderer_finish_frame(). */ } static void rpi_renderer_destroy(struct weston_compositor *compositor) { struct rpi_renderer *renderer = to_rpi_renderer(compositor); #if ENABLE_EGL if (renderer->has_bind_display) renderer->unbind_display(renderer->egl_display, compositor->wl_display); #endif free(renderer); compositor->renderer = NULL; } WL_EXPORT int rpi_renderer_create(struct weston_compositor *compositor, const struct rpi_renderer_parameters *params) { struct rpi_renderer *renderer; #if ENABLE_EGL const char *extensions; EGLBoolean ret; EGLint major, minor; #endif weston_log("Initializing the DispmanX compositing renderer\n"); renderer = zalloc(sizeof *renderer); if (renderer == NULL) return -1; renderer->single_buffer = params->single_buffer; renderer->enable_opaque_regions = params->opaque_regions; renderer->base.read_pixels = rpi_renderer_read_pixels; renderer->base.repaint_output = rpi_renderer_repaint_output; renderer->base.flush_damage = rpi_renderer_flush_damage; renderer->base.attach = rpi_renderer_attach; renderer->base.surface_set_color = rpi_renderer_surface_set_color; renderer->base.destroy = rpi_renderer_destroy; #ifdef ENABLE_EGL renderer->egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (renderer->egl_display == EGL_NO_DISPLAY) { weston_log("failed to create EGL display\n"); free(renderer); return -1; } if (!eglInitialize(renderer->egl_display, &major, &minor)) { weston_log("failed to initialize EGL display\n"); free(renderer); return -1; } renderer->bind_display = (void *) eglGetProcAddress("eglBindWaylandDisplayWL"); renderer->unbind_display = (void *) eglGetProcAddress("eglUnbindWaylandDisplayWL"); renderer->query_buffer = (void *) eglGetProcAddress("eglQueryWaylandBufferWL"); extensions = (const char *) eglQueryString(renderer->egl_display, EGL_EXTENSIONS); if (!extensions) { weston_log("Retrieving EGL extension string failed.\n"); eglTerminate(renderer->egl_display); free(renderer); return -1; } if (strstr(extensions, "EGL_WL_bind_wayland_display")) renderer->has_bind_display = 1; if (renderer->has_bind_display) { ret = renderer->bind_display(renderer->egl_display, compositor->wl_display); if (!ret) renderer->has_bind_display = 0; } #endif compositor->renderer = &renderer->base; compositor->read_format = PIXMAN_a8r8g8b8; /* WESTON_CAP_ROTATION_ANY not supported */ wl_display_add_shm_format(compositor->wl_display, WL_SHM_FORMAT_RGB565); return 0; } WL_EXPORT int rpi_renderer_output_create(struct weston_output *base, DISPMANX_DISPLAY_HANDLE_T display) { struct rpir_output *output; assert(base->renderer_state == NULL); output = zalloc(sizeof *output); if (output == NULL) return -1; output->display = display; output->update = DISPMANX_NO_HANDLE; wl_list_init(&output->view_list); wl_list_init(&output->view_cleanup_list); rpi_resource_init(&output->capture_buffer); base->renderer_state = output; return 0; } WL_EXPORT void rpi_renderer_output_destroy(struct weston_output *base) { struct rpir_output *output = to_rpir_output(base); struct rpir_view *view; DISPMANX_UPDATE_HANDLE_T update; rpi_resource_release(&output->capture_buffer); free(output->capture_data); output->capture_data = NULL; update = vc_dispmanx_update_start(0); rpir_output_dmx_remove_all(output, update); vc_dispmanx_update_submit_sync(update); while (!wl_list_empty(&output->view_cleanup_list)) { view = container_of(output->view_cleanup_list.next, struct rpir_view, link); rpir_view_destroy(view); } free(output); base->renderer_state = NULL; } WL_EXPORT void rpi_renderer_set_update_handle(struct weston_output *base, DISPMANX_UPDATE_HANDLE_T handle) { struct rpir_output *output = to_rpir_output(base); output->update = handle; } WL_EXPORT void rpi_renderer_finish_frame(struct weston_output *base) { struct rpir_output *output = to_rpir_output(base); struct weston_compositor *compositor = base->compositor; struct weston_view *wv; struct rpir_view *view; while (!wl_list_empty(&output->view_cleanup_list)) { view = container_of(output->view_cleanup_list.next, struct rpir_view, link); if (view->view) { /* The weston_view still exists, but is * temporarily not visible, and hence its Element * was removed. The current front buffer contents * must be preserved. */ if (!view->surface->visible_views) rpi_resource_release(view->surface->back); wl_list_remove(&view->link); wl_list_init(&view->link); } else { rpir_view_destroy(view); } } wl_list_for_each(wv, &compositor->view_list, link) { view = to_rpir_view(wv); if (view->surface->buffer_type != BUFFER_TYPE_EGL) continue; rpir_egl_buffer_destroy(view->surface->egl_old_front); view->surface->egl_old_front = NULL; } wl_signal_emit(&base->frame_signal, base); }
mit
ros-gbp/yaml_cpp-release
src/emitterstate.cpp
5
5815
#include "emitterstate.h" #include "yaml-cpp/exceptions.h" namespace YAML { EmitterState::EmitterState(): m_isGood(true), m_curIndent(0), m_requiresSoftSeparation(false), m_requiresHardSeparation(false) { // start up m_stateStack.push(ES_WAITING_FOR_DOC); // set default global manipulators m_charset.set(EmitNonAscii); m_strFmt.set(Auto); m_boolFmt.set(TrueFalseBool); m_boolLengthFmt.set(LongBool); m_boolCaseFmt.set(LowerCase); m_intFmt.set(Dec); m_indent.set(2); m_preCommentIndent.set(2); m_postCommentIndent.set(1); m_seqFmt.set(Block); m_mapFmt.set(Block); m_mapKeyFmt.set(Auto); } EmitterState::~EmitterState() { } // SetLocalValue // . We blindly tries to set all possible formatters to this value // . Only the ones that make sense will be accepted void EmitterState::SetLocalValue(EMITTER_MANIP value) { SetOutputCharset(value, LOCAL); SetStringFormat(value, LOCAL); SetBoolFormat(value, LOCAL); SetBoolCaseFormat(value, LOCAL); SetBoolLengthFormat(value, LOCAL); SetIntFormat(value, LOCAL); SetFlowType(GT_SEQ, value, LOCAL); SetFlowType(GT_MAP, value, LOCAL); SetMapKeyFormat(value, LOCAL); } void EmitterState::BeginGroup(GROUP_TYPE type) { unsigned lastIndent = (m_groups.empty() ? 0 : m_groups.top().indent); m_curIndent += lastIndent; std::auto_ptr<Group> pGroup(new Group(type)); // transfer settings (which last until this group is done) pGroup->modifiedSettings = m_modifiedSettings; // set up group pGroup->flow = GetFlowType(type); pGroup->indent = GetIndent(); pGroup->usingLongKey = (GetMapKeyFormat() == LongKey ? true : false); m_groups.push(pGroup); } void EmitterState::EndGroup(GROUP_TYPE type) { if(m_groups.empty()) return SetError(ErrorMsg::UNMATCHED_GROUP_TAG); // get rid of the current group { std::auto_ptr<Group> pFinishedGroup = m_groups.pop(); if(pFinishedGroup->type != type) return SetError(ErrorMsg::UNMATCHED_GROUP_TAG); } // reset old settings unsigned lastIndent = (m_groups.empty() ? 0 : m_groups.top().indent); assert(m_curIndent >= lastIndent); m_curIndent -= lastIndent; // some global settings that we changed may have been overridden // by a local setting we just popped, so we need to restore them m_globalModifiedSettings.restore(); } GROUP_TYPE EmitterState::GetCurGroupType() const { if(m_groups.empty()) return GT_NONE; return m_groups.top().type; } FLOW_TYPE EmitterState::GetCurGroupFlowType() const { if(m_groups.empty()) return FT_NONE; return (m_groups.top().flow == Flow ? FT_FLOW : FT_BLOCK); } bool EmitterState::CurrentlyInLongKey() { if(m_groups.empty()) return false; return m_groups.top().usingLongKey; } void EmitterState::StartLongKey() { if(!m_groups.empty()) m_groups.top().usingLongKey = true; } void EmitterState::StartSimpleKey() { if(!m_groups.empty()) m_groups.top().usingLongKey = false; } void EmitterState::ClearModifiedSettings() { m_modifiedSettings.clear(); } bool EmitterState::SetOutputCharset(EMITTER_MANIP value, FMT_SCOPE scope) { switch(value) { case EmitNonAscii: case EscapeNonAscii: _Set(m_charset, value, scope); return true; default: return false; } } bool EmitterState::SetStringFormat(EMITTER_MANIP value, FMT_SCOPE scope) { switch(value) { case Auto: case SingleQuoted: case DoubleQuoted: case Literal: _Set(m_strFmt, value, scope); return true; default: return false; } } bool EmitterState::SetBoolFormat(EMITTER_MANIP value, FMT_SCOPE scope) { switch(value) { case OnOffBool: case TrueFalseBool: case YesNoBool: _Set(m_boolFmt, value, scope); return true; default: return false; } } bool EmitterState::SetBoolLengthFormat(EMITTER_MANIP value, FMT_SCOPE scope) { switch(value) { case LongBool: case ShortBool: _Set(m_boolLengthFmt, value, scope); return true; default: return false; } } bool EmitterState::SetBoolCaseFormat(EMITTER_MANIP value, FMT_SCOPE scope) { switch(value) { case UpperCase: case LowerCase: case CamelCase: _Set(m_boolCaseFmt, value, scope); return true; default: return false; } } bool EmitterState::SetIntFormat(EMITTER_MANIP value, FMT_SCOPE scope) { switch(value) { case Dec: case Hex: case Oct: _Set(m_intFmt, value, scope); return true; default: return false; } } bool EmitterState::SetIndent(unsigned value, FMT_SCOPE scope) { if(value == 0) return false; _Set(m_indent, value, scope); return true; } bool EmitterState::SetPreCommentIndent(unsigned value, FMT_SCOPE scope) { if(value == 0) return false; _Set(m_preCommentIndent, value, scope); return true; } bool EmitterState::SetPostCommentIndent(unsigned value, FMT_SCOPE scope) { if(value == 0) return false; _Set(m_postCommentIndent, value, scope); return true; } bool EmitterState::SetFlowType(GROUP_TYPE groupType, EMITTER_MANIP value, FMT_SCOPE scope) { switch(value) { case Block: case Flow: _Set(groupType == GT_SEQ ? m_seqFmt : m_mapFmt, value, scope); return true; default: return false; } } EMITTER_MANIP EmitterState::GetFlowType(GROUP_TYPE groupType) const { // force flow style if we're currently in a flow FLOW_TYPE flowType = GetCurGroupFlowType(); if(flowType == FT_FLOW) return Flow; // otherwise, go with what's asked of use return (groupType == GT_SEQ ? m_seqFmt.get() : m_mapFmt.get()); } bool EmitterState::SetMapKeyFormat(EMITTER_MANIP value, FMT_SCOPE scope) { switch(value) { case Auto: case LongKey: _Set(m_mapKeyFmt, value, scope); return true; default: return false; } } }
mit
djsedulous/namecoind
libs/db-4.7.25.NC/test/scr023/q.c
6
18254
#include <sys/types.h> #include <sys/time.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "queue.h" #include "shqueue.h" typedef enum { FORWARD_WALK_FAILED = 1, FOREACH_WALK_FAILED, LIST_END_NOT_MARKED_FAILURE, PREV_WALK_FAILED, REVERSE_FOREACH_WALK_FAILED, EXPECTED_HEAD_FAILED } FAILURE_REASON; const char *failure_reason_names[] = { "", "walking the list using the _NEXT forward failed", "walking the list using the _FOREACH macro failed", "what was expected to be the last element wasn't marked as such", "walking the list using the _PREV macro failed", "walking the list using the _REVERSE_FOREACH macro failed", "expected to be at the head of the list" }; SH_LIST_HEAD(sh_lq); struct sh_le { char content; SH_LIST_ENTRY sh_les; }; /* create a string from the content of a list queue */ char * sh_l_as_string(l) struct sh_lq *l; { static char buf[1024]; struct sh_le *ele = SH_LIST_FIRST(l, sh_le); int i = 1; buf[0] = '"'; while (ele != NULL) { buf[i] = ele->content; ele = SH_LIST_NEXT(ele, sh_les, sh_le); if (ele != NULL) buf[++i] = ' '; i++; } buf[i++] = '"'; buf[i] = '\0'; return buf; } /* init a list queue */ struct sh_lq * sh_l_init(items) const char *items; { const char *c = items; struct sh_le *ele = NULL, *last_ele = (struct sh_le*)-1; struct sh_lq *l = calloc(1, sizeof(struct sh_lq)); SH_LIST_INIT(l); while (*c != '\0') { if (c[0] != ' ') { last_ele = ele; ele = calloc(1, sizeof(struct sh_le)); ele->content = c[0]; if (SH_LIST_EMPTY(l)) SH_LIST_INSERT_HEAD(l, ele, sh_les, sh_le); else SH_LIST_INSERT_AFTER( last_ele, ele, sh_les, sh_le); } c++; } return (l); } struct sh_lq * sh_l_remove_head(l) struct sh_lq *l; { struct sh_le *ele = SH_LIST_FIRST(l, sh_le); SH_LIST_REMOVE_HEAD(l, sh_les, sh_le); if (ele != NULL) free(ele); return (l); } struct sh_lq * sh_l_remove_tail(l) struct sh_lq *l; { struct sh_le *ele = SH_LIST_FIRST(l, sh_le); if (SH_LIST_EMPTY(l)) return (l); while (SH_LIST_NEXT(ele, sh_les, sh_le) != NULL) ele = SH_LIST_NEXT(ele, sh_les, sh_le); if (ele) { SH_LIST_REMOVE(ele, sh_les, sh_le); free(ele); } return (l); } struct sh_lq * sh_l_remove_item(l, item) struct sh_lq *l; const char *item; { struct sh_le *ele = SH_LIST_FIRST(l, sh_le); while (ele != NULL) { if (ele->content == item[0]) break; ele = SH_LIST_NEXT(ele, sh_les, sh_le); } if (ele) SH_LIST_REMOVE(ele, sh_les, sh_le); return (l); } struct sh_lq * sh_l_insert_head(l, item) struct sh_lq *l; const char *item; { struct sh_le *ele = calloc(1, sizeof(struct sh_le)); ele->content = item[0]; SH_LIST_INSERT_HEAD(l, ele, sh_les, sh_le); return (l); } struct sh_lq * sh_l_insert_tail(l, item) struct sh_lq *l; const char *item; { struct sh_le *ele = NULL; struct sh_le *last_ele = SH_LIST_FIRST(l, sh_le); if (last_ele != NULL) while (SH_LIST_NEXT(last_ele, sh_les, sh_le) != NULL) last_ele = SH_LIST_NEXT(last_ele, sh_les, sh_le); if (last_ele == NULL) { ele = calloc(1, sizeof(struct sh_le)); ele->content = item[0]; SH_LIST_INSERT_HEAD(l, ele, sh_les, sh_le); } else { ele = calloc(1, sizeof(struct sh_le)); ele->content = item[0]; SH_LIST_INSERT_AFTER(last_ele, ele, sh_les, sh_le); } return (l); } struct sh_lq * sh_l_insert_before(l, item, before_item) struct sh_lq *l; const char *item; const char *before_item; { struct sh_le *ele = NULL; struct sh_le *before_ele = SH_LIST_FIRST(l, sh_le); while (before_ele != NULL) { if (before_ele->content == before_item[0]) break; before_ele = SH_LIST_NEXT(before_ele, sh_les, sh_le); } if (before_ele != NULL) { ele = calloc(1, sizeof(struct sh_le)); ele->content = item[0]; SH_LIST_INSERT_BEFORE(l, before_ele, ele, sh_les, sh_le); } return (l); } struct sh_lq * sh_l_insert_after(l, item, after_item) struct sh_lq *l; const char *item; const char *after_item; { struct sh_le *ele = NULL; struct sh_le *after_ele = SH_LIST_FIRST(l, sh_le); while (after_ele != NULL) { if (after_ele->content == after_item[0]) break; after_ele = SH_LIST_NEXT(after_ele, sh_les, sh_le); } if (after_ele != NULL) { ele = calloc(1, sizeof(struct sh_le)); ele->content = item[0]; SH_LIST_INSERT_AFTER(after_ele, ele, sh_les, sh_le); } return (l); } void sh_l_discard(l) struct sh_lq *l; { struct sh_le *ele = NULL; while ((ele = SH_LIST_FIRST(l, sh_le)) != NULL) { SH_LIST_REMOVE(ele, sh_les, sh_le); free(ele); } free(l); } int sh_l_verify(l, items) struct sh_lq *l; const char *items; { const char *c = items; struct sh_le *ele = NULL, *lele = NULL; int i = 0, nele = 0; while (*c != '\0') { if (c[0] != ' ') nele++; c++; } /* use the FOREACH macro to walk the list */ c = items; i = 0; SH_LIST_FOREACH(ele, l, sh_les, sh_le) { if (ele->content != c[0]) return (FOREACH_WALK_FAILED); i++; c +=2; } if (i != nele) return (FOREACH_WALK_FAILED); i = 0; if (items[0] != '\0') { /* walk the list forward */ c = items; ele = SH_LIST_FIRST(l, sh_le); while (*c != '\0') { lele = ele; if (c[0] != ' ') { if (ele->content != c[0]) return (FORWARD_WALK_FAILED); i++; ele = SH_LIST_NEXT(ele, sh_les, sh_le); } c++; } ele = lele; if (i != nele) return (FOREACH_WALK_FAILED); /* ele should be the last element in the list... */ /* ... so sle_next should be -1 */ if (ele->sh_les.sle_next != -1) return (LIST_END_NOT_MARKED_FAILURE); /* and NEXT needs to be NULL */ if (SH_LIST_NEXT(ele, sh_les, sh_le) != NULL) return (LIST_END_NOT_MARKED_FAILURE); /* * walk the list backwards using PREV macro, first move c * back a bit */ c--; i = 0; while (c >= items) { if (c[0] != ' ') { lele = ele; if (ele->content != c[0]) return (PREV_WALK_FAILED); ele = SH_LIST_PREV(ele, sh_les, sh_le); i++; } c--; } ele = lele; if (i != nele) return (PREV_WALK_FAILED); if (ele != SH_LIST_FIRST(l, sh_le)) return (EXPECTED_HEAD_FAILED); } return (0); } SH_TAILQ_HEAD(sh_tq); struct sh_te { char content; SH_TAILQ_ENTRY sh_tes; }; /* create a string from the content of a list queue */ char * sh_t_as_string(l) struct sh_tq *l; { static char buf[1024]; struct sh_te *ele = SH_TAILQ_FIRST(l, sh_te); int i = 1; buf[0] = '"'; while (ele != NULL) { buf[i] = ele->content; ele = SH_TAILQ_NEXT(ele, sh_tes, sh_te); if (ele != NULL) buf[++i] = ' '; i++; } buf[i++] = '"'; buf[i] = '\0'; return (buf); } /* init a tail queue */ struct sh_tq * sh_t_init(items) const char *items; { const char *c = items; struct sh_te *ele = NULL, *last_ele = (struct sh_te*)-1; struct sh_tq *l = calloc(1, sizeof(struct sh_tq)); SH_TAILQ_INIT(l); while (*c != '\0') { if (c[0] != ' ') { ele = calloc(1, sizeof(struct sh_te)); ele->content = c[0]; if (SH_TAILQ_EMPTY(l)) SH_TAILQ_INSERT_HEAD(l, ele, sh_tes, sh_te); else SH_TAILQ_INSERT_AFTER( l, last_ele, ele, sh_tes, sh_te); last_ele = ele; } c++; } return (l); } struct sh_tq * sh_t_remove_head(l) struct sh_tq *l; { struct sh_te *ele = SH_TAILQ_FIRST(l, sh_te); if (ele != NULL) SH_TAILQ_REMOVE(l, ele, sh_tes, sh_te); free(ele); return (l); } struct sh_tq * sh_t_remove_tail(l) struct sh_tq *l; { struct sh_te *ele = SH_TAILQ_FIRST(l, sh_te); if (SH_TAILQ_EMPTY(l)) return (l); while (SH_TAILQ_NEXT(ele, sh_tes, sh_te) != NULL) ele = SH_TAILQ_NEXT(ele, sh_tes, sh_te); if (ele != NULL) { SH_TAILQ_REMOVE(l, ele, sh_tes, sh_te); free(ele); } return (l); } struct sh_tq * sh_t_remove_item(l, item) struct sh_tq *l; const char *item; { struct sh_te *ele = SH_TAILQ_FIRST(l, sh_te); while (ele != NULL) { if (ele->content == item[0]) break; ele = SH_TAILQ_NEXT(ele, sh_tes, sh_te); } if (ele != NULL) SH_TAILQ_REMOVE(l, ele, sh_tes, sh_te); return (l); } struct sh_tq * sh_t_insert_head(l, item) struct sh_tq *l; const char *item; { struct sh_te *ele = calloc(1, sizeof(struct sh_te)); ele->content = item[0]; SH_TAILQ_INSERT_HEAD(l, ele, sh_tes, sh_te); return (l); } struct sh_tq * sh_t_insert_tail(l, item) struct sh_tq *l; const char *item; { struct sh_te *ele = 0; ele = calloc(1, sizeof(struct sh_te)); ele->content = item[0]; SH_TAILQ_INSERT_TAIL(l, ele, sh_tes); return l; } struct sh_tq * sh_t_insert_before(l, item, before_item) struct sh_tq *l; const char *item; const char *before_item; { struct sh_te *ele = NULL; struct sh_te *before_ele = SH_TAILQ_FIRST(l, sh_te); while (before_ele != NULL) { if (before_ele->content == before_item[0]) break; before_ele = SH_TAILQ_NEXT(before_ele, sh_tes, sh_te); } if (before_ele != NULL) { ele = calloc(1, sizeof(struct sh_te)); ele->content = item[0]; SH_TAILQ_INSERT_BEFORE(l, before_ele, ele, sh_tes, sh_te); } return (l); } struct sh_tq * sh_t_insert_after(l, item, after_item) struct sh_tq *l; const char *item; const char *after_item; { struct sh_te *ele = NULL; struct sh_te *after_ele = SH_TAILQ_FIRST(l, sh_te); while (after_ele != NULL) { if (after_ele->content == after_item[0]) break; after_ele = SH_TAILQ_NEXT(after_ele, sh_tes, sh_te); } if (after_ele != NULL) { ele = calloc(1, sizeof(struct sh_te)); ele->content = item[0]; SH_TAILQ_INSERT_AFTER(l, after_ele, ele, sh_tes, sh_te); } return (l); } void sh_t_discard(l) struct sh_tq *l; { struct sh_te *ele = NULL; while ((ele = SH_TAILQ_FIRST(l, sh_te)) != NULL) { SH_TAILQ_REMOVE(l, ele, sh_tes, sh_te); free(ele); } free(l); } int sh_t_verify(l, items) struct sh_tq *l; const char *items; { const char *c = items, *b = NULL; struct sh_te *ele = NULL, *lele = NULL; int i = 0, nele = 0; while (*c != '\0') { if (c[0] != ' ') nele++; c++; } /* use the FOREACH macro to walk the list */ c = items; i = 0; SH_TAILQ_FOREACH(ele, l, sh_tes, sh_te) { if (ele->content != c[0]) return (FOREACH_WALK_FAILED); i++; c +=2; } if (i != nele) return (FOREACH_WALK_FAILED); i = 0; if (items[0] != '\0') { /* walk the list forward */ c = items; ele = SH_TAILQ_FIRST(l, sh_te); while (*c != '\0') { lele = ele; if (c[0] != ' ') { if (ele->content != c[0]) return (FORWARD_WALK_FAILED); i++; ele = SH_TAILQ_NEXT(ele, sh_tes, sh_te); } c++; } if (i != nele) return (FOREACH_WALK_FAILED); if (lele != SH_TAILQ_LAST(l, sh_tes, sh_te)) return (LIST_END_NOT_MARKED_FAILURE); ele = lele; /* ele should be the last element in the list... */ /* ... so sle_next should be -1 */ if (ele->sh_tes.stqe_next != -1) return (LIST_END_NOT_MARKED_FAILURE); /* and NEXT needs to be NULL */ if (SH_TAILQ_NEXT(ele, sh_tes, sh_te) != NULL) return (LIST_END_NOT_MARKED_FAILURE); /* walk the list backwards using SH_LIST_PREV macro */ c--; b = c; i = 0; while (c >= items) { if (c[0] != ' ') { lele = ele; if (ele->content != c[0]) return (PREV_WALK_FAILED); ele = SH_TAILQ_PREV(l, ele, sh_tes, sh_te); i++; } c--; } ele = lele; if (i != nele) return (PREV_WALK_FAILED); if (ele != SH_TAILQ_FIRST(l, sh_te)) return (-1); /* c should be the last character in the array, walk backwards from here using FOREACH_REVERSE and check the values again */ c = b; i = 0; ele = SH_TAILQ_LAST(l, sh_tes, sh_te); SH_TAILQ_FOREACH_REVERSE(ele, l, sh_tes, sh_te) { if (ele->content != c[0]) return (REVERSE_FOREACH_WALK_FAILED); i++; c -=2; } if (i != nele) return (REVERSE_FOREACH_WALK_FAILED); } return (0); } int sh_t_verify_TAILQ_LAST(l, items) struct sh_tq *l; const char *items; { const char *c = items; struct sh_te *ele = NULL; c = items; while (*c != '\0') { c++; } if (c == items) { /* items is empty, so last should be NULL */ if (SH_TAILQ_LAST(l, sh_tes, sh_te) != NULL) return (-1); } else { c--; ele = SH_TAILQ_LAST(l, sh_tes, sh_te); if (ele->content != c[0]) return (-1); } return (0); } typedef void *qds_t; struct { const char *name; qds_t *(*f_init)(const char *); qds_t *(*f_remove_head)(qds_t *); qds_t *(*f_remove_tail)(qds_t *); qds_t *(*f_remove_item)(qds_t *, const char *); qds_t *(*f_insert_head)(qds_t *, const char *); qds_t *(*f_insert_tail)(qds_t *, const char *); qds_t *(*f_insert_before)(qds_t *, const char *, const char *); qds_t *(*f_insert_after)(qds_t *, const char *, const char *); qds_t *(*f_discard)(qds_t *); char *(*f_as_string)(qds_t *); int (*f_verify)(qds_t *, const char *); } qfns[]= { { "sh_list", (qds_t*(*)(const char *))sh_l_init, (qds_t*(*)(qds_t *))sh_l_remove_head, (qds_t*(*)(qds_t *))sh_l_remove_tail, (qds_t*(*)(qds_t *, const char *))sh_l_remove_item, (qds_t*(*)(qds_t *, const char *))sh_l_insert_head, (qds_t*(*)(qds_t *, const char *))sh_l_insert_tail, (qds_t*(*)(qds_t *, const char *, const char *))sh_l_insert_before, (qds_t*(*)(qds_t *, const char *, const char *))sh_l_insert_after, (qds_t*(*)(qds_t *))sh_l_discard, (char *(*)(qds_t *))sh_l_as_string, (int(*)(qds_t *, const char *))sh_l_verify }, { "sh_tailq", (qds_t*(*)(const char *))sh_t_init, (qds_t*(*)(qds_t *))sh_t_remove_head, (qds_t*(*)(qds_t *))sh_t_remove_tail, (qds_t*(*)(qds_t *, const char *))sh_t_remove_item, (qds_t*(*)(qds_t *, const char *))sh_t_insert_head, (qds_t*(*)(qds_t *, const char *))sh_t_insert_tail, (qds_t*(*)(qds_t *, const char *, const char *))sh_t_insert_before, (qds_t*(*)(qds_t *, const char *, const char *))sh_t_insert_after, (qds_t*(*)(qds_t *))sh_t_discard, (char *(*)(qds_t *))sh_t_as_string, (int(*)(qds_t *, const char *))sh_t_verify } }; typedef enum { INSERT_BEFORE, INSERT_AFTER, INSERT_HEAD, INSERT_TAIL, REMOVE_HEAD, REMOVE_ITEM, REMOVE_TAIL, } OP; const char *op_names[] = { "INSERT_BEFORE", "INSERT_AFTER", "INSERT_HEAD", "INSERT_TAIL", "REMOVE_HEAD", "REMOVE_ITEM", "REMOVE_TAIL" }; struct { char *init; /* initial state. */ char *final; /* final state. */ char *elem; /* element to operate on */ char *insert; /* element to insert */ OP op; /* operation. */ } ops[] = { /* most operations on a empty list */ { "", "", NULL, NULL, REMOVE_HEAD }, { "", "", NULL, NULL, REMOVE_TAIL }, { "", "A", NULL, "A", INSERT_HEAD }, { "", "A", NULL, "A", INSERT_TAIL }, /* all operations on a one element list */ { "A", "", NULL, NULL, REMOVE_HEAD }, { "A", "", NULL, NULL, REMOVE_TAIL }, { "A", "", "A", NULL, REMOVE_ITEM }, { "B", "A B", NULL, "A", INSERT_HEAD }, { "A", "A B", NULL, "B", INSERT_TAIL }, { "B", "A B", "B", "A", INSERT_BEFORE }, { "A", "A B", "A", "B", INSERT_AFTER }, /* all operations on a two element list */ { "A B", "B", NULL, NULL, REMOVE_HEAD }, { "A B", "A", NULL, NULL, REMOVE_TAIL }, { "A B", "A", "B", NULL, REMOVE_ITEM }, { "A B", "B", "A", NULL, REMOVE_ITEM }, { "B C", "A B C", NULL, "A", INSERT_HEAD }, { "A B", "A B C", NULL, "C", INSERT_TAIL }, { "B C", "A B C", "B", "A", INSERT_BEFORE }, { "A C", "A B C", "C", "B", INSERT_BEFORE }, { "A C", "A B C", "A", "B", INSERT_AFTER }, { "A C", "A C B", "C", "B", INSERT_AFTER }, /* all operations on a three element list */ { "A B C", "B C", NULL, NULL, REMOVE_HEAD }, { "A B C", "A B", NULL, NULL, REMOVE_TAIL }, { "A B C", "A B", "C", NULL, REMOVE_ITEM }, { "A B C", "A C", "B", NULL, REMOVE_ITEM }, { "A B C", "B C", "A", NULL, REMOVE_ITEM }, { "B C D", "A B C D", NULL, "A", INSERT_HEAD }, { "A B C", "A B C D", NULL, "D", INSERT_TAIL }, { "A B C", "X A B C", "A", "X", INSERT_BEFORE }, { "A B C", "A X B C", "B", "X", INSERT_BEFORE }, { "A B C", "A B X C", "C", "X", INSERT_BEFORE }, { "A B C", "A X B C", "A", "X", INSERT_AFTER }, { "A B C", "A B X C", "B", "X", INSERT_AFTER }, { "A B C", "A B C X", "C", "X", INSERT_AFTER }, }; int main(argc, argv) int argc; char *argv[]; { void *list; int fc, tc; /* tc is total count, fc is failed count */ int eval, i, t, result; eval = 0; for (t = 0; t < sizeof(qfns) / sizeof(qfns[0]); ++t) { fc = tc = 0; printf("TESTING: %s\n", qfns[t].name); for (i = 0; i < sizeof(ops) / sizeof(ops[0]); i++) { list = qfns[t].f_init(ops[i].init); result = qfns[t].f_verify(list, ops[i].init); if (result == 0) { fc++; putchar('.'); } else { putchar('+'); /* + means failed before op */ printf("\nVerify failed: %s\n", failure_reason_names[result]); eval = 1; } if (!strcmp("sh_tailq", qfns[t].name)) { result = sh_t_verify_TAILQ_LAST(list, ops[i].init); } #ifdef VERBOSE printf("\ncase %d %s in %s init: \"%s\" desired: \"%s\" elem: \"%s\" insert: \"%s\"\n", i, op_names[ops[i].op], qfns[t].name, ops[i].init, ops[i].final, ops[i].elem, ops[i].insert); fflush(stdout); #endif tc++; switch (ops[i].op) { case REMOVE_HEAD: qfns[t].f_remove_head(list); break; case REMOVE_TAIL: qfns[t].f_remove_tail(list); break; case REMOVE_ITEM: qfns[t].f_remove_item(list, ops[i].elem); break; case INSERT_HEAD: qfns[t].f_insert_head(list, ops[i].insert); break; case INSERT_TAIL: qfns[t].f_insert_tail(list, ops[i].insert); break; case INSERT_BEFORE: qfns[t].f_insert_before( list, ops[i].insert, ops[i].elem); break; case INSERT_AFTER: qfns[t].f_insert_after( list, ops[i].insert, ops[i].elem); break; } if (!strcmp("sh_tailq", op_names[ops[i].op])) { result = sh_t_verify_TAILQ_LAST(list, ops[i].final); } if (result == 0) result = qfns[t].f_verify(list, ops[i].final); if (result == 0) { fc++; putchar('.'); } else { putchar('*'); /* * means failed after op */ printf("\ncase %d %s in %s init: \"%s\" desired: \"%s\" elem: \"%s\" insert: \"%s\" got: %s - %s\n", i, op_names[ops[i].op], qfns[t].name, ops[i].init, ops[i].final, ops[i].elem, ops[i].insert, qfns[t].f_as_string(list), failure_reason_names[result]); fflush(stdout); eval = 1; } tc++; qfns[t].f_discard(list); } printf("\t%0.2f%% passed (%d/%d).\n", (((double)fc/tc) * 100), fc, tc); } return (eval); }
mit
PUCSIE-embedded-course/stm32f4-examples
firmware/freertos/create_task/lib/FreeRTOSV8.2.3/FreeRTOS/Demo/Common/Full/flash.c
6
7056
/* FreeRTOS V8.2.3 - Copyright (C) 2015 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS 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 >>>> AND MODIFIED BY <<<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS 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. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /** * Creates eight tasks, each of which flash an LED at a different rate. The first * LED flashes every 125ms, the second every 250ms, the third every 375ms, etc. * * The LED flash tasks provide instant visual feedback. They show that the scheduler * is still operational. * * The PC port uses the standard parallel port for outputs, the Flashlite 186 port * uses IO port F. * * \page flashC flash.c * \ingroup DemoFiles * <HR> */ /* Changes from V2.0.0 + Delay periods are now specified using variables and constants of TickType_t rather than unsigned long. Changes from V2.1.1 + The stack size now uses configMINIMAL_STACK_SIZE. + String constants made file scope to decrease stack depth on 8051 port. */ #include <stdlib.h> /* Scheduler include files. */ #include "FreeRTOS.h" #include "task.h" /* Demo program include files. */ #include "partest.h" #include "flash.h" #include "print.h" #define ledSTACK_SIZE configMINIMAL_STACK_SIZE /* Structure used to pass parameters to the LED tasks. */ typedef struct LED_PARAMETERS { unsigned portBASE_TYPE uxLED; /*< The output the task should use. */ TickType_t xFlashRate; /*< The rate at which the LED should flash. */ } xLEDParameters; /* The task that is created eight times - each time with a different xLEDParaemtes structure passed in as the parameter. */ static void vLEDFlashTask( void *pvParameters ); /* String to print if USE_STDIO is defined. */ const char * const pcTaskStartMsg = "LED flash task started.\r\n"; /*-----------------------------------------------------------*/ void vStartLEDFlashTasks( unsigned portBASE_TYPE uxPriority ) { unsigned portBASE_TYPE uxLEDTask; xLEDParameters *pxLEDParameters; const unsigned portBASE_TYPE uxNumOfLEDs = 8; const TickType_t xFlashRate = 125; /* Create the eight tasks. */ for( uxLEDTask = 0; uxLEDTask < uxNumOfLEDs; ++uxLEDTask ) { /* Create and complete the structure used to pass parameters to the next created task. */ pxLEDParameters = ( xLEDParameters * ) pvPortMalloc( sizeof( xLEDParameters ) ); pxLEDParameters->uxLED = uxLEDTask; pxLEDParameters->xFlashRate = ( xFlashRate + ( xFlashRate * ( TickType_t ) uxLEDTask ) ); pxLEDParameters->xFlashRate /= portTICK_PERIOD_MS; /* Spawn the task. */ xTaskCreate( vLEDFlashTask, "LEDx", ledSTACK_SIZE, ( void * ) pxLEDParameters, uxPriority, ( TaskHandle_t * ) NULL ); } } /*-----------------------------------------------------------*/ static void vLEDFlashTask( void *pvParameters ) { xLEDParameters *pxParameters; /* Queue a message for printing to say the task has started. */ vPrintDisplayMessage( &pcTaskStartMsg ); pxParameters = ( xLEDParameters * ) pvParameters; for(;;) { /* Delay for half the flash period then turn the LED on. */ vTaskDelay( pxParameters->xFlashRate / ( TickType_t ) 2 ); vParTestToggleLED( pxParameters->uxLED ); /* Delay for half the flash period then turn the LED off. */ vTaskDelay( pxParameters->xFlashRate / ( TickType_t ) 2 ); vParTestToggleLED( pxParameters->uxLED ); } }
mit
davisp/python-spidermonkey
spidermonkey/string.c
6
1938
/* * Copyright 2009 Paul J. Davis <paul.joseph.davis@gmail.com> * * This file is part of the python-spidermonkey package released * under the MIT license. * */ #include "spidermonkey.h" JSString* py2js_string_obj(Context* cx, PyObject* str) { PyObject* conv = NULL; PyObject* encoded = NULL; JSString* ret = NULL; char* bytes; Py_ssize_t len; if(PyString_Check(str)) { conv = PyUnicode_FromEncodedObject(str, "utf-8", "replace"); if(conv == NULL) goto error; str = conv; } else if(!PyUnicode_Check(str)) { PyErr_SetString(PyExc_TypeError, "Invalid string conversion."); goto error; } encoded = PyUnicode_AsEncodedString(str, "utf-16", "strict"); if(encoded == NULL) goto error; if(PyString_AsStringAndSize(encoded, &bytes, &len) < 0) goto error; if(len < 2) { PyErr_SetString(PyExc_ValueError, "Failed to find byte-order mark."); goto error; } if(((unsigned short*) bytes)[0] != 0xFEFF) { PyErr_SetString(PyExc_ValueError, "Invalid UTF-16 BOM"); goto error; } ret = JS_NewUCStringCopyN(cx->cx, (jschar*) (bytes+2), (len/2)-1); goto success; error: success: Py_XDECREF(conv); Py_XDECREF(encoded); return ret; } jsval py2js_string(Context* cx, PyObject* str) { JSString* val = py2js_string_obj(cx, str); if(val == NULL) { PyErr_Clear(); return JSVAL_VOID; } return STRING_TO_JSVAL(val); } PyObject* js2py_string(Context* cx, jsval val) { JSString* str; jschar* bytes; size_t len; if(!JSVAL_IS_STRING(val)) { PyErr_SetString(PyExc_TypeError, "Value is not a JS String."); return NULL; } str = JSVAL_TO_STRING(val); len = JS_GetStringLength(str); bytes = JS_GetStringChars(str); return PyUnicode_Decode((const char*) bytes, len*2, "utf-16", "strict"); }
mit
iainmerrick/Urho3D
Source/Urho3D/Resource/Resource.cpp
7
5429
// // Copyright (c) 2008-2017 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Precompiled.h" #include "../Core/Profiler.h" #include "../IO/File.h" #include "../IO/Log.h" #include "../Resource/Resource.h" #include "../Resource/XMLElement.h" namespace Urho3D { Resource::Resource(Context* context) : Object(context), memoryUse_(0), asyncLoadState_(ASYNC_DONE) { } bool Resource::Load(Deserializer& source) { // Because BeginLoad() / EndLoad() can be called from worker threads, where profiling would be a no-op, // create a type name -based profile block here #ifdef URHO3D_PROFILING String profileBlockName("Load" + GetTypeName()); Profiler* profiler = GetSubsystem<Profiler>(); if (profiler) profiler->BeginBlock(profileBlockName.CString()); #endif // If we are loading synchronously in a non-main thread, behave as if async loading (for example use // GetTempResource() instead of GetResource() to load resource dependencies) SetAsyncLoadState(Thread::IsMainThread() ? ASYNC_DONE : ASYNC_LOADING); bool success = BeginLoad(source); if (success) success &= EndLoad(); SetAsyncLoadState(ASYNC_DONE); #ifdef URHO3D_PROFILING if (profiler) profiler->EndBlock(); #endif return success; } bool Resource::BeginLoad(Deserializer& source) { // This always needs to be overridden by subclasses return false; } bool Resource::EndLoad() { // If no GPU upload step is necessary, no override is necessary return true; } bool Resource::Save(Serializer& dest) const { URHO3D_LOGERROR("Save not supported for " + GetTypeName()); return false; } bool Resource::LoadFile(const String& fileName) { File file(context_); return file.Open(fileName, FILE_READ) && Load(file); } bool Resource::SaveFile(const String& fileName) const { File file(context_); return file.Open(fileName, FILE_WRITE) && Save(file); } void Resource::SetName(const String& name) { name_ = name; nameHash_ = name; } void Resource::SetMemoryUse(unsigned size) { memoryUse_ = size; } void Resource::ResetUseTimer() { useTimer_.Reset(); } void Resource::SetAsyncLoadState(AsyncLoadState newState) { asyncLoadState_ = newState; } unsigned Resource::GetUseTimer() { // If more references than the resource cache, return always 0 & reset the timer if (Refs() > 1) { useTimer_.Reset(); return 0; } else return useTimer_.GetMSec(false); } void ResourceWithMetadata::AddMetadata(const String& name, const Variant& value) { bool exists; metadata_.Insert(MakePair(StringHash(name), value), exists); if (!exists) metadataKeys_.Push(name); } void ResourceWithMetadata::RemoveMetadata(const String& name) { metadata_.Erase(name); metadataKeys_.Remove(name); } void ResourceWithMetadata::RemoveAllMetadata() { metadata_.Clear(); metadataKeys_.Clear(); } const Urho3D::Variant& ResourceWithMetadata::GetMetadata(const String& name) const { const Variant* value = metadata_[name]; return value ? *value : Variant::EMPTY; } bool ResourceWithMetadata::HasMetadata() const { return !metadata_.Empty(); } void ResourceWithMetadata::LoadMetadataFromXML(const XMLElement& source) { for (XMLElement elem = source.GetChild("metadata"); elem; elem = elem.GetNext("metadata")) AddMetadata(elem.GetAttribute("name"), elem.GetVariant()); } void ResourceWithMetadata::LoadMetadataFromJSON(const JSONArray& array) { for (unsigned i = 0; i < array.Size(); i++) { const JSONValue& value = array.At(i); AddMetadata(value.Get("name").GetString(), value.GetVariant()); } } void ResourceWithMetadata::SaveMetadataToXML(XMLElement& destination) const { for (unsigned i = 0; i < metadataKeys_.Size(); ++i) { XMLElement elem = destination.CreateChild("metadata"); elem.SetString("name", metadataKeys_[i]); elem.SetVariant(GetMetadata(metadataKeys_[i])); } } void ResourceWithMetadata::CopyMetadata(const ResourceWithMetadata& source) { metadata_ = source.metadata_; metadataKeys_ = source.metadataKeys_; } }
mit
Yndal/ArduPilot-SensorPlatform
PX4NuttX/nuttx/arch/z80/src/z80/z80_sigdeliver.c
8
4957
/**************************************************************************** * arch/z80/src/z80/z80_sigdeliver.c * * Copyright (C) 2007-2010 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sched.h> #include <debug.h> #include <nuttx/irq.h> #include <nuttx/arch.h> #include "chip/switch.h" #include "os_internal.h" #include "up_internal.h" #ifndef CONFIG_DISABLE_SIGNALS /**************************************************************************** * Definitions ****************************************************************************/ /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: up_sigdeliver * * Description: * This is the a signal handling trampoline. When a signal action was * posted. The task context was mucked with and forced to branch to this * location with interrupts disabled. * ****************************************************************************/ void up_sigdeliver(void) { #ifndef CONFIG_DISABLE_SIGNALS FAR struct tcb_s *rtcb = (struct tcb_s*)g_readytorun.head; chipreg_t regs[XCPTCONTEXT_REGS]; sig_deliver_t sigdeliver; /* Save the errno. This must be preserved throughout the signal handling * so that the user code final gets the correct errno value (probably * EINTR). */ int saved_errno = rtcb->pterrno; up_ledon(LED_SIGNAL); sdbg("rtcb=%p sigdeliver=%p sigpendactionq.head=%p\n", rtcb, rtcb->xcp.sigdeliver, rtcb->sigpendactionq.head); ASSERT(rtcb->xcp.sigdeliver != NULL); /* Save the real return state on the stack. */ z80_copystate(regs, rtcb->xcp.regs); regs[XCPT_PC] = rtcb->xcp.saved_pc; regs[XCPT_I] = rtcb->xcp.saved_i; /* Get a local copy of the sigdeliver function pointer. We do this so * that we can nullify the sigdeliver function pointer in the TCB and * accept more signal deliveries while processing the current pending * signals. */ sigdeliver = rtcb->xcp.sigdeliver; rtcb->xcp.sigdeliver = NULL; /* Then restore the task interrupt state. */ irqrestore(regs[XCPT_I]); /* Deliver the signals */ sigdeliver(rtcb); /* Output any debug messages BEFORE restoring errno (because they may * alter errno), then disable interrupts again and restore the original * errno that is needed by the user logic (it is probably EINTR). */ sdbg("Resuming\n"); (void)irqsave(); rtcb->pterrno = saved_errno; /* Then restore the correct state for this thread of execution. */ up_ledoff(LED_SIGNAL); z80_restoreusercontext(regs); #endif } #endif /* CONFIG_DISABLE_SIGNALS */
mit
airgames/vuforia-gamekit-integration
Gamekit/bullet/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.cpp
9
7653
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btContinuousConvexCollision.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h" #include "LinearMath/btTransformUtil.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" #include "btGjkPairDetector.h" #include "btPointCollector.h" #include "BulletCollision/CollisionShapes/btStaticPlaneShape.h" btContinuousConvexCollision::btContinuousConvexCollision ( const btConvexShape* convexA,const btConvexShape* convexB,btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* penetrationDepthSolver) :m_simplexSolver(simplexSolver), m_penetrationDepthSolver(penetrationDepthSolver), m_convexA(convexA),m_convexB1(convexB),m_planeShape(0) { } btContinuousConvexCollision::btContinuousConvexCollision( const btConvexShape* convexA,const btStaticPlaneShape* plane) :m_simplexSolver(0), m_penetrationDepthSolver(0), m_convexA(convexA),m_convexB1(0),m_planeShape(plane) { } /// This maximum should not be necessary. It allows for untested/degenerate cases in production code. /// You don't want your game ever to lock-up. #define MAX_ITERATIONS 64 void btContinuousConvexCollision::computeClosestPoints( const btTransform& transA, const btTransform& transB,btPointCollector& pointCollector) { if (m_convexB1) { m_simplexSolver->reset(); btGjkPairDetector gjk(m_convexA,m_convexB1,m_convexA->getShapeType(),m_convexB1->getShapeType(),m_convexA->getMargin(),m_convexB1->getMargin(),m_simplexSolver,m_penetrationDepthSolver); btGjkPairDetector::ClosestPointInput input; input.m_transformA = transA; input.m_transformB = transB; gjk.getClosestPoints(input,pointCollector,0); } else { //convex versus plane const btConvexShape* convexShape = m_convexA; const btStaticPlaneShape* planeShape = m_planeShape; bool hasCollision = false; const btVector3& planeNormal = planeShape->getPlaneNormal(); const btScalar& planeConstant = planeShape->getPlaneConstant(); btTransform convexWorldTransform = transA; btTransform convexInPlaneTrans; convexInPlaneTrans= transB.inverse() * convexWorldTransform; btTransform planeInConvex; planeInConvex= convexWorldTransform.inverse() * transB; btVector3 vtx = convexShape->localGetSupportingVertex(planeInConvex.getBasis()*-planeNormal); btVector3 vtxInPlane = convexInPlaneTrans(vtx); btScalar distance = (planeNormal.dot(vtxInPlane) - planeConstant); btVector3 vtxInPlaneProjected = vtxInPlane - distance*planeNormal; btVector3 vtxInPlaneWorld = transB * vtxInPlaneProjected; btVector3 normalOnSurfaceB = transB.getBasis() * planeNormal; pointCollector.addContactPoint( normalOnSurfaceB, vtxInPlaneWorld, distance); } } bool btContinuousConvexCollision::calcTimeOfImpact( const btTransform& fromA, const btTransform& toA, const btTransform& fromB, const btTransform& toB, CastResult& result) { /// compute linear and angular velocity for this interval, to interpolate btVector3 linVelA,angVelA,linVelB,angVelB; btTransformUtil::calculateVelocity(fromA,toA,btScalar(1.),linVelA,angVelA); btTransformUtil::calculateVelocity(fromB,toB,btScalar(1.),linVelB,angVelB); btScalar boundingRadiusA = m_convexA->getAngularMotionDisc(); btScalar boundingRadiusB = m_convexB1?m_convexB1->getAngularMotionDisc():0.f; btScalar maxAngularProjectedVelocity = angVelA.length() * boundingRadiusA + angVelB.length() * boundingRadiusB; btVector3 relLinVel = (linVelB-linVelA); btScalar relLinVelocLength = (linVelB-linVelA).length(); if ((relLinVelocLength+maxAngularProjectedVelocity) == 0.f) return false; btScalar lambda = btScalar(0.); btVector3 v(1,0,0); int maxIter = MAX_ITERATIONS; btVector3 n; n.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); bool hasResult = false; btVector3 c; btScalar lastLambda = lambda; //btScalar epsilon = btScalar(0.001); int numIter = 0; //first solution, using GJK btScalar radius = 0.001f; // result.drawCoordSystem(sphereTr); btPointCollector pointCollector1; { computeClosestPoints(fromA,fromB,pointCollector1); hasResult = pointCollector1.m_hasResult; c = pointCollector1.m_pointInWorld; } if (hasResult) { btScalar dist; dist = pointCollector1.m_distance + result.m_allowedPenetration; n = pointCollector1.m_normalOnBInWorld; btScalar projectedLinearVelocity = relLinVel.dot(n); if ((projectedLinearVelocity+ maxAngularProjectedVelocity)<=SIMD_EPSILON) return false; //not close enough while (dist > radius) { if (result.m_debugDrawer) { result.m_debugDrawer->drawSphere(c,0.2f,btVector3(1,1,1)); } btScalar dLambda = btScalar(0.); projectedLinearVelocity = relLinVel.dot(n); //don't report time of impact for motion away from the contact normal (or causes minor penetration) if ((projectedLinearVelocity+ maxAngularProjectedVelocity)<=SIMD_EPSILON) return false; dLambda = dist / (projectedLinearVelocity+ maxAngularProjectedVelocity); lambda = lambda + dLambda; if (lambda > btScalar(1.)) return false; if (lambda < btScalar(0.)) return false; //todo: next check with relative epsilon if (lambda <= lastLambda) { return false; //n.setValue(0,0,0); break; } lastLambda = lambda; //interpolate to next lambda btTransform interpolatedTransA,interpolatedTransB,relativeTrans; btTransformUtil::integrateTransform(fromA,linVelA,angVelA,lambda,interpolatedTransA); btTransformUtil::integrateTransform(fromB,linVelB,angVelB,lambda,interpolatedTransB); relativeTrans = interpolatedTransB.inverseTimes(interpolatedTransA); if (result.m_debugDrawer) { result.m_debugDrawer->drawSphere(interpolatedTransA.getOrigin(),0.2f,btVector3(1,0,0)); } result.DebugDraw( lambda ); btPointCollector pointCollector; computeClosestPoints(interpolatedTransA,interpolatedTransB,pointCollector); if (pointCollector.m_hasResult) { dist = pointCollector.m_distance+result.m_allowedPenetration; c = pointCollector.m_pointInWorld; n = pointCollector.m_normalOnBInWorld; } else { result.reportFailure(-1, numIter); return false; } numIter++; if (numIter > maxIter) { result.reportFailure(-2, numIter); return false; } } result.m_fraction = lambda; result.m_normal = n; result.m_hitPoint = c; return true; } return false; }
mit
alexhenrie/poedit
deps/boost/libs/fusion/test/sequence/adapt_assoc_struct_named_empty.cpp
10
3172
/*============================================================================= Copyright (c) 2016 Kohei Takahashi Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #include <boost/detail/lightweight_test.hpp> #include <boost/fusion/adapted/struct/adapt_assoc_struct_named.hpp> #include <boost/fusion/sequence/intrinsic/size.hpp> #include <boost/fusion/sequence/intrinsic/empty.hpp> #include <boost/fusion/sequence/intrinsic/begin.hpp> #include <boost/fusion/sequence/intrinsic/end.hpp> #include <boost/fusion/sequence/io/out.hpp> #include <boost/fusion/iterator/equal_to.hpp> #include <boost/fusion/container/vector/vector.hpp> #include <boost/fusion/container/list/list.hpp> #include <boost/fusion/container/generation/make_vector.hpp> #include <boost/fusion/sequence/comparison/equal_to.hpp> #include <boost/fusion/sequence/comparison/not_equal_to.hpp> #include <boost/fusion/sequence/comparison/less.hpp> #include <boost/fusion/sequence/comparison/less_equal.hpp> #include <boost/fusion/sequence/comparison/greater.hpp> #include <boost/fusion/sequence/comparison/greater_equal.hpp> #include <boost/fusion/mpl.hpp> #include <boost/fusion/support/is_view.hpp> #include <boost/mpl/is_sequence.hpp> #include <boost/mpl/assert.hpp> #include <iostream> class empty_struct{}; BOOST_FUSION_ADAPT_ASSOC_STRUCT_NAMED(::empty_struct,empty_struct,) int main() { using namespace boost::fusion; using namespace boost; std::cout << tuple_open('['); std::cout << tuple_close(']'); std::cout << tuple_delimiter(", "); empty_struct empty; { BOOST_MPL_ASSERT((traits::is_view<adapted::empty_struct>)); BOOST_STATIC_ASSERT(traits::is_view<adapted::empty_struct>::value); adapted::empty_struct e(empty); std::cout << e << std::endl; BOOST_TEST(e == make_vector()); BOOST_STATIC_ASSERT(fusion::result_of::size<adapted::empty_struct>::value == 0); BOOST_MPL_ASSERT((fusion::result_of::empty<adapted::empty_struct>)); BOOST_MPL_ASSERT((fusion::result_of::equal_to< fusion::result_of::begin<adapted::empty_struct>::type, fusion::result_of::end<adapted::empty_struct>::type>)); } { fusion::vector<> v; adapted::empty_struct e(empty); BOOST_TEST(v <= e); BOOST_TEST_NOT(e > v); BOOST_TEST_NOT(v < e); BOOST_TEST(v <= e); BOOST_TEST_NOT(e > v); BOOST_TEST(e >= v); } { adapted::empty_struct e(empty); // conversion from empty_struct to vector fusion::vector<> v(e); v = e; // FIXME // conversion from empty_struct to list //fusion::list<> l(e); //l = e; } BOOST_MPL_ASSERT((mpl::is_sequence<adapted::empty_struct>)); BOOST_MPL_ASSERT_NOT((fusion::result_of::has_key<adapted::empty_struct, void>)); BOOST_MPL_ASSERT_NOT((fusion::result_of::has_key<adapted::empty_struct, int>)); return boost::report_errors(); }
mit
eugeneko/Urho3D
Source/ThirdParty/DetourTileCache/Source/DetourTileCache.cpp
10
21712
// Modified by Lasse Oorni and cosmy1 for Urho3D #include "DetourTileCache.h" #include "DetourTileCacheBuilder.h" #include "DetourNavMeshBuilder.h" #include "DetourNavMesh.h" #include "DetourCommon.h" #include "DetourMath.h" #include "DetourAlloc.h" #include "DetourAssert.h" #include <string.h> #include <new> dtTileCache* dtAllocTileCache() { void* mem = dtAlloc(sizeof(dtTileCache), DT_ALLOC_PERM); if (!mem) return 0; return new(mem) dtTileCache; } void dtFreeTileCache(dtTileCache* tc) { if (!tc) return; tc->~dtTileCache(); dtFree(tc); } static bool contains(const dtCompressedTileRef* a, const int n, const dtCompressedTileRef v) { for (int i = 0; i < n; ++i) if (a[i] == v) return true; return false; } inline int computeTileHash(int x, int y, const int mask) { const unsigned int h1 = 0x8da6b343; // Large multiplicative constants; const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes unsigned int n = h1 * x + h2 * y; return (int)(n & mask); } struct NavMeshTileBuildContext { inline NavMeshTileBuildContext(struct dtTileCacheAlloc* a) : layer(0), lcset(0), lmesh(0), alloc(a) {} inline ~NavMeshTileBuildContext() { purge(); } void purge() { dtFreeTileCacheLayer(alloc, layer); layer = 0; dtFreeTileCacheContourSet(alloc, lcset); lcset = 0; dtFreeTileCachePolyMesh(alloc, lmesh); lmesh = 0; } struct dtTileCacheLayer* layer; struct dtTileCacheContourSet* lcset; struct dtTileCachePolyMesh* lmesh; struct dtTileCacheAlloc* alloc; }; dtTileCache::dtTileCache() : m_tileLutSize(0), m_tileLutMask(0), m_posLookup(0), m_nextFreeTile(0), m_tiles(0), m_saltBits(0), m_tileBits(0), m_talloc(0), m_tcomp(0), m_tmproc(0), m_obstacles(0), m_nextFreeObstacle(0), m_nreqs(0), m_nupdate(0) { memset(&m_params, 0, sizeof(m_params)); memset(m_reqs, 0, sizeof(ObstacleRequest) * MAX_REQUESTS); // Urho3D: initialize all class members memset(&m_update, 0, sizeof(m_update)); } dtTileCache::~dtTileCache() { // Urho3D: added null check for tile allocation if (m_tiles) { for (int i = 0; i < m_params.maxTiles; ++i) { if (m_tiles[i].flags & DT_COMPRESSEDTILE_FREE_DATA) { dtFree(m_tiles[i].data); m_tiles[i].data = 0; } } } dtFree(m_obstacles); m_obstacles = 0; dtFree(m_posLookup); m_posLookup = 0; dtFree(m_tiles); m_tiles = 0; m_nreqs = 0; m_nupdate = 0; } const dtCompressedTile* dtTileCache::getTileByRef(dtCompressedTileRef ref) const { if (!ref) return 0; unsigned int tileIndex = decodeTileIdTile(ref); unsigned int tileSalt = decodeTileIdSalt(ref); if ((int)tileIndex >= m_params.maxTiles) return 0; const dtCompressedTile* tile = &m_tiles[tileIndex]; if (tile->salt != tileSalt) return 0; return tile; } dtStatus dtTileCache::init(const dtTileCacheParams* params, dtTileCacheAlloc* talloc, dtTileCacheCompressor* tcomp, dtTileCacheMeshProcess* tmproc) { m_talloc = talloc; m_tcomp = tcomp; m_tmproc = tmproc; m_nreqs = 0; memcpy(&m_params, params, sizeof(m_params)); // Alloc space for obstacles. m_obstacles = (dtTileCacheObstacle*)dtAlloc(sizeof(dtTileCacheObstacle)*m_params.maxObstacles, DT_ALLOC_PERM); if (!m_obstacles) return DT_FAILURE | DT_OUT_OF_MEMORY; memset(m_obstacles, 0, sizeof(dtTileCacheObstacle)*m_params.maxObstacles); m_nextFreeObstacle = 0; for (int i = m_params.maxObstacles-1; i >= 0; --i) { m_obstacles[i].salt = 1; m_obstacles[i].next = m_nextFreeObstacle; m_nextFreeObstacle = &m_obstacles[i]; } // Init tiles m_tileLutSize = dtNextPow2(m_params.maxTiles/4); if (!m_tileLutSize) m_tileLutSize = 1; m_tileLutMask = m_tileLutSize-1; m_tiles = (dtCompressedTile*)dtAlloc(sizeof(dtCompressedTile)*m_params.maxTiles, DT_ALLOC_PERM); if (!m_tiles) return DT_FAILURE | DT_OUT_OF_MEMORY; m_posLookup = (dtCompressedTile**)dtAlloc(sizeof(dtCompressedTile*)*m_tileLutSize, DT_ALLOC_PERM); if (!m_posLookup) return DT_FAILURE | DT_OUT_OF_MEMORY; memset(m_tiles, 0, sizeof(dtCompressedTile)*m_params.maxTiles); memset(m_posLookup, 0, sizeof(dtCompressedTile*)*m_tileLutSize); m_nextFreeTile = 0; for (int i = m_params.maxTiles-1; i >= 0; --i) { m_tiles[i].salt = 1; m_tiles[i].next = m_nextFreeTile; m_nextFreeTile = &m_tiles[i]; } // Init ID generator values. m_tileBits = dtIlog2(dtNextPow2((unsigned int)m_params.maxTiles)); // Only allow 31 salt bits, since the salt mask is calculated using 32bit uint and it will overflow. m_saltBits = dtMin((unsigned int)31, 32 - m_tileBits); if (m_saltBits < 10) return DT_FAILURE | DT_INVALID_PARAM; return DT_SUCCESS; } int dtTileCache::getTilesAt(const int tx, const int ty, dtCompressedTileRef* tiles, const int maxTiles) const { int n = 0; // Find tile based on hash. int h = computeTileHash(tx,ty,m_tileLutMask); dtCompressedTile* tile = m_posLookup[h]; while (tile) { if (tile->header && tile->header->tx == tx && tile->header->ty == ty) { if (n < maxTiles) tiles[n++] = getTileRef(tile); } tile = tile->next; } return n; } dtCompressedTile* dtTileCache::getTileAt(const int tx, const int ty, const int tlayer) { // Find tile based on hash. int h = computeTileHash(tx,ty,m_tileLutMask); dtCompressedTile* tile = m_posLookup[h]; while (tile) { if (tile->header && tile->header->tx == tx && tile->header->ty == ty && tile->header->tlayer == tlayer) { return tile; } tile = tile->next; } return 0; } dtCompressedTileRef dtTileCache::getTileRef(const dtCompressedTile* tile) const { if (!tile) return 0; const unsigned int it = (unsigned int)(tile - m_tiles); return (dtCompressedTileRef)encodeTileId(tile->salt, it); } dtObstacleRef dtTileCache::getObstacleRef(const dtTileCacheObstacle* ob) const { if (!ob) return 0; const unsigned int idx = (unsigned int)(ob - m_obstacles); return encodeObstacleId(ob->salt, idx); } const dtTileCacheObstacle* dtTileCache::getObstacleByRef(dtObstacleRef ref) { if (!ref) return 0; unsigned int idx = decodeObstacleIdObstacle(ref); if ((int)idx >= m_params.maxObstacles) return 0; const dtTileCacheObstacle* ob = &m_obstacles[idx]; unsigned int salt = decodeObstacleIdSalt(ref); if (ob->salt != salt) return 0; return ob; } dtStatus dtTileCache::addTile(unsigned char* data, const int dataSize, unsigned char flags, dtCompressedTileRef* result) { // Make sure the data is in right format. dtTileCacheLayerHeader* header = (dtTileCacheLayerHeader*)data; if (header->magic != DT_TILECACHE_MAGIC) return DT_FAILURE | DT_WRONG_MAGIC; if (header->version != DT_TILECACHE_VERSION) return DT_FAILURE | DT_WRONG_VERSION; // Make sure the location is free. if (getTileAt(header->tx, header->ty, header->tlayer)) return DT_FAILURE; // Allocate a tile. dtCompressedTile* tile = 0; if (m_nextFreeTile) { tile = m_nextFreeTile; m_nextFreeTile = tile->next; tile->next = 0; } // Make sure we could allocate a tile. if (!tile) return DT_FAILURE | DT_OUT_OF_MEMORY; // Insert tile into the position lut. int h = computeTileHash(header->tx, header->ty, m_tileLutMask); tile->next = m_posLookup[h]; m_posLookup[h] = tile; // Init tile. const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader)); tile->header = (dtTileCacheLayerHeader*)data; tile->data = data; tile->dataSize = dataSize; tile->compressed = tile->data + headerSize; tile->compressedSize = tile->dataSize - headerSize; tile->flags = flags; if (result) *result = getTileRef(tile); return DT_SUCCESS; } dtStatus dtTileCache::removeTile(dtCompressedTileRef ref, unsigned char** data, int* dataSize) { if (!ref) return DT_FAILURE | DT_INVALID_PARAM; unsigned int tileIndex = decodeTileIdTile(ref); unsigned int tileSalt = decodeTileIdSalt(ref); if ((int)tileIndex >= m_params.maxTiles) return DT_FAILURE | DT_INVALID_PARAM; dtCompressedTile* tile = &m_tiles[tileIndex]; if (tile->salt != tileSalt) return DT_FAILURE | DT_INVALID_PARAM; // Remove tile from hash lookup. const int h = computeTileHash(tile->header->tx,tile->header->ty,m_tileLutMask); dtCompressedTile* prev = 0; dtCompressedTile* cur = m_posLookup[h]; while (cur) { if (cur == tile) { if (prev) prev->next = cur->next; else m_posLookup[h] = cur->next; break; } prev = cur; cur = cur->next; } // Reset tile. if (tile->flags & DT_COMPRESSEDTILE_FREE_DATA) { // Owns data dtFree(tile->data); tile->data = 0; tile->dataSize = 0; if (data) *data = 0; if (dataSize) *dataSize = 0; } else { if (data) *data = tile->data; if (dataSize) *dataSize = tile->dataSize; } tile->header = 0; tile->data = 0; tile->dataSize = 0; tile->compressed = 0; tile->compressedSize = 0; tile->flags = 0; // Update salt, salt should never be zero. tile->salt = (tile->salt+1) & ((1<<m_saltBits)-1); if (tile->salt == 0) tile->salt++; // Add to free list. tile->next = m_nextFreeTile; m_nextFreeTile = tile; return DT_SUCCESS; } dtStatus dtTileCache::addObstacle(const float* pos, const float radius, const float height, dtObstacleRef* result) { if (m_nreqs >= MAX_REQUESTS) return DT_FAILURE | DT_BUFFER_TOO_SMALL; dtTileCacheObstacle* ob = 0; if (m_nextFreeObstacle) { ob = m_nextFreeObstacle; m_nextFreeObstacle = ob->next; ob->next = 0; } if (!ob) return DT_FAILURE | DT_OUT_OF_MEMORY; unsigned short salt = ob->salt; memset(ob, 0, sizeof(dtTileCacheObstacle)); ob->salt = salt; ob->state = DT_OBSTACLE_PROCESSING; ob->type = DT_OBSTACLE_CYLINDER; dtVcopy(ob->cylinder.pos, pos); ob->cylinder.radius = radius; ob->cylinder.height = height; ObstacleRequest* req = &m_reqs[m_nreqs++]; memset(req, 0, sizeof(ObstacleRequest)); req->action = REQUEST_ADD; req->ref = getObstacleRef(ob); if (result) *result = req->ref; return DT_SUCCESS; } dtStatus dtTileCache::addBoxObstacle(const float* bmin, const float* bmax, dtObstacleRef* result) { if (m_nreqs >= MAX_REQUESTS) return DT_FAILURE | DT_BUFFER_TOO_SMALL; dtTileCacheObstacle* ob = 0; if (m_nextFreeObstacle) { ob = m_nextFreeObstacle; m_nextFreeObstacle = ob->next; ob->next = 0; } if (!ob) return DT_FAILURE | DT_OUT_OF_MEMORY; unsigned short salt = ob->salt; memset(ob, 0, sizeof(dtTileCacheObstacle)); ob->salt = salt; ob->state = DT_OBSTACLE_PROCESSING; ob->type = DT_OBSTACLE_BOX; dtVcopy(ob->box.bmin, bmin); dtVcopy(ob->box.bmax, bmax); ObstacleRequest* req = &m_reqs[m_nreqs++]; memset(req, 0, sizeof(ObstacleRequest)); req->action = REQUEST_ADD; req->ref = getObstacleRef(ob); if (result) *result = req->ref; return DT_SUCCESS; } dtStatus dtTileCache::addBoxObstacle(const float* center, const float* halfExtents, const float yRadians, dtObstacleRef* result) { if (m_nreqs >= MAX_REQUESTS) return DT_FAILURE | DT_BUFFER_TOO_SMALL; dtTileCacheObstacle* ob = 0; if (m_nextFreeObstacle) { ob = m_nextFreeObstacle; m_nextFreeObstacle = ob->next; ob->next = 0; } if (!ob) return DT_FAILURE | DT_OUT_OF_MEMORY; unsigned short salt = ob->salt; memset(ob, 0, sizeof(dtTileCacheObstacle)); ob->salt = salt; ob->state = DT_OBSTACLE_PROCESSING; ob->type = DT_OBSTACLE_ORIENTED_BOX; dtVcopy(ob->orientedBox.center, center); dtVcopy(ob->orientedBox.halfExtents, halfExtents); float coshalf= cosf(0.5f*yRadians); float sinhalf = sinf(-0.5f*yRadians); ob->orientedBox.rotAux[0] = coshalf*sinhalf; ob->orientedBox.rotAux[1] = coshalf*coshalf - 0.5f; ObstacleRequest* req = &m_reqs[m_nreqs++]; memset(req, 0, sizeof(ObstacleRequest)); req->action = REQUEST_ADD; req->ref = getObstacleRef(ob); if (result) *result = req->ref; return DT_SUCCESS; } dtStatus dtTileCache::removeObstacle(const dtObstacleRef ref) { if (!ref) return DT_SUCCESS; if (m_nreqs >= MAX_REQUESTS) return DT_FAILURE | DT_BUFFER_TOO_SMALL; ObstacleRequest* req = &m_reqs[m_nreqs++]; memset(req, 0, sizeof(ObstacleRequest)); req->action = REQUEST_REMOVE; req->ref = ref; return DT_SUCCESS; } dtStatus dtTileCache::queryTiles(const float* bmin, const float* bmax, dtCompressedTileRef* results, int* resultCount, const int maxResults) const { const int MAX_TILES = 32; dtCompressedTileRef tiles[MAX_TILES]; int n = 0; const float tw = m_params.width * m_params.cs; const float th = m_params.height * m_params.cs; const int tx0 = (int)dtMathFloorf((bmin[0]-m_params.orig[0]) / tw); const int tx1 = (int)dtMathFloorf((bmax[0]-m_params.orig[0]) / tw); const int ty0 = (int)dtMathFloorf((bmin[2]-m_params.orig[2]) / th); const int ty1 = (int)dtMathFloorf((bmax[2]-m_params.orig[2]) / th); for (int ty = ty0; ty <= ty1; ++ty) { for (int tx = tx0; tx <= tx1; ++tx) { const int ntiles = getTilesAt(tx,ty,tiles,MAX_TILES); for (int i = 0; i < ntiles; ++i) { const dtCompressedTile* tile = &m_tiles[decodeTileIdTile(tiles[i])]; float tbmin[3], tbmax[3]; calcTightTileBounds(tile->header, tbmin, tbmax); if (dtOverlapBounds(bmin,bmax, tbmin,tbmax)) { if (n < maxResults) results[n++] = tiles[i]; } } } } *resultCount = n; return DT_SUCCESS; } dtStatus dtTileCache::update(const float /*dt*/, dtNavMesh* navmesh, bool* upToDate) { if (m_nupdate == 0) { // Process requests. for (int i = 0; i < m_nreqs; ++i) { ObstacleRequest* req = &m_reqs[i]; unsigned int idx = decodeObstacleIdObstacle(req->ref); if ((int)idx >= m_params.maxObstacles) continue; dtTileCacheObstacle* ob = &m_obstacles[idx]; unsigned int salt = decodeObstacleIdSalt(req->ref); if (ob->salt != salt) continue; if (req->action == REQUEST_ADD) { // Find touched tiles. float bmin[3], bmax[3]; getObstacleBounds(ob, bmin, bmax); int ntouched = 0; queryTiles(bmin, bmax, ob->touched, &ntouched, DT_MAX_TOUCHED_TILES); ob->ntouched = (unsigned char)ntouched; // Add tiles to update list. ob->npending = 0; for (int j = 0; j < ob->ntouched; ++j) { if (m_nupdate < MAX_UPDATE) { if (!contains(m_update, m_nupdate, ob->touched[j])) m_update[m_nupdate++] = ob->touched[j]; ob->pending[ob->npending++] = ob->touched[j]; } } } else if (req->action == REQUEST_REMOVE) { // Prepare to remove obstacle. ob->state = DT_OBSTACLE_REMOVING; // Add tiles to update list. ob->npending = 0; for (int j = 0; j < ob->ntouched; ++j) { if (m_nupdate < MAX_UPDATE) { if (!contains(m_update, m_nupdate, ob->touched[j])) m_update[m_nupdate++] = ob->touched[j]; ob->pending[ob->npending++] = ob->touched[j]; } } } } m_nreqs = 0; } dtStatus status = DT_SUCCESS; // Process updates if (m_nupdate) { // Build mesh const dtCompressedTileRef ref = m_update[0]; status = buildNavMeshTile(ref, navmesh); m_nupdate--; if (m_nupdate > 0) memmove(m_update, m_update+1, m_nupdate*sizeof(dtCompressedTileRef)); // Update obstacle states. for (int i = 0; i < m_params.maxObstacles; ++i) { dtTileCacheObstacle* ob = &m_obstacles[i]; if (ob->state == DT_OBSTACLE_PROCESSING || ob->state == DT_OBSTACLE_REMOVING) { // Remove handled tile from pending list. for (int j = 0; j < (int)ob->npending; j++) { if (ob->pending[j] == ref) { ob->pending[j] = ob->pending[(int)ob->npending-1]; ob->npending--; break; } } // If all pending tiles processed, change state. if (ob->npending == 0) { if (ob->state == DT_OBSTACLE_PROCESSING) { ob->state = DT_OBSTACLE_PROCESSED; } else if (ob->state == DT_OBSTACLE_REMOVING) { ob->state = DT_OBSTACLE_EMPTY; // Update salt, salt should never be zero. ob->salt = (ob->salt+1) & ((1<<16)-1); if (ob->salt == 0) ob->salt++; // Return obstacle to free list. ob->next = m_nextFreeObstacle; m_nextFreeObstacle = ob; } } } } } if (upToDate) *upToDate = m_nupdate == 0 && m_nreqs == 0; return status; } dtStatus dtTileCache::buildNavMeshTilesAt(const int tx, const int ty, dtNavMesh* navmesh) { const int MAX_TILES = 32; dtCompressedTileRef tiles[MAX_TILES]; const int ntiles = getTilesAt(tx,ty,tiles,MAX_TILES); for (int i = 0; i < ntiles; ++i) { dtStatus status = buildNavMeshTile(tiles[i], navmesh); if (dtStatusFailed(status)) return status; } return DT_SUCCESS; } dtStatus dtTileCache::buildNavMeshTile(const dtCompressedTileRef ref, dtNavMesh* navmesh) { dtAssert(m_talloc); dtAssert(m_tcomp); unsigned int idx = decodeTileIdTile(ref); if (idx > (unsigned int)m_params.maxTiles) return DT_FAILURE | DT_INVALID_PARAM; const dtCompressedTile* tile = &m_tiles[idx]; unsigned int salt = decodeTileIdSalt(ref); if (tile->salt != salt) return DT_FAILURE | DT_INVALID_PARAM; m_talloc->reset(); NavMeshTileBuildContext bc(m_talloc); const int walkableClimbVx = (int)(m_params.walkableClimb / m_params.ch); dtStatus status; // Decompress tile layer data. status = dtDecompressTileCacheLayer(m_talloc, m_tcomp, tile->data, tile->dataSize, &bc.layer); if (dtStatusFailed(status)) return status; // Rasterize obstacles. for (int i = 0; i < m_params.maxObstacles; ++i) { const dtTileCacheObstacle* ob = &m_obstacles[i]; if (ob->state == DT_OBSTACLE_EMPTY || ob->state == DT_OBSTACLE_REMOVING) continue; if (contains(ob->touched, ob->ntouched, ref)) { if (ob->type == DT_OBSTACLE_CYLINDER) { dtMarkCylinderArea(*bc.layer, tile->header->bmin, m_params.cs, m_params.ch, ob->cylinder.pos, ob->cylinder.radius, ob->cylinder.height, 0); } else if (ob->type == DT_OBSTACLE_BOX) { dtMarkBoxArea(*bc.layer, tile->header->bmin, m_params.cs, m_params.ch, ob->box.bmin, ob->box.bmax, 0); } else if (ob->type == DT_OBSTACLE_ORIENTED_BOX) { dtMarkBoxArea(*bc.layer, tile->header->bmin, m_params.cs, m_params.ch, ob->orientedBox.center, ob->orientedBox.halfExtents, ob->orientedBox.rotAux, 0); } } } // Build navmesh status = dtBuildTileCacheRegions(m_talloc, *bc.layer, walkableClimbVx); if (dtStatusFailed(status)) return status; bc.lcset = dtAllocTileCacheContourSet(m_talloc); if (!bc.lcset) return DT_FAILURE | DT_OUT_OF_MEMORY; status = dtBuildTileCacheContours(m_talloc, *bc.layer, walkableClimbVx, m_params.maxSimplificationError, *bc.lcset); if (dtStatusFailed(status)) return status; bc.lmesh = dtAllocTileCachePolyMesh(m_talloc); if (!bc.lmesh) return DT_FAILURE | DT_OUT_OF_MEMORY; status = dtBuildTileCachePolyMesh(m_talloc, *bc.lcset, *bc.lmesh); if (dtStatusFailed(status)) return status; // Early out if the mesh tile is empty. if (!bc.lmesh->npolys) { // Remove existing tile. navmesh->removeTile(navmesh->getTileRefAt(tile->header->tx,tile->header->ty,tile->header->tlayer),0,0); return DT_SUCCESS; } dtNavMeshCreateParams params; memset(&params, 0, sizeof(params)); params.verts = bc.lmesh->verts; params.vertCount = bc.lmesh->nverts; params.polys = bc.lmesh->polys; params.polyAreas = bc.lmesh->areas; params.polyFlags = bc.lmesh->flags; params.polyCount = bc.lmesh->npolys; params.nvp = DT_VERTS_PER_POLYGON; params.walkableHeight = m_params.walkableHeight; params.walkableRadius = m_params.walkableRadius; params.walkableClimb = m_params.walkableClimb; params.tileX = tile->header->tx; params.tileY = tile->header->ty; params.tileLayer = tile->header->tlayer; params.cs = m_params.cs; params.ch = m_params.ch; params.buildBvTree = false; dtVcopy(params.bmin, tile->header->bmin); dtVcopy(params.bmax, tile->header->bmax); if (m_tmproc) { m_tmproc->process(&params, bc.lmesh->areas, bc.lmesh->flags); } unsigned char* navData = 0; int navDataSize = 0; if (!dtCreateNavMeshData(&params, &navData, &navDataSize)) return DT_FAILURE; // Remove existing tile. navmesh->removeTile(navmesh->getTileRefAt(tile->header->tx,tile->header->ty,tile->header->tlayer),0,0); // Add new tile, or leave the location empty. if (navData) { // Let the navmesh own the data. status = navmesh->addTile(navData,navDataSize,DT_TILE_FREE_DATA,0,0); if (dtStatusFailed(status)) { dtFree(navData); return status; } } return DT_SUCCESS; } void dtTileCache::calcTightTileBounds(const dtTileCacheLayerHeader* header, float* bmin, float* bmax) const { const float cs = m_params.cs; bmin[0] = header->bmin[0] + header->minx*cs; bmin[1] = header->bmin[1]; bmin[2] = header->bmin[2] + header->miny*cs; bmax[0] = header->bmin[0] + (header->maxx+1)*cs; bmax[1] = header->bmax[1]; bmax[2] = header->bmin[2] + (header->maxy+1)*cs; } void dtTileCache::getObstacleBounds(const struct dtTileCacheObstacle* ob, float* bmin, float* bmax) const { if (ob->type == DT_OBSTACLE_CYLINDER) { const dtObstacleCylinder &cl = ob->cylinder; bmin[0] = cl.pos[0] - cl.radius; bmin[1] = cl.pos[1]; bmin[2] = cl.pos[2] - cl.radius; bmax[0] = cl.pos[0] + cl.radius; bmax[1] = cl.pos[1] + cl.height; bmax[2] = cl.pos[2] + cl.radius; } else if (ob->type == DT_OBSTACLE_BOX) { dtVcopy(bmin, ob->box.bmin); dtVcopy(bmax, ob->box.bmax); } else if (ob->type == DT_OBSTACLE_ORIENTED_BOX) { const dtObstacleOrientedBox &orientedBox = ob->orientedBox; float maxr = 1.41f*dtMax(orientedBox.halfExtents[0], orientedBox.halfExtents[2]); bmin[0] = orientedBox.center[0] - maxr; bmax[0] = orientedBox.center[0] + maxr; bmin[1] = orientedBox.center[1] - orientedBox.halfExtents[1]; bmax[1] = orientedBox.center[1] + orientedBox.halfExtents[1]; bmin[2] = orientedBox.center[2] - maxr; bmax[2] = orientedBox.center[2] + maxr; } }
mit
zardus/z3
src/muz/duality/duality_dl_interface.cpp
12
21059
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: duality_dl_interface.cpp Abstract: SMT2 interface for Duality Author: Krystof Hoder (t-khoder) 2011-9-22. Modified by Ken McMIllan (kenmcmil) 2013-4-18. Revision History: --*/ #include "dl_context.h" #include "dl_mk_coi_filter.h" #include "dl_mk_interp_tail_simplifier.h" #include "dl_mk_subsumption_checker.h" #include "dl_mk_rule_inliner.h" #include "dl_rule.h" #include "dl_rule_transformer.h" #include "smt2parser.h" #include "duality_dl_interface.h" #include "dl_rule_set.h" #include "dl_mk_slice.h" #include "dl_mk_unfold.h" #include "dl_mk_coalesce.h" #include "expr_abstract.h" #include "model_smt2_pp.h" #include "model_v2_pp.h" #include "fixedpoint_params.hpp" #include "used_vars.h" #include "func_decl_dependencies.h" #include "dl_transforms.h" // template class symbol_table<family_id>; #ifdef WIN32 #pragma warning(disable:4996) #pragma warning(disable:4800) #pragma warning(disable:4267) #pragma warning(disable:4101) #endif #include "duality.h" #include "duality_profiling.h" // using namespace Duality; namespace Duality { enum DualityStatus {StatusModel, StatusRefutation, StatusUnknown, StatusNull}; class duality_data { public: context ctx; RPFP::LogicSolver *ls; RPFP *rpfp; DualityStatus status; std::vector<expr> clauses; std::vector<std::vector<RPFP::label_struct> > clause_labels; hash_map<RPFP::Edge *,int> map; // edges to clauses Solver *old_rs; Solver::Counterexample cex; duality_data(ast_manager &_m) : ctx(_m,config(params_ref())) { ls = 0; rpfp = 0; status = StatusNull; old_rs = 0; } ~duality_data(){ if(old_rs) dealloc(old_rs); if(rpfp) dealloc(rpfp); if(ls) dealloc(ls); } }; dl_interface::dl_interface(datalog::context& dl_ctx) : engine_base(dl_ctx.get_manager(), "duality"), m_ctx(dl_ctx) { _d = 0; // dl_ctx.get_manager().toggle_proof_mode(PGM_FINE); } dl_interface::~dl_interface() { if(_d) dealloc(_d); } // // Check if the new rules are weaker so that we can // re-use existing context. // #if 0 void dl_interface::check_reset() { // TODO datalog::rule_ref_vector const& new_rules = m_ctx.get_rules().get_rules(); datalog::rule_ref_vector const& old_rules = m_old_rules.get_rules(); bool is_subsumed = !old_rules.empty(); for (unsigned i = 0; is_subsumed && i < new_rules.size(); ++i) { is_subsumed = false; for (unsigned j = 0; !is_subsumed && j < old_rules.size(); ++j) { if (m_ctx.check_subsumes(*old_rules[j], *new_rules[i])) { is_subsumed = true; } } if (!is_subsumed) { TRACE("pdr", new_rules[i]->display(m_ctx, tout << "Fresh rule ");); m_context->reset(); } } m_old_rules.reset(); m_old_rules.add_rules(new_rules.size(), new_rules.c_ptr()); } #endif lbool dl_interface::query(::expr * query) { // we restore the initial state in the datalog context m_ctx.ensure_opened(); // if there is old data, get the cex and dispose (later) duality_data *old_data = _d; Solver *old_rs = 0; if(old_data){ old_rs = old_data->old_rs; old_rs->GetCounterexample().swap(old_data->cex); } scoped_proof generate_proofs_please(m_ctx.get_manager()); // make a new problem and solver _d = alloc(duality_data,m_ctx.get_manager()); _d->ctx.set("mbqi",m_ctx.get_params().mbqi()); _d->ls = alloc(RPFP::iZ3LogicSolver,_d->ctx); _d->rpfp = alloc(RPFP,_d->ls); expr_ref_vector rules(m_ctx.get_manager()); svector< ::symbol> names; vector<unsigned> bounds; // m_ctx.get_rules_as_formulas(rules, names); // If using SAS 2013 abstractiion, we need to perform some transforms expr_ref query_ref(m_ctx.get_manager()); if(m_ctx.quantify_arrays()){ datalog::rule_manager& rm = m_ctx.get_rule_manager(); rm.mk_query(query, m_ctx.get_rules()); apply_default_transformation(m_ctx); datalog::rule_set &rs = m_ctx.get_rules(); if(m_ctx.get_rules().get_output_predicates().empty()) query_ref = m_ctx.get_manager().mk_false(); else { func_decl_ref query_pred(m_ctx.get_manager()); query_pred = m_ctx.get_rules().get_output_predicate(); ptr_vector<sort> sorts; unsigned nargs = query_pred.get()->get_arity(); expr_ref_vector vars(m_ctx.get_manager()); for(unsigned i = 0; i < nargs; i++){ ::sort *s = query_pred.get()->get_domain(i); vars.push_back(m_ctx.get_manager().mk_var(nargs-1-i,s)); } query_ref = m_ctx.get_manager().mk_app(query_pred.get(),nargs,vars.c_ptr()); query = query_ref.get(); } unsigned nrules = rs.get_num_rules(); for(unsigned i = 0; i < nrules; i++){ expr_ref f(m_ctx.get_manager()); rs.get_rule(i)->to_formula(f); rules.push_back(f); } } else m_ctx.get_raw_rule_formulas(rules, names, bounds); // get all the rules as clauses std::vector<expr> &clauses = _d->clauses; clauses.clear(); for (unsigned i = 0; i < rules.size(); ++i) { expr e(_d->ctx,rules[i].get()); clauses.push_back(e); } std::vector<sort> b_sorts; std::vector<symbol> b_names; used_vars uv; uv.process(query); unsigned nuv = uv.get_max_found_var_idx_plus_1(); for(int i = nuv-1; i >= 0; i--){ // var indices are backward ::sort * s = uv.get(i); if(!s) s = _d->ctx.m().mk_bool_sort(); // missing var, whatever b_sorts.push_back(sort(_d->ctx,s)); b_names.push_back(symbol(_d->ctx,::symbol(i))); // names? } #if 0 // turn the query into a clause expr q(_d->ctx,m_ctx.bind_variables(query,false)); std::vector<sort> b_sorts; std::vector<symbol> b_names; if (q.is_quantifier() && !q.is_quantifier_forall()) { int bound = q.get_quantifier_num_bound(); for(int j = 0; j < bound; j++){ b_sorts.push_back(q.get_quantifier_bound_sort(j)); b_names.push_back(q.get_quantifier_bound_name(j)); } q = q.arg(0); } #else expr q(_d->ctx,query); #endif expr qc = implies(q,_d->ctx.bool_val(false)); qc = _d->ctx.make_quant(Forall,b_sorts,b_names,qc); clauses.push_back(qc); bounds.push_back(UINT_MAX); // get the background axioms unsigned num_asserts = m_ctx.get_num_assertions(); for (unsigned i = 0; i < num_asserts; ++i) { expr e(_d->ctx,m_ctx.get_assertion(i)); _d->rpfp->AssertAxiom(e); } // make sure each predicate is the head of at least one clause func_decl_set heads; for(unsigned i = 0; i < clauses.size(); i++){ expr cl = clauses[i]; while(true){ if(cl.is_app()){ decl_kind k = cl.decl().get_decl_kind(); if(k == Implies) cl = cl.arg(1); else { heads.insert(cl.decl()); break; } } else if(cl.is_quantifier()) cl = cl.body(); else break; } } ast_ref_vector const &pinned = m_ctx.get_pinned(); for(unsigned i = 0; i < pinned.size(); i++){ ::ast *fa = pinned[i]; if(is_func_decl(fa)){ ::func_decl *fd = to_func_decl(fa); if (m_ctx.is_predicate(fd)) { func_decl f(_d->ctx, fd); if (!heads.contains(fd)) { int arity = f.arity(); std::vector<expr> args; for (int j = 0; j < arity; j++) args.push_back(_d->ctx.fresh_func_decl("X", f.domain(j))()); expr c = implies(_d->ctx.bool_val(false), f(args)); c = _d->ctx.make_quant(Forall, args, c); clauses.push_back(c); bounds.push_back(UINT_MAX); } } } } unsigned rb = m_ctx.get_params().recursion_bound(); std::vector<unsigned> std_bounds; for(unsigned i = 0; i < bounds.size(); i++){ unsigned b = bounds[i]; if (b == UINT_MAX) b = rb; std_bounds.push_back(b); } // creates 1-1 map between clauses and rpfp edges _d->rpfp->FromClauses(clauses,&std_bounds); // populate the edge-to-clause map for(unsigned i = 0; i < _d->rpfp->edges.size(); ++i) _d->map[_d->rpfp->edges[i]] = i; // create a solver object Solver *rs = Solver::Create("duality", _d->rpfp); if(old_rs) rs->LearnFrom(old_rs); // new solver gets hints from old solver // set its options IF_VERBOSE(1, rs->SetOption("report","1");); rs->SetOption("full_expand",m_ctx.get_params().full_expand() ? "1" : "0"); rs->SetOption("no_conj",m_ctx.get_params().no_conj() ? "1" : "0"); rs->SetOption("feasible_edges",m_ctx.get_params().feasible_edges() ? "1" : "0"); rs->SetOption("use_underapprox",m_ctx.get_params().use_underapprox() ? "1" : "0"); rs->SetOption("stratified_inlining",m_ctx.get_params().stratified_inlining() ? "1" : "0"); rs->SetOption("batch_expand",m_ctx.get_params().batch_expand() ? "1" : "0"); rs->SetOption("conjecture_file",m_ctx.get_params().conjecture_file()); rs->SetOption("enable_restarts",m_ctx.get_params().enable_restarts() ? "1" : "0"); #if 0 if(rb != UINT_MAX){ std::ostringstream os; os << rb; rs->SetOption("recursion_bound", os.str()); } #endif // Solve! bool ans; try { ans = rs->Solve(); } catch (Duality::solver::cancel_exception &exn){ throw default_exception("duality canceled"); } catch (Duality::Solver::Incompleteness &exn){ throw default_exception("incompleteness"); } // profile! if(m_ctx.get_params().profile()) print_profile(std::cout); // save the result and counterexample if there is one _d->status = ans ? StatusModel : StatusRefutation; _d->cex.swap(rs->GetCounterexample()); // take ownership of cex _d->old_rs = rs; // save this for later hints if(old_data){ dealloc(old_data); // this deallocates the old solver if there is one } // dealloc(rs); this is now owned by data // true means the RPFP problem is SAT, so the query is UNSAT // but we return undef if the UNSAT result is bounded if(ans){ if(rs->IsResultRecursionBounded()){ #if 0 m_ctx.set_status(datalog::BOUNDED); return l_undef; #else return l_false; #endif } return l_false; } return l_true; } expr_ref dl_interface::get_cover_delta(int level, ::func_decl* pred_orig) { SASSERT(false); return expr_ref(m_ctx.get_manager()); } void dl_interface::add_cover(int level, ::func_decl* pred, ::expr* property) { SASSERT(false); } unsigned dl_interface::get_num_levels(::func_decl* pred) { SASSERT(false); return 0; } void dl_interface::collect_statistics(::statistics& st) const { } void dl_interface::reset_statistics() { } static hash_set<func_decl> *local_func_decls; static void print_proof(dl_interface *d, std::ostream& out, RPFP *tree, RPFP::Node *root) { context &ctx = d->dd()->ctx; RPFP::Node &node = *root; RPFP::Edge &edge = *node.Outgoing; // first, prove the children (that are actually used) for(unsigned i = 0; i < edge.Children.size(); i++){ if(!tree->Empty(edge.Children[i])){ print_proof(d,out,tree,edge.Children[i]); } } // print the label and the proved fact out << "(step s!" << node.number; out << " (" << node.Name.name(); for(unsigned i = 0; i < edge.F.IndParams.size(); i++) out << " " << tree->Eval(&edge,edge.F.IndParams[i]); out << ")\n"; // print the rule number out << " rule!" << node.Outgoing->map->number; // print the substitution out << " (subst\n"; RPFP::Edge *orig_edge = edge.map; int orig_clause = d->dd()->map[orig_edge]; expr &t = d->dd()->clauses[orig_clause]; if (t.is_quantifier() && t.is_quantifier_forall()) { int bound = t.get_quantifier_num_bound(); std::vector<sort> sorts; std::vector<symbol> names; hash_map<int,expr> subst; for(int j = 0; j < bound; j++){ sort the_sort = t.get_quantifier_bound_sort(j); symbol name = t.get_quantifier_bound_name(j); expr skolem = ctx.constant(symbol(ctx,name),sort(ctx,the_sort)); out << " (= " << skolem << " " << tree->Eval(&edge,skolem) << ")\n"; expr local_skolem = tree->Localize(&edge,skolem); (*local_func_decls).insert(local_skolem.decl()); } } out << " )\n"; out << " (labels"; std::vector<symbol> labels; tree->GetLabels(&edge,labels); for(unsigned j = 0; j < labels.size(); j++){ out << " " << labels[j]; } out << " )\n"; // reference the proofs of all the children, in syntactic order // "true" means the child is not needed out << " (ref "; for(unsigned i = 0; i < edge.Children.size(); i++){ if(!tree->Empty(edge.Children[i])) out << " s!" << edge.Children[i]->number; else out << " true"; } out << " )"; out << ")\n"; } void dl_interface::display_certificate(std::ostream& out) const { ((dl_interface *)this)->display_certificate_non_const(out); } void dl_interface::display_certificate_non_const(std::ostream& out) { if(_d->status == StatusModel){ ast_manager &m = m_ctx.get_manager(); model_ref md = get_model(); out << "(fixedpoint \n"; model_smt2_pp(out, m, *md.get(), 0); out << ")\n"; } else if(_d->status == StatusRefutation){ out << "(derivation\n"; // negation of the query is the last clause -- prove it hash_set<func_decl> locals; local_func_decls = &locals; print_proof(this,out,_d->cex.get_tree(),_d->cex.get_root()); out << ")\n"; out << "(model \n\""; ::model mod(m_ctx.get_manager()); model orig_model = _d->cex.get_tree()->dualModel; for(unsigned i = 0; i < orig_model.num_consts(); i++){ func_decl cnst = orig_model.get_const_decl(i); if (locals.find(cnst) == locals.end()) { expr thing = orig_model.get_const_interp(cnst); mod.register_decl(to_func_decl(cnst.raw()), to_expr(thing.raw())); } } for(unsigned i = 0; i < orig_model.num_funcs(); i++){ func_decl cnst = orig_model.get_func_decl(i); if (locals.find(cnst) == locals.end()) { func_interp thing = orig_model.get_func_interp(cnst); ::func_interp *thing_raw = thing; mod.register_decl(to_func_decl(cnst.raw()), thing_raw->copy()); } } model_v2_pp(out,mod); out << "\")\n"; } } expr_ref dl_interface::get_answer() { SASSERT(false); return expr_ref(m_ctx.get_manager()); } void dl_interface::cancel() { #if 0 if(_d && _d->ls) _d->ls->cancel(); #else // HACK: duality can't cancel at all times, we just exit here std::cout << "(error \"duality canceled\")\nunknown\n"; abort(); #endif } void dl_interface::cleanup() { } void dl_interface::updt_params() { } model_ref dl_interface::get_model() { ast_manager &m = m_ctx.get_manager(); model_ref md(alloc(::model, m)); std::vector<RPFP::Node *> &nodes = _d->rpfp->nodes; expr_ref_vector conjs(m); for (unsigned i = 0; i < nodes.size(); ++i) { RPFP::Node *node = nodes[i]; func_decl &pred = node->Name; expr_ref prop(m); prop = to_expr(node->Annotation.Formula); std::vector<expr> &params = node->Annotation.IndParams; expr_ref q(m); expr_ref_vector sig_vars(m); for (unsigned j = 0; j < params.size(); ++j) sig_vars.push_back(params[params.size()-j-1]); // TODO: why backwards? expr_abstract(m, 0, sig_vars.size(), sig_vars.c_ptr(), prop, q); if (params.empty()) { md->register_decl(pred, q); } else { ::func_interp* fi = alloc(::func_interp, m, params.size()); fi->set_else(q); md->register_decl(pred, fi); } } return md; } static proof_ref extract_proof(dl_interface *d, RPFP *tree, RPFP::Node *root) { context &ctx = d->dd()->ctx; ast_manager &mgr = ctx.m(); RPFP::Node &node = *root; RPFP::Edge &edge = *node.Outgoing; RPFP::Edge *orig_edge = edge.map; // first, prove the children (that are actually used) proof_ref_vector prems(mgr); ::vector<expr_ref_vector> substs; int orig_clause = d->dd()->map[orig_edge]; expr &t = d->dd()->clauses[orig_clause]; prems.push_back(mgr.mk_asserted(ctx.uncook(t))); substs.push_back(expr_ref_vector(mgr)); if (t.is_quantifier() && t.is_quantifier_forall()) { int bound = t.get_quantifier_num_bound(); std::vector<sort> sorts; std::vector<symbol> names; hash_map<int,expr> subst; for(int j = 0; j < bound; j++){ sort the_sort = t.get_quantifier_bound_sort(j); symbol name = t.get_quantifier_bound_name(j); expr skolem = ctx.constant(symbol(ctx,name),sort(ctx,the_sort)); expr val = tree->Eval(&edge,skolem); expr_ref thing(ctx.uncook(val),mgr); substs[0].push_back(thing); expr local_skolem = tree->Localize(&edge,skolem); (*local_func_decls).insert(local_skolem.decl()); } } svector<std::pair<unsigned, unsigned> > pos; for(unsigned i = 0; i < edge.Children.size(); i++){ if(!tree->Empty(edge.Children[i])){ pos.push_back(std::pair<unsigned,unsigned>(i+1,0)); proof_ref prem = extract_proof(d,tree,edge.Children[i]); prems.push_back(prem); substs.push_back(expr_ref_vector(mgr)); } } func_decl f = node.Name; std::vector<expr> args; for(unsigned i = 0; i < edge.F.IndParams.size(); i++) args.push_back(tree->Eval(&edge,edge.F.IndParams[i])); expr conc = f(args); ::vector< ::proof *> pprems; for(unsigned i = 0; i < prems.size(); i++) pprems.push_back(prems[i].get()); proof_ref res(mgr.mk_hyper_resolve(pprems.size(),&pprems[0], ctx.uncook(conc), pos, substs),mgr); return res; } proof_ref dl_interface::get_proof() { if(_d->status == StatusRefutation){ hash_set<func_decl> locals; local_func_decls = &locals; return extract_proof(this,_d->cex.get_tree(),_d->cex.get_root()); } else return proof_ref(m_ctx.get_manager()); } }
mit
vtsuperdarn/SuperDARN_MSI_ROS
qnx/root/operational_radar_code/ros/fftw-3.2.2/dft/scalar/codelets/t1_32.c
13
47289
/* * Copyright (c) 2003, 2007-8 Matteo Frigo * Copyright (c) 2003, 2007-8 Massachusetts Institute of Technology * * 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 * */ /* This file was automatically generated --- DO NOT EDIT */ /* Generated on Sun Jul 12 06:37:37 EDT 2009 */ #include "codelet-dft.h" #ifdef HAVE_FMA /* Generated by: ../../../genfft/gen_twiddle -fma -reorder-insns -schedule-for-pipeline -compact -variables 4 -pipeline-latency 4 -n 32 -name t1_32 -include t.h */ /* * This function contains 434 FP additions, 260 FP multiplications, * (or, 236 additions, 62 multiplications, 198 fused multiply/add), * 135 stack variables, 7 constants, and 128 memory accesses */ #include "t.h" static void t1_32(R *ri, R *ii, const R *W, stride rs, INT mb, INT me, INT ms) { DK(KP980785280, +0.980785280403230449126182236134239036973933731); DK(KP831469612, +0.831469612302545237078788377617905756738560812); DK(KP668178637, +0.668178637919298919997757686523080761552472251); DK(KP198912367, +0.198912367379658006911597622644676228597850501); DK(KP923879532, +0.923879532511286756128183189396788286822416626); DK(KP414213562, +0.414213562373095048801688724209698078569671875); DK(KP707106781, +0.707106781186547524400844362104849039284835938); INT m; for (m = mb, W = W + (mb * 62); m < me; m = m + 1, ri = ri + ms, ii = ii + ms, W = W + 62, MAKE_VOLATILE_STRIDE(rs)) { E T90, T8Z; { E T8x, T87, T8, T3w, T83, T3B, T8y, Tl, T6F, Tz, T3J, T5T, T6G, TM, T3Q; E T5U, T46, T5Y, T7D, T6L, T5X, T3Z, T6M, T1f, T7E, T6R, T60, T4e, T6O, T1G; E T61, T4l, T78, T7N, T54, T6f, T32, T7b, T6c, T5r, T6X, T7I, T4v, T68, T29; E T70, T65, T4S, T5s, T5b, T7O, T7e, T79, T3t, T5t, T5i, T4H, T2y, T4A, T71; E T2m, T4B, T4F, T2s; { E T44, T1d, T3X, T6J, T11, T40, T42, T17, T5h, T5c; { E Ta, Td, Tg, T3x, Tb, Tj, Tf, Tc, Ti; { E T1, T86, T3, T6, T2, T5; T1 = ri[0]; T86 = ii[0]; T3 = ri[WS(rs, 16)]; T6 = ii[WS(rs, 16)]; T2 = W[30]; T5 = W[31]; { E T84, T4, T9, T85, T7; Ta = ri[WS(rs, 8)]; Td = ii[WS(rs, 8)]; T84 = T2 * T6; T4 = T2 * T3; T9 = W[14]; Tg = ri[WS(rs, 24)]; T85 = FNMS(T5, T3, T84); T7 = FMA(T5, T6, T4); T3x = T9 * Td; Tb = T9 * Ta; T8x = T86 - T85; T87 = T85 + T86; T8 = T1 + T7; T3w = T1 - T7; Tj = ii[WS(rs, 24)]; Tf = W[46]; } Tc = W[15]; Ti = W[47]; } { E Tu, Tx, T3F, Ts, Tw, T3G, Tv; { E To, Tr, Tp, T3E, Tq, Tt; { E T3y, Te, T3A, Tk, T3z, Th, Tn; To = ri[WS(rs, 4)]; T3z = Tf * Tj; Th = Tf * Tg; T3y = FNMS(Tc, Ta, T3x); Te = FMA(Tc, Td, Tb); T3A = FNMS(Ti, Tg, T3z); Tk = FMA(Ti, Tj, Th); Tr = ii[WS(rs, 4)]; Tn = W[6]; T83 = T3y + T3A; T3B = T3y - T3A; T8y = Te - Tk; Tl = Te + Tk; Tp = Tn * To; T3E = Tn * Tr; } Tq = W[7]; Tu = ri[WS(rs, 20)]; Tx = ii[WS(rs, 20)]; Tt = W[38]; T3F = FNMS(Tq, To, T3E); Ts = FMA(Tq, Tr, Tp); Tw = W[39]; T3G = Tt * Tx; Tv = Tt * Tu; } { E T3M, TF, TH, TK, TG, TJ, TE, TD, TC; { E TB, T3H, Ty, TA, T3I, T3D, T3L; TB = ri[WS(rs, 28)]; TE = ii[WS(rs, 28)]; T3H = FNMS(Tw, Tu, T3G); Ty = FMA(Tw, Tx, Tv); TA = W[54]; TD = W[55]; T6F = T3F + T3H; T3I = T3F - T3H; Tz = Ts + Ty; T3D = Ts - Ty; T3L = TA * TE; TC = TA * TB; T3J = T3D + T3I; T5T = T3I - T3D; T3M = FNMS(TD, TB, T3L); } TF = FMA(TD, TE, TC); TH = ri[WS(rs, 12)]; TK = ii[WS(rs, 12)]; TG = W[22]; TJ = W[23]; { E TU, T3U, T13, T16, T3W, T10, T12, T15, T41, T14; { E T19, T1c, T18, T1b, T3P, T3K; { E TQ, TT, T3N, TI, TP, TS; TQ = ri[WS(rs, 2)]; TT = ii[WS(rs, 2)]; T3N = TG * TK; TI = TG * TH; TP = W[2]; TS = W[3]; { E T3O, TL, T3T, TR; T3O = FNMS(TJ, TH, T3N); TL = FMA(TJ, TK, TI); T3T = TP * TT; TR = TP * TQ; T6G = T3M + T3O; T3P = T3M - T3O; TM = TF + TL; T3K = TF - TL; TU = FMA(TS, TT, TR); T3U = FNMS(TS, TQ, T3T); } } T3Q = T3K - T3P; T5U = T3K + T3P; T19 = ri[WS(rs, 26)]; T1c = ii[WS(rs, 26)]; T18 = W[50]; T1b = W[51]; { E TW, TZ, TY, T3V, TX, T43, T1a, TV; TW = ri[WS(rs, 18)]; TZ = ii[WS(rs, 18)]; T43 = T18 * T1c; T1a = T18 * T19; TV = W[34]; TY = W[35]; T44 = FNMS(T1b, T19, T43); T1d = FMA(T1b, T1c, T1a); T3V = TV * TZ; TX = TV * TW; T13 = ri[WS(rs, 10)]; T16 = ii[WS(rs, 10)]; T3W = FNMS(TY, TW, T3V); T10 = FMA(TY, TZ, TX); T12 = W[18]; T15 = W[19]; } } T3X = T3U - T3W; T6J = T3U + T3W; T11 = TU + T10; T40 = TU - T10; T41 = T12 * T16; T14 = T12 * T13; T42 = FNMS(T15, T13, T41); T17 = FMA(T15, T16, T14); } } } } { E T49, T1l, T4j, T1E, T1u, T1x, T1w, T4b, T1r, T4g, T1v; { E T1A, T1D, T1C, T4i, T1B; { E T1h, T1k, T1g, T1j, T48, T1i, T1z; T1h = ri[WS(rs, 30)]; T1k = ii[WS(rs, 30)]; { E T6K, T45, T1e, T3Y; T6K = T42 + T44; T45 = T42 - T44; T1e = T17 + T1d; T3Y = T17 - T1d; T46 = T40 + T45; T5Y = T40 - T45; T7D = T6J + T6K; T6L = T6J - T6K; T5X = T3X + T3Y; T3Z = T3X - T3Y; T6M = T11 - T1e; T1f = T11 + T1e; T1g = W[58]; } T1j = W[59]; T1A = ri[WS(rs, 22)]; T1D = ii[WS(rs, 22)]; T48 = T1g * T1k; T1i = T1g * T1h; T1z = W[42]; T1C = W[43]; T49 = FNMS(T1j, T1h, T48); T1l = FMA(T1j, T1k, T1i); T4i = T1z * T1D; T1B = T1z * T1A; } { E T1n, T1q, T1m, T1p, T4a, T1o, T1t; T1n = ri[WS(rs, 14)]; T1q = ii[WS(rs, 14)]; T4j = FNMS(T1C, T1A, T4i); T1E = FMA(T1C, T1D, T1B); T1m = W[26]; T1p = W[27]; T1u = ri[WS(rs, 6)]; T1x = ii[WS(rs, 6)]; T4a = T1m * T1q; T1o = T1m * T1n; T1t = W[10]; T1w = W[11]; T4b = FNMS(T1p, T1n, T4a); T1r = FMA(T1p, T1q, T1o); T4g = T1t * T1x; T1v = T1t * T1u; } } { E T4c, T6P, T1s, T4f, T4h, T1y; T4c = T49 - T4b; T6P = T49 + T4b; T1s = T1l + T1r; T4f = T1l - T1r; T4h = FNMS(T1w, T1u, T4g); T1y = FMA(T1w, T1x, T1v); { E T4k, T6Q, T4d, T1F; T4k = T4h - T4j; T6Q = T4h + T4j; T4d = T1y - T1E; T1F = T1y + T1E; T7E = T6P + T6Q; T6R = T6P - T6Q; T60 = T4c + T4d; T4e = T4c - T4d; T6O = T1s - T1F; T1G = T1s + T1F; T61 = T4f - T4k; T4l = T4f + T4k; } } } { E T4Z, T2H, T5p, T30, T2Q, T2T, T2S, T51, T2N, T5m, T2R; { E T2W, T2Z, T2Y, T5o, T2X; { E T2D, T2G, T2C, T2F, T4Y, T2E, T2V; T2D = ri[WS(rs, 31)]; T2G = ii[WS(rs, 31)]; T2C = W[60]; T2F = W[61]; T2W = ri[WS(rs, 23)]; T2Z = ii[WS(rs, 23)]; T4Y = T2C * T2G; T2E = T2C * T2D; T2V = W[44]; T2Y = W[45]; T4Z = FNMS(T2F, T2D, T4Y); T2H = FMA(T2F, T2G, T2E); T5o = T2V * T2Z; T2X = T2V * T2W; } { E T2J, T2M, T2I, T2L, T50, T2K, T2P; T2J = ri[WS(rs, 15)]; T2M = ii[WS(rs, 15)]; T5p = FNMS(T2Y, T2W, T5o); T30 = FMA(T2Y, T2Z, T2X); T2I = W[28]; T2L = W[29]; T2Q = ri[WS(rs, 7)]; T2T = ii[WS(rs, 7)]; T50 = T2I * T2M; T2K = T2I * T2J; T2P = W[12]; T2S = W[13]; T51 = FNMS(T2L, T2J, T50); T2N = FMA(T2L, T2M, T2K); T5m = T2P * T2T; T2R = T2P * T2Q; } } { E T52, T76, T2O, T5l, T5n, T2U; T52 = T4Z - T51; T76 = T4Z + T51; T2O = T2H + T2N; T5l = T2H - T2N; T5n = FNMS(T2S, T2Q, T5m); T2U = FMA(T2S, T2T, T2R); { E T5q, T77, T53, T31; T5q = T5n - T5p; T77 = T5n + T5p; T53 = T2U - T30; T31 = T2U + T30; T78 = T76 - T77; T7N = T76 + T77; T54 = T52 - T53; T6f = T52 + T53; T32 = T2O + T31; T7b = T2O - T31; T6c = T5l - T5q; T5r = T5l + T5q; } } } { E T4q, T1O, T4Q, T27, T1X, T20, T1Z, T4s, T1U, T4N, T1Y; { E T23, T26, T25, T4P, T24; { E T1K, T1N, T1J, T1M, T4p, T1L, T22; T1K = ri[WS(rs, 1)]; T1N = ii[WS(rs, 1)]; T1J = W[0]; T1M = W[1]; T23 = ri[WS(rs, 25)]; T26 = ii[WS(rs, 25)]; T4p = T1J * T1N; T1L = T1J * T1K; T22 = W[48]; T25 = W[49]; T4q = FNMS(T1M, T1K, T4p); T1O = FMA(T1M, T1N, T1L); T4P = T22 * T26; T24 = T22 * T23; } { E T1Q, T1T, T1P, T1S, T4r, T1R, T1W; T1Q = ri[WS(rs, 17)]; T1T = ii[WS(rs, 17)]; T4Q = FNMS(T25, T23, T4P); T27 = FMA(T25, T26, T24); T1P = W[32]; T1S = W[33]; T1X = ri[WS(rs, 9)]; T20 = ii[WS(rs, 9)]; T4r = T1P * T1T; T1R = T1P * T1Q; T1W = W[16]; T1Z = W[17]; T4s = FNMS(T1S, T1Q, T4r); T1U = FMA(T1S, T1T, T1R); T4N = T1W * T20; T1Y = T1W * T1X; } } { E T4t, T6V, T1V, T4M, T4O, T21; T4t = T4q - T4s; T6V = T4q + T4s; T1V = T1O + T1U; T4M = T1O - T1U; T4O = FNMS(T1Z, T1X, T4N); T21 = FMA(T1Z, T20, T1Y); { E T4R, T6W, T4u, T28; T4R = T4O - T4Q; T6W = T4O + T4Q; T4u = T21 - T27; T28 = T21 + T27; T6X = T6V - T6W; T7I = T6V + T6W; T4v = T4t - T4u; T68 = T4t + T4u; T29 = T1V + T28; T70 = T1V - T28; T65 = T4M - T4R; T4S = T4M + T4R; } } } { E T56, T38, T5g, T3r, T3h, T3k, T3j, T58, T3e, T5d, T3i; { E T3n, T3q, T3p, T5f, T3o; { E T34, T37, T33, T36, T55, T35, T3m; T34 = ri[WS(rs, 3)]; T37 = ii[WS(rs, 3)]; T33 = W[4]; T36 = W[5]; T3n = ri[WS(rs, 11)]; T3q = ii[WS(rs, 11)]; T55 = T33 * T37; T35 = T33 * T34; T3m = W[20]; T3p = W[21]; T56 = FNMS(T36, T34, T55); T38 = FMA(T36, T37, T35); T5f = T3m * T3q; T3o = T3m * T3n; } { E T3a, T3d, T39, T3c, T57, T3b, T3g; T3a = ri[WS(rs, 19)]; T3d = ii[WS(rs, 19)]; T5g = FNMS(T3p, T3n, T5f); T3r = FMA(T3p, T3q, T3o); T39 = W[36]; T3c = W[37]; T3h = ri[WS(rs, 27)]; T3k = ii[WS(rs, 27)]; T57 = T39 * T3d; T3b = T39 * T3a; T3g = W[52]; T3j = W[53]; T58 = FNMS(T3c, T3a, T57); T3e = FMA(T3c, T3d, T3b); T5d = T3g * T3k; T3i = T3g * T3h; } } { E T59, T7c, T3f, T5a, T5e, T3l, T7d, T3s; T59 = T56 - T58; T7c = T56 + T58; T3f = T38 + T3e; T5a = T38 - T3e; T5e = FNMS(T3j, T3h, T5d); T3l = FMA(T3j, T3k, T3i); T5h = T5e - T5g; T7d = T5e + T5g; T3s = T3l + T3r; T5c = T3l - T3r; T5s = T5a + T59; T5b = T59 - T5a; T7O = T7c + T7d; T7e = T7c - T7d; T79 = T3s - T3f; T3t = T3f + T3s; } } { E T4x, T2f, T2o, T2r, T4z, T2l, T2n, T2q, T4E, T2p; { E T2u, T2x, T2t, T2w; { E T2b, T2e, T2d, T4w, T2c, T2a; T2b = ri[WS(rs, 5)]; T2e = ii[WS(rs, 5)]; T2a = W[8]; T5t = T5c - T5h; T5i = T5c + T5h; T2d = W[9]; T4w = T2a * T2e; T2c = T2a * T2b; T2u = ri[WS(rs, 13)]; T2x = ii[WS(rs, 13)]; T4x = FNMS(T2d, T2b, T4w); T2f = FMA(T2d, T2e, T2c); T2t = W[24]; T2w = W[25]; } { E T2h, T2k, T2j, T4y, T2i, T4G, T2v, T2g; T2h = ri[WS(rs, 21)]; T2k = ii[WS(rs, 21)]; T4G = T2t * T2x; T2v = T2t * T2u; T2g = W[40]; T2j = W[41]; T4H = FNMS(T2w, T2u, T4G); T2y = FMA(T2w, T2x, T2v); T4y = T2g * T2k; T2i = T2g * T2h; T2o = ri[WS(rs, 29)]; T2r = ii[WS(rs, 29)]; T4z = FNMS(T2j, T2h, T4y); T2l = FMA(T2j, T2k, T2i); T2n = W[56]; T2q = W[57]; } } T4A = T4x - T4z; T71 = T4x + T4z; T2m = T2f + T2l; T4B = T2f - T2l; T4E = T2n * T2r; T2p = T2n * T2o; T4F = FNMS(T2q, T2o, T4E); T2s = FMA(T2q, T2r, T2p); } } { E T4T, T4C, T4J, T4U, T7y, T8q, T8p, T7B; { E T6E, T8j, T73, T6Y, T6H, T8k, T8i, T8h; { E T7C, TO, T80, T7Z, T8e, T89, T8d, T1H, T8b, T3v, T7T, T7L, T7U, T7Q, T2A; E T7K, T7P, T7W, T1I; { E T7X, T7Y, T7J, T82, T88; { E Tm, T4I, T72, T4D, T2z, TN; T6E = T8 - Tl; Tm = T8 + Tl; T4T = T4B + T4A; T4C = T4A - T4B; T4I = T4F - T4H; T72 = T4F + T4H; T4D = T2s - T2y; T2z = T2s + T2y; TN = Tz + TM; T8j = TM - Tz; T73 = T71 - T72; T7J = T71 + T72; T4J = T4D + T4I; T4U = T4D - T4I; T2A = T2m + T2z; T6Y = T2z - T2m; T7C = Tm - TN; TO = Tm + TN; } T7K = T7I - T7J; T7X = T7I + T7J; T7Y = T7N + T7O; T7P = T7N - T7O; T6H = T6F - T6G; T82 = T6F + T6G; T88 = T83 + T87; T8k = T87 - T83; T80 = T7X + T7Y; T7Z = T7X - T7Y; T8e = T88 - T82; T89 = T82 + T88; } { E T7H, T7M, T2B, T3u; T7H = T29 - T2A; T2B = T29 + T2A; T3u = T32 + T3t; T7M = T32 - T3t; T8d = T1G - T1f; T1H = T1f + T1G; T8b = T3u - T2B; T3v = T2B + T3u; T7T = T7K - T7H; T7L = T7H + T7K; T7U = T7M + T7P; T7Q = T7M - T7P; } T7W = TO - T1H; T1I = TO + T1H; { E T7S, T8f, T8g, T7V; { E T7R, T8c, T8a, T7G, T81, T7F; T8i = T7Q - T7L; T7R = T7L + T7Q; T81 = T7D + T7E; T7F = T7D - T7E; ri[0] = T1I + T3v; ri[WS(rs, 16)] = T1I - T3v; ri[WS(rs, 8)] = T7W + T7Z; ri[WS(rs, 24)] = T7W - T7Z; T8c = T89 - T81; T8a = T81 + T89; T7G = T7C + T7F; T7S = T7C - T7F; T8h = T8e - T8d; T8f = T8d + T8e; ii[WS(rs, 24)] = T8c - T8b; ii[WS(rs, 8)] = T8b + T8c; ii[WS(rs, 16)] = T8a - T80; ii[0] = T80 + T8a; ri[WS(rs, 4)] = FMA(KP707106781, T7R, T7G); ri[WS(rs, 20)] = FNMS(KP707106781, T7R, T7G); T8g = T7T + T7U; T7V = T7T - T7U; } ii[WS(rs, 20)] = FNMS(KP707106781, T8g, T8f); ii[WS(rs, 4)] = FMA(KP707106781, T8g, T8f); ri[WS(rs, 12)] = FMA(KP707106781, T7V, T7S); ri[WS(rs, 28)] = FNMS(KP707106781, T7V, T7S); } } { E T7f, T7m, T6I, T7a, T7A, T7w, T8r, T8l, T8m, T6T, T7j, T75, T8s, T7p, T7z; E T7t; { E T7n, T6N, T6S, T7o, T7u, T7v; T7f = T7b - T7e; T7u = T7b + T7e; ii[WS(rs, 28)] = FNMS(KP707106781, T8i, T8h); ii[WS(rs, 12)] = FMA(KP707106781, T8i, T8h); T7m = T6E + T6H; T6I = T6E - T6H; T7v = T78 + T79; T7a = T78 - T79; T7n = T6M + T6L; T6N = T6L - T6M; T7A = FMA(KP414213562, T7u, T7v); T7w = FNMS(KP414213562, T7v, T7u); T8r = T8k - T8j; T8l = T8j + T8k; T6S = T6O + T6R; T7o = T6O - T6R; { E T7s, T7r, T6Z, T74; T7s = T6X + T6Y; T6Z = T6X - T6Y; T74 = T70 - T73; T7r = T70 + T73; T8m = T6N + T6S; T6T = T6N - T6S; T7j = FNMS(KP414213562, T6Z, T74); T75 = FMA(KP414213562, T74, T6Z); T8s = T7o - T7n; T7p = T7n + T7o; T7z = FNMS(KP414213562, T7r, T7s); T7t = FMA(KP414213562, T7s, T7r); } } { E T7i, T6U, T8t, T8v, T7k, T7g; T7i = FNMS(KP707106781, T6T, T6I); T6U = FMA(KP707106781, T6T, T6I); T8t = FMA(KP707106781, T8s, T8r); T8v = FNMS(KP707106781, T8s, T8r); T7k = FMA(KP414213562, T7a, T7f); T7g = FNMS(KP414213562, T7f, T7a); { E T7q, T7x, T8n, T8o; T7y = FNMS(KP707106781, T7p, T7m); T7q = FMA(KP707106781, T7p, T7m); { E T7l, T8u, T8w, T7h; T7l = T7j + T7k; T8u = T7k - T7j; T8w = T75 + T7g; T7h = T75 - T7g; ri[WS(rs, 30)] = FMA(KP923879532, T7l, T7i); ri[WS(rs, 14)] = FNMS(KP923879532, T7l, T7i); ii[WS(rs, 22)] = FNMS(KP923879532, T8u, T8t); ii[WS(rs, 6)] = FMA(KP923879532, T8u, T8t); ii[WS(rs, 30)] = FMA(KP923879532, T8w, T8v); ii[WS(rs, 14)] = FNMS(KP923879532, T8w, T8v); ri[WS(rs, 6)] = FMA(KP923879532, T7h, T6U); ri[WS(rs, 22)] = FNMS(KP923879532, T7h, T6U); T7x = T7t + T7w; T8q = T7w - T7t; } T8p = FNMS(KP707106781, T8m, T8l); T8n = FMA(KP707106781, T8m, T8l); T8o = T7z + T7A; T7B = T7z - T7A; ri[WS(rs, 2)] = FMA(KP923879532, T7x, T7q); ri[WS(rs, 18)] = FNMS(KP923879532, T7x, T7q); ii[WS(rs, 18)] = FNMS(KP923879532, T8o, T8n); ii[WS(rs, 2)] = FMA(KP923879532, T8o, T8n); } } } } { E T5S, T8O, T8N, T5V, T6d, T6g, T66, T69, T8G, T8F; { E T5C, T3S, T8C, T4n, T8H, T8B, T8I, T5F, T5k, T5L, T5u, T4K, T4V; { E T5D, T5E, T8z, T8A, T5j; { E T3C, T3R, T47, T4m; T5S = T3w - T3B; T3C = T3w + T3B; ri[WS(rs, 10)] = FMA(KP923879532, T7B, T7y); ri[WS(rs, 26)] = FNMS(KP923879532, T7B, T7y); ii[WS(rs, 26)] = FNMS(KP923879532, T8q, T8p); ii[WS(rs, 10)] = FMA(KP923879532, T8q, T8p); T3R = T3J + T3Q; T8O = T3Q - T3J; T5D = FMA(KP414213562, T3Z, T46); T47 = FNMS(KP414213562, T46, T3Z); T4m = FMA(KP414213562, T4l, T4e); T5E = FNMS(KP414213562, T4e, T4l); T8N = T8y + T8x; T8z = T8x - T8y; T5C = FMA(KP707106781, T3R, T3C); T3S = FNMS(KP707106781, T3R, T3C); T8C = T47 + T4m; T4n = T47 - T4m; T8A = T5T + T5U; T5V = T5T - T5U; } T6d = T5i - T5b; T5j = T5b + T5i; T8H = FNMS(KP707106781, T8A, T8z); T8B = FMA(KP707106781, T8A, T8z); T8I = T5E - T5D; T5F = T5D + T5E; T5k = FNMS(KP707106781, T5j, T54); T5L = FMA(KP707106781, T5j, T54); T5u = T5s + T5t; T6g = T5s - T5t; T66 = T4J - T4C; T4K = T4C + T4J; T4V = T4T + T4U; T69 = T4T - T4U; } { E T5M, T5Q, T5J, T5P, T8L, T8M; { E T5y, T4o, T5A, T5w, T5z, T4X, T8J, T5K, T5v, T8K, T5B, T5x; T5y = FNMS(KP923879532, T4n, T3S); T4o = FMA(KP923879532, T4n, T3S); T5K = FMA(KP707106781, T5u, T5r); T5v = FNMS(KP707106781, T5u, T5r); { E T5I, T4L, T5H, T4W; T5I = FMA(KP707106781, T4K, T4v); T4L = FNMS(KP707106781, T4K, T4v); T5H = FMA(KP707106781, T4V, T4S); T4W = FNMS(KP707106781, T4V, T4S); T5M = FNMS(KP198912367, T5L, T5K); T5Q = FMA(KP198912367, T5K, T5L); T5A = FMA(KP668178637, T5k, T5v); T5w = FNMS(KP668178637, T5v, T5k); T5J = FMA(KP198912367, T5I, T5H); T5P = FNMS(KP198912367, T5H, T5I); T5z = FNMS(KP668178637, T4L, T4W); T4X = FMA(KP668178637, T4W, T4L); } T8J = FMA(KP923879532, T8I, T8H); T8L = FNMS(KP923879532, T8I, T8H); T8K = T5A - T5z; T5B = T5z + T5A; T8M = T4X + T5w; T5x = T4X - T5w; ii[WS(rs, 21)] = FNMS(KP831469612, T8K, T8J); ii[WS(rs, 5)] = FMA(KP831469612, T8K, T8J); ri[WS(rs, 5)] = FMA(KP831469612, T5x, T4o); ri[WS(rs, 21)] = FNMS(KP831469612, T5x, T4o); ri[WS(rs, 29)] = FMA(KP831469612, T5B, T5y); ri[WS(rs, 13)] = FNMS(KP831469612, T5B, T5y); } { E T5O, T8D, T8E, T5R, T5G, T5N; T5O = FNMS(KP923879532, T5F, T5C); T5G = FMA(KP923879532, T5F, T5C); T5N = T5J + T5M; T8G = T5M - T5J; T8F = FNMS(KP923879532, T8C, T8B); T8D = FMA(KP923879532, T8C, T8B); ii[WS(rs, 29)] = FMA(KP831469612, T8M, T8L); ii[WS(rs, 13)] = FNMS(KP831469612, T8M, T8L); ri[WS(rs, 1)] = FMA(KP980785280, T5N, T5G); ri[WS(rs, 17)] = FNMS(KP980785280, T5N, T5G); T8E = T5P + T5Q; T5R = T5P - T5Q; ii[WS(rs, 17)] = FNMS(KP980785280, T8E, T8D); ii[WS(rs, 1)] = FMA(KP980785280, T8E, T8D); ri[WS(rs, 9)] = FMA(KP980785280, T5R, T5O); ri[WS(rs, 25)] = FNMS(KP980785280, T5R, T5O); } } } { E T6o, T5W, T8W, T63, T8V, T8P, T8Q, T6r, T67, T6u, T6y, T6C, T6m, T6i; { E T6p, T5Z, T62, T6q; T6p = FNMS(KP414213562, T5X, T5Y); T5Z = FMA(KP414213562, T5Y, T5X); ii[WS(rs, 25)] = FNMS(KP980785280, T8G, T8F); ii[WS(rs, 9)] = FMA(KP980785280, T8G, T8F); T6o = FNMS(KP707106781, T5V, T5S); T5W = FMA(KP707106781, T5V, T5S); T62 = FNMS(KP414213562, T61, T60); T6q = FMA(KP414213562, T60, T61); T8W = T5Z + T62; T63 = T5Z - T62; T8V = FNMS(KP707106781, T8O, T8N); T8P = FMA(KP707106781, T8O, T8N); { E T6x, T6e, T6w, T6h; T8Q = T6q - T6p; T6r = T6p + T6q; T6x = FMA(KP707106781, T6d, T6c); T6e = FNMS(KP707106781, T6d, T6c); T6w = FMA(KP707106781, T6g, T6f); T6h = FNMS(KP707106781, T6g, T6f); T67 = FNMS(KP707106781, T66, T65); T6u = FMA(KP707106781, T66, T65); T6y = FNMS(KP198912367, T6x, T6w); T6C = FMA(KP198912367, T6w, T6x); T6m = FMA(KP668178637, T6e, T6h); T6i = FNMS(KP668178637, T6h, T6e); } } { E T6k, T64, T8R, T8T, T6t, T6a; T6k = FNMS(KP923879532, T63, T5W); T64 = FMA(KP923879532, T63, T5W); T8R = FMA(KP923879532, T8Q, T8P); T8T = FNMS(KP923879532, T8Q, T8P); T6t = FMA(KP707106781, T69, T68); T6a = FNMS(KP707106781, T69, T68); { E T6A, T8X, T8Y, T6D; { E T6s, T6B, T6l, T6b, T6z, T6v; T6A = FMA(KP923879532, T6r, T6o); T6s = FNMS(KP923879532, T6r, T6o); T6v = FMA(KP198912367, T6u, T6t); T6B = FNMS(KP198912367, T6t, T6u); T6l = FNMS(KP668178637, T67, T6a); T6b = FMA(KP668178637, T6a, T67); T6z = T6v - T6y; T90 = T6v + T6y; T8Z = FMA(KP923879532, T8W, T8V); T8X = FNMS(KP923879532, T8W, T8V); { E T6n, T8S, T8U, T6j; T6n = T6l - T6m; T8S = T6l + T6m; T8U = T6i - T6b; T6j = T6b + T6i; ri[WS(rs, 7)] = FMA(KP980785280, T6z, T6s); ri[WS(rs, 23)] = FNMS(KP980785280, T6z, T6s); ri[WS(rs, 11)] = FMA(KP831469612, T6n, T6k); ri[WS(rs, 27)] = FNMS(KP831469612, T6n, T6k); ii[WS(rs, 19)] = FNMS(KP831469612, T8S, T8R); ii[WS(rs, 3)] = FMA(KP831469612, T8S, T8R); ii[WS(rs, 27)] = FNMS(KP831469612, T8U, T8T); ii[WS(rs, 11)] = FMA(KP831469612, T8U, T8T); ri[WS(rs, 3)] = FMA(KP831469612, T6j, T64); ri[WS(rs, 19)] = FNMS(KP831469612, T6j, T64); T8Y = T6C - T6B; T6D = T6B + T6C; } } ii[WS(rs, 23)] = FNMS(KP980785280, T8Y, T8X); ii[WS(rs, 7)] = FMA(KP980785280, T8Y, T8X); ri[WS(rs, 31)] = FMA(KP980785280, T6D, T6A); ri[WS(rs, 15)] = FNMS(KP980785280, T6D, T6A); } } } } } } ii[WS(rs, 31)] = FMA(KP980785280, T90, T8Z); ii[WS(rs, 15)] = FNMS(KP980785280, T90, T8Z); } } static const tw_instr twinstr[] = { {TW_FULL, 0, 32}, {TW_NEXT, 1, 0} }; static const ct_desc desc = { 32, "t1_32", twinstr, &GENUS, {236, 62, 198, 0}, 0, 0, 0 }; void X(codelet_t1_32) (planner *p) { X(kdft_dit_register) (p, t1_32, &desc); } #else /* HAVE_FMA */ /* Generated by: ../../../genfft/gen_twiddle -compact -variables 4 -pipeline-latency 4 -n 32 -name t1_32 -include t.h */ /* * This function contains 434 FP additions, 208 FP multiplications, * (or, 340 additions, 114 multiplications, 94 fused multiply/add), * 96 stack variables, 7 constants, and 128 memory accesses */ #include "t.h" static void t1_32(R *ri, R *ii, const R *W, stride rs, INT mb, INT me, INT ms) { DK(KP195090322, +0.195090322016128267848284868477022240927691618); DK(KP980785280, +0.980785280403230449126182236134239036973933731); DK(KP555570233, +0.555570233019602224742830813948532874374937191); DK(KP831469612, +0.831469612302545237078788377617905756738560812); DK(KP382683432, +0.382683432365089771728459984030398866761344562); DK(KP923879532, +0.923879532511286756128183189396788286822416626); DK(KP707106781, +0.707106781186547524400844362104849039284835938); INT m; for (m = mb, W = W + (mb * 62); m < me; m = m + 1, ri = ri + ms, ii = ii + ms, W = W + 62, MAKE_VOLATILE_STRIDE(rs)) { E Tj, T5F, T7C, T7Q, T35, T4T, T78, T7m, T1Q, T61, T5Y, T6J, T3K, T59, T41; E T56, T2B, T67, T6e, T6O, T4b, T5d, T4s, T5g, TG, T7l, T5I, T73, T3a, T4U; E T3f, T4V, T14, T5N, T5M, T6E, T3m, T4Y, T3r, T4Z, T1r, T5P, T5S, T6F, T3x; E T51, T3C, T52, T2d, T5Z, T64, T6K, T3V, T57, T44, T5a, T2Y, T6f, T6a, T6P; E T4m, T5h, T4v, T5e; { E T1, T76, T6, T75, Tc, T32, Th, T33; T1 = ri[0]; T76 = ii[0]; { E T3, T5, T2, T4; T3 = ri[WS(rs, 16)]; T5 = ii[WS(rs, 16)]; T2 = W[30]; T4 = W[31]; T6 = FMA(T2, T3, T4 * T5); T75 = FNMS(T4, T3, T2 * T5); } { E T9, Tb, T8, Ta; T9 = ri[WS(rs, 8)]; Tb = ii[WS(rs, 8)]; T8 = W[14]; Ta = W[15]; Tc = FMA(T8, T9, Ta * Tb); T32 = FNMS(Ta, T9, T8 * Tb); } { E Te, Tg, Td, Tf; Te = ri[WS(rs, 24)]; Tg = ii[WS(rs, 24)]; Td = W[46]; Tf = W[47]; Th = FMA(Td, Te, Tf * Tg); T33 = FNMS(Tf, Te, Td * Tg); } { E T7, Ti, T7A, T7B; T7 = T1 + T6; Ti = Tc + Th; Tj = T7 + Ti; T5F = T7 - Ti; T7A = T76 - T75; T7B = Tc - Th; T7C = T7A - T7B; T7Q = T7B + T7A; } { E T31, T34, T74, T77; T31 = T1 - T6; T34 = T32 - T33; T35 = T31 - T34; T4T = T31 + T34; T74 = T32 + T33; T77 = T75 + T76; T78 = T74 + T77; T7m = T77 - T74; } } { E T1y, T3G, T1O, T3Z, T1D, T3H, T1J, T3Y; { E T1v, T1x, T1u, T1w; T1v = ri[WS(rs, 1)]; T1x = ii[WS(rs, 1)]; T1u = W[0]; T1w = W[1]; T1y = FMA(T1u, T1v, T1w * T1x); T3G = FNMS(T1w, T1v, T1u * T1x); } { E T1L, T1N, T1K, T1M; T1L = ri[WS(rs, 25)]; T1N = ii[WS(rs, 25)]; T1K = W[48]; T1M = W[49]; T1O = FMA(T1K, T1L, T1M * T1N); T3Z = FNMS(T1M, T1L, T1K * T1N); } { E T1A, T1C, T1z, T1B; T1A = ri[WS(rs, 17)]; T1C = ii[WS(rs, 17)]; T1z = W[32]; T1B = W[33]; T1D = FMA(T1z, T1A, T1B * T1C); T3H = FNMS(T1B, T1A, T1z * T1C); } { E T1G, T1I, T1F, T1H; T1G = ri[WS(rs, 9)]; T1I = ii[WS(rs, 9)]; T1F = W[16]; T1H = W[17]; T1J = FMA(T1F, T1G, T1H * T1I); T3Y = FNMS(T1H, T1G, T1F * T1I); } { E T1E, T1P, T5W, T5X; T1E = T1y + T1D; T1P = T1J + T1O; T1Q = T1E + T1P; T61 = T1E - T1P; T5W = T3G + T3H; T5X = T3Y + T3Z; T5Y = T5W - T5X; T6J = T5W + T5X; } { E T3I, T3J, T3X, T40; T3I = T3G - T3H; T3J = T1J - T1O; T3K = T3I + T3J; T59 = T3I - T3J; T3X = T1y - T1D; T40 = T3Y - T3Z; T41 = T3X - T40; T56 = T3X + T40; } } { E T2j, T4o, T2z, T49, T2o, T4p, T2u, T48; { E T2g, T2i, T2f, T2h; T2g = ri[WS(rs, 31)]; T2i = ii[WS(rs, 31)]; T2f = W[60]; T2h = W[61]; T2j = FMA(T2f, T2g, T2h * T2i); T4o = FNMS(T2h, T2g, T2f * T2i); } { E T2w, T2y, T2v, T2x; T2w = ri[WS(rs, 23)]; T2y = ii[WS(rs, 23)]; T2v = W[44]; T2x = W[45]; T2z = FMA(T2v, T2w, T2x * T2y); T49 = FNMS(T2x, T2w, T2v * T2y); } { E T2l, T2n, T2k, T2m; T2l = ri[WS(rs, 15)]; T2n = ii[WS(rs, 15)]; T2k = W[28]; T2m = W[29]; T2o = FMA(T2k, T2l, T2m * T2n); T4p = FNMS(T2m, T2l, T2k * T2n); } { E T2r, T2t, T2q, T2s; T2r = ri[WS(rs, 7)]; T2t = ii[WS(rs, 7)]; T2q = W[12]; T2s = W[13]; T2u = FMA(T2q, T2r, T2s * T2t); T48 = FNMS(T2s, T2r, T2q * T2t); } { E T2p, T2A, T6c, T6d; T2p = T2j + T2o; T2A = T2u + T2z; T2B = T2p + T2A; T67 = T2p - T2A; T6c = T4o + T4p; T6d = T48 + T49; T6e = T6c - T6d; T6O = T6c + T6d; } { E T47, T4a, T4q, T4r; T47 = T2j - T2o; T4a = T48 - T49; T4b = T47 - T4a; T5d = T47 + T4a; T4q = T4o - T4p; T4r = T2u - T2z; T4s = T4q + T4r; T5g = T4q - T4r; } } { E To, T36, TE, T3d, Tt, T37, Tz, T3c; { E Tl, Tn, Tk, Tm; Tl = ri[WS(rs, 4)]; Tn = ii[WS(rs, 4)]; Tk = W[6]; Tm = W[7]; To = FMA(Tk, Tl, Tm * Tn); T36 = FNMS(Tm, Tl, Tk * Tn); } { E TB, TD, TA, TC; TB = ri[WS(rs, 12)]; TD = ii[WS(rs, 12)]; TA = W[22]; TC = W[23]; TE = FMA(TA, TB, TC * TD); T3d = FNMS(TC, TB, TA * TD); } { E Tq, Ts, Tp, Tr; Tq = ri[WS(rs, 20)]; Ts = ii[WS(rs, 20)]; Tp = W[38]; Tr = W[39]; Tt = FMA(Tp, Tq, Tr * Ts); T37 = FNMS(Tr, Tq, Tp * Ts); } { E Tw, Ty, Tv, Tx; Tw = ri[WS(rs, 28)]; Ty = ii[WS(rs, 28)]; Tv = W[54]; Tx = W[55]; Tz = FMA(Tv, Tw, Tx * Ty); T3c = FNMS(Tx, Tw, Tv * Ty); } { E Tu, TF, T5G, T5H; Tu = To + Tt; TF = Tz + TE; TG = Tu + TF; T7l = TF - Tu; T5G = T36 + T37; T5H = T3c + T3d; T5I = T5G - T5H; T73 = T5G + T5H; } { E T38, T39, T3b, T3e; T38 = T36 - T37; T39 = To - Tt; T3a = T38 - T39; T4U = T39 + T38; T3b = Tz - TE; T3e = T3c - T3d; T3f = T3b + T3e; T4V = T3b - T3e; } } { E TM, T3i, T12, T3p, TR, T3j, TX, T3o; { E TJ, TL, TI, TK; TJ = ri[WS(rs, 2)]; TL = ii[WS(rs, 2)]; TI = W[2]; TK = W[3]; TM = FMA(TI, TJ, TK * TL); T3i = FNMS(TK, TJ, TI * TL); } { E TZ, T11, TY, T10; TZ = ri[WS(rs, 26)]; T11 = ii[WS(rs, 26)]; TY = W[50]; T10 = W[51]; T12 = FMA(TY, TZ, T10 * T11); T3p = FNMS(T10, TZ, TY * T11); } { E TO, TQ, TN, TP; TO = ri[WS(rs, 18)]; TQ = ii[WS(rs, 18)]; TN = W[34]; TP = W[35]; TR = FMA(TN, TO, TP * TQ); T3j = FNMS(TP, TO, TN * TQ); } { E TU, TW, TT, TV; TU = ri[WS(rs, 10)]; TW = ii[WS(rs, 10)]; TT = W[18]; TV = W[19]; TX = FMA(TT, TU, TV * TW); T3o = FNMS(TV, TU, TT * TW); } { E TS, T13, T5K, T5L; TS = TM + TR; T13 = TX + T12; T14 = TS + T13; T5N = TS - T13; T5K = T3i + T3j; T5L = T3o + T3p; T5M = T5K - T5L; T6E = T5K + T5L; } { E T3k, T3l, T3n, T3q; T3k = T3i - T3j; T3l = TX - T12; T3m = T3k + T3l; T4Y = T3k - T3l; T3n = TM - TR; T3q = T3o - T3p; T3r = T3n - T3q; T4Z = T3n + T3q; } } { E T19, T3t, T1p, T3A, T1e, T3u, T1k, T3z; { E T16, T18, T15, T17; T16 = ri[WS(rs, 30)]; T18 = ii[WS(rs, 30)]; T15 = W[58]; T17 = W[59]; T19 = FMA(T15, T16, T17 * T18); T3t = FNMS(T17, T16, T15 * T18); } { E T1m, T1o, T1l, T1n; T1m = ri[WS(rs, 22)]; T1o = ii[WS(rs, 22)]; T1l = W[42]; T1n = W[43]; T1p = FMA(T1l, T1m, T1n * T1o); T3A = FNMS(T1n, T1m, T1l * T1o); } { E T1b, T1d, T1a, T1c; T1b = ri[WS(rs, 14)]; T1d = ii[WS(rs, 14)]; T1a = W[26]; T1c = W[27]; T1e = FMA(T1a, T1b, T1c * T1d); T3u = FNMS(T1c, T1b, T1a * T1d); } { E T1h, T1j, T1g, T1i; T1h = ri[WS(rs, 6)]; T1j = ii[WS(rs, 6)]; T1g = W[10]; T1i = W[11]; T1k = FMA(T1g, T1h, T1i * T1j); T3z = FNMS(T1i, T1h, T1g * T1j); } { E T1f, T1q, T5Q, T5R; T1f = T19 + T1e; T1q = T1k + T1p; T1r = T1f + T1q; T5P = T1f - T1q; T5Q = T3t + T3u; T5R = T3z + T3A; T5S = T5Q - T5R; T6F = T5Q + T5R; } { E T3v, T3w, T3y, T3B; T3v = T3t - T3u; T3w = T1k - T1p; T3x = T3v + T3w; T51 = T3v - T3w; T3y = T19 - T1e; T3B = T3z - T3A; T3C = T3y - T3B; T52 = T3y + T3B; } } { E T1V, T3R, T20, T3S, T3Q, T3T, T26, T3M, T2b, T3N, T3L, T3O; { E T1S, T1U, T1R, T1T; T1S = ri[WS(rs, 5)]; T1U = ii[WS(rs, 5)]; T1R = W[8]; T1T = W[9]; T1V = FMA(T1R, T1S, T1T * T1U); T3R = FNMS(T1T, T1S, T1R * T1U); } { E T1X, T1Z, T1W, T1Y; T1X = ri[WS(rs, 21)]; T1Z = ii[WS(rs, 21)]; T1W = W[40]; T1Y = W[41]; T20 = FMA(T1W, T1X, T1Y * T1Z); T3S = FNMS(T1Y, T1X, T1W * T1Z); } T3Q = T1V - T20; T3T = T3R - T3S; { E T23, T25, T22, T24; T23 = ri[WS(rs, 29)]; T25 = ii[WS(rs, 29)]; T22 = W[56]; T24 = W[57]; T26 = FMA(T22, T23, T24 * T25); T3M = FNMS(T24, T23, T22 * T25); } { E T28, T2a, T27, T29; T28 = ri[WS(rs, 13)]; T2a = ii[WS(rs, 13)]; T27 = W[24]; T29 = W[25]; T2b = FMA(T27, T28, T29 * T2a); T3N = FNMS(T29, T28, T27 * T2a); } T3L = T26 - T2b; T3O = T3M - T3N; { E T21, T2c, T62, T63; T21 = T1V + T20; T2c = T26 + T2b; T2d = T21 + T2c; T5Z = T2c - T21; T62 = T3R + T3S; T63 = T3M + T3N; T64 = T62 - T63; T6K = T62 + T63; } { E T3P, T3U, T42, T43; T3P = T3L - T3O; T3U = T3Q + T3T; T3V = KP707106781 * (T3P - T3U); T57 = KP707106781 * (T3U + T3P); T42 = T3T - T3Q; T43 = T3L + T3O; T44 = KP707106781 * (T42 - T43); T5a = KP707106781 * (T42 + T43); } } { E T2G, T4c, T2L, T4d, T4e, T4f, T2R, T4i, T2W, T4j, T4h, T4k; { E T2D, T2F, T2C, T2E; T2D = ri[WS(rs, 3)]; T2F = ii[WS(rs, 3)]; T2C = W[4]; T2E = W[5]; T2G = FMA(T2C, T2D, T2E * T2F); T4c = FNMS(T2E, T2D, T2C * T2F); } { E T2I, T2K, T2H, T2J; T2I = ri[WS(rs, 19)]; T2K = ii[WS(rs, 19)]; T2H = W[36]; T2J = W[37]; T2L = FMA(T2H, T2I, T2J * T2K); T4d = FNMS(T2J, T2I, T2H * T2K); } T4e = T4c - T4d; T4f = T2G - T2L; { E T2O, T2Q, T2N, T2P; T2O = ri[WS(rs, 27)]; T2Q = ii[WS(rs, 27)]; T2N = W[52]; T2P = W[53]; T2R = FMA(T2N, T2O, T2P * T2Q); T4i = FNMS(T2P, T2O, T2N * T2Q); } { E T2T, T2V, T2S, T2U; T2T = ri[WS(rs, 11)]; T2V = ii[WS(rs, 11)]; T2S = W[20]; T2U = W[21]; T2W = FMA(T2S, T2T, T2U * T2V); T4j = FNMS(T2U, T2T, T2S * T2V); } T4h = T2R - T2W; T4k = T4i - T4j; { E T2M, T2X, T68, T69; T2M = T2G + T2L; T2X = T2R + T2W; T2Y = T2M + T2X; T6f = T2X - T2M; T68 = T4c + T4d; T69 = T4i + T4j; T6a = T68 - T69; T6P = T68 + T69; } { E T4g, T4l, T4t, T4u; T4g = T4e - T4f; T4l = T4h + T4k; T4m = KP707106781 * (T4g - T4l); T5h = KP707106781 * (T4g + T4l); T4t = T4h - T4k; T4u = T4f + T4e; T4v = KP707106781 * (T4t - T4u); T5e = KP707106781 * (T4u + T4t); } } { E T1t, T6X, T7a, T7c, T30, T7b, T70, T71; { E TH, T1s, T72, T79; TH = Tj + TG; T1s = T14 + T1r; T1t = TH + T1s; T6X = TH - T1s; T72 = T6E + T6F; T79 = T73 + T78; T7a = T72 + T79; T7c = T79 - T72; } { E T2e, T2Z, T6Y, T6Z; T2e = T1Q + T2d; T2Z = T2B + T2Y; T30 = T2e + T2Z; T7b = T2Z - T2e; T6Y = T6J + T6K; T6Z = T6O + T6P; T70 = T6Y - T6Z; T71 = T6Y + T6Z; } ri[WS(rs, 16)] = T1t - T30; ii[WS(rs, 16)] = T7a - T71; ri[0] = T1t + T30; ii[0] = T71 + T7a; ri[WS(rs, 24)] = T6X - T70; ii[WS(rs, 24)] = T7c - T7b; ri[WS(rs, 8)] = T6X + T70; ii[WS(rs, 8)] = T7b + T7c; } { E T6H, T6T, T7g, T7i, T6M, T6U, T6R, T6V; { E T6D, T6G, T7e, T7f; T6D = Tj - TG; T6G = T6E - T6F; T6H = T6D + T6G; T6T = T6D - T6G; T7e = T1r - T14; T7f = T78 - T73; T7g = T7e + T7f; T7i = T7f - T7e; } { E T6I, T6L, T6N, T6Q; T6I = T1Q - T2d; T6L = T6J - T6K; T6M = T6I + T6L; T6U = T6L - T6I; T6N = T2B - T2Y; T6Q = T6O - T6P; T6R = T6N - T6Q; T6V = T6N + T6Q; } { E T6S, T7d, T6W, T7h; T6S = KP707106781 * (T6M + T6R); ri[WS(rs, 20)] = T6H - T6S; ri[WS(rs, 4)] = T6H + T6S; T7d = KP707106781 * (T6U + T6V); ii[WS(rs, 4)] = T7d + T7g; ii[WS(rs, 20)] = T7g - T7d; T6W = KP707106781 * (T6U - T6V); ri[WS(rs, 28)] = T6T - T6W; ri[WS(rs, 12)] = T6T + T6W; T7h = KP707106781 * (T6R - T6M); ii[WS(rs, 12)] = T7h + T7i; ii[WS(rs, 28)] = T7i - T7h; } } { E T5J, T7n, T7t, T6n, T5U, T7k, T6x, T6B, T6q, T7s, T66, T6k, T6u, T6A, T6h; E T6l; { E T5O, T5T, T60, T65; T5J = T5F - T5I; T7n = T7l + T7m; T7t = T7m - T7l; T6n = T5F + T5I; T5O = T5M - T5N; T5T = T5P + T5S; T5U = KP707106781 * (T5O - T5T); T7k = KP707106781 * (T5O + T5T); { E T6v, T6w, T6o, T6p; T6v = T67 + T6a; T6w = T6e + T6f; T6x = FNMS(KP382683432, T6w, KP923879532 * T6v); T6B = FMA(KP923879532, T6w, KP382683432 * T6v); T6o = T5N + T5M; T6p = T5P - T5S; T6q = KP707106781 * (T6o + T6p); T7s = KP707106781 * (T6p - T6o); } T60 = T5Y - T5Z; T65 = T61 - T64; T66 = FMA(KP923879532, T60, KP382683432 * T65); T6k = FNMS(KP923879532, T65, KP382683432 * T60); { E T6s, T6t, T6b, T6g; T6s = T5Y + T5Z; T6t = T61 + T64; T6u = FMA(KP382683432, T6s, KP923879532 * T6t); T6A = FNMS(KP382683432, T6t, KP923879532 * T6s); T6b = T67 - T6a; T6g = T6e - T6f; T6h = FNMS(KP923879532, T6g, KP382683432 * T6b); T6l = FMA(KP382683432, T6g, KP923879532 * T6b); } } { E T5V, T6i, T7r, T7u; T5V = T5J + T5U; T6i = T66 + T6h; ri[WS(rs, 22)] = T5V - T6i; ri[WS(rs, 6)] = T5V + T6i; T7r = T6k + T6l; T7u = T7s + T7t; ii[WS(rs, 6)] = T7r + T7u; ii[WS(rs, 22)] = T7u - T7r; } { E T6j, T6m, T7v, T7w; T6j = T5J - T5U; T6m = T6k - T6l; ri[WS(rs, 30)] = T6j - T6m; ri[WS(rs, 14)] = T6j + T6m; T7v = T6h - T66; T7w = T7t - T7s; ii[WS(rs, 14)] = T7v + T7w; ii[WS(rs, 30)] = T7w - T7v; } { E T6r, T6y, T7j, T7o; T6r = T6n + T6q; T6y = T6u + T6x; ri[WS(rs, 18)] = T6r - T6y; ri[WS(rs, 2)] = T6r + T6y; T7j = T6A + T6B; T7o = T7k + T7n; ii[WS(rs, 2)] = T7j + T7o; ii[WS(rs, 18)] = T7o - T7j; } { E T6z, T6C, T7p, T7q; T6z = T6n - T6q; T6C = T6A - T6B; ri[WS(rs, 26)] = T6z - T6C; ri[WS(rs, 10)] = T6z + T6C; T7p = T6x - T6u; T7q = T7n - T7k; ii[WS(rs, 10)] = T7p + T7q; ii[WS(rs, 26)] = T7q - T7p; } } { E T3h, T4D, T7R, T7X, T3E, T7O, T4N, T4R, T46, T4A, T4G, T7W, T4K, T4Q, T4x; E T4B, T3g, T7P; T3g = KP707106781 * (T3a - T3f); T3h = T35 - T3g; T4D = T35 + T3g; T7P = KP707106781 * (T4V - T4U); T7R = T7P + T7Q; T7X = T7Q - T7P; { E T3s, T3D, T4L, T4M; T3s = FNMS(KP923879532, T3r, KP382683432 * T3m); T3D = FMA(KP382683432, T3x, KP923879532 * T3C); T3E = T3s - T3D; T7O = T3s + T3D; T4L = T4b + T4m; T4M = T4s + T4v; T4N = FNMS(KP555570233, T4M, KP831469612 * T4L); T4R = FMA(KP831469612, T4M, KP555570233 * T4L); } { E T3W, T45, T4E, T4F; T3W = T3K - T3V; T45 = T41 - T44; T46 = FMA(KP980785280, T3W, KP195090322 * T45); T4A = FNMS(KP980785280, T45, KP195090322 * T3W); T4E = FMA(KP923879532, T3m, KP382683432 * T3r); T4F = FNMS(KP923879532, T3x, KP382683432 * T3C); T4G = T4E + T4F; T7W = T4F - T4E; } { E T4I, T4J, T4n, T4w; T4I = T3K + T3V; T4J = T41 + T44; T4K = FMA(KP555570233, T4I, KP831469612 * T4J); T4Q = FNMS(KP555570233, T4J, KP831469612 * T4I); T4n = T4b - T4m; T4w = T4s - T4v; T4x = FNMS(KP980785280, T4w, KP195090322 * T4n); T4B = FMA(KP195090322, T4w, KP980785280 * T4n); } { E T3F, T4y, T7V, T7Y; T3F = T3h + T3E; T4y = T46 + T4x; ri[WS(rs, 23)] = T3F - T4y; ri[WS(rs, 7)] = T3F + T4y; T7V = T4A + T4B; T7Y = T7W + T7X; ii[WS(rs, 7)] = T7V + T7Y; ii[WS(rs, 23)] = T7Y - T7V; } { E T4z, T4C, T7Z, T80; T4z = T3h - T3E; T4C = T4A - T4B; ri[WS(rs, 31)] = T4z - T4C; ri[WS(rs, 15)] = T4z + T4C; T7Z = T4x - T46; T80 = T7X - T7W; ii[WS(rs, 15)] = T7Z + T80; ii[WS(rs, 31)] = T80 - T7Z; } { E T4H, T4O, T7N, T7S; T4H = T4D + T4G; T4O = T4K + T4N; ri[WS(rs, 19)] = T4H - T4O; ri[WS(rs, 3)] = T4H + T4O; T7N = T4Q + T4R; T7S = T7O + T7R; ii[WS(rs, 3)] = T7N + T7S; ii[WS(rs, 19)] = T7S - T7N; } { E T4P, T4S, T7T, T7U; T4P = T4D - T4G; T4S = T4Q - T4R; ri[WS(rs, 27)] = T4P - T4S; ri[WS(rs, 11)] = T4P + T4S; T7T = T4N - T4K; T7U = T7R - T7O; ii[WS(rs, 11)] = T7T + T7U; ii[WS(rs, 27)] = T7U - T7T; } } { E T4X, T5p, T7D, T7J, T54, T7y, T5z, T5D, T5c, T5m, T5s, T7I, T5w, T5C, T5j; E T5n, T4W, T7z; T4W = KP707106781 * (T4U + T4V); T4X = T4T - T4W; T5p = T4T + T4W; T7z = KP707106781 * (T3a + T3f); T7D = T7z + T7C; T7J = T7C - T7z; { E T50, T53, T5x, T5y; T50 = FNMS(KP382683432, T4Z, KP923879532 * T4Y); T53 = FMA(KP923879532, T51, KP382683432 * T52); T54 = T50 - T53; T7y = T50 + T53; T5x = T5d + T5e; T5y = T5g + T5h; T5z = FNMS(KP195090322, T5y, KP980785280 * T5x); T5D = FMA(KP195090322, T5x, KP980785280 * T5y); } { E T58, T5b, T5q, T5r; T58 = T56 - T57; T5b = T59 - T5a; T5c = FMA(KP555570233, T58, KP831469612 * T5b); T5m = FNMS(KP831469612, T58, KP555570233 * T5b); T5q = FMA(KP382683432, T4Y, KP923879532 * T4Z); T5r = FNMS(KP382683432, T51, KP923879532 * T52); T5s = T5q + T5r; T7I = T5r - T5q; } { E T5u, T5v, T5f, T5i; T5u = T56 + T57; T5v = T59 + T5a; T5w = FMA(KP980785280, T5u, KP195090322 * T5v); T5C = FNMS(KP195090322, T5u, KP980785280 * T5v); T5f = T5d - T5e; T5i = T5g - T5h; T5j = FNMS(KP831469612, T5i, KP555570233 * T5f); T5n = FMA(KP831469612, T5f, KP555570233 * T5i); } { E T55, T5k, T7H, T7K; T55 = T4X + T54; T5k = T5c + T5j; ri[WS(rs, 21)] = T55 - T5k; ri[WS(rs, 5)] = T55 + T5k; T7H = T5m + T5n; T7K = T7I + T7J; ii[WS(rs, 5)] = T7H + T7K; ii[WS(rs, 21)] = T7K - T7H; } { E T5l, T5o, T7L, T7M; T5l = T4X - T54; T5o = T5m - T5n; ri[WS(rs, 29)] = T5l - T5o; ri[WS(rs, 13)] = T5l + T5o; T7L = T5j - T5c; T7M = T7J - T7I; ii[WS(rs, 13)] = T7L + T7M; ii[WS(rs, 29)] = T7M - T7L; } { E T5t, T5A, T7x, T7E; T5t = T5p + T5s; T5A = T5w + T5z; ri[WS(rs, 17)] = T5t - T5A; ri[WS(rs, 1)] = T5t + T5A; T7x = T5C + T5D; T7E = T7y + T7D; ii[WS(rs, 1)] = T7x + T7E; ii[WS(rs, 17)] = T7E - T7x; } { E T5B, T5E, T7F, T7G; T5B = T5p - T5s; T5E = T5C - T5D; ri[WS(rs, 25)] = T5B - T5E; ri[WS(rs, 9)] = T5B + T5E; T7F = T5z - T5w; T7G = T7D - T7y; ii[WS(rs, 9)] = T7F + T7G; ii[WS(rs, 25)] = T7G - T7F; } } } } static const tw_instr twinstr[] = { {TW_FULL, 0, 32}, {TW_NEXT, 1, 0} }; static const ct_desc desc = { 32, "t1_32", twinstr, &GENUS, {340, 114, 94, 0}, 0, 0, 0 }; void X(codelet_t1_32) (planner *p) { X(kdft_dit_register) (p, t1_32, &desc); } #endif /* HAVE_FMA */
mit
SoCdesign/audiomixer
ZedBoard_Linux_Design/hw/xps_proj/SDK/SDK_Export/FSBL_bsp/ps7_cortexa9_0/libsrc/scugic_v1_05_a/src/xscugic_intr.c
14
7224
/****************************************************************************** * * (c) Copyright 2010-2013 Xilinx, Inc. All rights reserved. * * This file contains confidential and proprietary information of Xilinx, Inc. * and is protected under U.S. and international copyright and other * intellectual property laws. * * DISCLAIMER * This disclaimer is not a license and does not grant any rights to the * materials distributed herewith. Except as otherwise provided in a valid * license issued to you by Xilinx, and to the maximum extent permitted by * applicable law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL * FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS, * IMPLIED, OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF * MERCHANTABILITY, NON-INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; * and (2) Xilinx shall not be liable (whether in contract or tort, including * negligence, or under any other theory of liability) for any loss or damage * of any kind or nature related to, arising under or in connection with these * materials, including for any direct, or any indirect, special, incidental, * or consequential loss or damage (including loss of data, profits, goodwill, * or any type of loss or damage suffered as a result of any action brought by * a third party) even if such damage or loss was reasonably foreseeable or * Xilinx had been advised of the possibility of the same. * * CRITICAL APPLICATIONS * Xilinx products are not designed or intended to be fail-safe, or for use in * any application requiring fail-safe performance, such as life-support or * safety devices or systems, Class III medical devices, nuclear facilities, * applications related to the deployment of airbags, or any other applications * that could lead to death, personal injury, or severe property or * environmental damage (individually and collectively, "Critical * Applications"). Customer assumes the sole risk and liability of any use of * Xilinx products in Critical Applications, subject only to applicable laws * and regulations governing limitations on product liability. * * THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE * AT ALL TIMES. * ******************************************************************************/ /*****************************************************************************/ /** * * @file xscugic_intr.c * * This file contains the interrupt processing for the driver for the Xilinx * Interrupt Controller. The interrupt processing is partitioned separately such * that users are not required to use the provided interrupt processing. This * file requires other files of the driver to be linked in also. * * The interrupt handler, XScuGic_InterruptHandler, uses an input argument which * is an instance pointer to an interrupt controller driver such that multiple * interrupt controllers can be supported. This handler requires the calling * function to pass it the appropriate argument, so another level of indirection * may be required. * * The interrupt processing may be used by connecting the interrupt handler to * the interrupt system. The handler does not save and restore the processor * context but only handles the processing of the Interrupt Controller. The user * is encouraged to supply their own interrupt handler when performance tuning is * deemed necessary. * * <pre> * MODIFICATION HISTORY: * * Ver Who Date Changes * ----- ---- -------- --------------------------------------------------------- * 1.00a drg 01/19/10 First release * 1.01a sdm 11/09/11 XScuGic_InterruptHandler has changed correspondingly * since the HandlerTable has now moved to XScuGic_Config. * * </pre> * * @internal * * This driver assumes that the context of the processor has been saved prior to * the calling of the Interrupt Controller interrupt handler and then restored * after the handler returns. This requires either the running RTOS to save the * state of the machine or that a wrapper be used as the destination of the * interrupt vector to save the state of the processor and restore the state * after the interrupt handler returns. * ******************************************************************************/ /***************************** Include Files *********************************/ #include "xil_types.h" #include "xil_assert.h" #include "xscugic.h" /************************** Constant Definitions *****************************/ /**************************** Type Definitions *******************************/ /***************** Macros (Inline Functions) Definitions *********************/ /************************** Function Prototypes ******************************/ /************************** Variable Definitions *****************************/ /*****************************************************************************/ /** * This function is the primary interrupt handler for the driver. It must be * connected to the interrupt source such that it is called when an interrupt of * the interrupt controller is active. It will resolve which interrupts are * active and enabled and call the appropriate interrupt handler. It uses * the Interrupt Type information to determine when to acknowledge the interrupt. * Highest priority interrupts are serviced first. * * This function assumes that an interrupt vector table has been previously * initialized. It does not verify that entries in the table are valid before * calling an interrupt handler. * * * @param InstancePtr is a pointer to the XScuGic instance. * * @return None. * * @note None. * ******************************************************************************/ void XScuGic_InterruptHandler(XScuGic *InstancePtr) { u32 IntID; XScuGic_VectorTableEntry *TablePtr; /* Assert that the pointer to the instance is valid */ Xil_AssertVoid(InstancePtr != NULL); /* * Read the int_ack register to identify the highest priority interrupt ID * and make sure it is valid. Reading Int_Ack will clear the interrupt * in the GIC. */ IntID = XScuGic_CPUReadReg(InstancePtr, XSCUGIC_INT_ACK_OFFSET) & XSCUGIC_ACK_INTID_MASK; if(XSCUGIC_MAX_NUM_INTR_INPUTS < IntID){ goto IntrExit; } /* * If the interrupt is shared, do some locking here if there are multiple * processors. */ /* * If pre-eption is required: * Re-enable pre-emption by setting the CPSR I bit for non-secure , * interrupts or the F bit for secure interrupts */ /* * If we need to change security domains, issue a SMC instruction here. */ /* * Execute the ISR. Jump into the Interrupt service routine based on the * IRQSource. A software trigger is cleared by the ACK. */ TablePtr = &(InstancePtr->Config->HandlerTable[IntID]); TablePtr->Handler(TablePtr->CallBackRef); IntrExit: /* * Write to the EOI register, we are all done here. * Let this function return, the boot code will restore the stack. */ XScuGic_CPUWriteReg(InstancePtr, XSCUGIC_EOI_OFFSET, IntID); /* * Return from the interrupt. Change security domains could happen here. */ }
mit
shadowmint/kivy-ios
src/SDL/src/video/SDL_clipboard.c
17
2152
/* Simple DirectMedia Layer Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "SDL_config.h" #include "SDL_clipboard.h" #include "SDL_sysvideo.h" int SDL_SetClipboardText(const char *text) { SDL_VideoDevice *_this = SDL_GetVideoDevice(); if (!text) { text = ""; } if (_this->SetClipboardText) { return _this->SetClipboardText(_this, text); } else { if (_this->clipboard_text) { SDL_free(_this->clipboard_text); } _this->clipboard_text = SDL_strdup(text); return 0; } } char * SDL_GetClipboardText(void) { SDL_VideoDevice *_this = SDL_GetVideoDevice(); if (_this->GetClipboardText) { return _this->GetClipboardText(_this); } else { const char *text = _this->clipboard_text; if (!text) { text = ""; } return SDL_strdup(text); } } SDL_bool SDL_HasClipboardText(void) { SDL_VideoDevice *_this = SDL_GetVideoDevice(); if (_this->HasClipboardText) { return _this->HasClipboardText(_this); } else { if ((_this->clipboard_text) && (SDL_strlen(_this->clipboard_text)>0)) { return SDL_TRUE; } else { return SDL_FALSE; } } } /* vi: set ts=4 sw=4 expandtab: */
mit
vinnyrom/coreclr
src/pal/src/cruntime/malloc.cpp
24
1880
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*++ Module Name: malloc.cpp Abstract: Implementation of suspension safe memory allocation functions. Revision History: --*/ #include "pal/corunix.hpp" #include "pal/thread.hpp" #include "pal/malloc.hpp" #include "pal/dbgmsg.h" #include <string.h> SET_DEFAULT_DEBUG_CHANNEL(CRT); using namespace CorUnix; void * __cdecl PAL_realloc( void* pvMemblock, size_t szSize ) { return InternalRealloc(pvMemblock, szSize); } void * CorUnix::InternalRealloc( void* pvMemblock, size_t szSize ) { void *pvMem; PERF_ENTRY(InternalRealloc); ENTRY("realloc (memblock:%p size=%d)\n", pvMemblock, szSize); if (szSize == 0) { // If pvMemblock is NULL, there's no reason to call free. if (pvMemblock != NULL) { InternalFree(pvMemblock); } pvMem = NULL; } else { pvMem = realloc(pvMemblock, szSize); } LOGEXIT("realloc returns void * %p\n", pvMem); PERF_EXIT(InternalRealloc); return pvMem; } void __cdecl PAL_free( void *pvMem ) { InternalFree(pvMem); } void CorUnix::InternalFree( void *pvMem ) { free(pvMem); } void * __cdecl PAL_malloc( size_t szSize ) { return InternalMalloc(szSize); } void * CorUnix::InternalMalloc( size_t szSize ) { void *pvMem; if (szSize == 0) { // malloc may return null for a requested size of zero bytes. Force a nonzero size to get a valid pointer. szSize = 1; } pvMem = (void*)malloc(szSize); return pvMem; } char * __cdecl PAL__strdup( const char *c_szStr ) { return strdup(c_szStr); }
mit