text
stringlengths
1
1.05M
// Copyright (c) Chris Hafey. // SPDX-License-Identifier: MIT #include <fstream> #include <iostream> #include <vector> #include <iterator> #include <time.h> #include <algorithm> #include "../../src/J2KDecoder.hpp" #include "../../src/J2KEncoder.hpp" void readFile(std::string fileName, std::vector<uint8_t>& vec) { // open the file: std::ifstream file(fileName, std::ios::in | std::ios::binary); // Stop eating new lines in binary mode!!! file.unsetf(std::ios::skipws); // get its size: std::streampos fileSize; file.seekg(0, std::ios::end); fileSize = file.tellg(); file.seekg(0, std::ios::beg); // reserve capacity vec.reserve(fileSize); // read the data: vec.insert(vec.begin(), std::istream_iterator<uint8_t>(file), std::istream_iterator<uint8_t>()); //std::istreambuf_iterator iter(file); //std::copy(iter.begin(), iter.end(), std::back_inserter(vec)); } void writeFile(std::string fileName, const std::vector<uint8_t>& vec) { std::ofstream file(fileName, std::ios::out | std::ofstream::binary); std::copy(vec.begin(), vec.end(), std::ostreambuf_iterator<char>(file)); } enum { NS_PER_SECOND = 1000000000 }; void sub_timespec(struct timespec t1, struct timespec t2, struct timespec *td) { td->tv_nsec = t2.tv_nsec - t1.tv_nsec; td->tv_sec = t2.tv_sec - t1.tv_sec; if (td->tv_sec > 0 && td->tv_nsec < 0) { td->tv_nsec += NS_PER_SECOND; td->tv_sec--; } else if (td->tv_sec < 0 && td->tv_nsec > 0) { td->tv_nsec -= NS_PER_SECOND; td->tv_sec++; } } void decodeFile(const char* path) { J2KDecoder decoder; std::vector<uint8_t>& encodedBytes = decoder.getEncodedBytes(); readFile(path, encodedBytes); // cut buffer in half to test partial decoding const size_t numBytes = 25050; //const size_t numBytes = 0; encodedBytes.resize(encodedBytes.size() - numBytes); timespec start, finish, delta; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); decoder.readHeader(); //Size resolutionAtLevel = decoder.calculateDecompositionLevel(1); //std::cout << resolutionAtLevel.width << ',' << resolutionAtLevel.height << std::endl; decoder.decodeSubResolution(0, 0);//1, 1); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &finish); sub_timespec(start, finish, &delta); const double ms = (double)(delta.tv_nsec) / 1000000.0; printf("Decode of %s took %f ms\n", path, ms); } void encodeFile(const char* inPath, const FrameInfo frameInfo, const char* outPath) { J2KEncoder encoder; std::vector<uint8_t>& rawBytes = encoder.getDecodedBytes(frameInfo); readFile(inPath, rawBytes); timespec start, finish, delta; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); encoder.encode(); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &finish); sub_timespec(start, finish, &delta); const double ms = (double)(delta.tv_nsec) / 1000000.0; printf("Encode of %s took %f ms\n", inPath, ms); if(outPath) { const std::vector<uint8_t>& encodedBytes = encoder.getEncodedBytes(); writeFile(outPath, encodedBytes); } } int main(int argc, char** argv) { decodeFile("test/fixtures/j2k/CT1-0decomp.j2k"); //decodeFile("test/fixtures/j2c/CT2.j2c"); //decodeFile("test/fixtures/j2c/MG1.j2c"); //decodeFile("test/fixtures/j2k/NM1.j2k"); //encodeFile("test/fixtures/raw/CT1.RAW", {.width = 512, .height = 512, .bitsPerSample = 16, .componentCount = 1, .isSigned = true}, "test/fixtures/j2c/CT1.j2c"); return 0; }
/* * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. 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 "core/layout/line/InlineBox.h" #include "core/layout/HitTestLocation.h" #include "core/layout/LayoutBlockFlow.h" #include "core/layout/api/LineLayoutBlockFlow.h" #include "core/layout/line/InlineFlowBox.h" #include "core/layout/line/RootInlineBox.h" #include "core/paint/BlockPainter.h" #include "core/paint/PaintInfo.h" #include "platform/fonts/FontMetrics.h" #include "platform/wtf/allocator/Partitions.h" #ifndef NDEBUG #include <stdio.h> #endif namespace blink { class LayoutObject; struct SameSizeAsInlineBox : DisplayItemClient { virtual ~SameSizeAsInlineBox() {} void* a[4]; LayoutPoint b; LayoutUnit c; uint32_t bitfields; #if DCHECK_IS_ON() bool f; #endif }; static_assert(sizeof(InlineBox) == sizeof(SameSizeAsInlineBox), "InlineBox should stay small"); #if DCHECK_IS_ON() InlineBox::~InlineBox() { if (!has_bad_parent_ && parent_) parent_->SetHasBadChildList(); } #endif DISABLE_CFI_PERF void InlineBox::Destroy() { // We do not need to issue invalidations if the page is being destroyed // since these objects will never be repainted. if (!line_layout_item_.DocumentBeingDestroyed()) { SetLineLayoutItemShouldDoFullPaintInvalidationIfNeeded(); // TODO(crbug.com/619630): Make this fast. line_layout_item_.SlowSetPaintingLayerNeedsRepaint(); } delete this; } void InlineBox::Remove(MarkLineBoxes mark_line_boxes) { if (Parent()) Parent()->RemoveChild(this, mark_line_boxes); } void* InlineBox::operator new(size_t sz) { return PartitionAlloc(WTF::Partitions::LayoutPartition(), sz, WTF_HEAP_PROFILER_TYPE_NAME(InlineBox)); } void InlineBox::operator delete(void* ptr) { WTF::PartitionFree(ptr); } const char* InlineBox::BoxName() const { return "InlineBox"; } String InlineBox::DebugName() const { return BoxName(); } LayoutRect InlineBox::VisualRect() const { // TODO(chrishtr): tighten these bounds. return GetLineLayoutItem().VisualRect(); } #ifndef NDEBUG void InlineBox::ShowTreeForThis() const { GetLineLayoutItem().ShowTreeForThis(); } void InlineBox::ShowLineTreeForThis() const { GetLineLayoutItem().ContainingBlock().ShowLineTreeAndMark(this, "*"); } void InlineBox::ShowLineTreeAndMark(const InlineBox* marked_box1, const char* marked_label1, const InlineBox* marked_box2, const char* marked_label2, const LayoutObject* obj, int depth) const { int printed_characters = 0; if (this == marked_box1) printed_characters += fprintf(stderr, "%s", marked_label1); if (this == marked_box2) printed_characters += fprintf(stderr, "%s", marked_label2); if (GetLineLayoutItem().IsEqual(obj)) printed_characters += fprintf(stderr, "*"); for (; printed_characters < depth * 2; printed_characters++) fputc(' ', stderr); ShowBox(printed_characters); } void InlineBox::ShowBox(int printed_characters) const { printed_characters += fprintf(stderr, "%s %p", BoxName(), this); for (; printed_characters < kShowTreeCharacterOffset; printed_characters++) fputc(' ', stderr); fprintf(stderr, "\t%s %p {pos=%g,%g size=%g,%g} baseline=%i/%i\n", GetLineLayoutItem().DecoratedName().Ascii().data(), GetLineLayoutItem().DebugPointer(), X().ToFloat(), Y().ToFloat(), Width().ToFloat(), Height().ToFloat(), BaselinePosition(kAlphabeticBaseline), BaselinePosition(kIdeographicBaseline)); } #endif LayoutUnit InlineBox::LogicalHeight() const { if (HasVirtualLogicalHeight()) return VirtualLogicalHeight(); const SimpleFontData* font_data = GetLineLayoutItem().Style(IsFirstLineStyle())->GetFont().PrimaryFont(); if (GetLineLayoutItem().IsText()) { DCHECK(font_data); return bitfields_.IsText() && font_data ? LayoutUnit(font_data->GetFontMetrics().Height()) : LayoutUnit(); } if (GetLineLayoutItem().IsBox() && Parent()) { return IsHorizontal() ? LineLayoutBox(GetLineLayoutItem()).Size().Height() : LineLayoutBox(GetLineLayoutItem()).Size().Width(); } DCHECK(IsInlineFlowBox()); LineLayoutBoxModel flow_object = BoxModelObject(); DCHECK(font_data); LayoutUnit result(font_data ? font_data->GetFontMetrics().Height() : 0); if (Parent()) result += flow_object.BorderAndPaddingLogicalHeight(); return result; } int InlineBox::BaselinePosition(FontBaseline baseline_type) const { return BoxModelObject().BaselinePosition( baseline_type, bitfields_.FirstLine(), IsHorizontal() ? kHorizontalLine : kVerticalLine, kPositionOnContainingLine); } LayoutUnit InlineBox::LineHeight() const { return BoxModelObject().LineHeight( bitfields_.FirstLine(), IsHorizontal() ? kHorizontalLine : kVerticalLine, kPositionOnContainingLine); } int InlineBox::CaretMinOffset() const { return GetLineLayoutItem().CaretMinOffset(); } int InlineBox::CaretMaxOffset() const { return GetLineLayoutItem().CaretMaxOffset(); } void InlineBox::DirtyLineBoxes() { MarkDirty(); for (InlineFlowBox* curr = Parent(); curr && !curr->IsDirty(); curr = curr->Parent()) curr->MarkDirty(); } void InlineBox::DeleteLine() { if (!bitfields_.Extracted() && GetLineLayoutItem().IsBox()) LineLayoutBox(GetLineLayoutItem()).SetInlineBoxWrapper(nullptr); Destroy(); } void InlineBox::ExtractLine() { bitfields_.SetExtracted(true); if (GetLineLayoutItem().IsBox()) LineLayoutBox(GetLineLayoutItem()).SetInlineBoxWrapper(nullptr); } void InlineBox::AttachLine() { bitfields_.SetExtracted(false); if (GetLineLayoutItem().IsBox()) LineLayoutBox(GetLineLayoutItem()).SetInlineBoxWrapper(this); } void InlineBox::Move(const LayoutSize& delta) { location_.Move(delta); if (GetLineLayoutItem().IsAtomicInlineLevel()) LineLayoutBox(GetLineLayoutItem()).Move(delta.Width(), delta.Height()); SetLineLayoutItemShouldDoFullPaintInvalidationIfNeeded(); } void InlineBox::Paint(const PaintInfo& paint_info, const LayoutPoint& paint_offset, LayoutUnit /* lineTop */, LayoutUnit /* lineBottom */) const { BlockPainter::PaintInlineBox(*this, paint_info, paint_offset); } bool InlineBox::NodeAtPoint(HitTestResult& result, const HitTestLocation& location_in_container, const LayoutPoint& accumulated_offset, LayoutUnit /* lineTop */, LayoutUnit /* lineBottom */) { // Hit test all phases of replaced elements atomically, as though the replaced // element established its own stacking context. (See Appendix E.2, section // 6.4 on inline block/table elements in the CSS2.1 specification.) LayoutPoint child_point = accumulated_offset; // Faster than calling containingBlock(). if (Parent()->GetLineLayoutItem().HasFlippedBlocksWritingMode()) child_point = GetLineLayoutItem().ContainingBlock().FlipForWritingModeForChild( LineLayoutBox(GetLineLayoutItem()), child_point); return GetLineLayoutItem().HitTest(result, location_in_container, child_point); } const RootInlineBox& InlineBox::Root() const { if (parent_) return parent_->Root(); DCHECK(IsRootInlineBox()); return static_cast<const RootInlineBox&>(*this); } RootInlineBox& InlineBox::Root() { if (parent_) return parent_->Root(); DCHECK(IsRootInlineBox()); return static_cast<RootInlineBox&>(*this); } InlineBox* InlineBox::NextLeafChild() const { InlineBox* leaf = nullptr; for (InlineBox* box = NextOnLine(); box && !leaf; box = box->NextOnLine()) leaf = box->IsLeaf() ? box : ToInlineFlowBox(box)->FirstLeafChild(); if (!leaf && Parent()) leaf = Parent()->NextLeafChild(); return leaf; } InlineBox* InlineBox::PrevLeafChild() const { InlineBox* leaf = nullptr; for (InlineBox* box = PrevOnLine(); box && !leaf; box = box->PrevOnLine()) leaf = box->IsLeaf() ? box : ToInlineFlowBox(box)->LastLeafChild(); if (!leaf && Parent()) leaf = Parent()->PrevLeafChild(); return leaf; } InlineBox* InlineBox::NextLeafChildIgnoringLineBreak() const { InlineBox* leaf = NextLeafChild(); return (leaf && leaf->IsLineBreak()) ? nullptr : leaf; } InlineBox* InlineBox::PrevLeafChildIgnoringLineBreak() const { InlineBox* leaf = PrevLeafChild(); return (leaf && leaf->IsLineBreak()) ? nullptr : leaf; } SelectionState InlineBox::GetSelectionState() const { return GetLineLayoutItem().GetSelectionState(); } bool InlineBox::CanAccommodateEllipsis(bool ltr, LayoutUnit block_edge, LayoutUnit ellipsis_width) const { // Non-atomic inline-level elements can always accommodate an ellipsis. // Skip list markers and try the next box. if (!GetLineLayoutItem().IsAtomicInlineLevel() || GetLineLayoutItem().IsListMarker()) return true; LayoutRect box_rect(X(), LayoutUnit(), logical_width_, LayoutUnit(10)); LayoutRect ellipsis_rect(ltr ? block_edge - ellipsis_width : block_edge, LayoutUnit(), ellipsis_width, LayoutUnit(10)); return !(box_rect.Intersects(ellipsis_rect)); } LayoutUnit InlineBox::PlaceEllipsisBox(bool, LayoutUnit, LayoutUnit, LayoutUnit, LayoutUnit& truncated_width, InlineBox**, LayoutUnit) { // Use -1 to mean "we didn't set the position." truncated_width += LogicalWidth(); return LayoutUnit(-1); } void InlineBox::ClearKnownToHaveNoOverflow() { bitfields_.SetKnownToHaveNoOverflow(false); if (Parent() && Parent()->KnownToHaveNoOverflow()) Parent()->ClearKnownToHaveNoOverflow(); } LayoutPoint InlineBox::PhysicalLocation() const { LayoutRect rect(Location(), Size()); FlipForWritingMode(rect); return rect.Location(); } void InlineBox::LogicalRectToPhysicalRect(LayoutRect& rect) const { if (!IsHorizontal()) rect = rect.TransposedRect(); FlipForWritingMode(rect); } void InlineBox::FlipForWritingMode(FloatRect& rect) const { if (!UNLIKELY(GetLineLayoutItem().HasFlippedBlocksWritingMode())) return; Root().Block().FlipForWritingMode(rect); } FloatPoint InlineBox::FlipForWritingMode(const FloatPoint& point) const { if (!UNLIKELY(GetLineLayoutItem().HasFlippedBlocksWritingMode())) return point; return Root().Block().FlipForWritingMode(point); } void InlineBox::FlipForWritingMode(LayoutRect& rect) const { if (!UNLIKELY(GetLineLayoutItem().HasFlippedBlocksWritingMode())) return; Root().Block().FlipForWritingMode(rect); } LayoutPoint InlineBox::FlipForWritingMode(const LayoutPoint& point) const { if (!UNLIKELY(GetLineLayoutItem().HasFlippedBlocksWritingMode())) return point; return Root().Block().FlipForWritingMode(point); } void InlineBox::SetShouldDoFullPaintInvalidationRecursively() { GetLineLayoutItem().SetShouldDoFullPaintInvalidation(); if (!IsInlineFlowBox()) return; for (InlineBox* child = ToInlineFlowBox(this)->FirstChild(); child; child = child->NextOnLine()) child->SetShouldDoFullPaintInvalidationRecursively(); } void InlineBox::SetLineLayoutItemShouldDoFullPaintInvalidationIfNeeded() { // For RootInlineBox, we only need to invalidate if it's using the first line // style. Otherwise it paints nothing so we don't need to invalidate it. if (!IsRootInlineBox() || IsFirstLineStyle()) line_layout_item_.SetShouldDoFullPaintInvalidation(); } } // namespace blink #ifndef NDEBUG void showTree(const blink::InlineBox* b) { if (b) b->ShowTreeForThis(); else fprintf(stderr, "Cannot showTree for (nil) InlineBox.\n"); } void showLineTree(const blink::InlineBox* b) { if (b) b->ShowLineTreeForThis(); else fprintf(stderr, "Cannot showLineTree for (nil) InlineBox.\n"); } #endif
; void _lldiv_(lldiv_t *ld, int64_t numer, int64_t denom) SECTION code_clib SECTION code_stdlib PUBLIC __lldiv__callee EXTERN asm__lldiv __lldiv__callee: push ix ld ix,6 add ix,sp call asm__lldiv pop ix pop de ld hl,18 add hl,sp ld sp,hl ex de,hl jp (hl)
; A099483: A Fibonacci convolution. ; 0,1,3,7,18,48,126,329,861,2255,5904,15456,40464,105937,277347,726103,1900962,4976784,13029390,34111385,89304765,233802911,612103968,1602508992,4195423008,10983760033,28755857091,75283811239,197095576626 add $0,1 mul $0,2 seq $0,293544 ; a(n) is the integer k that minimizes | k/Fibonacci(n) - 1/3 |.
; ; Sharp OZ family functions ; ; ported from the OZ-7xx SDK by by Alexander R. Pruss ; by Stefano Bodrato - Oct. 2003 ; ; ; clock functions ; ; unsigned ozsec() ; ; ; ------ ; $Id: ozsec.asm,v 1.2 2015/01/19 01:33:04 pauloscustodio Exp $ ; PUBLIC ozsec EXTERN Compute ozsec: ld c,31h jp Compute
SCR equ $4000 ; Sets a constant org $8000 ; Where our program will being in the computer's memory MAIN ld bc,STRING ld de,SCR LOOP ; Marker ld a,(bc) cp 0 ; zero not 'o' jr z,EXIT rst $10 inc bc inc de jr LOOP EXIT ret STRING defb "Demo 2019!" defb 13,0 ; zero not 'o' end
;=============================================================================== ; Constants Black = 0 White = 1 Red = 2 Cyan = 3 Purple = 4 Green = 5 Blue = 6 Yellow = 7 Orange = 8 Brown = 9 LightRed = 10 DarkGray = 11 MediumGray = 12 LightGreen = 13 LightBlue = 14 LightGray = 15 SpaceCharacter = 32 False = 0 True = 1 ;=============================================================================== ; Variables Operator Calc ScreenRAMRowStartLow ; SCREENRAM + 40*0, 40*1, 40*2 ... 40*24 byte <SCREENRAM, <SCREENRAM+40, <SCREENRAM+80 byte <SCREENRAM+120, <SCREENRAM+160, <SCREENRAM+200 byte <SCREENRAM+240, <SCREENRAM+280, <SCREENRAM+320 byte <SCREENRAM+360, <SCREENRAM+400, <SCREENRAM+440 byte <SCREENRAM+480, <SCREENRAM+520, <SCREENRAM+560 byte <SCREENRAM+600, <SCREENRAM+640, <SCREENRAM+680 byte <SCREENRAM+720, <SCREENRAM+760, <SCREENRAM+800 byte <SCREENRAM+840, <SCREENRAM+880, <SCREENRAM+920 byte <SCREENRAM+960 ScreenRAMRowStartHigh ; SCREENRAM + 40*0, 40*1, 40*2 ... 40*24 byte >SCREENRAM, >SCREENRAM+40, >SCREENRAM+80 byte >SCREENRAM+120, >SCREENRAM+160, >SCREENRAM+200 byte >SCREENRAM+240, >SCREENRAM+280, >SCREENRAM+320 byte >SCREENRAM+360, >SCREENRAM+400, >SCREENRAM+440 byte >SCREENRAM+480, >SCREENRAM+520, >SCREENRAM+560 byte >SCREENRAM+600, >SCREENRAM+640, >SCREENRAM+680 byte >SCREENRAM+720, >SCREENRAM+760, >SCREENRAM+800 byte >SCREENRAM+840, >SCREENRAM+880, >SCREENRAM+920 byte >SCREENRAM+960 ColorRAMRowStartLow ; COLORRAM + 40*0, 40*1, 40*2 ... 40*24 byte <COLORRAM, <COLORRAM+40, <COLORRAM+80 byte <COLORRAM+120, <COLORRAM+160, <COLORRAM+200 byte <COLORRAM+240, <COLORRAM+280, <COLORRAM+320 byte <COLORRAM+360, <COLORRAM+400, <COLORRAM+440 byte <COLORRAM+480, <COLORRAM+520, <COLORRAM+560 byte <COLORRAM+600, <COLORRAM+640, <COLORRAM+680 byte <COLORRAM+720, <COLORRAM+760, <COLORRAM+800 byte <COLORRAM+840, <COLORRAM+880, <COLORRAM+920 byte <COLORRAM+960 ColorRAMRowStartHigh ; COLORRAM + 40*0, 40*1, 40*2 ... 40*24 byte >COLORRAM, >COLORRAM+40, >COLORRAM+80 byte >COLORRAM+120, >COLORRAM+160, >COLORRAM+200 byte >COLORRAM+240, >COLORRAM+280, >COLORRAM+320 byte >COLORRAM+360, >COLORRAM+400, >COLORRAM+440 byte >COLORRAM+480, >COLORRAM+520, >COLORRAM+560 byte >COLORRAM+600, >COLORRAM+640, >COLORRAM+680 byte >COLORRAM+720, >COLORRAM+760, >COLORRAM+800 byte >COLORRAM+840, >COLORRAM+880, >COLORRAM+920 byte >COLORRAM+960 Operator HiLo screenColumn byte 0 screenScrollXValue byte 0 ;=============================================================================== ; Macros/Subroutines defm LIBSCREEN_COPYMAPROW_VVA ; /1 = Map Row (Value) ; /2 = Screen Row (Value) ; /3 = Start Offset (Address) lda #/1 sta ZeroPageParam1 lda #/2 sta ZeroPageParam2 lda /3 sta ZeroPageParam3 jsr libScreen_CopyMapRow endm libScreen_CopyMapRow ldy ZeroPageParam1 ; load y position as index into list lda MapRAMRowStartLow,Y ; load low address byte sta ZeroPageLow2 lda MapRAMRowStartHigh,Y ; load high address byte sta ZeroPageHigh2 ; add on the offset to the map address LIBMATH_ADD16BIT_AAVAAA ZeroPageHigh2, ZeroPageLow2, 0, ZeroPageParam3, ZeroPageHigh2, ZeroPageLow2 ldy ZeroPageParam2 ; load y position as index into list lda ScreenRAMRowStartLow,Y ; load low address byte sta ZeroPageLow lda ScreenRAMRowStartHigh,Y ; load high address byte sta ZeroPageHigh ldy #0 lSCMRLoop lda (ZeroPageLow2),y sta (ZeroPageLow),y iny cpy #39 bne lSCMRLoop rts ;============================================================================== defm LIBSCREEN_COPYMAPROWCOLOR_VVA ; /1 = Map Row (Value) ; /2 = Screen Row (Value) ; /3 = Start Offset (Address) lda #/1 sta ZeroPageParam1 lda #/2 sta ZeroPageParam2 lda /3 sta ZeroPageParam3 jsr libScreen_CopyMapRowColor endm libScreen_CopyMapRowColor ldy ZeroPageParam1 ; load y position as index into list lda MapRAMCOLRowStartLow,Y ; load low address byte sta ZeroPageLow2 lda MapRAMCOLRowStartHigh,Y ; load high address byte sta ZeroPageHigh2 ; add on the offset to the map address LIBMATH_ADD16BIT_AAVAAA ZeroPageHigh2, ZeroPageLow2, 0, ZeroPageParam3, ZeroPageHigh2, ZeroPageLow2 ldy ZeroPageParam2 ; load y position as index into list lda ColorRAMRowStartLow,Y ; load low address byte sta ZeroPageLow lda ColorRAMRowStartHigh,Y ; load high address byte sta ZeroPageHigh ldy #0 lSCMRCLoop lda (ZeroPageLow2),y ora #%00001000 ; set multicolor bit sta (ZeroPageLow),y iny cpy #39 bne lSCMRCLoop rts ;=============================================================================== defm LIBSCREEN_DEBUG8BIT_VVA ; /1 = X Position Absolute ; /2 = Y Position Absolute ; /3 = 1st Number Low Byte Pointer lda #White sta $0286 ; set text color lda #$20 ; space jsr $ffd2 ; print 4 spaces jsr $ffd2 jsr $ffd2 jsr $ffd2 ;jsr $E566 ; reset cursor ldx #/2 ; Select row ldy #/1 ; Select column jsr $E50C ; Set cursor lda #0 ldx /3 jsr $BDCD ; print number endm ;=============================================================================== defm LIBSCREEN_DEBUG16BIT_VVAA ; /1 = X Position Absolute ; /2 = Y Position Absolute ; /3 = 1st Number High Byte Pointer ; /4 = 1st Number Low Byte Pointer lda #White sta $0286 ; set text color lda #$20 ; space jsr $ffd2 ; print 4 spaces jsr $ffd2 jsr $ffd2 jsr $ffd2 ;jsr $E566 ; reset cursor ldx #/2 ; Select row ldy #/1 ; Select column jsr $E50C ; Set cursor lda /3 ldx /4 jsr $BDCD ; print number endm ;============================================================================== defm LIBSCREEN_DRAWTEXT_AAAV ; /1 = X Position 0-39 (Address) ; /2 = Y Position 0-24 (Address) ; /3 = 0 terminated string (Address) ; /4 = Text Color (Value) ldy /2 ; load y position as index into list lda ScreenRAMRowStartLow,Y ; load low address byte sta ZeroPageLow lda ScreenRAMRowStartHigh,Y ; load high address byte sta ZeroPageHigh ldy /1 ; load x position into Y register ldx #0 @loop lda /3,X cmp #0 beq @done sta (ZeroPageLow),Y inx iny jmp @loop @done ldy /2 ; load y position as index into list lda ColorRAMRowStartLow,Y ; load low address byte sta ZeroPageLow lda ColorRAMRowStartHigh,Y ; load high address byte sta ZeroPageHigh ldy /1 ; load x position into Y register ldx #0 @loop2 lda /3,X cmp #0 beq @done2 lda #/4 sta (ZeroPageLow),Y inx iny jmp @loop2 @done2 endm ;=============================================================================== defm LIBSCREEN_DRAWDECIMAL_AAAV ; /1 = X Position 0-39 (Address) ; /2 = Y Position 0-24 (Address) ; /3 = decimal number 2 nybbles (Address) ; /4 = Text Color (Value) ldy /2 ; load y position as index into list lda ScreenRAMRowStartLow,Y ; load low address byte sta ZeroPageLow lda ScreenRAMRowStartHigh,Y ; load high address byte sta ZeroPageHigh ldy /1 ; load x position into Y register ; get high nybble lda /3 and #$F0 ; convert to ascii lsr lsr lsr lsr ora #$30 sta (ZeroPageLow),Y ; move along to next screen position iny ; get low nybble lda /3 and #$0F ; convert to ascii ora #$30 sta (ZeroPageLow),Y ; now set the colors ldy /2 ; load y position as index into list lda ColorRAMRowStartLow,Y ; load low address byte sta ZeroPageLow lda ColorRAMRowStartHigh,Y ; load high address byte sta ZeroPageHigh ldy /1 ; load x position into Y register lda #/4 sta (ZeroPageLow),Y ; move along to next screen position iny sta (ZeroPageLow),Y endm ;============================================================================== defm LIBSCREEN_GETCHAR ; /1 = Return character code (Address) lda (ZeroPageLow),Y sta /1 endm ;=============================================================================== defm LIBSCREEN_PIXELTOCHAR_AAVAVAAAA ; /1 = XHighPixels (Address) ; /2 = XLowPixels (Address) ; /3 = XAdjust (Value) ; /4 = YPixels (Address) ; /5 = YAdjust (Value) ; /6 = XChar (Address) ; /7 = XOffset (Address) ; /8 = YChar (Address) ; /9 = YOffset (Address) lda /1 sta ZeroPageParam1 lda /2 sta ZeroPageParam2 lda #/3 sta ZeroPageParam3 lda /4 sta ZeroPageParam4 lda #/5 sta ZeroPageParam5 jsr libScreen_PixelToChar lda ZeroPageParam6 sta /6 lda ZeroPageParam7 sta /7 lda ZeroPageParam8 sta /8 lda ZeroPageParam9 sta /9 endm libScreen_PixelToChar ; subtract XAdjust pixels from XPixels as left of a sprite is first visible at x = 24 LIBMATH_SUB16BIT_AAVAAA ZeroPageParam1, ZeroPageParam2, 0, ZeroPageParam3, ZeroPageParam6, ZeroPageParam7 lda ZeroPageParam6 sta ZeroPageTemp ; divide by 8 to get character X lda ZeroPageParam7 lsr A ; divide by 2 lsr A ; and again = /4 lsr A ; and again = /8 sta ZeroPageParam6 ; AND 7 to get pixel offset X lda ZeroPageParam7 and #7 sta ZeroPageParam7 ; Adjust for XHigh lda ZeroPageTemp beq @nothigh LIBMATH_ADD8BIT_AVA ZeroPageParam6, 32, ZeroPageParam6 ; shift across 32 chars @nothigh ; subtract YAdjust pixels from YPixels as top of a sprite is first visible at y = 50 LIBMATH_SUB8BIT_AAA ZeroPageParam4, ZeroPageParam5, ZeroPageParam9 ; divide by 8 to get character Y lda ZeroPageParam9 lsr A ; divide by 2 lsr A ; and again = /4 lsr A ; and again = /8 sta ZeroPageParam8 ; AND 7 to get pixel offset Y lda ZeroPageParam9 and #7 sta ZeroPageParam9 rts ;============================================================================== defm LIBSCREEN_SCROLLXLEFT_A ; /1 = update subroutine (Address) dec screenScrollXValue lda screenScrollXValue and #%00000111 sta screenScrollXValue lda SCROLX and #%11111000 ora screenScrollXValue sta SCROLX lda screenScrollXValue cmp #7 bne @finished ; move to next column inc screenColumn jsr /1 ; call the passed in function to update the screen rows @finished endm ;============================================================================== defm LIBSCREEN_SCROLLXRIGHT_A ; /1 = update subroutine (Address) inc screenScrollXValue lda screenScrollXValue and #%00000111 sta screenScrollXValue lda SCROLX and #%11111000 ora screenScrollXValue sta SCROLX lda screenScrollXValue cmp #0 bne @finished ; move to previous column dec screenColumn jsr /1 ; call the passed in function to update the screen rows @finished endm ;============================================================================== defm LIBSCREEN_SCROLLXRESET_A ; /1 = update subroutine (Address) lda #0 sta screenColumn sta screenScrollXValue lda SCROLX and #%11111000 ora screenScrollXValue sta SCROLX jsr /1 ; call the passed in function to update the screen rows endm ;============================================================================== defm LIBSCREEN_SETSCROLLXVALUE_A ; /1 = ScrollX value (Address) lda SCROLX and #%11111000 ora /1 sta SCROLX endm ;============================================================================== defm LIBSCREEN_SETSCROLLXVALUE_V ; /1 = ScrollX value (Value) lda SCROLX and #%11111000 ora #/1 sta SCROLX endm ;============================================================================== ; Sets 1000 bytes of memory from start address with a value defm LIBSCREEN_SET1000 ; /1 = Start (Address) ; /2 = Number (Value) lda #/2 ; Get number to set ldx #250 ; Set loop value @loop dex ; Step -1 sta /1,x ; Set start + x sta /1+250,x ; Set start + 250 + x sta /1+500,x ; Set start + 500 + x sta /1+750,x ; Set start + 750 + x bne @loop ; If x<>0 loop endm ;============================================================================== defm LIBSCREEN_SET38COLUMNMODE lda SCROLX and #%11110111 ; clear bit 3 sta SCROLX endm ;============================================================================== defm LIBSCREEN_SET40COLUMNMODE lda SCROLX ora #%00001000 ; set bit 3 sta SCROLX endm ;============================================================================== defm LIBSCREEN_SETCHARMEMORY ; /1 = Character Memory Slot (Value) ; point vic (lower 4 bits of $d018)to new character data lda VMCSB and #%11110000 ; keep higher 4 bits ; p208 M Jong book ora #/1;$0E ; maps to $3800 memory address sta VMCSB endm ;============================================================================== defm LIBSCREEN_SETCHAR_V ; /1 = Character Code (Value) lda #/1 sta (ZeroPageLow),Y endm ;============================================================================== defm LIBSCREEN_SETCHAR_A ; /1 = Character Code (Address) lda /1 sta (ZeroPageLow),Y endm ;============================================================================== defm LIBSCREEN_SETCHARPOSITION_AA ; /1 = X Position 0-39 (Address) ; /2 = Y Position 0-24 (Address) ldy /2 ; load y position as index into list lda ScreenRAMRowStartLow,Y ; load low address byte sta ZeroPageLow lda ScreenRAMRowStartHigh,Y ; load high address byte sta ZeroPageHigh ldy /1 ; load x position into Y register endm ;============================================================================== defm LIBSCREEN_SETCOLORPOSITION_AA ; /1 = X Position 0-39 (Address) ; /2 = Y Position 0-24 (Address) ldy /2 ; load y position as index into list lda ColorRAMRowStartLow,Y ; load low address byte sta ZeroPageLow lda ColorRAMRowStartHigh,Y ; load high address byte sta ZeroPageHigh ldy /1 ; load x position into Y register endm ;=============================================================================== ; Sets the border and background colors defm LIBSCREEN_SETCOLORS ; /1 = Border Color (Value) ; /2 = Background Color 0 (Value) ; /3 = Background Color 1 (Value) ; /4 = Background Color 2 (Value) ; /5 = Background Color 3 (Value) lda #/1 ; Color0 -> A sta EXTCOL ; A -> EXTCOL lda #/2 ; Color1 -> A sta BGCOL0 ; A -> BGCOL0 lda #/3 ; Color2 -> A sta BGCOL1 ; A -> BGCOL1 lda #/4 ; Color3 -> A sta BGCOL2 ; A -> BGCOL2 lda #/5 ; Color4 -> A sta BGCOL3 ; A -> BGCOL3 endm ;============================================================================== defm LIBSCREEN_SETMAPCHAR_VAAV ; /1 = Map Row (Value) ; /2 = Screen Offset (Address) ; /3 = Char Offset (Address) ; /4 = Character (Value) lda #/1 sta ZeroPageParam1 lda /2 sta ZeroPageParam2 lda /3 sta ZeroPageParam3 lda #/4 sta ZeroPageParam4 jsr libScreen_SetMapChar endm libScreen_SetMapChar ldy ZeroPageParam1 ; load y position as index into list lda MapRAMRowStartLow,Y ; load low address byte sta ZeroPageLow lda MapRAMRowStartHigh,Y ; load high address byte sta ZeroPageHigh ; add on the screen offset to the map address LIBMATH_ADD16BIT_AAVAAA ZeroPageHigh, ZeroPageLow, 0, ZeroPageParam2, ZeroPageHigh, ZeroPageLow ; set the char lda ZeroPageParam4 ldy ZeroPageParam3 ; index with the char offset sta (ZeroPageLow),y rts ;============================================================================== defm LIBSCREEN_SETMULTICOLORMODE lda SCROLX ora #%00010000 ; set bit 5 sta SCROLX endm ;=============================================================================== ; Waits for a given scanline defm LIBSCREEN_WAIT_V ; /1 = Scanline (Value) @loop lda #/1 ; Scanline -> A cmp RASTER ; Compare A to current raster line bne @loop ; Loop if raster line not reached 255 endm
_pecho: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 51 push %ecx e: 83 ec 08 sub $0x8,%esp 11: 8b 41 04 mov 0x4(%ecx),%eax printf(1, "%s", argv[1]); 14: ff 70 04 pushl 0x4(%eax) 17: 68 98 07 00 00 push $0x798 1c: 6a 01 push $0x1 1e: e8 0d 04 00 00 call 430 <printf> exit(); 23: e8 59 02 00 00 call 281 <exit> 28: 66 90 xchg %ax,%ax 2a: 66 90 xchg %ax,%ax 2c: 66 90 xchg %ax,%ax 2e: 66 90 xchg %ax,%ax 00000030 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 30: 55 push %ebp char *os; os = s; while((*s++ = *t++) != 0) 31: 31 d2 xor %edx,%edx { 33: 89 e5 mov %esp,%ebp 35: 53 push %ebx 36: 8b 45 08 mov 0x8(%ebp),%eax 39: 8b 5d 0c mov 0xc(%ebp),%ebx 3c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi while((*s++ = *t++) != 0) 40: 0f b6 0c 13 movzbl (%ebx,%edx,1),%ecx 44: 88 0c 10 mov %cl,(%eax,%edx,1) 47: 83 c2 01 add $0x1,%edx 4a: 84 c9 test %cl,%cl 4c: 75 f2 jne 40 <strcpy+0x10> ; return os; } 4e: 5b pop %ebx 4f: 5d pop %ebp 50: c3 ret 51: eb 0d jmp 60 <strcmp> 53: 90 nop 54: 90 nop 55: 90 nop 56: 90 nop 57: 90 nop 58: 90 nop 59: 90 nop 5a: 90 nop 5b: 90 nop 5c: 90 nop 5d: 90 nop 5e: 90 nop 5f: 90 nop 00000060 <strcmp>: int strcmp(const char *p, const char *q) { 60: 55 push %ebp 61: 89 e5 mov %esp,%ebp 63: 56 push %esi 64: 53 push %ebx 65: 8b 5d 08 mov 0x8(%ebp),%ebx 68: 8b 75 0c mov 0xc(%ebp),%esi while(*p && *p == *q) 6b: 0f b6 13 movzbl (%ebx),%edx 6e: 0f b6 0e movzbl (%esi),%ecx 71: 84 d2 test %dl,%dl 73: 74 1e je 93 <strcmp+0x33> 75: b8 01 00 00 00 mov $0x1,%eax 7a: 38 ca cmp %cl,%dl 7c: 74 09 je 87 <strcmp+0x27> 7e: eb 20 jmp a0 <strcmp+0x40> 80: 83 c0 01 add $0x1,%eax 83: 38 ca cmp %cl,%dl 85: 75 19 jne a0 <strcmp+0x40> 87: 0f b6 14 03 movzbl (%ebx,%eax,1),%edx 8b: 0f b6 0c 06 movzbl (%esi,%eax,1),%ecx 8f: 84 d2 test %dl,%dl 91: 75 ed jne 80 <strcmp+0x20> 93: 31 c0 xor %eax,%eax p++, q++; return (uchar)*p - (uchar)*q; } 95: 5b pop %ebx 96: 5e pop %esi return (uchar)*p - (uchar)*q; 97: 29 c8 sub %ecx,%eax } 99: 5d pop %ebp 9a: c3 ret 9b: 90 nop 9c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi a0: 0f b6 c2 movzbl %dl,%eax a3: 5b pop %ebx a4: 5e pop %esi return (uchar)*p - (uchar)*q; a5: 29 c8 sub %ecx,%eax } a7: 5d pop %ebp a8: c3 ret a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000000b0 <strlen>: uint strlen(char *s) { b0: 55 push %ebp b1: 89 e5 mov %esp,%ebp b3: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) b6: 80 39 00 cmpb $0x0,(%ecx) b9: 74 15 je d0 <strlen+0x20> bb: 31 d2 xor %edx,%edx bd: 8d 76 00 lea 0x0(%esi),%esi c0: 83 c2 01 add $0x1,%edx c3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) c7: 89 d0 mov %edx,%eax c9: 75 f5 jne c0 <strlen+0x10> ; return n; } cb: 5d pop %ebp cc: c3 ret cd: 8d 76 00 lea 0x0(%esi),%esi for(n = 0; s[n]; n++) d0: 31 c0 xor %eax,%eax } d2: 5d pop %ebp d3: c3 ret d4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi da: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000000e0 <memset>: void* memset(void *dst, int c, uint n) { e0: 55 push %ebp e1: 89 e5 mov %esp,%ebp e3: 57 push %edi e4: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : e7: 8b 4d 10 mov 0x10(%ebp),%ecx ea: 8b 45 0c mov 0xc(%ebp),%eax ed: 89 d7 mov %edx,%edi ef: fc cld f0: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } f2: 89 d0 mov %edx,%eax f4: 5f pop %edi f5: 5d pop %ebp f6: c3 ret f7: 89 f6 mov %esi,%esi f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000100 <strchr>: char* strchr(const char *s, char c) { 100: 55 push %ebp 101: 89 e5 mov %esp,%ebp 103: 53 push %ebx 104: 8b 45 08 mov 0x8(%ebp),%eax 107: 8b 55 0c mov 0xc(%ebp),%edx for(; *s; s++) 10a: 0f b6 18 movzbl (%eax),%ebx 10d: 84 db test %bl,%bl 10f: 74 1d je 12e <strchr+0x2e> 111: 89 d1 mov %edx,%ecx if(*s == c) 113: 38 d3 cmp %dl,%bl 115: 75 0d jne 124 <strchr+0x24> 117: eb 17 jmp 130 <strchr+0x30> 119: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 120: 38 ca cmp %cl,%dl 122: 74 0c je 130 <strchr+0x30> for(; *s; s++) 124: 83 c0 01 add $0x1,%eax 127: 0f b6 10 movzbl (%eax),%edx 12a: 84 d2 test %dl,%dl 12c: 75 f2 jne 120 <strchr+0x20> return (char*)s; return 0; 12e: 31 c0 xor %eax,%eax } 130: 5b pop %ebx 131: 5d pop %ebp 132: c3 ret 133: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 139: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000140 <gets>: char* gets(char *buf, int max) { 140: 55 push %ebp 141: 89 e5 mov %esp,%ebp 143: 57 push %edi 144: 56 push %esi int i, cc; char c; for(i=0; i+1 < max; ){ 145: 31 f6 xor %esi,%esi { 147: 53 push %ebx 148: 89 f3 mov %esi,%ebx 14a: 83 ec 1c sub $0x1c,%esp 14d: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 150: eb 2f jmp 181 <gets+0x41> 152: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 158: 83 ec 04 sub $0x4,%esp 15b: 8d 45 e7 lea -0x19(%ebp),%eax 15e: 6a 01 push $0x1 160: 50 push %eax 161: 6a 00 push $0x0 163: e8 31 01 00 00 call 299 <read> if(cc < 1) 168: 83 c4 10 add $0x10,%esp 16b: 85 c0 test %eax,%eax 16d: 7e 1c jle 18b <gets+0x4b> break; buf[i++] = c; 16f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 173: 83 c7 01 add $0x1,%edi 176: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 179: 3c 0a cmp $0xa,%al 17b: 74 23 je 1a0 <gets+0x60> 17d: 3c 0d cmp $0xd,%al 17f: 74 1f je 1a0 <gets+0x60> for(i=0; i+1 < max; ){ 181: 83 c3 01 add $0x1,%ebx 184: 89 fe mov %edi,%esi 186: 3b 5d 0c cmp 0xc(%ebp),%ebx 189: 7c cd jl 158 <gets+0x18> 18b: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 18d: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 190: c6 03 00 movb $0x0,(%ebx) } 193: 8d 65 f4 lea -0xc(%ebp),%esp 196: 5b pop %ebx 197: 5e pop %esi 198: 5f pop %edi 199: 5d pop %ebp 19a: c3 ret 19b: 90 nop 19c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 1a0: 8b 75 08 mov 0x8(%ebp),%esi 1a3: 8b 45 08 mov 0x8(%ebp),%eax 1a6: 01 de add %ebx,%esi 1a8: 89 f3 mov %esi,%ebx buf[i] = '\0'; 1aa: c6 03 00 movb $0x0,(%ebx) } 1ad: 8d 65 f4 lea -0xc(%ebp),%esp 1b0: 5b pop %ebx 1b1: 5e pop %esi 1b2: 5f pop %edi 1b3: 5d pop %ebp 1b4: c3 ret 1b5: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 1b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000001c0 <stat>: int stat(char *n, struct stat *st) { 1c0: 55 push %ebp 1c1: 89 e5 mov %esp,%ebp 1c3: 56 push %esi 1c4: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 1c5: 83 ec 08 sub $0x8,%esp 1c8: 6a 00 push $0x0 1ca: ff 75 08 pushl 0x8(%ebp) 1cd: e8 ef 00 00 00 call 2c1 <open> if(fd < 0) 1d2: 83 c4 10 add $0x10,%esp 1d5: 85 c0 test %eax,%eax 1d7: 78 27 js 200 <stat+0x40> return -1; r = fstat(fd, st); 1d9: 83 ec 08 sub $0x8,%esp 1dc: ff 75 0c pushl 0xc(%ebp) 1df: 89 c3 mov %eax,%ebx 1e1: 50 push %eax 1e2: e8 f2 00 00 00 call 2d9 <fstat> close(fd); 1e7: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 1ea: 89 c6 mov %eax,%esi close(fd); 1ec: e8 b8 00 00 00 call 2a9 <close> return r; 1f1: 83 c4 10 add $0x10,%esp } 1f4: 8d 65 f8 lea -0x8(%ebp),%esp 1f7: 89 f0 mov %esi,%eax 1f9: 5b pop %ebx 1fa: 5e pop %esi 1fb: 5d pop %ebp 1fc: c3 ret 1fd: 8d 76 00 lea 0x0(%esi),%esi return -1; 200: be ff ff ff ff mov $0xffffffff,%esi 205: eb ed jmp 1f4 <stat+0x34> 207: 89 f6 mov %esi,%esi 209: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000210 <atoi>: int atoi(const char *s) { 210: 55 push %ebp 211: 89 e5 mov %esp,%ebp 213: 53 push %ebx 214: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 217: 0f be 11 movsbl (%ecx),%edx 21a: 8d 42 d0 lea -0x30(%edx),%eax 21d: 3c 09 cmp $0x9,%al n = 0; 21f: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 224: 77 1f ja 245 <atoi+0x35> 226: 8d 76 00 lea 0x0(%esi),%esi 229: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 230: 83 c1 01 add $0x1,%ecx 233: 8d 04 80 lea (%eax,%eax,4),%eax 236: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 23a: 0f be 11 movsbl (%ecx),%edx 23d: 8d 5a d0 lea -0x30(%edx),%ebx 240: 80 fb 09 cmp $0x9,%bl 243: 76 eb jbe 230 <atoi+0x20> return n; } 245: 5b pop %ebx 246: 5d pop %ebp 247: c3 ret 248: 90 nop 249: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000250 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 250: 55 push %ebp 251: 89 e5 mov %esp,%ebp 253: 57 push %edi 254: 8b 55 10 mov 0x10(%ebp),%edx 257: 8b 45 08 mov 0x8(%ebp),%eax 25a: 56 push %esi 25b: 8b 75 0c mov 0xc(%ebp),%esi char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 25e: 85 d2 test %edx,%edx 260: 7e 13 jle 275 <memmove+0x25> 262: 01 c2 add %eax,%edx dst = vdst; 264: 89 c7 mov %eax,%edi 266: 8d 76 00 lea 0x0(%esi),%esi 269: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi *dst++ = *src++; 270: a4 movsb %ds:(%esi),%es:(%edi) while(n-- > 0) 271: 39 fa cmp %edi,%edx 273: 75 fb jne 270 <memmove+0x20> return vdst; } 275: 5e pop %esi 276: 5f pop %edi 277: 5d pop %ebp 278: c3 ret 00000279 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 279: b8 01 00 00 00 mov $0x1,%eax 27e: cd 40 int $0x40 280: c3 ret 00000281 <exit>: SYSCALL(exit) 281: b8 02 00 00 00 mov $0x2,%eax 286: cd 40 int $0x40 288: c3 ret 00000289 <wait>: SYSCALL(wait) 289: b8 03 00 00 00 mov $0x3,%eax 28e: cd 40 int $0x40 290: c3 ret 00000291 <pipe>: SYSCALL(pipe) 291: b8 04 00 00 00 mov $0x4,%eax 296: cd 40 int $0x40 298: c3 ret 00000299 <read>: SYSCALL(read) 299: b8 05 00 00 00 mov $0x5,%eax 29e: cd 40 int $0x40 2a0: c3 ret 000002a1 <write>: SYSCALL(write) 2a1: b8 10 00 00 00 mov $0x10,%eax 2a6: cd 40 int $0x40 2a8: c3 ret 000002a9 <close>: SYSCALL(close) 2a9: b8 15 00 00 00 mov $0x15,%eax 2ae: cd 40 int $0x40 2b0: c3 ret 000002b1 <kill>: SYSCALL(kill) 2b1: b8 06 00 00 00 mov $0x6,%eax 2b6: cd 40 int $0x40 2b8: c3 ret 000002b9 <exec>: SYSCALL(exec) 2b9: b8 07 00 00 00 mov $0x7,%eax 2be: cd 40 int $0x40 2c0: c3 ret 000002c1 <open>: SYSCALL(open) 2c1: b8 0f 00 00 00 mov $0xf,%eax 2c6: cd 40 int $0x40 2c8: c3 ret 000002c9 <mknod>: SYSCALL(mknod) 2c9: b8 11 00 00 00 mov $0x11,%eax 2ce: cd 40 int $0x40 2d0: c3 ret 000002d1 <unlink>: SYSCALL(unlink) 2d1: b8 12 00 00 00 mov $0x12,%eax 2d6: cd 40 int $0x40 2d8: c3 ret 000002d9 <fstat>: SYSCALL(fstat) 2d9: b8 08 00 00 00 mov $0x8,%eax 2de: cd 40 int $0x40 2e0: c3 ret 000002e1 <link>: SYSCALL(link) 2e1: b8 13 00 00 00 mov $0x13,%eax 2e6: cd 40 int $0x40 2e8: c3 ret 000002e9 <mkdir>: SYSCALL(mkdir) 2e9: b8 14 00 00 00 mov $0x14,%eax 2ee: cd 40 int $0x40 2f0: c3 ret 000002f1 <chdir>: SYSCALL(chdir) 2f1: b8 09 00 00 00 mov $0x9,%eax 2f6: cd 40 int $0x40 2f8: c3 ret 000002f9 <dup>: SYSCALL(dup) 2f9: b8 0a 00 00 00 mov $0xa,%eax 2fe: cd 40 int $0x40 300: c3 ret 00000301 <getpid>: SYSCALL(getpid) 301: b8 0b 00 00 00 mov $0xb,%eax 306: cd 40 int $0x40 308: c3 ret 00000309 <sbrk>: SYSCALL(sbrk) 309: b8 0c 00 00 00 mov $0xc,%eax 30e: cd 40 int $0x40 310: c3 ret 00000311 <sleep>: SYSCALL(sleep) 311: b8 0d 00 00 00 mov $0xd,%eax 316: cd 40 int $0x40 318: c3 ret 00000319 <uptime>: SYSCALL(uptime) 319: b8 0e 00 00 00 mov $0xe,%eax 31e: cd 40 int $0x40 320: c3 ret 00000321 <trace>: SYSCALL(trace) 321: b8 16 00 00 00 mov $0x16,%eax 326: cd 40 int $0x40 328: c3 ret 00000329 <getsharem>: SYSCALL(getsharem) 329: b8 17 00 00 00 mov $0x17,%eax 32e: cd 40 int $0x40 330: c3 ret 00000331 <releasesharem>: SYSCALL(releasesharem) 331: b8 18 00 00 00 mov $0x18,%eax 336: cd 40 int $0x40 338: c3 ret 00000339 <split>: SYSCALL(split) 339: b8 19 00 00 00 mov $0x19,%eax 33e: cd 40 int $0x40 340: c3 ret 00000341 <memo>: SYSCALL(memo) 341: b8 1a 00 00 00 mov $0x1a,%eax 346: cd 40 int $0x40 348: c3 ret 00000349 <getmemo>: SYSCALL(getmemo) 349: b8 1b 00 00 00 mov $0x1b,%eax 34e: cd 40 int $0x40 350: c3 ret 00000351 <setmemo>: SYSCALL(setmemo) 351: b8 1c 00 00 00 mov $0x1c,%eax 356: cd 40 int $0x40 358: c3 ret 00000359 <att>: SYSCALL(att) 359: b8 1d 00 00 00 mov $0x1d,%eax 35e: cd 40 int $0x40 360: c3 ret 361: 66 90 xchg %ax,%ax 363: 66 90 xchg %ax,%ax 365: 66 90 xchg %ax,%ax 367: 66 90 xchg %ax,%ax 369: 66 90 xchg %ax,%ax 36b: 66 90 xchg %ax,%ax 36d: 66 90 xchg %ax,%ax 36f: 90 nop 00000370 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 370: 55 push %ebp 371: 89 e5 mov %esp,%ebp 373: 57 push %edi 374: 56 push %esi 375: 53 push %ebx uint x; neg = 0; if(sgn && xx < 0){ neg = 1; x = -xx; 376: 89 d3 mov %edx,%ebx { 378: 83 ec 3c sub $0x3c,%esp 37b: 89 45 bc mov %eax,-0x44(%ebp) if(sgn && xx < 0){ 37e: 85 d2 test %edx,%edx 380: 0f 89 92 00 00 00 jns 418 <printint+0xa8> 386: f6 45 08 01 testb $0x1,0x8(%ebp) 38a: 0f 84 88 00 00 00 je 418 <printint+0xa8> neg = 1; 390: c7 45 c0 01 00 00 00 movl $0x1,-0x40(%ebp) x = -xx; 397: f7 db neg %ebx } else { x = xx; } i = 0; 399: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 3a0: 8d 75 d7 lea -0x29(%ebp),%esi 3a3: eb 08 jmp 3ad <printint+0x3d> 3a5: 8d 76 00 lea 0x0(%esi),%esi do{ buf[i++] = digits[x % base]; 3a8: 89 7d c4 mov %edi,-0x3c(%ebp) }while((x /= base) != 0); 3ab: 89 c3 mov %eax,%ebx buf[i++] = digits[x % base]; 3ad: 89 d8 mov %ebx,%eax 3af: 31 d2 xor %edx,%edx 3b1: 8b 7d c4 mov -0x3c(%ebp),%edi 3b4: f7 f1 div %ecx 3b6: 83 c7 01 add $0x1,%edi 3b9: 0f b6 92 a4 07 00 00 movzbl 0x7a4(%edx),%edx 3c0: 88 14 3e mov %dl,(%esi,%edi,1) }while((x /= base) != 0); 3c3: 39 d9 cmp %ebx,%ecx 3c5: 76 e1 jbe 3a8 <printint+0x38> if(neg) 3c7: 8b 45 c0 mov -0x40(%ebp),%eax 3ca: 85 c0 test %eax,%eax 3cc: 74 0d je 3db <printint+0x6b> buf[i++] = '-'; 3ce: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1) 3d3: ba 2d 00 00 00 mov $0x2d,%edx buf[i++] = digits[x % base]; 3d8: 89 7d c4 mov %edi,-0x3c(%ebp) 3db: 8b 45 c4 mov -0x3c(%ebp),%eax 3de: 8b 7d bc mov -0x44(%ebp),%edi 3e1: 8d 5c 05 d7 lea -0x29(%ebp,%eax,1),%ebx 3e5: eb 0f jmp 3f6 <printint+0x86> 3e7: 89 f6 mov %esi,%esi 3e9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 3f0: 0f b6 13 movzbl (%ebx),%edx 3f3: 83 eb 01 sub $0x1,%ebx write(fd, &c, 1); 3f6: 83 ec 04 sub $0x4,%esp 3f9: 88 55 d7 mov %dl,-0x29(%ebp) 3fc: 6a 01 push $0x1 3fe: 56 push %esi 3ff: 57 push %edi 400: e8 9c fe ff ff call 2a1 <write> while(--i >= 0) 405: 83 c4 10 add $0x10,%esp 408: 39 de cmp %ebx,%esi 40a: 75 e4 jne 3f0 <printint+0x80> putc(fd, buf[i]); } 40c: 8d 65 f4 lea -0xc(%ebp),%esp 40f: 5b pop %ebx 410: 5e pop %esi 411: 5f pop %edi 412: 5d pop %ebp 413: c3 ret 414: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 418: c7 45 c0 00 00 00 00 movl $0x0,-0x40(%ebp) 41f: e9 75 ff ff ff jmp 399 <printint+0x29> 424: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 42a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000430 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 430: 55 push %ebp 431: 89 e5 mov %esp,%ebp 433: 57 push %edi 434: 56 push %esi 435: 53 push %ebx 436: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 439: 8b 75 0c mov 0xc(%ebp),%esi 43c: 0f b6 1e movzbl (%esi),%ebx 43f: 84 db test %bl,%bl 441: 0f 84 b9 00 00 00 je 500 <printf+0xd0> ap = (uint*)(void*)&fmt + 1; 447: 8d 45 10 lea 0x10(%ebp),%eax 44a: 83 c6 01 add $0x1,%esi write(fd, &c, 1); 44d: 8d 7d e7 lea -0x19(%ebp),%edi state = 0; 450: 31 d2 xor %edx,%edx ap = (uint*)(void*)&fmt + 1; 452: 89 45 d0 mov %eax,-0x30(%ebp) 455: eb 38 jmp 48f <printf+0x5f> 457: 89 f6 mov %esi,%esi 459: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 460: 89 55 d4 mov %edx,-0x2c(%ebp) c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ state = '%'; 463: ba 25 00 00 00 mov $0x25,%edx if(c == '%'){ 468: 83 f8 25 cmp $0x25,%eax 46b: 74 17 je 484 <printf+0x54> write(fd, &c, 1); 46d: 83 ec 04 sub $0x4,%esp 470: 88 5d e7 mov %bl,-0x19(%ebp) 473: 6a 01 push $0x1 475: 57 push %edi 476: ff 75 08 pushl 0x8(%ebp) 479: e8 23 fe ff ff call 2a1 <write> 47e: 8b 55 d4 mov -0x2c(%ebp),%edx } else { putc(fd, c); 481: 83 c4 10 add $0x10,%esp 484: 83 c6 01 add $0x1,%esi for(i = 0; fmt[i]; i++){ 487: 0f b6 5e ff movzbl -0x1(%esi),%ebx 48b: 84 db test %bl,%bl 48d: 74 71 je 500 <printf+0xd0> c = fmt[i] & 0xff; 48f: 0f be cb movsbl %bl,%ecx 492: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 495: 85 d2 test %edx,%edx 497: 74 c7 je 460 <printf+0x30> } } else if(state == '%'){ 499: 83 fa 25 cmp $0x25,%edx 49c: 75 e6 jne 484 <printf+0x54> if(c == 'd'){ 49e: 83 f8 64 cmp $0x64,%eax 4a1: 0f 84 99 00 00 00 je 540 <printf+0x110> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 4a7: 81 e1 f7 00 00 00 and $0xf7,%ecx 4ad: 83 f9 70 cmp $0x70,%ecx 4b0: 74 5e je 510 <printf+0xe0> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 4b2: 83 f8 73 cmp $0x73,%eax 4b5: 0f 84 d5 00 00 00 je 590 <printf+0x160> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 4bb: 83 f8 63 cmp $0x63,%eax 4be: 0f 84 8c 00 00 00 je 550 <printf+0x120> putc(fd, *ap); ap++; } else if(c == '%'){ 4c4: 83 f8 25 cmp $0x25,%eax 4c7: 0f 84 b3 00 00 00 je 580 <printf+0x150> write(fd, &c, 1); 4cd: 83 ec 04 sub $0x4,%esp 4d0: c6 45 e7 25 movb $0x25,-0x19(%ebp) 4d4: 6a 01 push $0x1 4d6: 57 push %edi 4d7: ff 75 08 pushl 0x8(%ebp) 4da: e8 c2 fd ff ff call 2a1 <write> putc(fd, c); } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); 4df: 88 5d e7 mov %bl,-0x19(%ebp) write(fd, &c, 1); 4e2: 83 c4 0c add $0xc,%esp 4e5: 6a 01 push $0x1 4e7: 83 c6 01 add $0x1,%esi 4ea: 57 push %edi 4eb: ff 75 08 pushl 0x8(%ebp) 4ee: e8 ae fd ff ff call 2a1 <write> for(i = 0; fmt[i]; i++){ 4f3: 0f b6 5e ff movzbl -0x1(%esi),%ebx putc(fd, c); 4f7: 83 c4 10 add $0x10,%esp } state = 0; 4fa: 31 d2 xor %edx,%edx for(i = 0; fmt[i]; i++){ 4fc: 84 db test %bl,%bl 4fe: 75 8f jne 48f <printf+0x5f> } } } 500: 8d 65 f4 lea -0xc(%ebp),%esp 503: 5b pop %ebx 504: 5e pop %esi 505: 5f pop %edi 506: 5d pop %ebp 507: c3 ret 508: 90 nop 509: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi printint(fd, *ap, 16, 0); 510: 83 ec 0c sub $0xc,%esp 513: b9 10 00 00 00 mov $0x10,%ecx 518: 6a 00 push $0x0 51a: 8b 5d d0 mov -0x30(%ebp),%ebx 51d: 8b 45 08 mov 0x8(%ebp),%eax 520: 8b 13 mov (%ebx),%edx 522: e8 49 fe ff ff call 370 <printint> ap++; 527: 89 d8 mov %ebx,%eax 529: 83 c4 10 add $0x10,%esp state = 0; 52c: 31 d2 xor %edx,%edx ap++; 52e: 83 c0 04 add $0x4,%eax 531: 89 45 d0 mov %eax,-0x30(%ebp) 534: e9 4b ff ff ff jmp 484 <printf+0x54> 539: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi printint(fd, *ap, 10, 1); 540: 83 ec 0c sub $0xc,%esp 543: b9 0a 00 00 00 mov $0xa,%ecx 548: 6a 01 push $0x1 54a: eb ce jmp 51a <printf+0xea> 54c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi putc(fd, *ap); 550: 8b 5d d0 mov -0x30(%ebp),%ebx write(fd, &c, 1); 553: 83 ec 04 sub $0x4,%esp putc(fd, *ap); 556: 8b 03 mov (%ebx),%eax write(fd, &c, 1); 558: 6a 01 push $0x1 ap++; 55a: 83 c3 04 add $0x4,%ebx write(fd, &c, 1); 55d: 57 push %edi 55e: ff 75 08 pushl 0x8(%ebp) putc(fd, *ap); 561: 88 45 e7 mov %al,-0x19(%ebp) write(fd, &c, 1); 564: e8 38 fd ff ff call 2a1 <write> ap++; 569: 89 5d d0 mov %ebx,-0x30(%ebp) 56c: 83 c4 10 add $0x10,%esp state = 0; 56f: 31 d2 xor %edx,%edx 571: e9 0e ff ff ff jmp 484 <printf+0x54> 576: 8d 76 00 lea 0x0(%esi),%esi 579: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi putc(fd, c); 580: 88 5d e7 mov %bl,-0x19(%ebp) write(fd, &c, 1); 583: 83 ec 04 sub $0x4,%esp 586: e9 5a ff ff ff jmp 4e5 <printf+0xb5> 58b: 90 nop 58c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi s = (char*)*ap; 590: 8b 45 d0 mov -0x30(%ebp),%eax 593: 8b 18 mov (%eax),%ebx ap++; 595: 83 c0 04 add $0x4,%eax 598: 89 45 d0 mov %eax,-0x30(%ebp) if(s == 0) 59b: 85 db test %ebx,%ebx 59d: 74 17 je 5b6 <printf+0x186> while(*s != 0){ 59f: 0f b6 03 movzbl (%ebx),%eax state = 0; 5a2: 31 d2 xor %edx,%edx while(*s != 0){ 5a4: 84 c0 test %al,%al 5a6: 0f 84 d8 fe ff ff je 484 <printf+0x54> 5ac: 89 75 d4 mov %esi,-0x2c(%ebp) 5af: 89 de mov %ebx,%esi 5b1: 8b 5d 08 mov 0x8(%ebp),%ebx 5b4: eb 1a jmp 5d0 <printf+0x1a0> s = "(null)"; 5b6: bb 9b 07 00 00 mov $0x79b,%ebx while(*s != 0){ 5bb: 89 75 d4 mov %esi,-0x2c(%ebp) 5be: b8 28 00 00 00 mov $0x28,%eax 5c3: 89 de mov %ebx,%esi 5c5: 8b 5d 08 mov 0x8(%ebp),%ebx 5c8: 90 nop 5c9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi write(fd, &c, 1); 5d0: 83 ec 04 sub $0x4,%esp s++; 5d3: 83 c6 01 add $0x1,%esi 5d6: 88 45 e7 mov %al,-0x19(%ebp) write(fd, &c, 1); 5d9: 6a 01 push $0x1 5db: 57 push %edi 5dc: 53 push %ebx 5dd: e8 bf fc ff ff call 2a1 <write> while(*s != 0){ 5e2: 0f b6 06 movzbl (%esi),%eax 5e5: 83 c4 10 add $0x10,%esp 5e8: 84 c0 test %al,%al 5ea: 75 e4 jne 5d0 <printf+0x1a0> 5ec: 8b 75 d4 mov -0x2c(%ebp),%esi state = 0; 5ef: 31 d2 xor %edx,%edx 5f1: e9 8e fe ff ff jmp 484 <printf+0x54> 5f6: 66 90 xchg %ax,%ax 5f8: 66 90 xchg %ax,%ax 5fa: 66 90 xchg %ax,%ax 5fc: 66 90 xchg %ax,%ax 5fe: 66 90 xchg %ax,%ax 00000600 <free>: static Header base; static Header *freep; void free(void *ap) { 600: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 601: a1 4c 0a 00 00 mov 0xa4c,%eax { 606: 89 e5 mov %esp,%ebp 608: 57 push %edi 609: 56 push %esi 60a: 53 push %ebx 60b: 8b 5d 08 mov 0x8(%ebp),%ebx 60e: 8b 10 mov (%eax),%edx bp = (Header*)ap - 1; 610: 8d 4b f8 lea -0x8(%ebx),%ecx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 613: 39 c8 cmp %ecx,%eax 615: 73 19 jae 630 <free+0x30> 617: 89 f6 mov %esi,%esi 619: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 620: 39 d1 cmp %edx,%ecx 622: 72 14 jb 638 <free+0x38> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 624: 39 d0 cmp %edx,%eax 626: 73 10 jae 638 <free+0x38> { 628: 89 d0 mov %edx,%eax 62a: 8b 10 mov (%eax),%edx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 62c: 39 c8 cmp %ecx,%eax 62e: 72 f0 jb 620 <free+0x20> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 630: 39 d0 cmp %edx,%eax 632: 72 f4 jb 628 <free+0x28> 634: 39 d1 cmp %edx,%ecx 636: 73 f0 jae 628 <free+0x28> break; if(bp + bp->s.size == p->s.ptr){ 638: 8b 73 fc mov -0x4(%ebx),%esi 63b: 8d 3c f1 lea (%ecx,%esi,8),%edi 63e: 39 fa cmp %edi,%edx 640: 74 1e je 660 <free+0x60> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 642: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 645: 8b 50 04 mov 0x4(%eax),%edx 648: 8d 34 d0 lea (%eax,%edx,8),%esi 64b: 39 f1 cmp %esi,%ecx 64d: 74 28 je 677 <free+0x77> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 64f: 89 08 mov %ecx,(%eax) freep = p; } 651: 5b pop %ebx freep = p; 652: a3 4c 0a 00 00 mov %eax,0xa4c } 657: 5e pop %esi 658: 5f pop %edi 659: 5d pop %ebp 65a: c3 ret 65b: 90 nop 65c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp->s.size += p->s.ptr->s.size; 660: 03 72 04 add 0x4(%edx),%esi 663: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 666: 8b 10 mov (%eax),%edx 668: 8b 12 mov (%edx),%edx 66a: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 66d: 8b 50 04 mov 0x4(%eax),%edx 670: 8d 34 d0 lea (%eax,%edx,8),%esi 673: 39 f1 cmp %esi,%ecx 675: 75 d8 jne 64f <free+0x4f> p->s.size += bp->s.size; 677: 03 53 fc add -0x4(%ebx),%edx freep = p; 67a: a3 4c 0a 00 00 mov %eax,0xa4c p->s.size += bp->s.size; 67f: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 682: 8b 53 f8 mov -0x8(%ebx),%edx 685: 89 10 mov %edx,(%eax) } 687: 5b pop %ebx 688: 5e pop %esi 689: 5f pop %edi 68a: 5d pop %ebp 68b: c3 ret 68c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000690 <malloc>: return freep; } void* malloc(uint nbytes) { 690: 55 push %ebp 691: 89 e5 mov %esp,%ebp 693: 57 push %edi 694: 56 push %esi 695: 53 push %ebx 696: 83 ec 1c sub $0x1c,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 699: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 69c: 8b 3d 4c 0a 00 00 mov 0xa4c,%edi nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6a2: 8d 70 07 lea 0x7(%eax),%esi 6a5: c1 ee 03 shr $0x3,%esi 6a8: 83 c6 01 add $0x1,%esi if((prevp = freep) == 0){ 6ab: 85 ff test %edi,%edi 6ad: 0f 84 ad 00 00 00 je 760 <malloc+0xd0> base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 6b3: 8b 17 mov (%edi),%edx if(p->s.size >= nunits){ 6b5: 8b 4a 04 mov 0x4(%edx),%ecx 6b8: 39 ce cmp %ecx,%esi 6ba: 76 72 jbe 72e <malloc+0x9e> 6bc: 81 fe 00 10 00 00 cmp $0x1000,%esi 6c2: bb 00 10 00 00 mov $0x1000,%ebx 6c7: 0f 43 de cmovae %esi,%ebx p = sbrk(nu * sizeof(Header)); 6ca: 8d 04 dd 00 00 00 00 lea 0x0(,%ebx,8),%eax 6d1: 89 45 e4 mov %eax,-0x1c(%ebp) 6d4: eb 1b jmp 6f1 <malloc+0x61> 6d6: 8d 76 00 lea 0x0(%esi),%esi 6d9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 6e0: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 6e2: 8b 48 04 mov 0x4(%eax),%ecx 6e5: 39 f1 cmp %esi,%ecx 6e7: 73 4f jae 738 <malloc+0xa8> 6e9: 8b 3d 4c 0a 00 00 mov 0xa4c,%edi 6ef: 89 c2 mov %eax,%edx p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 6f1: 39 d7 cmp %edx,%edi 6f3: 75 eb jne 6e0 <malloc+0x50> p = sbrk(nu * sizeof(Header)); 6f5: 83 ec 0c sub $0xc,%esp 6f8: ff 75 e4 pushl -0x1c(%ebp) 6fb: e8 09 fc ff ff call 309 <sbrk> if(p == (char*)-1) 700: 83 c4 10 add $0x10,%esp 703: 83 f8 ff cmp $0xffffffff,%eax 706: 74 1c je 724 <malloc+0x94> hp->s.size = nu; 708: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 70b: 83 ec 0c sub $0xc,%esp 70e: 83 c0 08 add $0x8,%eax 711: 50 push %eax 712: e8 e9 fe ff ff call 600 <free> return freep; 717: 8b 15 4c 0a 00 00 mov 0xa4c,%edx if((p = morecore(nunits)) == 0) 71d: 83 c4 10 add $0x10,%esp 720: 85 d2 test %edx,%edx 722: 75 bc jne 6e0 <malloc+0x50> return 0; } } 724: 8d 65 f4 lea -0xc(%ebp),%esp return 0; 727: 31 c0 xor %eax,%eax } 729: 5b pop %ebx 72a: 5e pop %esi 72b: 5f pop %edi 72c: 5d pop %ebp 72d: c3 ret if(p->s.size >= nunits){ 72e: 89 d0 mov %edx,%eax 730: 89 fa mov %edi,%edx 732: 8d b6 00 00 00 00 lea 0x0(%esi),%esi if(p->s.size == nunits) 738: 39 ce cmp %ecx,%esi 73a: 74 54 je 790 <malloc+0x100> p->s.size -= nunits; 73c: 29 f1 sub %esi,%ecx 73e: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 741: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 744: 89 70 04 mov %esi,0x4(%eax) freep = prevp; 747: 89 15 4c 0a 00 00 mov %edx,0xa4c } 74d: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); 750: 83 c0 08 add $0x8,%eax } 753: 5b pop %ebx 754: 5e pop %esi 755: 5f pop %edi 756: 5d pop %ebp 757: c3 ret 758: 90 nop 759: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; 760: c7 05 4c 0a 00 00 50 movl $0xa50,0xa4c 767: 0a 00 00 base.s.size = 0; 76a: bf 50 0a 00 00 mov $0xa50,%edi base.s.ptr = freep = prevp = &base; 76f: c7 05 50 0a 00 00 50 movl $0xa50,0xa50 776: 0a 00 00 for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 779: 89 fa mov %edi,%edx base.s.size = 0; 77b: c7 05 54 0a 00 00 00 movl $0x0,0xa54 782: 00 00 00 if(p->s.size >= nunits){ 785: e9 32 ff ff ff jmp 6bc <malloc+0x2c> 78a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi prevp->s.ptr = p->s.ptr; 790: 8b 08 mov (%eax),%ecx 792: 89 0a mov %ecx,(%edx) 794: eb b1 jmp 747 <malloc+0xb7>
check_cpuid: ; Check if CPUID is supported by attempting to flip the ID bit (bit 21) ; in the FLAGS register. If we can flip it, CPUID is available. ; Copy FLAGS in to EAX via stack pushfd pop eax ; Copy to ECX as well for comparing later on mov ecx, eax ; Flip the ID bit xor eax, 1 << 21 ; Copy EAX to FLAGS via the stack push eax popfd ; Copy FLAGS back to EAX (with the flipped bit if CPUID is supported) pushfd pop eax ; Restore FLAGS from the old version stored in ECX (i.e. flipping the ; ID bit back if it was ever flipped). push ecx popfd ; Compare EAX and ECX. If they are equal then that means the bit ; wasn't flipped, and CPUID isn't supported. cmp eax, ecx je .no_cpuid ret .no_cpuid: mov eax, no_cpuid_msg jmp errmsg
_myprogram: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(void) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 51 push %ecx e: 83 ec 04 sub $0x4,%esp printf(1, "Unix V6 was released in the year %d\n", getyear()); 11: e8 0d 03 00 00 call 323 <getyear> 16: 83 ec 04 sub $0x4,%esp 19: 50 push %eax 1a: 68 58 07 00 00 push $0x758 1f: 6a 01 push $0x1 21: e8 ca 03 00 00 call 3f0 <printf> //printf("Unix V6 was released in the year %d\n", getyear()); exit(); 26: e8 58 02 00 00 call 283 <exit> 2b: 66 90 xchg %ax,%ax 2d: 66 90 xchg %ax,%ax 2f: 90 nop 00000030 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { 30: 55 push %ebp char *os; os = s; while((*s++ = *t++) != 0) 31: 31 c0 xor %eax,%eax { 33: 89 e5 mov %esp,%ebp 35: 53 push %ebx 36: 8b 4d 08 mov 0x8(%ebp),%ecx 39: 8b 5d 0c mov 0xc(%ebp),%ebx 3c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi while((*s++ = *t++) != 0) 40: 0f b6 14 03 movzbl (%ebx,%eax,1),%edx 44: 88 14 01 mov %dl,(%ecx,%eax,1) 47: 83 c0 01 add $0x1,%eax 4a: 84 d2 test %dl,%dl 4c: 75 f2 jne 40 <strcpy+0x10> ; return os; } 4e: 8b 5d fc mov -0x4(%ebp),%ebx 51: 89 c8 mov %ecx,%eax 53: c9 leave 54: c3 ret 55: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 5c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000060 <strcmp>: int strcmp(const char *p, const char *q) { 60: 55 push %ebp 61: 89 e5 mov %esp,%ebp 63: 53 push %ebx 64: 8b 4d 08 mov 0x8(%ebp),%ecx 67: 8b 55 0c mov 0xc(%ebp),%edx while(*p && *p == *q) 6a: 0f b6 01 movzbl (%ecx),%eax 6d: 0f b6 1a movzbl (%edx),%ebx 70: 84 c0 test %al,%al 72: 75 1d jne 91 <strcmp+0x31> 74: eb 2a jmp a0 <strcmp+0x40> 76: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 7d: 8d 76 00 lea 0x0(%esi),%esi 80: 0f b6 41 01 movzbl 0x1(%ecx),%eax p++, q++; 84: 83 c1 01 add $0x1,%ecx 87: 83 c2 01 add $0x1,%edx return (uchar)*p - (uchar)*q; 8a: 0f b6 1a movzbl (%edx),%ebx while(*p && *p == *q) 8d: 84 c0 test %al,%al 8f: 74 0f je a0 <strcmp+0x40> 91: 38 d8 cmp %bl,%al 93: 74 eb je 80 <strcmp+0x20> return (uchar)*p - (uchar)*q; 95: 29 d8 sub %ebx,%eax } 97: 8b 5d fc mov -0x4(%ebp),%ebx 9a: c9 leave 9b: c3 ret 9c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi a0: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; a2: 29 d8 sub %ebx,%eax } a4: 8b 5d fc mov -0x4(%ebp),%ebx a7: c9 leave a8: c3 ret a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000000b0 <strlen>: uint strlen(const char *s) { b0: 55 push %ebp b1: 89 e5 mov %esp,%ebp b3: 8b 55 08 mov 0x8(%ebp),%edx int n; for(n = 0; s[n]; n++) b6: 80 3a 00 cmpb $0x0,(%edx) b9: 74 15 je d0 <strlen+0x20> bb: 31 c0 xor %eax,%eax bd: 8d 76 00 lea 0x0(%esi),%esi c0: 83 c0 01 add $0x1,%eax c3: 80 3c 02 00 cmpb $0x0,(%edx,%eax,1) c7: 89 c1 mov %eax,%ecx c9: 75 f5 jne c0 <strlen+0x10> ; return n; } cb: 89 c8 mov %ecx,%eax cd: 5d pop %ebp ce: c3 ret cf: 90 nop for(n = 0; s[n]; n++) d0: 31 c9 xor %ecx,%ecx } d2: 5d pop %ebp d3: 89 c8 mov %ecx,%eax d5: c3 ret d6: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi dd: 8d 76 00 lea 0x0(%esi),%esi 000000e0 <memset>: void* memset(void *dst, int c, uint n) { e0: 55 push %ebp e1: 89 e5 mov %esp,%ebp e3: 57 push %edi e4: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : e7: 8b 4d 10 mov 0x10(%ebp),%ecx ea: 8b 45 0c mov 0xc(%ebp),%eax ed: 89 d7 mov %edx,%edi ef: fc cld f0: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } f2: 8b 7d fc mov -0x4(%ebp),%edi f5: 89 d0 mov %edx,%eax f7: c9 leave f8: c3 ret f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000100 <strchr>: char* strchr(const char *s, char c) { 100: 55 push %ebp 101: 89 e5 mov %esp,%ebp 103: 8b 45 08 mov 0x8(%ebp),%eax 106: 0f b6 4d 0c movzbl 0xc(%ebp),%ecx for(; *s; s++) 10a: 0f b6 10 movzbl (%eax),%edx 10d: 84 d2 test %dl,%dl 10f: 75 12 jne 123 <strchr+0x23> 111: eb 1d jmp 130 <strchr+0x30> 113: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 117: 90 nop 118: 0f b6 50 01 movzbl 0x1(%eax),%edx 11c: 83 c0 01 add $0x1,%eax 11f: 84 d2 test %dl,%dl 121: 74 0d je 130 <strchr+0x30> if(*s == c) 123: 38 d1 cmp %dl,%cl 125: 75 f1 jne 118 <strchr+0x18> return (char*)s; return 0; } 127: 5d pop %ebp 128: c3 ret 129: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi return 0; 130: 31 c0 xor %eax,%eax } 132: 5d pop %ebp 133: c3 ret 134: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 13b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 13f: 90 nop 00000140 <gets>: char* gets(char *buf, int max) { 140: 55 push %ebp 141: 89 e5 mov %esp,%ebp 143: 57 push %edi 144: 56 push %esi int i, cc; char c; for(i=0; i+1 < max; ){ 145: 31 f6 xor %esi,%esi { 147: 53 push %ebx 148: 89 f3 mov %esi,%ebx 14a: 83 ec 1c sub $0x1c,%esp 14d: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 150: eb 2f jmp 181 <gets+0x41> 152: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 158: 83 ec 04 sub $0x4,%esp 15b: 8d 45 e7 lea -0x19(%ebp),%eax 15e: 6a 01 push $0x1 160: 50 push %eax 161: 6a 00 push $0x0 163: e8 33 01 00 00 call 29b <read> if(cc < 1) 168: 83 c4 10 add $0x10,%esp 16b: 85 c0 test %eax,%eax 16d: 7e 1c jle 18b <gets+0x4b> break; buf[i++] = c; 16f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax if(c == '\n' || c == '\r') 173: 83 c7 01 add $0x1,%edi buf[i++] = c; 176: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 179: 3c 0a cmp $0xa,%al 17b: 74 23 je 1a0 <gets+0x60> 17d: 3c 0d cmp $0xd,%al 17f: 74 1f je 1a0 <gets+0x60> for(i=0; i+1 < max; ){ 181: 83 c3 01 add $0x1,%ebx buf[i++] = c; 184: 89 fe mov %edi,%esi for(i=0; i+1 < max; ){ 186: 3b 5d 0c cmp 0xc(%ebp),%ebx 189: 7c cd jl 158 <gets+0x18> 18b: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 18d: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 190: c6 03 00 movb $0x0,(%ebx) } 193: 8d 65 f4 lea -0xc(%ebp),%esp 196: 5b pop %ebx 197: 5e pop %esi 198: 5f pop %edi 199: 5d pop %ebp 19a: c3 ret 19b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 19f: 90 nop buf[i] = '\0'; 1a0: 8b 75 08 mov 0x8(%ebp),%esi } 1a3: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 1a6: 01 de add %ebx,%esi 1a8: 89 f3 mov %esi,%ebx 1aa: c6 03 00 movb $0x0,(%ebx) } 1ad: 8d 65 f4 lea -0xc(%ebp),%esp 1b0: 5b pop %ebx 1b1: 5e pop %esi 1b2: 5f pop %edi 1b3: 5d pop %ebp 1b4: c3 ret 1b5: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 1bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 000001c0 <stat>: int stat(const char *n, struct stat *st) { 1c0: 55 push %ebp 1c1: 89 e5 mov %esp,%ebp 1c3: 56 push %esi 1c4: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 1c5: 83 ec 08 sub $0x8,%esp 1c8: 6a 00 push $0x0 1ca: ff 75 08 pushl 0x8(%ebp) 1cd: e8 f1 00 00 00 call 2c3 <open> if(fd < 0) 1d2: 83 c4 10 add $0x10,%esp 1d5: 85 c0 test %eax,%eax 1d7: 78 27 js 200 <stat+0x40> return -1; r = fstat(fd, st); 1d9: 83 ec 08 sub $0x8,%esp 1dc: ff 75 0c pushl 0xc(%ebp) 1df: 89 c3 mov %eax,%ebx 1e1: 50 push %eax 1e2: e8 f4 00 00 00 call 2db <fstat> close(fd); 1e7: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 1ea: 89 c6 mov %eax,%esi close(fd); 1ec: e8 ba 00 00 00 call 2ab <close> return r; 1f1: 83 c4 10 add $0x10,%esp } 1f4: 8d 65 f8 lea -0x8(%ebp),%esp 1f7: 89 f0 mov %esi,%eax 1f9: 5b pop %ebx 1fa: 5e pop %esi 1fb: 5d pop %ebp 1fc: c3 ret 1fd: 8d 76 00 lea 0x0(%esi),%esi return -1; 200: be ff ff ff ff mov $0xffffffff,%esi 205: eb ed jmp 1f4 <stat+0x34> 207: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 20e: 66 90 xchg %ax,%ax 00000210 <atoi>: int atoi(const char *s) { 210: 55 push %ebp 211: 89 e5 mov %esp,%ebp 213: 53 push %ebx 214: 8b 55 08 mov 0x8(%ebp),%edx int n; n = 0; while('0' <= *s && *s <= '9') 217: 0f be 02 movsbl (%edx),%eax 21a: 8d 48 d0 lea -0x30(%eax),%ecx 21d: 80 f9 09 cmp $0x9,%cl n = 0; 220: b9 00 00 00 00 mov $0x0,%ecx while('0' <= *s && *s <= '9') 225: 77 1e ja 245 <atoi+0x35> 227: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 22e: 66 90 xchg %ax,%ax n = n*10 + *s++ - '0'; 230: 83 c2 01 add $0x1,%edx 233: 8d 0c 89 lea (%ecx,%ecx,4),%ecx 236: 8d 4c 48 d0 lea -0x30(%eax,%ecx,2),%ecx while('0' <= *s && *s <= '9') 23a: 0f be 02 movsbl (%edx),%eax 23d: 8d 58 d0 lea -0x30(%eax),%ebx 240: 80 fb 09 cmp $0x9,%bl 243: 76 eb jbe 230 <atoi+0x20> return n; } 245: 8b 5d fc mov -0x4(%ebp),%ebx 248: 89 c8 mov %ecx,%eax 24a: c9 leave 24b: c3 ret 24c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000250 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 250: 55 push %ebp 251: 89 e5 mov %esp,%ebp 253: 57 push %edi 254: 8b 45 10 mov 0x10(%ebp),%eax 257: 8b 55 08 mov 0x8(%ebp),%edx 25a: 56 push %esi 25b: 8b 75 0c mov 0xc(%ebp),%esi char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 25e: 85 c0 test %eax,%eax 260: 7e 13 jle 275 <memmove+0x25> 262: 01 d0 add %edx,%eax dst = vdst; 264: 89 d7 mov %edx,%edi 266: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 26d: 8d 76 00 lea 0x0(%esi),%esi *dst++ = *src++; 270: a4 movsb %ds:(%esi),%es:(%edi) while(n-- > 0) 271: 39 f8 cmp %edi,%eax 273: 75 fb jne 270 <memmove+0x20> return vdst; } 275: 5e pop %esi 276: 89 d0 mov %edx,%eax 278: 5f pop %edi 279: 5d pop %ebp 27a: c3 ret 0000027b <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 27b: b8 01 00 00 00 mov $0x1,%eax 280: cd 40 int $0x40 282: c3 ret 00000283 <exit>: SYSCALL(exit) 283: b8 02 00 00 00 mov $0x2,%eax 288: cd 40 int $0x40 28a: c3 ret 0000028b <wait>: SYSCALL(wait) 28b: b8 03 00 00 00 mov $0x3,%eax 290: cd 40 int $0x40 292: c3 ret 00000293 <pipe>: SYSCALL(pipe) 293: b8 04 00 00 00 mov $0x4,%eax 298: cd 40 int $0x40 29a: c3 ret 0000029b <read>: SYSCALL(read) 29b: b8 05 00 00 00 mov $0x5,%eax 2a0: cd 40 int $0x40 2a2: c3 ret 000002a3 <write>: SYSCALL(write) 2a3: b8 10 00 00 00 mov $0x10,%eax 2a8: cd 40 int $0x40 2aa: c3 ret 000002ab <close>: SYSCALL(close) 2ab: b8 15 00 00 00 mov $0x15,%eax 2b0: cd 40 int $0x40 2b2: c3 ret 000002b3 <kill>: SYSCALL(kill) 2b3: b8 06 00 00 00 mov $0x6,%eax 2b8: cd 40 int $0x40 2ba: c3 ret 000002bb <exec>: SYSCALL(exec) 2bb: b8 07 00 00 00 mov $0x7,%eax 2c0: cd 40 int $0x40 2c2: c3 ret 000002c3 <open>: SYSCALL(open) 2c3: b8 0f 00 00 00 mov $0xf,%eax 2c8: cd 40 int $0x40 2ca: c3 ret 000002cb <mknod>: SYSCALL(mknod) 2cb: b8 11 00 00 00 mov $0x11,%eax 2d0: cd 40 int $0x40 2d2: c3 ret 000002d3 <unlink>: SYSCALL(unlink) 2d3: b8 12 00 00 00 mov $0x12,%eax 2d8: cd 40 int $0x40 2da: c3 ret 000002db <fstat>: SYSCALL(fstat) 2db: b8 08 00 00 00 mov $0x8,%eax 2e0: cd 40 int $0x40 2e2: c3 ret 000002e3 <link>: SYSCALL(link) 2e3: b8 13 00 00 00 mov $0x13,%eax 2e8: cd 40 int $0x40 2ea: c3 ret 000002eb <mkdir>: SYSCALL(mkdir) 2eb: b8 14 00 00 00 mov $0x14,%eax 2f0: cd 40 int $0x40 2f2: c3 ret 000002f3 <chdir>: SYSCALL(chdir) 2f3: b8 09 00 00 00 mov $0x9,%eax 2f8: cd 40 int $0x40 2fa: c3 ret 000002fb <dup>: SYSCALL(dup) 2fb: b8 0a 00 00 00 mov $0xa,%eax 300: cd 40 int $0x40 302: c3 ret 00000303 <getpid>: SYSCALL(getpid) 303: b8 0b 00 00 00 mov $0xb,%eax 308: cd 40 int $0x40 30a: c3 ret 0000030b <sbrk>: SYSCALL(sbrk) 30b: b8 0c 00 00 00 mov $0xc,%eax 310: cd 40 int $0x40 312: c3 ret 00000313 <sleep>: SYSCALL(sleep) 313: b8 0d 00 00 00 mov $0xd,%eax 318: cd 40 int $0x40 31a: c3 ret 0000031b <uptime>: SYSCALL(uptime) 31b: b8 0e 00 00 00 mov $0xe,%eax 320: cd 40 int $0x40 322: c3 ret 00000323 <getyear>: SYSCALL(getyear) 323: b8 16 00 00 00 mov $0x16,%eax 328: cd 40 int $0x40 32a: c3 ret 0000032b <lseek>: 32b: b8 17 00 00 00 mov $0x17,%eax 330: cd 40 int $0x40 332: c3 ret 333: 66 90 xchg %ax,%ax 335: 66 90 xchg %ax,%ax 337: 66 90 xchg %ax,%ax 339: 66 90 xchg %ax,%ax 33b: 66 90 xchg %ax,%ax 33d: 66 90 xchg %ax,%ax 33f: 90 nop 00000340 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 340: 55 push %ebp 341: 89 e5 mov %esp,%ebp 343: 57 push %edi 344: 56 push %esi 345: 53 push %ebx 346: 83 ec 3c sub $0x3c,%esp 349: 89 4d c4 mov %ecx,-0x3c(%ebp) uint x; neg = 0; if(sgn && xx < 0){ neg = 1; x = -xx; 34c: 89 d1 mov %edx,%ecx { 34e: 89 45 b8 mov %eax,-0x48(%ebp) if(sgn && xx < 0){ 351: 85 d2 test %edx,%edx 353: 0f 89 7f 00 00 00 jns 3d8 <printint+0x98> 359: f6 45 08 01 testb $0x1,0x8(%ebp) 35d: 74 79 je 3d8 <printint+0x98> neg = 1; 35f: c7 45 bc 01 00 00 00 movl $0x1,-0x44(%ebp) x = -xx; 366: f7 d9 neg %ecx } else { x = xx; } i = 0; 368: 31 db xor %ebx,%ebx 36a: 8d 75 d7 lea -0x29(%ebp),%esi 36d: 8d 76 00 lea 0x0(%esi),%esi do{ buf[i++] = digits[x % base]; 370: 89 c8 mov %ecx,%eax 372: 31 d2 xor %edx,%edx 374: 89 cf mov %ecx,%edi 376: f7 75 c4 divl -0x3c(%ebp) 379: 0f b6 92 84 07 00 00 movzbl 0x784(%edx),%edx 380: 89 45 c0 mov %eax,-0x40(%ebp) 383: 89 d8 mov %ebx,%eax 385: 8d 5b 01 lea 0x1(%ebx),%ebx }while((x /= base) != 0); 388: 8b 4d c0 mov -0x40(%ebp),%ecx buf[i++] = digits[x % base]; 38b: 88 14 1e mov %dl,(%esi,%ebx,1) }while((x /= base) != 0); 38e: 39 7d c4 cmp %edi,-0x3c(%ebp) 391: 76 dd jbe 370 <printint+0x30> if(neg) 393: 8b 4d bc mov -0x44(%ebp),%ecx 396: 85 c9 test %ecx,%ecx 398: 74 0c je 3a6 <printint+0x66> buf[i++] = '-'; 39a: c6 44 1d d8 2d movb $0x2d,-0x28(%ebp,%ebx,1) buf[i++] = digits[x % base]; 39f: 89 d8 mov %ebx,%eax buf[i++] = '-'; 3a1: ba 2d 00 00 00 mov $0x2d,%edx while(--i >= 0) 3a6: 8b 7d b8 mov -0x48(%ebp),%edi 3a9: 8d 5c 05 d7 lea -0x29(%ebp,%eax,1),%ebx 3ad: eb 07 jmp 3b6 <printint+0x76> 3af: 90 nop putc(fd, buf[i]); 3b0: 0f b6 13 movzbl (%ebx),%edx 3b3: 83 eb 01 sub $0x1,%ebx write(fd, &c, 1); 3b6: 83 ec 04 sub $0x4,%esp 3b9: 88 55 d7 mov %dl,-0x29(%ebp) 3bc: 6a 01 push $0x1 3be: 56 push %esi 3bf: 57 push %edi 3c0: e8 de fe ff ff call 2a3 <write> while(--i >= 0) 3c5: 83 c4 10 add $0x10,%esp 3c8: 39 de cmp %ebx,%esi 3ca: 75 e4 jne 3b0 <printint+0x70> } 3cc: 8d 65 f4 lea -0xc(%ebp),%esp 3cf: 5b pop %ebx 3d0: 5e pop %esi 3d1: 5f pop %edi 3d2: 5d pop %ebp 3d3: c3 ret 3d4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 3d8: c7 45 bc 00 00 00 00 movl $0x0,-0x44(%ebp) 3df: eb 87 jmp 368 <printint+0x28> 3e1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 3e8: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 3ef: 90 nop 000003f0 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 3f0: 55 push %ebp 3f1: 89 e5 mov %esp,%ebp 3f3: 57 push %edi 3f4: 56 push %esi 3f5: 53 push %ebx 3f6: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 3f9: 8b 75 0c mov 0xc(%ebp),%esi 3fc: 0f b6 1e movzbl (%esi),%ebx 3ff: 84 db test %bl,%bl 401: 0f 84 b8 00 00 00 je 4bf <printf+0xcf> ap = (uint*)(void*)&fmt + 1; 407: 8d 45 10 lea 0x10(%ebp),%eax 40a: 83 c6 01 add $0x1,%esi write(fd, &c, 1); 40d: 8d 7d e7 lea -0x19(%ebp),%edi state = 0; 410: 31 d2 xor %edx,%edx ap = (uint*)(void*)&fmt + 1; 412: 89 45 d0 mov %eax,-0x30(%ebp) 415: eb 37 jmp 44e <printf+0x5e> 417: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 41e: 66 90 xchg %ax,%ax 420: 89 55 d4 mov %edx,-0x2c(%ebp) c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ state = '%'; 423: ba 25 00 00 00 mov $0x25,%edx if(c == '%'){ 428: 83 f8 25 cmp $0x25,%eax 42b: 74 17 je 444 <printf+0x54> write(fd, &c, 1); 42d: 83 ec 04 sub $0x4,%esp 430: 88 5d e7 mov %bl,-0x19(%ebp) 433: 6a 01 push $0x1 435: 57 push %edi 436: ff 75 08 pushl 0x8(%ebp) 439: e8 65 fe ff ff call 2a3 <write> 43e: 8b 55 d4 mov -0x2c(%ebp),%edx } else { putc(fd, c); 441: 83 c4 10 add $0x10,%esp for(i = 0; fmt[i]; i++){ 444: 0f b6 1e movzbl (%esi),%ebx 447: 83 c6 01 add $0x1,%esi 44a: 84 db test %bl,%bl 44c: 74 71 je 4bf <printf+0xcf> c = fmt[i] & 0xff; 44e: 0f be cb movsbl %bl,%ecx 451: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 454: 85 d2 test %edx,%edx 456: 74 c8 je 420 <printf+0x30> } } else if(state == '%'){ 458: 83 fa 25 cmp $0x25,%edx 45b: 75 e7 jne 444 <printf+0x54> if(c == 'd'){ 45d: 83 f8 64 cmp $0x64,%eax 460: 0f 84 9a 00 00 00 je 500 <printf+0x110> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 466: 81 e1 f7 00 00 00 and $0xf7,%ecx 46c: 83 f9 70 cmp $0x70,%ecx 46f: 74 5f je 4d0 <printf+0xe0> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 471: 83 f8 73 cmp $0x73,%eax 474: 0f 84 d6 00 00 00 je 550 <printf+0x160> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 47a: 83 f8 63 cmp $0x63,%eax 47d: 0f 84 8d 00 00 00 je 510 <printf+0x120> putc(fd, *ap); ap++; } else if(c == '%'){ 483: 83 f8 25 cmp $0x25,%eax 486: 0f 84 b4 00 00 00 je 540 <printf+0x150> write(fd, &c, 1); 48c: 83 ec 04 sub $0x4,%esp 48f: c6 45 e7 25 movb $0x25,-0x19(%ebp) 493: 6a 01 push $0x1 495: 57 push %edi 496: ff 75 08 pushl 0x8(%ebp) 499: e8 05 fe ff ff call 2a3 <write> putc(fd, c); } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); 49e: 88 5d e7 mov %bl,-0x19(%ebp) write(fd, &c, 1); 4a1: 83 c4 0c add $0xc,%esp 4a4: 6a 01 push $0x1 for(i = 0; fmt[i]; i++){ 4a6: 83 c6 01 add $0x1,%esi write(fd, &c, 1); 4a9: 57 push %edi 4aa: ff 75 08 pushl 0x8(%ebp) 4ad: e8 f1 fd ff ff call 2a3 <write> for(i = 0; fmt[i]; i++){ 4b2: 0f b6 5e ff movzbl -0x1(%esi),%ebx putc(fd, c); 4b6: 83 c4 10 add $0x10,%esp } state = 0; 4b9: 31 d2 xor %edx,%edx for(i = 0; fmt[i]; i++){ 4bb: 84 db test %bl,%bl 4bd: 75 8f jne 44e <printf+0x5e> } } } 4bf: 8d 65 f4 lea -0xc(%ebp),%esp 4c2: 5b pop %ebx 4c3: 5e pop %esi 4c4: 5f pop %edi 4c5: 5d pop %ebp 4c6: c3 ret 4c7: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 4ce: 66 90 xchg %ax,%ax printint(fd, *ap, 16, 0); 4d0: 83 ec 0c sub $0xc,%esp 4d3: b9 10 00 00 00 mov $0x10,%ecx 4d8: 6a 00 push $0x0 4da: 8b 5d d0 mov -0x30(%ebp),%ebx 4dd: 8b 45 08 mov 0x8(%ebp),%eax 4e0: 8b 13 mov (%ebx),%edx 4e2: e8 59 fe ff ff call 340 <printint> ap++; 4e7: 89 d8 mov %ebx,%eax 4e9: 83 c4 10 add $0x10,%esp state = 0; 4ec: 31 d2 xor %edx,%edx ap++; 4ee: 83 c0 04 add $0x4,%eax 4f1: 89 45 d0 mov %eax,-0x30(%ebp) 4f4: e9 4b ff ff ff jmp 444 <printf+0x54> 4f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi printint(fd, *ap, 10, 1); 500: 83 ec 0c sub $0xc,%esp 503: b9 0a 00 00 00 mov $0xa,%ecx 508: 6a 01 push $0x1 50a: eb ce jmp 4da <printf+0xea> 50c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi putc(fd, *ap); 510: 8b 5d d0 mov -0x30(%ebp),%ebx write(fd, &c, 1); 513: 83 ec 04 sub $0x4,%esp putc(fd, *ap); 516: 8b 03 mov (%ebx),%eax write(fd, &c, 1); 518: 6a 01 push $0x1 ap++; 51a: 83 c3 04 add $0x4,%ebx write(fd, &c, 1); 51d: 57 push %edi 51e: ff 75 08 pushl 0x8(%ebp) putc(fd, *ap); 521: 88 45 e7 mov %al,-0x19(%ebp) write(fd, &c, 1); 524: e8 7a fd ff ff call 2a3 <write> ap++; 529: 89 5d d0 mov %ebx,-0x30(%ebp) 52c: 83 c4 10 add $0x10,%esp state = 0; 52f: 31 d2 xor %edx,%edx 531: e9 0e ff ff ff jmp 444 <printf+0x54> 536: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 53d: 8d 76 00 lea 0x0(%esi),%esi putc(fd, c); 540: 88 5d e7 mov %bl,-0x19(%ebp) write(fd, &c, 1); 543: 83 ec 04 sub $0x4,%esp 546: e9 59 ff ff ff jmp 4a4 <printf+0xb4> 54b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 54f: 90 nop s = (char*)*ap; 550: 8b 45 d0 mov -0x30(%ebp),%eax 553: 8b 18 mov (%eax),%ebx ap++; 555: 83 c0 04 add $0x4,%eax 558: 89 45 d0 mov %eax,-0x30(%ebp) if(s == 0) 55b: 85 db test %ebx,%ebx 55d: 74 17 je 576 <printf+0x186> while(*s != 0){ 55f: 0f b6 03 movzbl (%ebx),%eax state = 0; 562: 31 d2 xor %edx,%edx while(*s != 0){ 564: 84 c0 test %al,%al 566: 0f 84 d8 fe ff ff je 444 <printf+0x54> 56c: 89 75 d4 mov %esi,-0x2c(%ebp) 56f: 89 de mov %ebx,%esi 571: 8b 5d 08 mov 0x8(%ebp),%ebx 574: eb 1a jmp 590 <printf+0x1a0> s = "(null)"; 576: bb 7d 07 00 00 mov $0x77d,%ebx while(*s != 0){ 57b: 89 75 d4 mov %esi,-0x2c(%ebp) 57e: b8 28 00 00 00 mov $0x28,%eax 583: 89 de mov %ebx,%esi 585: 8b 5d 08 mov 0x8(%ebp),%ebx 588: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 58f: 90 nop write(fd, &c, 1); 590: 83 ec 04 sub $0x4,%esp s++; 593: 83 c6 01 add $0x1,%esi 596: 88 45 e7 mov %al,-0x19(%ebp) write(fd, &c, 1); 599: 6a 01 push $0x1 59b: 57 push %edi 59c: 53 push %ebx 59d: e8 01 fd ff ff call 2a3 <write> while(*s != 0){ 5a2: 0f b6 06 movzbl (%esi),%eax 5a5: 83 c4 10 add $0x10,%esp 5a8: 84 c0 test %al,%al 5aa: 75 e4 jne 590 <printf+0x1a0> state = 0; 5ac: 8b 75 d4 mov -0x2c(%ebp),%esi 5af: 31 d2 xor %edx,%edx 5b1: e9 8e fe ff ff jmp 444 <printf+0x54> 5b6: 66 90 xchg %ax,%ax 5b8: 66 90 xchg %ax,%ax 5ba: 66 90 xchg %ax,%ax 5bc: 66 90 xchg %ax,%ax 5be: 66 90 xchg %ax,%ax 000005c0 <free>: static Header base; static Header *freep; void free(void *ap) { 5c0: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5c1: a1 28 0a 00 00 mov 0xa28,%eax { 5c6: 89 e5 mov %esp,%ebp 5c8: 57 push %edi 5c9: 56 push %esi 5ca: 53 push %ebx 5cb: 8b 5d 08 mov 0x8(%ebp),%ebx bp = (Header*)ap - 1; 5ce: 8d 4b f8 lea -0x8(%ebx),%ecx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5d1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 5d8: 89 c2 mov %eax,%edx 5da: 8b 00 mov (%eax),%eax 5dc: 39 ca cmp %ecx,%edx 5de: 73 30 jae 610 <free+0x50> 5e0: 39 c1 cmp %eax,%ecx 5e2: 72 04 jb 5e8 <free+0x28> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5e4: 39 c2 cmp %eax,%edx 5e6: 72 f0 jb 5d8 <free+0x18> break; if(bp + bp->s.size == p->s.ptr){ 5e8: 8b 73 fc mov -0x4(%ebx),%esi 5eb: 8d 3c f1 lea (%ecx,%esi,8),%edi 5ee: 39 f8 cmp %edi,%eax 5f0: 74 30 je 622 <free+0x62> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 5f2: 89 43 f8 mov %eax,-0x8(%ebx) if(p + p->s.size == bp){ 5f5: 8b 42 04 mov 0x4(%edx),%eax 5f8: 8d 34 c2 lea (%edx,%eax,8),%esi 5fb: 39 f1 cmp %esi,%ecx 5fd: 74 3a je 639 <free+0x79> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 5ff: 89 0a mov %ecx,(%edx) freep = p; } 601: 5b pop %ebx freep = p; 602: 89 15 28 0a 00 00 mov %edx,0xa28 } 608: 5e pop %esi 609: 5f pop %edi 60a: 5d pop %ebp 60b: c3 ret 60c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 610: 39 c2 cmp %eax,%edx 612: 72 c4 jb 5d8 <free+0x18> 614: 39 c1 cmp %eax,%ecx 616: 73 c0 jae 5d8 <free+0x18> if(bp + bp->s.size == p->s.ptr){ 618: 8b 73 fc mov -0x4(%ebx),%esi 61b: 8d 3c f1 lea (%ecx,%esi,8),%edi 61e: 39 f8 cmp %edi,%eax 620: 75 d0 jne 5f2 <free+0x32> bp->s.size += p->s.ptr->s.size; 622: 03 70 04 add 0x4(%eax),%esi 625: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 628: 8b 02 mov (%edx),%eax 62a: 8b 00 mov (%eax),%eax 62c: 89 43 f8 mov %eax,-0x8(%ebx) if(p + p->s.size == bp){ 62f: 8b 42 04 mov 0x4(%edx),%eax 632: 8d 34 c2 lea (%edx,%eax,8),%esi 635: 39 f1 cmp %esi,%ecx 637: 75 c6 jne 5ff <free+0x3f> p->s.size += bp->s.size; 639: 03 43 fc add -0x4(%ebx),%eax freep = p; 63c: 89 15 28 0a 00 00 mov %edx,0xa28 p->s.size += bp->s.size; 642: 89 42 04 mov %eax,0x4(%edx) p->s.ptr = bp->s.ptr; 645: 8b 43 f8 mov -0x8(%ebx),%eax 648: 89 02 mov %eax,(%edx) } 64a: 5b pop %ebx 64b: 5e pop %esi 64c: 5f pop %edi 64d: 5d pop %ebp 64e: c3 ret 64f: 90 nop 00000650 <malloc>: return freep; } void* malloc(uint nbytes) { 650: 55 push %ebp 651: 89 e5 mov %esp,%ebp 653: 57 push %edi 654: 56 push %esi 655: 53 push %ebx 656: 83 ec 1c sub $0x1c,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 659: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 65c: 8b 3d 28 0a 00 00 mov 0xa28,%edi nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 662: 8d 70 07 lea 0x7(%eax),%esi 665: c1 ee 03 shr $0x3,%esi 668: 83 c6 01 add $0x1,%esi if((prevp = freep) == 0){ 66b: 85 ff test %edi,%edi 66d: 0f 84 ad 00 00 00 je 720 <malloc+0xd0> base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 673: 8b 07 mov (%edi),%eax if(p->s.size >= nunits){ 675: 8b 48 04 mov 0x4(%eax),%ecx 678: 39 f1 cmp %esi,%ecx 67a: 73 71 jae 6ed <malloc+0x9d> 67c: 81 fe 00 10 00 00 cmp $0x1000,%esi 682: bb 00 10 00 00 mov $0x1000,%ebx 687: 0f 43 de cmovae %esi,%ebx p = sbrk(nu * sizeof(Header)); 68a: 8d 0c dd 00 00 00 00 lea 0x0(,%ebx,8),%ecx 691: 89 4d e4 mov %ecx,-0x1c(%ebp) 694: eb 1b jmp 6b1 <malloc+0x61> 696: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 69d: 8d 76 00 lea 0x0(%esi),%esi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 6a0: 8b 10 mov (%eax),%edx if(p->s.size >= nunits){ 6a2: 8b 4a 04 mov 0x4(%edx),%ecx 6a5: 39 f1 cmp %esi,%ecx 6a7: 73 4f jae 6f8 <malloc+0xa8> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 6a9: 8b 3d 28 0a 00 00 mov 0xa28,%edi 6af: 89 d0 mov %edx,%eax 6b1: 39 c7 cmp %eax,%edi 6b3: 75 eb jne 6a0 <malloc+0x50> p = sbrk(nu * sizeof(Header)); 6b5: 83 ec 0c sub $0xc,%esp 6b8: ff 75 e4 pushl -0x1c(%ebp) 6bb: e8 4b fc ff ff call 30b <sbrk> if(p == (char*)-1) 6c0: 83 c4 10 add $0x10,%esp 6c3: 83 f8 ff cmp $0xffffffff,%eax 6c6: 74 1b je 6e3 <malloc+0x93> hp->s.size = nu; 6c8: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 6cb: 83 ec 0c sub $0xc,%esp 6ce: 83 c0 08 add $0x8,%eax 6d1: 50 push %eax 6d2: e8 e9 fe ff ff call 5c0 <free> return freep; 6d7: a1 28 0a 00 00 mov 0xa28,%eax if((p = morecore(nunits)) == 0) 6dc: 83 c4 10 add $0x10,%esp 6df: 85 c0 test %eax,%eax 6e1: 75 bd jne 6a0 <malloc+0x50> return 0; } } 6e3: 8d 65 f4 lea -0xc(%ebp),%esp return 0; 6e6: 31 c0 xor %eax,%eax } 6e8: 5b pop %ebx 6e9: 5e pop %esi 6ea: 5f pop %edi 6eb: 5d pop %ebp 6ec: c3 ret if(p->s.size >= nunits){ 6ed: 89 c2 mov %eax,%edx 6ef: 89 f8 mov %edi,%eax 6f1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if(p->s.size == nunits) 6f8: 39 ce cmp %ecx,%esi 6fa: 74 54 je 750 <malloc+0x100> p->s.size -= nunits; 6fc: 29 f1 sub %esi,%ecx 6fe: 89 4a 04 mov %ecx,0x4(%edx) p += p->s.size; 701: 8d 14 ca lea (%edx,%ecx,8),%edx p->s.size = nunits; 704: 89 72 04 mov %esi,0x4(%edx) freep = prevp; 707: a3 28 0a 00 00 mov %eax,0xa28 } 70c: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); 70f: 8d 42 08 lea 0x8(%edx),%eax } 712: 5b pop %ebx 713: 5e pop %esi 714: 5f pop %edi 715: 5d pop %ebp 716: c3 ret 717: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 71e: 66 90 xchg %ax,%ax base.s.ptr = freep = prevp = &base; 720: c7 05 28 0a 00 00 2c movl $0xa2c,0xa28 727: 0a 00 00 base.s.size = 0; 72a: bf 2c 0a 00 00 mov $0xa2c,%edi base.s.ptr = freep = prevp = &base; 72f: c7 05 2c 0a 00 00 2c movl $0xa2c,0xa2c 736: 0a 00 00 for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 739: 89 f8 mov %edi,%eax base.s.size = 0; 73b: c7 05 30 0a 00 00 00 movl $0x0,0xa30 742: 00 00 00 if(p->s.size >= nunits){ 745: e9 32 ff ff ff jmp 67c <malloc+0x2c> 74a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi prevp->s.ptr = p->s.ptr; 750: 8b 0a mov (%edx),%ecx 752: 89 08 mov %ecx,(%eax) 754: eb b1 jmp 707 <malloc+0xb7>
; A167499: a(n) = n*(n+3)/2 + 6. ; 6,8,11,15,20,26,33,41,50,60,71,83,96,110,125,141,158,176,195,215,236,258,281,305,330,356,383,411,440,470,501,533,566,600,635,671,708,746,785,825,866,908,951,995,1040,1086,1133,1181,1230,1280,1331,1383,1436,1490,1545,1601,1658,1716,1775,1835,1896,1958,2021,2085,2150,2216,2283,2351,2420,2490,2561,2633,2706,2780,2855,2931,3008,3086,3165,3245,3326,3408,3491,3575,3660,3746,3833,3921,4010,4100,4191,4283,4376,4470,4565,4661,4758,4856,4955,5055 add $0,2 bin $0,2 add $0,5
; ; This file is automatically generated ; ; Do not edit!!! ; ; djm 12/2/2000 ; ; ZSock Lib function: tcp_regcatchall XLIB tcp_regcatchall LIB no_zsock INCLUDE "packages.def" INCLUDE "zsock.def" .tcp_regcatchall ld a,r_tcp_regcatchall call_pkg(tcp_all) ret nc ; We failed..are we installed? cp rc_pnf scf ;signal error ret nz ;Internal error call_pkg(tcp_ayt) jr nc,tcp_regcatchall jp no_zsock
; A217221: Theta series of Kagome net with respect to a deep hole. ; Submitted by Christian Krause ; 0,6,0,6,0,0,0,12,0,6,0,0,0,12,0,0,0,0,0,12,0,12,0,0,0,6,0,6,0,0,0,12,0,0,0,0,0,12,0,12,0,0,0,12,0,0,0,0,0,18,0,0,0,0,0,0,0,12,0,0,0,12,0,12,0,0,0,12,0,0,0,0,0,12,0,6,0,0,0,12,0,6,0,0,0,0,0,0,0,0,0,24,0,12,0,0,0,12,0,0 mov $2,$0 seq $0,4016 ; Theta series of planar hexagonal lattice A_2. mod $2,2 mul $0,$2
/*Copyright 2010-2012 George Karagoulis Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ #include <QtCore/QString> #include <QtTest/QtTest> #include "gutil_icollections.h" #include "gutil_vector.h" #include "gutil_list.h" #include "gutil_dlist.h" #include "gutil_slist.h" USING_NAMESPACE_GUTIL; class QueueTest : public QObject { Q_OBJECT public: QueueTest(); private Q_SLOTS: void test_vectorQueue(); void test_listQueue(); void test_slistQueue(); void test_dlistQueue(); private: void _test_queue(Queue<int> &q); }; QueueTest::QueueTest() { } void QueueTest::test_vectorQueue() { VectorQueue<int> q; _test_queue(q); } void QueueTest::test_listQueue() { ListQueue<int> q; _test_queue(q); } void QueueTest::test_slistQueue() { SListQueue<int> q; _test_queue(q); } void QueueTest::test_dlistQueue() { DListQueue<int> q; _test_queue(q); } #define ITEM_COUNT 10000 void QueueTest::_test_queue(Queue<int> &q) { for(int i(0); i < ITEM_COUNT; ++i) { q.Enqueue(i); QVERIFY(q.CountQueueItems() == (i + 1)); // Check both front functions for correctness QVERIFY(q.Front() == 0); QVERIFY(const_cast<const Queue<int> &>(q).Front() == 0); } for(int i(0); i < ITEM_COUNT; ++i) { // Check both front functions for correctness QVERIFY(q.Front() == i); QVERIFY(const_cast<const Queue<int> &>(q).Front() == i); QVERIFY(q.CountQueueItems() == (ITEM_COUNT - i)); q.Dequeue(); } const int cnt( 10 ); for(int i(0); i < cnt; i++) { q.Enqueue(i); } QVERIFY(q.CountQueueItems() == cnt); q.FlushQueue(); QVERIFY(q.CountQueueItems() == 0); } QTEST_APPLESS_MAIN(QueueTest); #include "tst_queuetest.moc"
; this sample shows how to use scasw instruction to find a word (2 bytes). org 100h jmp start dat1 dw 1234h, 5678h, 9075h, 3456h find_what equ 9075h s_found db '"yes" - found!', 0Dh,0Ah, '$' s_not db '"no" - not found!', 0Dh,0Ah, '$' start: ; set forward direction: cld ; set counter to data size: mov cx, 4 ; load string address into es:di mov ax, cs mov es, ax lea di, dat1 ; we will look for the word in data string: mov ax, find_what repne scasw jz found not_found: ; "no" - not found! mov dx, offset s_not mov ah, 9 int 21h jmp exit_here found: ; "yes" - found! mov dx, offset s_found mov ah, 9 int 21h ; di contains the address of searched word: dec di ; wait for any key press... mov ah, 0 int 16h exit_here: ret ; return control to operating system...
#include <iostream> using namespace std; int mergeBits(int m, int n, int start, int end) { if(start<0 || start>32 || end<0 || end>32) { return -1; } int max = ~0; //all 1 int left = max - (1<<end -1); //111000000 int right = 1<<start -1; //000000011 int mask = left | right; //111000011 return (n&mask) | (m<<start); } int main() { int m = 21; //10101 int n = 193; //11000001 cout <<"result is : "<<mergeBits(m, n, 2, 6)<<endl; }
; A127328: Inverse binomial transform of A026641; binomial transform of A127361. ; Submitted by Christian Krause ; 1,0,3,3,15,30,99,252,747,2064,5973,16995,49089,141414,409755,1188243,3455811,10064952,29368377,85809681,251067645,735446106,2156695533,6330729438,18600079221,54693760680,160951905819,473984678037,1396755865527,4118553190254,12151196262939,35869669573308,105938809336371,313032084569856,925372414848393,2736699305672817,8096741765540589,23963862919633818,70950930393211833,210138753648888444,622577833606168017,1845074018260203600,5469658978747179231,16219114673138922321,48107080199477432115 add $0,1 lpb $0 sub $0,1 mov $2,$1 bin $2,$0 trn $0,1 mov $3,$4 bin $3,$1 add $1,1 mul $3,$2 add $4,3 add $5,$3 lpe mov $0,$5
; ; CPC Maths Routines ; ; August 2003 **_|warp6|_** <kbaccam /at/ free.fr> ; ; $Id: sin.asm,v 1.2 2009/06/22 21:44:17 dom Exp $ ; INCLUDE "cpcfirm.def" INCLUDE "cpcfp.def" XLIB sin XDEF sinc LIB get_para .sin call get_para call firmware .sinc defw CPCFP_FLO_SIN ret
;******************************************************************************************************** ; uC/OS-II ; The Real-Time Kernel ; ; Copyright 1992-2020 Silicon Laboratories Inc. www.silabs.com ; ; SPDX-License-Identifier: APACHE-2.0 ; ; This software is subject to an open source license and is distributed by ; Silicon Laboratories Inc. pursuant to the terms of the Apache License, ; Version 2.0 available at www.apache.org/licenses/LICENSE-2.0. ; ;******************************************************************************************************** ;******************************************************************************************************** ; ; ARMv7-R Port ; ; Filename : os_cpu_a_vfp-none.asm ; Version : V2.93.00 ;******************************************************************************************************** ; For : ARMv7-R Cortex-R ; Mode : ARM or Thumb ; Toolchain : IAR EWARM V5.xx and higher ;******************************************************************************************************** ; Note(s) : (1) See Note #2 of os_cpu.h for important informations about this file. ;******************************************************************************************************** ;******************************************************************************************************** ; EXTERNAL REFERENCE ;******************************************************************************************************** ; External references. EXTERN OSRunning EXTERN OSPrioCur EXTERN OSPrioHighRdy EXTERN OSTCBCur EXTERN OSTCBHighRdy EXTERN OSIntNesting EXTERN OSIntExit EXTERN OSTaskSwHook EXTERN OS_CPU_ExceptStkBase EXTERN OS_CPU_ExceptStkPtr EXTERN OS_CPU_ExceptHndlr ; Chip Support/BSP specific exception handler. ;******************************************************************************************************** ; FUNCTIONS ;******************************************************************************************************** ; Functions declared in this file. PUBLIC OS_CPU_SR_Save PUBLIC OS_CPU_SR_Restore PUBLIC OSStartHighRdy PUBLIC OSCtxSw PUBLIC OSIntCtxSw ; Functions related to exception handling. PUBLIC OS_CPU_ARM_ExceptUndefInstrHndlr PUBLIC OS_CPU_ARM_ExceptSwiHndlr PUBLIC OS_CPU_ARM_ExceptPrefetchAbortHndlr PUBLIC OS_CPU_ARM_ExceptDataAbortHndlr PUBLIC OS_CPU_ARM_ExceptIrqHndlr PUBLIC OS_CPU_ARM_ExceptFiqHndlr PUBLIC OS_CPU_SR_INT_Dis PUBLIC OS_CPU_SR_INT_En PUBLIC OS_CPU_SR_FIQ_Dis PUBLIC OS_CPU_SR_FIQ_En PUBLIC OS_CPU_SR_IRQ_Dis PUBLIC OS_CPU_SR_IRQ_En PUBLIC OS_CPU_ARM_DRegCntGet ;******************************************************************************************************** ; EQUATES ;******************************************************************************************************** OS_CPU_ARM_CONTROL_INT_DIS EQU 0xC0 ; Disable both FIQ and IRQ. OS_CPU_ARM_CONTROL_FIQ_DIS EQU 0x40 ; Disable FIQ. OS_CPU_ARM_CONTROL_IRQ_DIS EQU 0x80 ; Disable IRQ. OS_CPU_ARM_CONTROL_THUMB EQU 0x20 ; Set THUMB mode. OS_CPU_ARM_CONTROL_ARM EQU 0x00 ; Set ARM mode. OS_CPU_ARM_MODE_MASK EQU 0x1F OS_CPU_ARM_MODE_USR EQU 0x10 OS_CPU_ARM_MODE_FIQ EQU 0x11 OS_CPU_ARM_MODE_IRQ EQU 0x12 OS_CPU_ARM_MODE_SVC EQU 0x13 OS_CPU_ARM_MODE_ABT EQU 0x17 OS_CPU_ARM_MODE_UND EQU 0x1B OS_CPU_ARM_MODE_SYS EQU 0x1F OS_CPU_ARM_EXCEPT_RESET EQU 0x00 OS_CPU_ARM_EXCEPT_UNDEF_INSTR EQU 0x01 OS_CPU_ARM_EXCEPT_SWI EQU 0x02 OS_CPU_ARM_EXCEPT_PREFETCH_ABORT EQU 0x03 OS_CPU_ARM_EXCEPT_DATA_ABORT EQU 0x04 OS_CPU_ARM_EXCEPT_ADDR_ABORT EQU 0x05 OS_CPU_ARM_EXCEPT_IRQ EQU 0x06 OS_CPU_ARM_EXCEPT_FIQ EQU 0x07 OS_CPU_ARM_FPEXC_EN EQU 0x40000000 ;******************************************************************************************************** ; CODE GENERATION DIRECTIVES ;******************************************************************************************************** RSEG CODE:CODE:NOROOT(2) AAPCS INTERWORK PRESERVE8 REQUIRE8 CODE32 ;******************************************************************************************************** ; CRITICAL SECTION METHOD 3 FUNCTIONS ; ; Description: Disable/Enable interrupts by preserving the state of interrupts. Generally speaking you ; would store the state of the interrupt disable flag in the local variable 'cpu_sr' and then ; disable interrupts. 'cpu_sr' is allocated in all of uC/OS-II's functions that need to ; disable interrupts. You would restore the interrupt disable state by copying back 'cpu_sr' ; into the CPU's status register. ; ; Prototypes : OS_CPU_SR OS_CPU_SR_Save (void); ; void OS_CPU_SR_Restore (OS_CPU_SR os_cpu_sr); ; ; ; Note(s) : (1) These functions are used in general like this: ; ; void Task (void *p_arg) ; { ; /* Allocate storage for CPU status register. */ ; #if (OS_CRITICAL_METHOD == 3) ; OS_CPU_SR os_cpu_sr; ; #endif ; ; : ; : ; OS_ENTER_CRITICAL(); /* os_cpu_sr = OS_CPU_SR_Save(); */ ; : ; : ; OS_EXIT_CRITICAL(); /* OS_CPU_SR_Restore(cpu_sr); */ ; : ; : ; } ;******************************************************************************************************** OS_CPU_SR_Save MRS R0, CPSR CPSID IF ; Set IRQ & FIQ bits in CPSR to DISABLE all interrupts DSB BX LR ; DISABLED, return the original CPSR contents in R0 OS_CPU_SR_Restore ; See Note #2 DSB MSR CPSR_c, R0 BX LR ;******************************************************************************************************** ; START MULTITASKING ; void OSStartHighRdy(void) ; ; Note(s) : 1) OSStartHighRdy() MUST: ; a) Call OSTaskSwHook() then, ; b) Set OSRunning to OS_STATE_OS_RUNNING, ; c) Switch to the highest priority task. ;******************************************************************************************************** OSStartHighRdy ; Change to SVC mode. MSR CPSR_c, #(OS_CPU_ARM_CONTROL_INT_DIS | OS_CPU_ARM_MODE_SVC) CLREX ; Clear exclusive monitor. BL OSTaskSwHook ; OSTaskSwHook(); MOV32 R0, OSRunning ; OSRunning = TRUE; MOV R1, #1 STRB R1, [R0] ; SWITCH TO HIGHEST PRIORITY TASK: MOV32 R0, OSTCBHighRdy ; Get highest priority task TCB address, LDR R0, [R0] ; Get stack pointer, LDR SP, [R0] ; Switch to the new stack, LDR R0, [SP], #4 ; Pop new task's CPSR, MSR SPSR_cxsf, R0 LDMFD SP!, {R0-R12, LR, PC}^ ; Pop new task's context. ;******************************************************************************************************** ; PERFORM A CONTEXT SWITCH (From task level) - OSCtxSw() ; ; Note(s) : 1) OSCtxSw() is called in SVC mode with BOTH FIQ and IRQ interrupts DISABLED. ; ; 2) The pseudo-code for OSCtxSw() is: ; a) Save the current task's context onto the current task's stack, ; b) OSTCBCur->StkPtr = SP; ; c) OSTaskSwHook(); ; d) OSPrioCur = OSPrioHighRdy; ; e) OSTCBCurPtr = OSTCBHighRdy; ; f) SP = OSTCBHighRdy->StkPtr; ; g) Restore the new task's context from the new task's stack, ; h) Return to new task's code. ; ; 3) Upon entry: ; OSTCBCurPtr points to the OS_TCB of the task to suspend, ; OSTCBHighRdyPtr points to the OS_TCB of the task to resume. ;******************************************************************************************************** OSCtxSw ; SAVE CURRENT TASK'S CONTEXT: STMFD SP!, {LR} ; Push return address, STMFD SP!, {LR} STMFD SP!, {R0-R12} ; Push registers, MRS R0, CPSR ; Push current CPSR, TST LR, #1 ; See if called from Thumb mode, ORRNE R0, R0, #OS_CPU_ARM_CONTROL_THUMB ; If yes, set the T-bit. STMFD SP!, {R0} CLREX ; Clear exclusive monitor. MOV32 R0, OSTCBCur ; OSTCBCur->StkPtr = SP; LDR R1, [R0] STR SP, [R1] BL OSTaskSwHook ; OSTaskSwHook(); MOV32 R0, OSPrioCur ; OSPrioCur = OSPrioHighRdy; MOV32 R1, OSPrioHighRdy LDRB R2, [R1] STRB R2, [R0] MOV32 R0, OSTCBCur ; OSTCBCur = OSTCBHighRdy; MOV32 R1, OSTCBHighRdy LDR R2, [R1] STR R2, [R0] LDR SP, [R2] ; SP = OSTCBHighRdy->OSTCBStkPtr; ; RESTORE NEW TASK'S CONTEXT: LDMFD SP!, {R0} ; Pop new task's CPSR, MSR SPSR_cxsf, R0 LDMFD SP!, {R0-R12, LR, PC}^ ; Pop new task's context. ;******************************************************************************************************** ; PERFORM A CONTEXT SWITCH (From interrupt level) - OSIntCtxSw() ; ; Note(s) : 1) OSIntCtxSw() is called in SVC mode with BOTH FIQ and IRQ interrupts DISABLED. ; ; 2) The pseudo-code for OSCtxSw() is: ; a) OSTaskSwHook(); ; b) OSPrioCur = OSPrioHighRdy; ; c) OSTCBCurPtr = OSTCBHighRdyPtr; ; d) SP = OSTCBHighRdyPtr->OSTCBStkPtr; ; e) Restore the new task's context from the new task's stack, ; f) Return to new task's code. ; ; 3) Upon entry: ; OSTCBCurPtr points to the OS_TCB of the task to suspend, ; OSTCBHighRdyPtr points to the OS_TCB of the task to resume. ;******************************************************************************************************** OSIntCtxSw BL OSTaskSwHook ; OSTaskSwHook(); MOV32 R0, OSPrioCur ; OSPrioCur = OSPrioHighRdy; MOV32 R1, OSPrioHighRdy LDRB R2, [R1] STRB R2, [R0] MOV32 R0, OSTCBCur ; OSTCBCurPtr = OSTCBHighRdy; MOV32 R1, OSTCBHighRdy LDR R2, [R1] STR R2, [R0] LDR SP, [R2] ; SP = OSTCBHighRdyPtr->OSTCBStkPtr; ; RESTORE NEW TASK'S CONTEXT: LDMFD SP!, {R0} ; Pop new task's CPSR, MSR SPSR_cxsf, R0 LDMFD SP!, {R0-R12, LR, PC}^ ; Pop new task's context. ;******************************************************************************************************** ; UNDEFINED INSTRUCTION EXCEPTION HANDLER ; ; Register Usage: R0 Exception Type ; R1 ; R2 Return PC ;******************************************************************************************************** OS_CPU_ARM_ExceptUndefInstrHndlr ; LR offset to return from this exception: 0. STMFD SP!, {R0-R3} ; Push working registers. MOV R2, LR ; Save link register. MOV R0, #OS_CPU_ARM_EXCEPT_UNDEF_INSTR ; Set exception ID to OS_CPU_ARM_EXCEPT_UNDEF_INSTR. B OS_CPU_ARM_ExceptHndlr ; Branch to global exception handler. ;******************************************************************************************************** ; SOFTWARE INTERRUPT EXCEPTION HANDLER ; ; Register Usage: R0 Exception Type ; R1 ; R2 Return PC ;******************************************************************************************************** OS_CPU_ARM_ExceptSwiHndlr ; LR offset to return from this exception: 0. STMFD SP!, {R0-R3} ; Push working registers. MOV R2, LR ; Save link register. MOV R0, #OS_CPU_ARM_EXCEPT_SWI ; Set exception ID to OS_CPU_ARM_EXCEPT_SWI. B OS_CPU_ARM_ExceptHndlr ; Branch to global exception handler. ;******************************************************************************************************** ; PREFETCH ABORT EXCEPTION HANDLER ; ; Register Usage: R0 Exception Type ; R1 ; R2 Return PC ;******************************************************************************************************** OS_CPU_ARM_ExceptPrefetchAbortHndlr SUB LR, LR, #4 ; LR offset to return from this exception: -4. STMFD SP!, {R0-R3} ; Push working registers. MOV R2, LR ; Save link register. MOV R0, #OS_CPU_ARM_EXCEPT_PREFETCH_ABORT ; Set exception ID to OS_CPU_ARM_EXCEPT_PREFETCH_ABORT. B OS_CPU_ARM_ExceptHndlr ; Branch to global exception handler. ;******************************************************************************************************** ; DATA ABORT EXCEPTION HANDLER ; ; Register Usage: R0 Exception Type ; R1 ; R2 Return PC ;******************************************************************************************************** OS_CPU_ARM_ExceptDataAbortHndlr SUB LR, LR, #8 ; LR offset to return from this exception: -8. STMFD SP!, {R0-R3} ; Push working registers. MOV R2, LR ; Save link register. MOV R0, #OS_CPU_ARM_EXCEPT_DATA_ABORT ; Set exception ID to OS_CPU_ARM_EXCEPT_DATA_ABORT. B OS_CPU_ARM_ExceptHndlr ; Branch to global exception handler. ;******************************************************************************************************** ; ADDRESS ABORT EXCEPTION HANDLER ; ; Register Usage: R0 Exception Type ; R1 ; R2 Return PC ;******************************************************************************************************** OS_CPU_ARM_ExceptAddrAbortHndlr SUB LR, LR, #8 ; LR offset to return from this exception: -8. STMFD SP!, {R0-R3} ; Push working registers. MOV R2, LR ; Save link register. MOV R0, #OS_CPU_ARM_EXCEPT_ADDR_ABORT ; Set exception ID to OS_CPU_ARM_EXCEPT_ADDR_ABORT. B OS_CPU_ARM_ExceptHndlr ; Branch to global exception handler. ;******************************************************************************************************** ; INTERRUPT REQUEST EXCEPTION HANDLER ; ; Register Usage: R0 Exception Type ; R1 ; R2 Return PC ;******************************************************************************************************** OS_CPU_ARM_ExceptIrqHndlr SUB LR, LR, #4 ; LR offset to return from this exception: -4. STMFD SP!, {R0-R3} ; Push working registers. MOV R2, LR ; Save link register. MOV R0, #OS_CPU_ARM_EXCEPT_IRQ ; Set exception ID to OS_CPU_ARM_EXCEPT_IRQ. B OS_CPU_ARM_ExceptHndlr ; Branch to global exception handler. ;******************************************************************************************************** ; FAST INTERRUPT REQUEST EXCEPTION HANDLER ; ; Register Usage: R0 Exception Type ; R1 ; R2 Return PC ;******************************************************************************************************** OS_CPU_ARM_ExceptFiqHndlr SUB LR, LR, #4 ; LR offset to return from this exception: -4. STMFD SP!, {R0-R3} ; Push working registers. MOV R2, LR ; Save link register. MOV R0, #OS_CPU_ARM_EXCEPT_FIQ ; Set exception ID to OS_CPU_ARM_EXCEPT_FIQ. B OS_CPU_ARM_ExceptHndlr ; Branch to global exception handler. ;******************************************************************************************************** ; GLOBAL EXCEPTION HANDLER ; ; Register Usage: R0 Exception Type ; R1 Exception's SPSR ; R2 Return PC ; R3 Exception's SP ; ; Note(s) : 1) An exception can occur in three different circumstances; in each of these, the ; SVC stack pointer will point to a different entity : ; ; a) CONDITION: An exception occurs before the OS has been fully initialized. ; SVC STACK: Should point to a stack initialized by the application's startup code. ; STK USAGE: Interrupted context -- SVC stack. ; Exception -- SVC stack. ; Nested exceptions -- SVC stack. ; ; b) CONDITION: An exception interrupts a task. ; SVC STACK: Should point to task stack. ; STK USAGE: Interrupted context -- Task stack. ; Exception -- Exception stack 'OS_CPU_ExceptStk[]'. ; Nested exceptions -- Exception stack 'OS_CPU_ExceptStk[]'. ; ; c) CONDITION: An exception interrupts another exception. ; SVC STACK: Should point to location in exception stack, 'OS_CPU_ExceptStk[]'. ; STK USAGE: Interrupted context -- Exception stack 'OS_CPU_ExceptStk[]'. ; Exception -- Exception stack 'OS_CPU_ExceptStk[]'. ; Nested exceptions -- Exception stack 'OS_CPU_ExceptStk[]'. ;******************************************************************************************************** OS_CPU_ARM_ExceptHndlr MRS R1, SPSR ; Save CPSR (i.e. exception's SPSR). MOV R3, SP ; Save exception's stack pointer. ; Adjust exception stack pointer. This is needed because ; exception stack is not used when restoring task context. ADD SP, SP, #(4 * 4) ; Change to SVC mode & disable interruptions. MSR CPSR_c, #(OS_CPU_ARM_CONTROL_INT_DIS | OS_CPU_ARM_MODE_SVC) CLREX ; Clear exclusive monitor. STMFD SP!, {R2} ; Push task's PC, STMFD SP!, {LR} ; Push task's LR, STMFD SP!, {R4-R12} ; Push task's R12-R4, LDMFD R3!, {R5-R8} ; Move task's R3-R0 from exception stack to task's stack. STMFD SP!, {R5-R8} STMFD SP!, {R1} ; Push task's CPSR (i.e. exception SPSR). ; if (OSRunning == 1) MOV32 R3, OSRunning LDRB R4, [R3] CMP R4, #1 BNE OS_CPU_ARM_ExceptHndlr_BreakNothing ; HANDLE NESTING COUNTER: MOV32 R3, OSIntNesting ; OSIntNesting++; LDRB R4, [R3] ADD R4, R4, #1 STRB R4, [R3] CMP R4, #1 ; if (OSIntNesting == 1) BNE OS_CPU_ARM_ExceptHndlr_BreakExcept ;******************************************************************************************************** ; EXCEPTION HANDLER: TASK INTERRUPTED ; ; Register Usage: R0 Exception Type ; R1 ; R2 ; R3 ;******************************************************************************************************** OS_CPU_ARM_ExceptHndlr_BreakTask MOV32 R3, OSTCBCur ; OSTCBCurPtr->StkPtr = SP; LDR R4, [R3] STR SP, [R4] MOV32 R3, OS_CPU_ExceptStkBase ; Switch to exception stack. LDR SP, [R3] ; EXECUTE EXCEPTION HANDLER: BL OS_CPU_ExceptHndlr ; OS_CPU_ExceptHndlr(except_type = R0) ; Change to SVC mode & disable interruptions. MSR CPSR_c, #(OS_CPU_ARM_CONTROL_INT_DIS | OS_CPU_ARM_MODE_SVC) ; Call OSIntExit(). This call MAY never return if a ready ; task with higher priority than the interrupted one is ; found. BL OSIntExit MOV32 R3, OSTCBCur ; SP = OSTCBCurPtr->StkPtr; LDR R4, [R3] LDR SP, [R4] ; RESTORE NEW TASK'S CONTEXT: LDMFD SP!, {R0} ; Pop new task's CPSR, MSR SPSR_cxsf, R0 LDMFD SP!, {R0-R12, LR, PC}^ ; Pop new task's context. ;******************************************************************************************************** ; EXCEPTION HANDLER: EXCEPTION INTERRUPTED ; ; Register Usage: R0 Exception Type ; R1 ; R2 ; R3 ;******************************************************************************************************** OS_CPU_ARM_ExceptHndlr_BreakExcept MOV R1, SP AND R1, R1, #4 SUB SP, SP, R1 STMFD SP!, {R1, LR} ; EXECUTE EXCEPTION HANDLER: BL OS_CPU_ExceptHndlr ; OS_CPU_ExceptHndlr(except_type = R0) LDMIA SP!, {R1, LR} ADD SP, SP, R1 ; Change to SVC mode & disable interruptions. MSR CPSR_c, #(OS_CPU_ARM_CONTROL_INT_DIS | OS_CPU_ARM_MODE_SVC) ; HANDLE NESTING COUNTER: MOV32 R3, OSIntNesting ; OSIntNestingCtr--; LDRB R4, [R3] SUB R4, R4, #1 STRB R4, [R3] ; RESTORE OLD CONTEXT: LDMFD SP!, {R0} ; Pop old CPSR, MSR SPSR_cxsf, R0 LDMFD SP!, {R0-R12, LR, PC}^ ; Pull working registers and return from exception. ;******************************************************************************************************** ; EXCEPTION HANDLER: 'NOTHING' INTERRUPTED ; ; Register Usage: R0 Exception Type ; R1 ; R2 ; R3 ;******************************************************************************************************** OS_CPU_ARM_ExceptHndlr_BreakNothing MOV R1, SP AND R1, R1, #4 SUB SP, SP, R1 STMFD SP!, {R1, LR} ; EXECUTE EXCEPTION HANDLER: BL OS_CPU_ExceptHndlr ; OS_CPU_ExceptHndlr(except_type = R0) LDMIA SP!, {R1, LR} ADD SP, SP, R1 ; Change to SVC mode & disable interruptions. MSR CPSR_c, #(OS_CPU_ARM_CONTROL_INT_DIS | OS_CPU_ARM_MODE_SVC) ; RESTORE OLD CONTEXT: LDMFD SP!, {R0} ; Pop old CPSR, MSR SPSR_cxsf, R0 LDMFD SP!, {R0-R12, LR, PC}^ ; Pull working registers and return from exception. ;******************************************************************************************************** ;******************************************************************************************************** ; ENABLE & DISABLE INTERRUPTS, IRQs, FIQs ;******************************************************************************************************** ;******************************************************************************************************** ;******************************************************************************************************** ; ENABLE & DISABLE INTERRUPTS ; ; Note(s) : 1) OS_CPU_SR_INT_En() can be called by OS_CPU_ExceptHndlr() AFTER the external ; interrupt source has been cleared. This function will enable IRQs and FIQs so that ; nesting can occur. ; ; 2) OS_CPU_ARM_INT_Dis() can be called to disable IRQs and FIQs so that nesting will not occur. ;******************************************************************************************************** OS_CPU_SR_INT_En DSB MRS R0, CPSR BIC R0, R0, #OS_CPU_ARM_CONTROL_INT_DIS ; Clear IRQ and FIQ bits in CPSR to enable all interrupts. MSR CPSR_c, R0 BX LR OS_CPU_SR_INT_Dis MRS R0, CPSR ORR R0, R0, #OS_CPU_ARM_CONTROL_INT_DIS ; Set IRQ and FIQ bits in CPSR to disable all interrupts. MSR CPSR_c, R0 DSB BX LR ;******************************************************************************************************** ; ENABLE & DISABLE IRQs ; ; Note(s) : 1) OS_CPU_SR_IRQ_En() can be called by OS_CPU_ExceptHndlr() AFTER the external ; interrupt source has been cleared. This function will enable IRQs so that IRQ nesting ; can occur. ; ; 2) OS_CPU_ARM_IRQ_Dis() can be called to disable IRQs so that IRQ nesting will not occur. ;******************************************************************************************************** OS_CPU_SR_IRQ_En DSB MRS R0, CPSR BIC R0, R0, #OS_CPU_ARM_CONTROL_IRQ_DIS ; Clear IRQ bit in CPSR to enable IRQs. MSR CPSR_c, R0 BX LR OS_CPU_SR_IRQ_Dis MRS R0, CPSR ORR R0, R0, #OS_CPU_ARM_CONTROL_IRQ_DIS ; Set IRQ bit in CPSR to disable IRQs. MSR CPSR_c, R0 DSB BX LR ;******************************************************************************************************** ; ENABLE & DISABLE FIQs ; ; Note(s) : 1) OS_CPU_SR_FIQ_En() can be called by OS_CPU_ExceptHndlr() AFTER the external ; interrupt source has been cleared. This function will enable FIQs so that FIQ nesting ; can occur. ; ; 2) OS_CPU_ARM_FIQ_Dis() can be called to disable FIQs so that FIQ nesting will not occur. ;******************************************************************************************************** OS_CPU_SR_FIQ_En DSB MRS R0, CPSR BIC R0, R0, #OS_CPU_ARM_CONTROL_FIQ_DIS ; Clear FIQ bit in CPSR to enable FIQs. MSR CPSR_c, R0 BX LR OS_CPU_SR_FIQ_Dis MRS R0, CPSR ORR R0, R0, #OS_CPU_ARM_CONTROL_FIQ_DIS ; Set FIQ bit in CPSR to disable FIQs. MSR CPSR_c, R0 DSB BX LR ;******************************************************************************************************** ; VFP/NEON REGISTER COUNT ; ; Register Usage: R0 Double Register Count ;******************************************************************************************************** OS_CPU_ARM_DRegCntGet MOV R0, #0 BX LR END
CeladonPokecenterObject: db $0 ; border block db $2 ; warps db $7, $3, $5, $ff db $7, $4, $5, $ff db $0 ; signs db $4 ; objects object SPRITE_NURSE, $3, $1, STAY, DOWN, $1 ; person object SPRITE_GENTLEMAN, $7, $3, WALK, $2, $2 ; person object SPRITE_FOULARD_WOMAN, $a, $5, WALK, $0, $3 ; person object SPRITE_NURSE, $b, $2, STAY, DOWN, $4 ; person ; warp-to EVENT_DISP CELADON_POKECENTER_WIDTH, $7, $3 EVENT_DISP CELADON_POKECENTER_WIDTH, $7, $4
; A053088: a(n) = 3*a(n-2) + 2*a(n-3) for n > 2, a(0)=1, a(1)=0, a(2)=3. ; Submitted by Jon Maiga ; 1,0,3,2,9,12,31,54,117,224,459,906,1825,3636,7287,14558,29133,58248,116515,233010,466041,932060,1864143,3728262,7456549,14913072,29826171,59652314,119304657,238609284,477218599,954437166,1908874365,3817748696,7635497427,15270994818,30541989673,61083979308,122167958655,244335917270,488671834581,977343669120,1954687338283,3909374676522,7818749353089,15637498706132,31274997412311,62549994824574,125099989649197,250199979298344,500399958596739,1000799917193426,2001599834386905,4003199668773756 add $0,2 mov $1,-2 pow $1,$0 sub $1,1 div $1,3 add $1,$0 gcd $2,$1 mov $0,$2 div $0,3
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r14 push %r15 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_WT_ht+0x1abf8, %r13 nop nop and %r9, %r9 mov (%r13), %r11 nop nop xor %r15, %r15 lea addresses_WC_ht+0x692e, %r14 nop nop nop add %rbx, %rbx movw $0x6162, (%r14) nop nop nop nop inc %r14 lea addresses_D_ht+0xca76, %rsi lea addresses_UC_ht+0xc39a, %rdi nop nop nop add %r13, %r13 mov $42, %rcx rep movsq nop nop nop nop nop dec %r14 lea addresses_UC_ht+0x176a2, %rsi clflush (%rsi) inc %r14 movups (%rsi), %xmm4 vpextrq $1, %xmm4, %r13 nop nop nop xor $15235, %r15 lea addresses_normal_ht+0x5b2, %r9 nop nop add %r13, %r13 mov $0x6162636465666768, %r14 movq %r14, %xmm7 vmovups %ymm7, (%r9) nop nop nop inc %r14 lea addresses_A_ht+0x5a02, %rbx dec %r9 mov $0x6162636465666768, %r11 movq %r11, %xmm6 movups %xmm6, (%rbx) nop nop nop and $61626, %r9 lea addresses_normal_ht+0x1319a, %rcx nop nop nop nop nop cmp %r11, %r11 mov (%rcx), %r14w nop nop cmp %r15, %r15 lea addresses_A_ht+0x9562, %rsi lea addresses_normal_ht+0x102a2, %rdi nop nop nop nop nop sub %rbx, %rbx mov $81, %rcx rep movsl nop nop nop add %rbx, %rbx lea addresses_D_ht+0x9b48, %r14 clflush (%r14) nop nop nop cmp %rdi, %rdi movb (%r14), %r9b nop add %rsi, %rsi lea addresses_normal_ht+0x109a2, %rsi xor %r13, %r13 mov $0x6162636465666768, %r14 movq %r14, %xmm2 movups %xmm2, (%rsi) nop nop nop and $10868, %rsi lea addresses_D_ht+0x112a2, %r11 nop nop nop add %rcx, %rcx movb (%r11), %bl nop nop nop nop xor %r11, %r11 lea addresses_A_ht+0x1c8a2, %rdi nop add $53662, %r14 mov $0x6162636465666768, %rcx movq %rcx, %xmm2 vmovups %ymm2, (%rdi) add $42381, %rbx lea addresses_normal_ht+0x598e, %r14 nop nop xor %r13, %r13 mov (%r14), %rbx nop nop nop sub $64459, %r15 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r15 pop %r14 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r9 push %rax push %rbx push %rdi push %rdx // Store lea addresses_normal+0x8ea2, %rbx nop nop nop sub $10131, %r9 mov $0x5152535455565758, %rdi movq %rdi, (%rbx) nop nop nop xor $53194, %r14 // Faulty Load lea addresses_PSE+0x1c4a2, %rbx nop add $21620, %rax mov (%rbx), %edx lea oracles, %rdi and $0xff, %rdx shlq $12, %rdx mov (%rdi,%rdx,1), %rdx pop %rdx pop %rdi pop %rbx pop %rax pop %r9 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_PSE', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal', 'congruent': 8}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_PSE', 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WT_ht', 'congruent': 1}} {'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 2, 'type': 'addresses_WC_ht', 'congruent': 2}, 'OP': 'STOR'} {'dst': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_D_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_UC_ht', 'congruent': 8}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_normal_ht', 'congruent': 4}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_A_ht', 'congruent': 4}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal_ht', 'congruent': 3}} {'dst': {'same': False, 'congruent': 8, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_A_ht'}} {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': True, 'size': 1, 'type': 'addresses_D_ht', 'congruent': 1}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal_ht', 'congruent': 6}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_D_ht', 'congruent': 5}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_A_ht', 'congruent': 3}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal_ht', 'congruent': 0}} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
.orig x0 ld r3, four test_lsl: ld r0, lsl_test_val ld r1, lsl_test_expected lsl r0, r0, r3 xor r0, r0, r1 brnp fail test_lsr: ld r0, lsr_test_val ld r1, lsr_test_expected lsr r0, r0, r3 xor r0, r0, r1 brnp fail done: out r0, #0 fail: br fail lsl_test_val .fill xFFFF lsl_test_expected .fill xFFF0 lsr_test_val .fill xF000 lsr_test_expected .fill x0F00 rshfa_test_val .fill xF000 rshfa_test_expected .fill xFF00 four .fill 4 .end
; Z88 Small C+ Run Time Library ; Long functions ; XLIB l_long_ule LIB l_long_ucmp ; ;......logical operations: HL set to 0 (false) or 1 (true) ; ; DE <= HL [unsigned] .l_long_ule call l_long_ucmp ret c scf ret z ccf dec hl ret
; file: day1_part2_asm.asm ; Searches for three values whose sum is 2020 in list of 32-bit unsigned integers, ; and returns the product of the three values. segment .text global day1_part2_asm ; Parameters: ; #1 (EBP+8): Pointer to data ; #2: (EBP+12): Number of elements ; ; Local variables: ; #1 (EBP-4): Outer loop counter ; #2 (EBP-8): Inner loop counter ; #3 (EBP-12): Innermost loop counter ; ; Return value: Product of the first three elements in the data that add up to 2020. Zero is returned if not found. day1_part2_asm: push ebp ; Save the old base pointer value. mov ebp, esp ; Set the new base pointer value. sub esp, 12 ; Make room for three 4-byte local variable. ; Save the values of registers that the function ; will modify. This function uses EBX push ebx ; Subroutine Body ;mov esi, [ebp+8] ; Set ESI to base address of data mov dword [ebp-4], 0 ; Initialize outer loop counter outer_loop: ;mov edi, [ebp+8] ; Set EDI to base address of data mov dword [ebp-8], 0 ; Initialize inner loop counter inner_loop: mov eax, [ebp-4] cmp eax, [ebp-8] ; Don't compare elements of same idnex je inner_loop_next mov dword [ebp-12], 0 ; Initialize innermost loop counter innermost_loop: mov eax, [ebp-4] cmp eax, [ebp-12] je innermost_loop_next mov eax, [ebp-8] cmp eax, [ebp-12] je innermost_loop_next ; Get element from outer loop mov eax, [ebp-4] ; Element num shl eax, 2 ; Multiply by 4 - 4 bytes per element add eax, [ebp+8] ; Add base address ; Get element from inner loop mov ebx, [ebp-8] shl ebx, 2 add ebx, [ebp+8] ; Get element from innermost loop mov ecx, [ebp-12] shl ecx, 2 add ecx, [ebp+8] mov eax, [eax] add eax, [ebx] add eax, [ecx] cmp dword eax, 2020 je match_found innermost_loop_next: add dword [ebp-12], 1 ; Increase innermost loop mov eax, [ebp-12] cmp eax, [ebp+12] ; Compare innermost loop counter with num elements jne innermost_loop inner_loop_next: add dword [ebp-8], 1 ; Increase inner loop mov eax, [ebp-8] cmp eax, [ebp+12] ; Compare inner loop counter with num elements jne inner_loop outer_loop_next: add dword [ebp-4], 1 ; Increase outer loop mov eax, [ebp-4] cmp eax, [ebp+12] ; Compare outer loop counter with num elements je match_not_found ; Searched all elements, no match jmp outer_loop match_found: ; Get element from outer loop mov eax, [ebp-4] ; Element num shl eax, 2 ; Multiply by 4 - 4 bytes per element add eax, [ebp+8] ; Add base address ; Get element from inner loop mov ebx, [ebp-8] shl ebx, 2 add ebx, [ebp+8] ; Get element from innermost loop mov ecx, [ebp-12] shl ecx, 2 add ecx, [ebp+8] ; Multiply elements mov eax, [eax] mul dword [ebx] mul dword [ecx] jmp done match_not_found: mov eax, 0 done: ; Subroutine Epilogue pop ebx ; Recover register values mov esp, ebp ; Deallocate local variables pop ebp ; Restore the caller's base pointer value ret
;/* ; * Microsoft Confidential ; * Copyright (C) Microsoft Corporation 1991 ; * All Rights Reserved. ; */ ;*************************************************** ; CHARACTER FONT FILE ; Source Assembler File ; ; CODE PAGE: 850 ; FONT RESOLUTION: 8 x 8 ; ; DATE CREATED:05-28-1987 ; ; ; Output file from: MULTIFON, Version 1A ; ;*************************************************** Db 000h,000h,000h,000h,000h,000h,000h,000h ; Hex #0 Db 07Eh,081h,0A5h,081h,0BDh,099h,081h,07Eh ; Hex #1 Db 07Eh,0FFh,0DBh,0FFh,0C3h,0E7h,0FFh,07Eh ; Hex #2 Db 06Ch,0FEh,0FEh,0FEh,07Ch,038h,010h,000h ; Hex #3 Db 010h,038h,07Ch,0FEh,07Ch,038h,010h,000h ; Hex #4 Db 038h,07Ch,038h,0FEh,0FEh,0D6h,010h,038h ; Hex #5 Db 010h,038h,07Ch,0FEh,0FEh,07Ch,010h,038h ; Hex #6 Db 000h,000h,018h,03Ch,03Ch,018h,000h,000h ; Hex #7 Db 0FFh,0FFh,0E7h,0C3h,0C3h,0E7h,0FFh,0FFh ; Hex #8 Db 000h,03Ch,066h,042h,042h,066h,03Ch,000h ; Hex #9 Db 0FFh,0C3h,099h,0BDh,0BDh,099h,0C3h,0FFh ; Hex #A Db 00Fh,007h,00Fh,07Dh,0CCh,0CCh,0CCh,078h ; Hex #B Db 03Ch,066h,066h,066h,03Ch,018h,07Eh,018h ; Hex #C Db 03Fh,033h,03Fh,030h,030h,070h,0F0h,0E0h ; Hex #D Db 07Fh,063h,07Fh,063h,063h,067h,0E6h,0C0h ; Hex #E Db 018h,0DBh,03Ch,0E7h,0E7h,03Ch,0DBh,018h ; Hex #F Db 080h,0E0h,0F8h,0FEh,0F8h,0E0h,080h,000h ; Hex #10 Db 002h,00Eh,03Eh,0FEh,03Eh,00Eh,002h,000h ; Hex #11 Db 018h,03Ch,07Eh,018h,018h,07Eh,03Ch,018h ; Hex #12 Db 066h,066h,066h,066h,066h,000h,066h,000h ; Hex #13 Db 07Fh,0DBh,0DBh,07Bh,01Bh,01Bh,01Bh,000h ; Hex #14 Db 03Eh,061h,03Ch,066h,066h,03Ch,086h,07Ch ; Hex #15 Db 000h,000h,000h,000h,07Eh,07Eh,07Eh,000h ; Hex #16 Db 018h,03Ch,07Eh,018h,07Eh,03Ch,018h,0FFh ; Hex #17 Db 018h,03Ch,07Eh,018h,018h,018h,018h,000h ; Hex #18 Db 018h,018h,018h,018h,07Eh,03Ch,018h,000h ; Hex #19 Db 000h,018h,00Ch,0FEh,00Ch,018h,000h,000h ; Hex #1A Db 000h,030h,060h,0FEh,060h,030h,000h,000h ; Hex #1B Db 000h,000h,0C0h,0C0h,0C0h,0FEh,000h,000h ; Hex #1C Db 000h,024h,066h,0FFh,066h,024h,000h,000h ; Hex #1D Db 000h,018h,03Ch,07Eh,0FFh,0FFh,000h,000h ; Hex #1E Db 000h,0FFh,0FFh,07Eh,03Ch,018h,000h,000h ; Hex #1F Db 000h,000h,000h,000h,000h,000h,000h,000h ; Hex #20 Db 018h,03Ch,03Ch,018h,018h,000h,018h,000h ; Hex #21 Db 066h,066h,024h,000h,000h,000h,000h,000h ; Hex #22 Db 06Ch,06Ch,0FEh,06Ch,0FEh,06Ch,06Ch,000h ; Hex #23 Db 018h,03Eh,060h,03Ch,006h,07Ch,018h,000h ; Hex #24 Db 000h,0C6h,0CCh,018h,030h,066h,0C6h,000h ; Hex #25 Db 038h,06Ch,038h,076h,0DCh,0CCh,076h,000h ; Hex #26 Db 018h,018h,030h,000h,000h,000h,000h,000h ; Hex #27 Db 00Ch,018h,030h,030h,030h,018h,00Ch,000h ; Hex #28 Db 030h,018h,00Ch,00Ch,00Ch,018h,030h,000h ; Hex #29 Db 000h,066h,03Ch,0FFh,03Ch,066h,000h,000h ; Hex #2A Db 000h,018h,018h,07Eh,018h,018h,000h,000h ; Hex #2B Db 000h,000h,000h,000h,000h,018h,018h,030h ; Hex #2C Db 000h,000h,000h,07Eh,000h,000h,000h,000h ; Hex #2D Db 000h,000h,000h,000h,000h,018h,018h,000h ; Hex #2E Db 006h,00Ch,018h,030h,060h,0C0h,080h,000h ; Hex #2F Db 038h,06Ch,0C6h,0D6h,0C6h,06Ch,038h,000h ; Hex #30 Db 018h,038h,018h,018h,018h,018h,07Eh,000h ; Hex #31 Db 07Ch,0C6h,006h,01Ch,030h,066h,0FEh,000h ; Hex #32 Db 07Ch,0C6h,006h,03Ch,006h,0C6h,07Ch,000h ; Hex #33 Db 01Ch,03Ch,06Ch,0CCh,0FEh,00Ch,01Eh,000h ; Hex #34 Db 0FEh,0C0h,0C0h,0FCh,006h,0C6h,07Ch,000h ; Hex #35 Db 038h,060h,0C0h,0FCh,0C6h,0C6h,07Ch,000h ; Hex #36 Db 0FEh,0C6h,00Ch,018h,030h,030h,030h,000h ; Hex #37 Db 07Ch,0C6h,0C6h,07Ch,0C6h,0C6h,07Ch,000h ; Hex #38 Db 07Ch,0C6h,0C6h,07Eh,006h,00Ch,078h,000h ; Hex #39 Db 000h,018h,018h,000h,000h,018h,018h,000h ; Hex #3A Db 000h,018h,018h,000h,000h,018h,018h,030h ; Hex #3B Db 006h,00Ch,018h,030h,018h,00Ch,006h,000h ; Hex #3C Db 000h,000h,07Eh,000h,000h,07Eh,000h,000h ; Hex #3D Db 060h,030h,018h,00Ch,018h,030h,060h,000h ; Hex #3E Db 07Ch,0C6h,00Ch,018h,018h,000h,018h,000h ; Hex #3F Db 07Ch,0C6h,0DEh,0DEh,0DEh,0C0h,078h,000h ; Hex #40 Db 038h,06Ch,0C6h,0FEh,0C6h,0C6h,0C6h,000h ; Hex #41 Db 0FCh,066h,066h,07Ch,066h,066h,0FCh,000h ; Hex #42 Db 03Ch,066h,0C0h,0C0h,0C0h,066h,03Ch,000h ; Hex #43 Db 0F8h,06Ch,066h,066h,066h,06Ch,0F8h,000h ; Hex #44 Db 0FEh,062h,068h,078h,068h,062h,0FEh,000h ; Hex #45 Db 0FEh,062h,068h,078h,068h,060h,0F0h,000h ; Hex #46 Db 03Ch,066h,0C0h,0C0h,0CEh,066h,03Ah,000h ; Hex #47 Db 0C6h,0C6h,0C6h,0FEh,0C6h,0C6h,0C6h,000h ; Hex #48 Db 03Ch,018h,018h,018h,018h,018h,03Ch,000h ; Hex #49 Db 01Eh,00Ch,00Ch,00Ch,0CCh,0CCh,078h,000h ; Hex #4A Db 0E6h,066h,06Ch,078h,06Ch,066h,0E6h,000h ; Hex #4B Db 0F0h,060h,060h,060h,062h,066h,0FEh,000h ; Hex #4C Db 0C6h,0EEh,0FEh,0FEh,0D6h,0C6h,0C6h,000h ; Hex #4D Db 0C6h,0E6h,0F6h,0DEh,0CEh,0C6h,0C6h,000h ; Hex #4E Db 07Ch,0C6h,0C6h,0C6h,0C6h,0C6h,07Ch,000h ; Hex #4F Db 0FCh,066h,066h,07Ch,060h,060h,0F0h,000h ; Hex #50 Db 07Ch,0C6h,0C6h,0C6h,0C6h,0CEh,07Ch,00Eh ; Hex #51 Db 0FCh,066h,066h,07Ch,06Ch,066h,0E6h,000h ; Hex #52 Db 03Ch,066h,030h,018h,00Ch,066h,03Ch,000h ; Hex #53 Db 07Eh,07Eh,05Ah,018h,018h,018h,03Ch,000h ; Hex #54 Db 0C6h,0C6h,0C6h,0C6h,0C6h,0C6h,07Ch,000h ; Hex #55 Db 0C6h,0C6h,0C6h,0C6h,0C6h,06Ch,038h,000h ; Hex #56 Db 0C6h,0C6h,0C6h,0D6h,0D6h,0FEh,06Ch,000h ; Hex #57 Db 0C6h,0C6h,06Ch,038h,06Ch,0C6h,0C6h,000h ; Hex #58 Db 066h,066h,066h,03Ch,018h,018h,03Ch,000h ; Hex #59 Db 0FEh,0C6h,08Ch,018h,032h,066h,0FEh,000h ; Hex #5A Db 03Ch,030h,030h,030h,030h,030h,03Ch,000h ; Hex #5B Db 0C0h,060h,030h,018h,00Ch,006h,002h,000h ; Hex #5C Db 03Ch,00Ch,00Ch,00Ch,00Ch,00Ch,03Ch,000h ; Hex #5D Db 010h,038h,06Ch,0C6h,000h,000h,000h,000h ; Hex #5E Db 000h,000h,000h,000h,000h,000h,000h,0FFh ; Hex #5F Db 030h,018h,00Ch,000h,000h,000h,000h,000h ; Hex #60 Db 000h,000h,078h,00Ch,07Ch,0CCh,076h,000h ; Hex #61 Db 0E0h,060h,07Ch,066h,066h,066h,0DCh,000h ; Hex #62 Db 000h,000h,07Ch,0C6h,0C0h,0C6h,07Ch,000h ; Hex #63 Db 01Ch,00Ch,07Ch,0CCh,0CCh,0CCh,076h,000h ; Hex #64 Db 000h,000h,07Ch,0C6h,0FEh,0C0h,07Ch,000h ; Hex #65 Db 03Ch,066h,060h,0F8h,060h,060h,0F0h,000h ; Hex #66 Db 000h,000h,076h,0CCh,0CCh,07Ch,00Ch,0F8h ; Hex #67 Db 0E0h,060h,06Ch,076h,066h,066h,0E6h,000h ; Hex #68 Db 018h,000h,038h,018h,018h,018h,03Ch,000h ; Hex #69 Db 006h,000h,006h,006h,006h,066h,066h,03Ch ; Hex #6A Db 0E0h,060h,066h,06Ch,078h,06Ch,0E6h,000h ; Hex #6B Db 038h,018h,018h,018h,018h,018h,03Ch,000h ; Hex #6C Db 000h,000h,0ECh,0FEh,0D6h,0D6h,0D6h,000h ; Hex #6D Db 000h,000h,0DCh,066h,066h,066h,066h,000h ; Hex #6E Db 000h,000h,07Ch,0C6h,0C6h,0C6h,07Ch,000h ; Hex #6F Db 000h,000h,0DCh,066h,066h,07Ch,060h,0F0h ; Hex #70 Db 000h,000h,076h,0CCh,0CCh,07Ch,00Ch,01Eh ; Hex #71 Db 000h,000h,0DCh,076h,060h,060h,0F0h,000h ; Hex #72 Db 000h,000h,07Eh,0C0h,07Ch,006h,0FCh,000h ; Hex #73 Db 030h,030h,0FCh,030h,030h,036h,01Ch,000h ; Hex #74 Db 000h,000h,0CCh,0CCh,0CCh,0CCh,076h,000h ; Hex #75 Db 000h,000h,0C6h,0C6h,0C6h,06Ch,038h,000h ; Hex #76 Db 000h,000h,0C6h,0D6h,0D6h,0FEh,06Ch,000h ; Hex #77 Db 000h,000h,0C6h,06Ch,038h,06Ch,0C6h,000h ; Hex #78 Db 000h,000h,0C6h,0C6h,0C6h,07Eh,006h,0FCh ; Hex #79 Db 000h,000h,07Eh,04Ch,018h,032h,07Eh,000h ; Hex #7A Db 00Eh,018h,018h,070h,018h,018h,00Eh,000h ; Hex #7B Db 018h,018h,018h,018h,018h,018h,018h,000h ; Hex #7C Db 070h,018h,018h,00Eh,018h,018h,070h,000h ; Hex #7D Db 076h,0DCh,000h,000h,000h,000h,000h,000h ; Hex #7E Db 000h,010h,038h,06Ch,0C6h,0C6h,0FEh,000h ; Hex #7F Db 07Ch,0C6h,0C0h,0C0h,0C6h,07Ch,00Ch,078h ; Hex #80 Db 0CCh,000h,0CCh,0CCh,0CCh,0CCh,076h,000h ; Hex #81 Db 00Ch,018h,07Ch,0C6h,0FEh,0C0h,07Ch,000h ; Hex #82 Db 07Ch,082h,078h,00Ch,07Ch,0CCh,076h,000h ; Hex #83 Db 0C6h,000h,078h,00Ch,07Ch,0CCh,076h,000h ; Hex #84 Db 030h,018h,078h,00Ch,07Ch,0CCh,076h,000h ; Hex #85 Db 030h,030h,078h,00Ch,07Ch,0CCh,076h,000h ; Hex #86 Db 000h,000h,07Eh,0C0h,0C0h,07Eh,00Ch,038h ; Hex #87 Db 07Ch,082h,07Ch,0C6h,0FEh,0C0h,07Ch,000h ; Hex #88 Db 0C6h,000h,07Ch,0C6h,0FEh,0C0h,07Ch,000h ; Hex #89 Db 030h,018h,07Ch,0C6h,0FEh,0C0h,07Ch,000h ; Hex #8A Db 066h,000h,038h,018h,018h,018h,03Ch,000h ; Hex #8B Db 07Ch,082h,038h,018h,018h,018h,03Ch,000h ; Hex #8C Db 030h,018h,000h,038h,018h,018h,03Ch,000h ; Hex #8D Db 0C6h,038h,06Ch,0C6h,0FEh,0C6h,0C6h,000h ; Hex #8E Db 038h,06Ch,07Ch,0C6h,0FEh,0C6h,0C6h,000h ; Hex #8F Db 018h,030h,0FEh,0C0h,0F8h,0C0h,0FEh,000h ; Hex #90 Db 000h,000h,07Eh,012h,0fEh,090h,0fEh,000h ; Hex #91 Db 03Eh,06Ch,0CCh,0FEh,0CCh,0CCh,0CEh,000h ; Hex #92 Db 07Ch,082h,07Ch,0C6h,0C6h,0C6h,07Ch,000h ; Hex #93 Db 0C6h,000h,07Ch,0C6h,0C6h,0C6h,07Ch,000h ; Hex #94 Db 030h,018h,07Ch,0C6h,0C6h,0C6h,07Ch,000h ; Hex #95 Db 078h,084h,000h,0CCh,0CCh,0CCh,076h,000h ; Hex #96 Db 060h,030h,0CCh,0CCh,0CCh,0CCh,076h,000h ; Hex #97 Db 0C6h,000h,0C6h,0C6h,0C6h,07Eh,006h,0FCh ; Hex #98 Db 0C6h,038h,06Ch,0C6h,0C6h,06Ch,038h,000h ; Hex #99 Db 0C6h,000h,0C6h,0C6h,0C6h,0C6h,07Ch,000h ; Hex #9A Db 000h,002h,07Ch,0CEh,0D6h,0E6h,07Ch,080h ; Hex #9B Db 038h,06Ch,064h,0F0h,060h,066h,0FCh,000h ; Hex #9C Db 03Ah,06Ch,0CEh,0D6h,0E6h,06Ch,0B8h,000h ; Hex #9D Db 000h,0C6h,06Ch,038h,06Ch,0C6h,000h,000h ; Hex #9E Db 00Eh,01Bh,018h,03Ch,018h,0D8h,070h,000h ; Hex #9F Db 018h,030h,078h,00Ch,07Ch,0CCh,076h,000h ; Hex #A0 Db 00Ch,018h,000h,038h,018h,018h,03Ch,000h ; Hex #A1 Db 00Ch,018h,07Ch,0C6h,0C6h,0C6h,07Ch,000h ; Hex #A2 Db 018h,030h,0CCh,0CCh,0CCh,0CCh,076h,000h ; Hex #A3 Db 076h,0DCh,000h,0DCh,066h,066h,066h,000h ; Hex #A4 Db 076h,0DCh,000h,0E6h,0F6h,0DEh,0CEh,000h ; Hex #A5 Db 03Ch,06Ch,06Ch,03Eh,000h,07Eh,000h,000h ; Hex #A6 Db 038h,06Ch,06Ch,038h,000h,07Ch,000h,000h ; Hex #A7 Db 018h,000h,018h,018h,030h,063h,03Eh,000h ; Hex #A8 Db 07Eh,081h,0B9h,0A5h,0B9h,0A5h,081h,07Eh ; Hex #A9 Db 000h,000h,000h,0FEh,006h,006h,000h,000h ; Hex #AA Db 063h,0E6h,06Ch,07Eh,033h,066h,0CCh,00Fh ; Hex #AB Db 063h,0E6h,06Ch,07Ah,036h,06Ah,0DFh,006h ; Hex #AC Db 018h,000h,018h,018h,03Ch,03Ch,018h,000h ; Hex #AD Db 000h,033h,066h,0CCh,066h,033h,000h,000h ; Hex #AE Db 000h,0CCh,066h,033h,066h,0CCh,000h,000h ; Hex #AF Db 022h,088h,022h,088h,022h,088h,022h,088h ; Hex #B0 Db 055h,0AAh,055h,0AAh,055h,0AAh,055h,0AAh ; Hex #B1 Db 077h,0DDh,077h,0DDh,077h,0DDh,077h,0DDh ; Hex #B2 Db 018h,018h,018h,018h,018h,018h,018h,018h ; Hex #B3 Db 018h,018h,018h,018h,0F8h,018h,018h,018h ; Hex #B4 Db 030h,060h,038h,06Ch,0C6h,0FEh,0C6h,000h ; Hex #B5 Db 07Ch,082h,038h,06Ch,0C6h,0FEh,0C6h,000h ; Hex #B6 Db 018h,00Ch,038h,06Ch,0C6h,0FEh,0C6h,000h ; Hex #B7 Db 07Eh,081h,09Dh,0A1h,0A1h,09Dh,081h,07Eh ; Hex #B8 Db 036h,036h,0F6h,006h,0F6h,036h,036h,036h ; Hex #B9 Db 036h,036h,036h,036h,036h,036h,036h,036h ; Hex #BA Db 000h,000h,0FEh,006h,0F6h,036h,036h,036h ; Hex #BB Db 036h,036h,0F6h,006h,0FEh,000h,000h,000h ; Hex #BC Db 018h,018h,07Eh,0C0h,0C0h,07Eh,018h,018h ; Hex #BD Db 066h,066h,03Ch,07Eh,018h,07Eh,018h,018h ; Hex #BE Db 000h,000h,000h,000h,0F8h,018h,018h,018h ; Hex #BF Db 018h,018h,018h,018h,01Fh,000h,000h,000h ; Hex #C0 Db 018h,018h,018h,018h,0FFh,000h,000h,000h ; Hex #C1 Db 000h,000h,000h,000h,0FFh,018h,018h,018h ; Hex #C2 Db 018h,018h,018h,018h,01Fh,018h,018h,018h ; Hex #C3 Db 000h,000h,000h,000h,0FFh,000h,000h,000h ; Hex #C4 Db 018h,018h,018h,018h,0FFh,018h,018h,018h ; Hex #C5 Db 076h,0DCh,07Ch,006h,07Eh,0C6h,07Eh,000h ; Hex #C6 Db 076h,0DCh,038h,06Ch,0C6h,0FEh,0C6h,000h ; Hex #C7 Db 036h,036h,037h,030h,03Fh,000h,000h,000h ; Hex #C8 Db 000h,000h,03Fh,030h,037h,036h,036h,036h ; Hex #C9 Db 036h,036h,0F7h,000h,0FFh,000h,000h,000h ; Hex #CA Db 000h,000h,0FFh,000h,0F7h,036h,036h,036h ; Hex #CB Db 036h,036h,037h,030h,037h,036h,036h,036h ; Hex #CC Db 000h,000h,0FFh,000h,0FFh,000h,000h,000h ; Hex #CD Db 036h,036h,0F7h,000h,0F7h,036h,036h,036h ; Hex #CE Db 000h,0C6h,07Ch,0C6h,0C6h,07Ch,0C6h,000h ; Hex #CF Db 030h,07Eh,00Ch,07Ch,0CCh,0CCh,078h,000h ; Hex #D0 Db 0F8h,06Ch,066h,0F6h,066h,06Ch,0F8h,000h ; Hex #D1 Db 07Ch,082h,0FEh,0C0h,0FCh,0C0h,0FEh,000h ; Hex #D2 Db 0C6h,000h,0FEh,0C0h,0FCh,0C0h,0FEh,000h ; Hex #D3 Db 030h,018h,0FEh,0C0h,0FCh,0C0h,0FEh,000h ; Hex #D4 Db 000h,000h,038h,018h,018h,018h,03Ch,000h ; Hex #D5 Db 00Ch,018h,03Ch,018h,018h,018h,03Ch,000h ; Hex #D6 Db 03Ch,042h,03Ch,018h,018h,018h,03Ch,000h ; Hex #D7 Db 066h,000h,03Ch,018h,018h,018h,03Ch,000h ; Hex #D8 Db 018h,018h,018h,018h,0F8h,000h,000h,000h ; Hex #D9 Db 000h,000h,000h,000h,01Fh,018h,018h,018h ; Hex #DA Db 0FFh,0FFh,0FFh,0FFh,0FFh,0FFh,0FFh,0FFh ; Hex #DB Db 000h,000h,000h,000h,0FFh,0FFh,0FFh,0FFh ; Hex #DC Db 018h,018h,018h,000h,000h,018h,018h,018h ; Hex #DD Db 030h,018h,03Ch,018h,018h,018h,03Ch,000h ; Hex #DE Db 0FFh,0FFh,0FFh,0FFh,000h,000h,000h,000h ; Hex #DF Db 030h,060h,038h,06Ch,0C6h,06Ch,038h,000h ; Hex #E0 Db 078h,0CCh,0CCh,0D8h,0CCh,0C6h,0CCh,000h ; Hex #E1 Db 07Ch,082h,038h,06Ch,0C6h,06Ch,038h,000h ; Hex #E2 Db 00Ch,006h,038h,06Ch,0C6h,06Ch,038h,000h ; Hex #E3 Db 076h,0DCh,07Ch,0C6h,0C6h,0C6h,07Ch,000h ; Hex #E4 Db 076h,0DCh,038h,06Ch,0C6h,06Ch,038h,000h ; Hex #E5 Db 000h,000h,066h,066h,066h,066h,07Ch,0C0h ; Hex #E6 Db 0E0h,060h,07Ch,066h,066h,07Ch,060h,0F0h ; Hex #E7 Db 0F0h,060h,07Ch,066h,07Ch,060h,0F0h,000h ; Hex #E8 Db 018h,030h,0C6h,0C6h,0C6h,0C6h,07Ch,000h ; Hex #E9 Db 07Ch,082h,000h,0C6h,0C6h,0C6h,07Ch,000h ; Hex #EA Db 060h,030h,0C6h,0C6h,0C6h,0C6h,07Ch,000h ; Hex #EB Db 018h,030h,0C6h,0C6h,0C6h,07Eh,006h,0FCh ; Hex #EC Db 00Ch,018h,066h,066h,03Ch,018h,03Ch,000h ; Hex #ED Db 0FFh,000h,000h,000h,000h,000h,000h,000h ; Hex #EE Db 00Ch,018h,030h,000h,000h,000h,000h,000h ; Hex #EF Db 000h,000h,000h,07Eh,000h,000h,000h,000h ; Hex #F0 Db 018h,018h,07Eh,018h,018h,000h,07Eh,000h ; Hex #F1 Db 000h,000h,000h,000h,000h,0FFh,000h,0FFh ; Hex #F2 Db 0E1h,032h,0E4h,03Ah,0F6h,02Ah,05Fh,086h ; Hex #F3 Db 07Fh,0DBh,0DBh,07Bh,01Bh,01Bh,01Bh,000h ; Hex #F4 Db 03Eh,061h,03Ch,066h,066h,03Ch,086h,07Ch ; Hex #F5 Db 000h,018h,000h,07Eh,000h,018h,000h,000h ; Hex #F6 Db 000h,000h,000h,000h,000h,018h,00Ch,038h ; Hex #F7 Db 038h,06Ch,06Ch,038h,000h,000h,000h,000h ; Hex #F8 Db 000h,0C6h,000h,000h,000h,000h,000h,000h ; Hex #F9 Db 000h,000h,000h,018h,000h,000h,000h,000h ; Hex #FA Db 018h,038h,018h,018h,03Ch,000h,000h,000h ; Hex #FB Db 078h,00Ch,038h,00Ch,078h,000h,000h,000h ; Hex #FC Db 078h,00Ch,018h,030h,07Ch,000h,000h,000h ; Hex #FD Db 000h,000h,03Ch,03Ch,03Ch,03Ch,000h,000h ; Hex #FE Db 000h,000h,000h,000h,000h,000h,000h,000h ; Hex #FF 
;-------------------------------------------------------- ; File Created by SDCC : free open source ANSI-C Compiler ; Version 4.1.4 #12246 (Mac OS X x86_64) ;-------------------------------------------------------- .module scene_3_colors .optsdcc -mgbz80 ;-------------------------------------------------------- ; Public variables in this module ;-------------------------------------------------------- .globl _scene_3_colors .globl ___bank_scene_3_colors ;-------------------------------------------------------- ; special function registers ;-------------------------------------------------------- ;-------------------------------------------------------- ; ram data ;-------------------------------------------------------- .area _DATA ;-------------------------------------------------------- ; ram data ;-------------------------------------------------------- .area _INITIALIZED ;-------------------------------------------------------- ; absolute external ram data ;-------------------------------------------------------- .area _DABS (ABS) ;-------------------------------------------------------- ; global & static initialisations ;-------------------------------------------------------- .area _HOME .area _GSINIT .area _GSFINAL .area _GSINIT ;-------------------------------------------------------- ; Home ;-------------------------------------------------------- .area _HOME .area _HOME ;-------------------------------------------------------- ; code ;-------------------------------------------------------- .area _CODE_255 .area _CODE_255 ___bank_scene_3_colors = 0x00ff _scene_3_colors: .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .db #0x00 ; 0 .area _INITIALIZER .area _CABS (ABS)
; -------------------------------------- ; Test INR and DCR. ; -------------------------------------- Start: ; -------------------------------------- mvi a,1 ; Initialize the register. mvi b,2 mvi c,3 mvi d,4 mvi e,5 mvi h,6 mvi l,7 out 38 ; Print the register values. ; + regA: 1 = 001 = 00000001 ; + regB: 2 = 002 = 00000010 regC: 3 = 003 = 00000011 ; + regD: 4 = 004 = 00000100 regE: 5 = 005 = 00000101 ; + regH: 6 = 006 = 00000110 regL: 7 = 007 = 00000111 ; ; -------------------------------------- ; Test by incrementing the registers up. inr a ; Increment register A. inr b inr c inr d inr e inr h inr l out 38 ; Print the register values. ; + regA: 2 = 002 = 00000010 ; + regB: 3 = 003 = 00000011 regC: 4 = 004 = 00000100 ; + regD: 5 = 005 = 00000101 regE: 6 = 006 = 00000110 ; + regH: 7 = 007 = 00000111 regL: 8 = 010 = 00001000 ; ; -------------------------------------- ; Test by decrementing the registers down. dcr a ; Decrement register A. dcr b dcr c dcr d dcr e dcr h dcr l out 38 ; Print the register values. ; + regA: 1 = 001 = 00000001 ; + regB: 2 = 002 = 00000010 regC: 3 = 003 = 00000011 ; + regD: 4 = 004 = 00000100 regE: 5 = 005 = 00000101 ; + regH: 6 = 006 = 00000110 regL: 7 = 007 = 00000111 ; ; -------------------------------------- ; Test by incrementing and decrementing the data value at address hb:lb. ; mvi a,6 ; Move # to register A. sta 128 ; Store register A's data value to the address H:L. lda 128 ; Load register A from the address H:L. out 37 ; Print register A = 6. ; mvi l,128 ; Set address H:L to 128. mvi h,0 inr m ; Increment the byte(M) at address H:L. lda 128 ; Load register A from the address H:L. out 37 ; Print register A = 7. dcr m ; Decrement the byte(M) at address H:L. lda 128 ; Load register A from the address H:L. out 37 ; Print register A = 6. ; -------------------------------------- mvi a,'\n' out 3 mvi a,'\r' out 3 hlt jmp Start ; -------------------------------------- end ; -------------------------------------- ; Successful run: + runProcessor() ------------ + regA: 1 = 001 = 00000001 + regB: 2 = 002 = 00000010 regC: 3 = 003 = 00000011 + regD: 4 = 004 = 00000100 regE: 5 = 005 = 00000101 + regH: 6 = 006 = 00000110 regL: 7 = 007 = 00000111 ------------------------ + regA: 2 = 002 = 00000010 + regB: 3 = 003 = 00000011 regC: 4 = 004 = 00000100 + regD: 5 = 005 = 00000101 regE: 6 = 006 = 00000110 + regH: 7 = 007 = 00000111 regL: 8 = 010 = 00001000 ------------------------ + regA: 1 = 001 = 00000001 + regB: 2 = 002 = 00000010 regC: 3 = 003 = 00000011 + regD: 4 = 004 = 00000100 regE: 5 = 005 = 00000101 + regH: 6 = 006 = 00000110 regL: 7 = 007 = 00000111 ------------ > Register A = 6 = 006 = 00000110 > Register A = 7 = 007 = 00000111 > Register A = 6 = 006 = 00000110 ++ HALT, host_read_status_led_WAIT() = 0 ; ; --------------------------------------
Name: zel_gsub1.asm Type: file Size: 3376 Last-Modified: '2016-05-13T04:20:48Z' SHA-1: 1A2BE9471F01252C3463F8CA67E3D429B9A75D08 Description: null
; A166520: a(n) = (10*n + 11*(-1)^n + 5)/4. ; 1,9,6,14,11,19,16,24,21,29,26,34,31,39,36,44,41,49,46,54,51,59,56,64,61,69,66,74,71,79,76,84,81,89,86,94,91,99,96,104,101,109,106,114,111,119,116,124,121,129,126,134,131,139,136,144,141,149,146,154,151,159,156,164,161,169,166,174,171,179,176,184,181,189,186,194,191,199,196,204,201,209,206,214,211,219,216,224,221,229,226,234,231,239,236,244,241,249,246,254,251,259,256,264,261,269,266,274,271,279,276,284,281,289,286,294,291,299,296,304,301,309,306,314,311,319,316,324,321,329,326,334,331,339,336,344,341,349,346,354,351,359,356,364,361,369,366,374,371,379,376,384,381,389,386,394,391,399,396,404,401,409,406,414,411,419,416,424,421,429,426,434,431,439,436,444,441,449,446,454,451,459,456,464,461,469,466,474,471,479,476,484,481,489,486,494,491,499,496,504,501,509,506,514,511,519,516,524,521,529,526,534,531,539,536,544,541,549,546,554,551,559,556,564,561,569,566,574,571,579,576,584,581,589,586,594,591,599,596,604,601,609,606,614,611,619,616,624,621,629 mov $1,8 mul $1,$0 div $0,2 mul $0,11 add $1,1 sub $1,$0
; A121937: a(n) = least m >= 2 such that (n mod m) > (n+2 mod m). ; 3,3,4,3,3,4,3,3,5,3,3,7,3,3,4,3,3,4,3,3,11,3,3,5,3,3,4,3,3,4,3,3,5,3,3,19,3,3,4,3,3,4,3,3,23,3,3,5,3,3,4,3,3,4,3,3,29,3,3,31,3,3,4,3,3,4,3,3,5,3,3,37,3,3,4,3,3,4,3,3,41,3,3,5,3,3,4,3,3,4,3,3,5,3,3,7,3,3,4,3,3,4 mov $1,2 lpb $0 mov $2,$0 sub $0,1 add $1,1 mod $2,$1 mov $4,2 trn $4,$2 add $0,$4 add $3,1 lpe add $1,$3 sub $1,2 div $1,2 add $1,3
title "Trap Processing" ;++ ; ; Copyright (c) 1996 Microsoft Corporation ; ; Module Name: ; ; trap.asm ; ; Abstract: ; ; This module implements the code necessary to field and process i386 ; trap conditions. ; ; Author: ; ; David N. Cutler (davec) 1-Dec-96 ; ; Environment: ; ; Kernel mode only. ; ; Revision History: ; ;-- .386p .xlist KERNELONLY equ 1 include ks386.inc include callconv.inc include i386\kimacro.inc include mac386.inc .list extrn _BdDebugRoutine:DWORD page ,132 subttl "Equated Values" ; ; Debug register 6 (dr6) BS (single step) bit mask ; DR6_BS_MASK EQU 4000H ; ; EFLAGS single step bit ; EFLAGS_TF_BIT EQU 100h EFLAGS_OF_BIT EQU 4000H _TEXT$00 SEGMENT PUBLIC 'CODE' ASSUME DS:NOTHING, ES:NOTHING, SS:FLAT, FS:NOTHING, GS:NOTHING page ,132 subttl "Macros" ;++ ; ; GENERATE_TRAP_FRAME ; ; Macro Dexcription: ; ; This macro generates a trap frame and saves the current register state. ; ; Arguments: ; ; None. ; ;-- GENERATE_TRAP_FRAME macro ; ; Build trap frame minus the V86 and privilege level transition arguments. ; ; N.B. It is assumed that the error code has already been pushed on the stack. ; push ebp ; save nonvolatile registers push ebx ; push esi ; push edi ; push fs ; save FS segment register push -1 ; push dummy exception list push -1 ; dummy previous mode push eax ; save the volatile registers push ecx ; push edx ; push ds ; save segment registers push es ; push gs ; sub esp, TsSegGs ; allocate remainder of trap frame mov ebp, esp ; set ebp to base of trap frame cld ; clear direction bit endm page ,132 subttl "Debug Exception" ;++ ; ; Routine Description: ; ; Handle debug exceptions. ; ; This exception is generated for the following reasons: ; ; Instruction breakpoint fault. ; Data address breakpoint trap. ; General detect fault. ; Single-step trap. ; Task-switch breadkpoint trap. ; ; Arguments: ; ; On entry the stack contains: ; ; eflags ; cs ; eip ; ; N.B. There are no privilege transitions in the boot debugger. Therefore, ; the none of the previous ss, esp, or V86 registers are saved. ; ; Return value: ; ; None ;-- ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING align 16 public _BdTrap01@0 _BdTrap01@0 proc .FPO (0, 0, 0, 0, 0, FPO_TRAPFRAME) push 0 ; push dummy error code GENERATE_TRAP_FRAME ; generate trap frame ; ; Set exception parameters. ; and dword ptr [ebp] + TsEflags, not EFLAGS_TF_BIT ; clear TF flag mov eax, STATUS_SINGLE_STEP ; set exception code mov ebx, [ebp] + TsEip ; set address of faulting instruction xor ecx, ecx ; set number of parameters call _BdDispatch ; dispatch exception jmp _BdExit ; dummy _BdTrap01@0 endp page ,132 subttl "Int 3 Breakpoint" ;++ ; ; Routine Description: ; ; Handle int 3 (breakpoint). ; ; This trap is caused by the int 3 instruction. ; ; Arguments: ; ; On entry the stack contains: ; ; eflags ; cs ; eip ; ; N.B. There are no privilege transitions in the boot debugger. Therefore, ; the none of the previous ss, esp, or V86 registers are saved. ; ; Return value: ; ; None ; ;-- ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING align 16 public _BdTrap03@0 _BdTrap03@0 proc .FPO (0, 0, 0, 0, 0, FPO_TRAPFRAME) push 0 ; push dummy error code GENERATE_TRAP_FRAME ; generate trap frame ; ; Set exception parameters. ; dec dword ptr [ebp] + TsEip ; back up to int 3 instruction mov eax, STATUS_BREAKPOINT ; set exception code mov ebx, [ebp] + TsEip ; set address of faulting instruction mov ecx, 1 ; set number of parameters mov edx, BREAKPOINT_BREAK ; set service name call _BdDispatch ; dispatch exception jmp _BdExit ; dummy _BdTrap03@0 endp page ,132 subttl "General Protect" ;++ ; ; Routine Description: ; ; General protect violation. ; ; Arguments: ; ; On entry the stack contains: ; ; eflags ; cs ; eip ; error code ; ; N.B. There are no privilege transitions in the boot debugger. Therefore, ; the none of the previous ss, esp, or V86 registers are saved. ; ; Return value: ; ; N.B. There is no return from this fault. ; ;-- ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING align 16 public _BdTrap0d@0 _BdTrap0d@0 proc .FPO (0, 0, 0, 0, 0, FPO_TRAPFRAME) GENERATE_TRAP_FRAME ; generate trap frame ; ; Set exception parameters. ; _BdTrap0d10: ; mov eax, STATUS_ACCESS_VIOLATION ; set exception code mov ebx, [ebp] + TsEip ; set address of faulting instruction mov ecx, 1 ; set number of parameters mov edx, [ebp] + TsErrCode ; set error code and edx, 0FFFFH ; call _BdDispatch ; dispatch exception jmp _BdTrap0d10 ; repeat _BdTrap0d@0 endp page ,132 subttl "Page Fault" ;++ ; ; Routine Description: ; ; Page fault. ; ; Arguments: ; ; On entry the stack contains: ; ; eflags ; cs ; eip ; error code ; ; N.B. There are no privilege transitions in the boot debugger. Therefore, ; the none of the previous ss, esp, or V86 registers are saved. ; ; Return value: ; ; N.B. There is no return from this fault. ; ;-- ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING align 16 public _BdTrap0e@0 _BdTrap0e@0 proc .FPO (0, 0, 0, 0, 0, FPO_TRAPFRAME) GENERATE_TRAP_FRAME ; generate trap frame ; ; Set exception parameters. ; _BdTrap0e10: ; mov eax, STATUS_ACCESS_VIOLATION ; set exception code mov ebx, [ebp] + TsEip ; set address of faulting instruction mov ecx, 3 ; set number of parameters mov edx, [ebp] + TsErrCode ; set read/write code and edx, 2 ; mov edi, cr2 ; set fault address xor esi, esi ; set previous mode call _BdDispatch ; dispatch exception jmp _BdTrap0e10 ; repeat _BdTrap0e@0 endp page ,132 subttl "Debug Service" ;++ ; ; Routine Description: ; ; Handle int 2d (debug service). ; ; The trap is caused by an int 2d instruction. This instruction is used ; instead of an int 3 instruction so parameters can be passed to the ; requested debug service. ; ; N.B. An int 3 instruction must immediately follow the int 2d instruction. ; ; Arguments: ; ; On entry the stack contains: ; ; eflags ; cs ; eip ; ; N.B. There are no privilege transitions in the boot debugger. Therefore, ; the none of the previous ss, esp, or V86 registers are saved. ; ; Service (eax) - Supplies the service to perform. ; Argument1 (ecx) - Supplies the first argument. ; Argument2 (edx) - Supplies the second argument. ; ;-- ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING align 16 public _BdTrap2d@0 _BdTrap2d@0 proc .FPO (0, 0, 0, 0, 0, FPO_TRAPFRAME) ; ; Build trap frame minus the V86 and privilege level transition arguments. ; push 0 ; push dummy error code GENERATE_TRAP_FRAME ; generate trap frame ; ; Set exception parameters. ; mov eax, STATUS_BREAKPOINT ; set exception code mov ebx, [ebp] + TsEip ; set address of faulting instruction mov ecx, 3 ; set number of parameters mov edx, [ebp] + TsEax ; set service name mov edi, [ebp] + TsEcx ; set first argument value mov esi, [ebp] + TsEdx ; set second argument value call _BdDispatch ; dispatch exception jmp _BdExit ; dummy _BdTrap2d@0 endp page , 132 subttl "Exception Dispatch" ;++ ; ; Dispatch ; ; Routine Description: ; ; This functions allocates an exception record, initializes the exception ; record, and calls the general exception dispatch routine. ; ; Arguments: ; ; Code (eax) - Suppplies the exception code. ; Address (ebx) = Supplies the address of the exception. ; Number (ecx) = Supplies the number of parameters. ; Parameter1 (edx) - Supplies exception parameter 1; ; Parameter2 (edi) - Supplies exception parameter 2; ; Parameter3 (esi) - Supplies exception parameter 3. ; ; Return Value: ; ; None. ; ;-- align 16 public _BdDispatch _BdDispatch proc .FPO (ExceptionRecordLength / 4, 0, 0, 0, 0, FPO_TRAPFRAME) ; ; Allocate and initialize exception record. ; sub esp, ExceptionRecordLength ; allocate exception record mov [esp] + ErExceptionCode, eax ; set exception code xor eax, eax ; zero register mov [esp] + ErExceptionFlags, eax ; zero exception flags mov [esp] + ErExceptionRecord, eax ; zero associated exception record mov [esp] + ErExceptionAddress, ebx ; set exception address mov [esp] + ErNumberParameters, ecx ; set number of parameters mov [esp] + ErExceptionInformation + 0, edx ; set parameter 1 mov [esp] + ErExceptionInformation + 4, edi ; set parameter 2 mov [esp] + ErExceptionInformation + 8, esi ; set parameter 3 ; ; Save debug registers in trap frame. ; mov eax, dr0 ; save dr0 mov [ebp] + TsDr0, eax ; mov eax, dr1 ; save dr1 mov [ebp] + TsDr1, eax ; mov eax, dr2 ; save dr2 mov [ebp] + TsDr2, eax ; mov eax, dr3 ; save dr3 mov [ebp] + TsDr3, eax ; mov eax, dr6 ; save dr6 mov [ebp] + TsDr6, eax ; mov eax, dr7 ; save dr7 mov [ebp] + TsDr7, eax ; ; ; Save previous stack address and segment selector. ; mov eax, ss ; save stack segment register mov [ebp] + TsTempSegCs, eax ; mov [ebp] + TsTempEsp, ebp ; compute previous stack address add [ebp] + TsTempEsp, TsEFlags + 4 ; ; ; Call the general exception dispatcher. ; mov ecx, esp ; set address of exception record push ebp ; push address of trap frame push 0 ; push address of exception frame push ecx ; push address of exception record call [_BdDebugRoutine] ; call dispatch routine add esp, ExceptionRecordLength ; deallocate exception record ret ; _BdDispatch endp page ,132 subttl "Common Trap Exit" ;++ ; ; Exit ; ; Routine Description: ; ; This code is transfered to at the end of the processing for an exception. ; Its function is to restore machine state and continue execution. ; ; Arguments: ; ; ebp - Supplies the address of the trap frame. ; ; Return Value: ; ; None. ; ;-- align 16 public _BdExit _BdExit proc .FPO (0, 0, 0, 0, 0, FPO_TRAPFRAME) lea esp, [ebp] + TsSegGs ; get address of save area pop gs ; restore segment registers pop es ; pop ds ; pop edx ; restore volatile registers pop ecx ; pop eax ; add esp, 8 ; remove mode and exception list pop fs ; restore FS segment register pop edi ; restore nonvolatile registers pop esi ; pop ebx ; pop ebp ; add esp, 4 ; remove error code iretd ; return _BdExit endp _TEXT$00 ends end
/* * Copyright (c) 2013-2020, The PurpleI2P Project * * This file is part of Purple i2pd project and licensed under BSD3 * * See full license text in LICENSE file at top of project tree * */ #include <openssl/rand.h> #include <openssl/sha.h> #include <openssl/hmac.h> #include <stdlib.h> #include <vector> #include "Log.h" #include "I2PEndian.h" #include "Crypto.h" #include "Siphash.h" #include "RouterContext.h" #include "Transports.h" #include "NetDb.hpp" #include "NTCP2.h" #include "HTTP.h" #include "util.h" namespace i2p { namespace transport { NTCP2Establisher::NTCP2Establisher (): m_SessionRequestBuffer (nullptr), m_SessionCreatedBuffer (nullptr), m_SessionConfirmedBuffer (nullptr) { } NTCP2Establisher::~NTCP2Establisher () { delete[] m_SessionRequestBuffer; delete[] m_SessionCreatedBuffer; delete[] m_SessionConfirmedBuffer; } void NTCP2Establisher::KeyDerivationFunction1 (const uint8_t * pub, i2p::crypto::X25519Keys& priv, const uint8_t * rs, const uint8_t * epub) { i2p::crypto::InitNoiseXKState (*this, rs); // h = SHA256(h || epub) MixHash (epub, 32); // x25519 between pub and priv uint8_t inputKeyMaterial[32]; priv.Agree (pub, inputKeyMaterial); MixKey (inputKeyMaterial); } void NTCP2Establisher::KDF1Alice () { KeyDerivationFunction1 (m_RemoteStaticKey, *m_EphemeralKeys, m_RemoteStaticKey, GetPub ()); } void NTCP2Establisher::KDF1Bob () { KeyDerivationFunction1 (GetRemotePub (), i2p::context.GetStaticKeys (), i2p::context.GetNTCP2StaticPublicKey (), GetRemotePub ()); } void NTCP2Establisher::KeyDerivationFunction2 (const uint8_t * sessionRequest, size_t sessionRequestLen, const uint8_t * epub) { MixHash (sessionRequest + 32, 32); // encrypted payload int paddingLength = sessionRequestLen - 64; if (paddingLength > 0) MixHash (sessionRequest + 64, paddingLength); MixHash (epub, 32); // x25519 between remote pub and ephemaral priv uint8_t inputKeyMaterial[32]; m_EphemeralKeys->Agree (GetRemotePub (), inputKeyMaterial); MixKey (inputKeyMaterial); } void NTCP2Establisher::KDF2Alice () { KeyDerivationFunction2 (m_SessionRequestBuffer, m_SessionRequestBufferLen, GetRemotePub ()); } void NTCP2Establisher::KDF2Bob () { KeyDerivationFunction2 (m_SessionRequestBuffer, m_SessionRequestBufferLen, GetPub ()); } void NTCP2Establisher::KDF3Alice () { uint8_t inputKeyMaterial[32]; i2p::context.GetStaticKeys ().Agree (GetRemotePub (), inputKeyMaterial); MixKey (inputKeyMaterial); } void NTCP2Establisher::KDF3Bob () { uint8_t inputKeyMaterial[32]; m_EphemeralKeys->Agree (m_RemoteStaticKey, inputKeyMaterial); MixKey (inputKeyMaterial); } void NTCP2Establisher::CreateEphemeralKey () { m_EphemeralKeys = i2p::transport::transports.GetNextX25519KeysPair (); } void NTCP2Establisher::CreateSessionRequestMessage () { // create buffer and fill padding auto paddingLength = rand () % (287 - 64); // message length doesn't exceed 287 bytes m_SessionRequestBufferLen = paddingLength + 64; m_SessionRequestBuffer = new uint8_t[m_SessionRequestBufferLen]; RAND_bytes (m_SessionRequestBuffer + 64, paddingLength); // encrypt X i2p::crypto::CBCEncryption encryption; encryption.SetKey (m_RemoteIdentHash); encryption.SetIV (m_IV); encryption.Encrypt (GetPub (), 32, m_SessionRequestBuffer); // X encryption.GetIV (m_IV); // save IV for SessionCreated // encryption key for next block KDF1Alice (); // fill options uint8_t options[32]; // actual options size is 16 bytes memset (options, 0, 16); options[0] = i2p::context.GetNetID (); // network ID options[1] = 2; // ver htobe16buf (options + 2, paddingLength); // padLen // m3p2Len auto bufLen = i2p::context.GetRouterInfo ().GetBufferLen (); m3p2Len = bufLen + 4 + 16; // (RI header + RI + MAC for now) TODO: implement options htobe16buf (options + 4, m3p2Len); // fill m3p2 payload (RouterInfo block) m_SessionConfirmedBuffer = new uint8_t[m3p2Len + 48]; // m3p1 is 48 bytes uint8_t * m3p2 = m_SessionConfirmedBuffer + 48; m3p2[0] = eNTCP2BlkRouterInfo; // block htobe16buf (m3p2 + 1, bufLen + 1); // flag + RI m3p2[3] = 0; // flag memcpy (m3p2 + 4, i2p::context.GetRouterInfo ().GetBuffer (), bufLen); // TODO: own RI should be protected by mutex // 2 bytes reserved htobe32buf (options + 8, i2p::util::GetSecondsSinceEpoch ()); // tsA // 4 bytes reserved // sign and encrypt options, use m_H as AD uint8_t nonce[12]; memset (nonce, 0, 12); // set nonce to zero i2p::crypto::AEADChaCha20Poly1305 (options, 16, GetH (), 32, GetK (), nonce, m_SessionRequestBuffer + 32, 32, true); // encrypt } void NTCP2Establisher::CreateSessionCreatedMessage () { auto paddingLen = rand () % (287 - 64); m_SessionCreatedBufferLen = paddingLen + 64; m_SessionCreatedBuffer = new uint8_t[m_SessionCreatedBufferLen]; RAND_bytes (m_SessionCreatedBuffer + 64, paddingLen); // encrypt Y i2p::crypto::CBCEncryption encryption; encryption.SetKey (i2p::context.GetIdentHash ()); encryption.SetIV (m_IV); encryption.Encrypt (GetPub (), 32, m_SessionCreatedBuffer); // Y // encryption key for next block (m_K) KDF2Bob (); uint8_t options[16]; memset (options, 0, 16); htobe16buf (options + 2, paddingLen); // padLen htobe32buf (options + 8, i2p::util::GetSecondsSinceEpoch ()); // tsB // sign and encrypt options, use m_H as AD uint8_t nonce[12]; memset (nonce, 0, 12); // set nonce to zero i2p::crypto::AEADChaCha20Poly1305 (options, 16, GetH (), 32, GetK (), nonce, m_SessionCreatedBuffer + 32, 32, true); // encrypt } void NTCP2Establisher::CreateSessionConfirmedMessagePart1 (const uint8_t * nonce) { // update AD MixHash (m_SessionCreatedBuffer + 32, 32); // encrypted payload int paddingLength = m_SessionCreatedBufferLen - 64; if (paddingLength > 0) MixHash (m_SessionCreatedBuffer + 64, paddingLength); // part1 48 bytes i2p::crypto::AEADChaCha20Poly1305 (i2p::context.GetNTCP2StaticPublicKey (), 32, GetH (), 32, GetK (), nonce, m_SessionConfirmedBuffer, 48, true); // encrypt } void NTCP2Establisher::CreateSessionConfirmedMessagePart2 (const uint8_t * nonce) { // part 2 // update AD again MixHash (m_SessionConfirmedBuffer, 48); // encrypt m3p2, it must be filled in SessionRequest KDF3Alice (); uint8_t * m3p2 = m_SessionConfirmedBuffer + 48; i2p::crypto::AEADChaCha20Poly1305 (m3p2, m3p2Len - 16, GetH (), 32, GetK (), nonce, m3p2, m3p2Len, true); // encrypt // update h again MixHash (m3p2, m3p2Len); //h = SHA256(h || ciphertext) } bool NTCP2Establisher::ProcessSessionRequestMessage (uint16_t& paddingLen) { // decrypt X i2p::crypto::CBCDecryption decryption; decryption.SetKey (i2p::context.GetIdentHash ()); decryption.SetIV (i2p::context.GetNTCP2IV ()); decryption.Decrypt (m_SessionRequestBuffer, 32, GetRemotePub ()); decryption.GetIV (m_IV); // save IV for SessionCreated // decryption key for next block KDF1Bob (); // verify MAC and decrypt options block (32 bytes), use m_H as AD uint8_t nonce[12], options[16]; memset (nonce, 0, 12); // set nonce to zero if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionRequestBuffer + 32, 16, GetH (), 32, GetK (), nonce, options, 16, false)) // decrypt { // options if (options[0] && options[0] != i2p::context.GetNetID ()) { LogPrint (eLogWarning, "NTCP2: SessionRequest networkID ", (int)options[0], " mismatch. Expected ", i2p::context.GetNetID ()); return false; } if (options[1] == 2) // ver is always 2 { paddingLen = bufbe16toh (options + 2); m_SessionRequestBufferLen = paddingLen + 64; m3p2Len = bufbe16toh (options + 4); if (m3p2Len < 16) { LogPrint (eLogWarning, "NTCP2: SessionRequest m3p2len=", m3p2Len, " is too short"); return false; } // check timestamp auto ts = i2p::util::GetSecondsSinceEpoch (); uint32_t tsA = bufbe32toh (options + 8); if (tsA < ts - NTCP2_CLOCK_SKEW || tsA > ts + NTCP2_CLOCK_SKEW) { LogPrint (eLogWarning, "NTCP2: SessionRequest time difference ", (int)(ts - tsA), " exceeds clock skew"); return false; } } else { LogPrint (eLogWarning, "NTCP2: SessionRequest version mismatch ", (int)options[1]); return false; } } else { LogPrint (eLogWarning, "NTCP2: SessionRequest AEAD verification failed "); return false; } return true; } bool NTCP2Establisher::ProcessSessionCreatedMessage (uint16_t& paddingLen) { m_SessionCreatedBufferLen = 64; // decrypt Y i2p::crypto::CBCDecryption decryption; decryption.SetKey (m_RemoteIdentHash); decryption.SetIV (m_IV); decryption.Decrypt (m_SessionCreatedBuffer, 32, GetRemotePub ()); // decryption key for next block (m_K) KDF2Alice (); // decrypt and verify MAC uint8_t payload[16]; uint8_t nonce[12]; memset (nonce, 0, 12); // set nonce to zero if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionCreatedBuffer + 32, 16, GetH (), 32, GetK (), nonce, payload, 16, false)) // decrypt { // options paddingLen = bufbe16toh(payload + 2); // check timestamp auto ts = i2p::util::GetSecondsSinceEpoch (); uint32_t tsB = bufbe32toh (payload + 8); if (tsB < ts - NTCP2_CLOCK_SKEW || tsB > ts + NTCP2_CLOCK_SKEW) { LogPrint (eLogWarning, "NTCP2: SessionCreated time difference ", (int)(ts - tsB), " exceeds clock skew"); return false; } } else { LogPrint (eLogWarning, "NTCP2: SessionCreated AEAD verification failed "); return false; } return true; } bool NTCP2Establisher::ProcessSessionConfirmedMessagePart1 (const uint8_t * nonce) { // update AD MixHash (m_SessionCreatedBuffer + 32, 32); // encrypted payload int paddingLength = m_SessionCreatedBufferLen - 64; if (paddingLength > 0) MixHash (m_SessionCreatedBuffer + 64, paddingLength); if (!i2p::crypto::AEADChaCha20Poly1305 (m_SessionConfirmedBuffer, 32, GetH (), 32, GetK (), nonce, m_RemoteStaticKey, 32, false)) // decrypt S { LogPrint (eLogWarning, "NTCP2: SessionConfirmed Part1 AEAD verification failed "); return false; } return true; } bool NTCP2Establisher::ProcessSessionConfirmedMessagePart2 (const uint8_t * nonce, uint8_t * m3p2Buf) { // update AD again MixHash (m_SessionConfirmedBuffer, 48); KDF3Bob (); if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionConfirmedBuffer + 48, m3p2Len - 16, GetH (), 32, GetK (), nonce, m3p2Buf, m3p2Len - 16, false)) // decrypt // caclulate new h again for KDF data MixHash (m_SessionConfirmedBuffer + 48, m3p2Len); // h = SHA256(h || ciphertext) else { LogPrint (eLogWarning, "NTCP2: SessionConfirmed Part2 AEAD verification failed "); return false; } return true; } NTCP2Session::NTCP2Session (NTCP2Server& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter, std::shared_ptr<const i2p::data::RouterInfo::Address> addr): TransportSession (in_RemoteRouter, NTCP2_ESTABLISH_TIMEOUT), m_Server (server), m_Socket (m_Server.GetService ()), m_IsEstablished (false), m_IsTerminated (false), m_Establisher (new NTCP2Establisher), m_SendSipKey (nullptr), m_ReceiveSipKey (nullptr), #if OPENSSL_SIPHASH m_SendMDCtx(nullptr), m_ReceiveMDCtx (nullptr), #endif m_NextReceivedLen (0), m_NextReceivedBuffer (nullptr), m_NextSendBuffer (nullptr), m_ReceiveSequenceNumber (0), m_SendSequenceNumber (0), m_IsSending (false) { if (in_RemoteRouter) // Alice { m_Establisher->m_RemoteIdentHash = GetRemoteIdentity ()->GetIdentHash (); if (addr) { memcpy (m_Establisher->m_RemoteStaticKey, addr->ntcp2->staticKey, 32); memcpy (m_Establisher->m_IV, addr->ntcp2->iv, 16); m_RemoteEndpoint = boost::asio::ip::tcp::endpoint (addr->host, addr->port); } else LogPrint (eLogWarning, "NTCP2: Missing NTCP2 address"); } m_NextRouterInfoResendTime = i2p::util::GetSecondsSinceEpoch () + NTCP2_ROUTERINFO_RESEND_INTERVAL + rand ()%NTCP2_ROUTERINFO_RESEND_INTERVAL_THRESHOLD; } NTCP2Session::~NTCP2Session () { delete[] m_NextReceivedBuffer; delete[] m_NextSendBuffer; #if OPENSSL_SIPHASH if (m_SendSipKey) EVP_PKEY_free (m_SendSipKey); if (m_ReceiveSipKey) EVP_PKEY_free (m_ReceiveSipKey); if (m_SendMDCtx) EVP_MD_CTX_destroy (m_SendMDCtx); if (m_ReceiveMDCtx) EVP_MD_CTX_destroy (m_ReceiveMDCtx); #endif } void NTCP2Session::Terminate () { if (!m_IsTerminated) { m_IsTerminated = true; m_IsEstablished = false; boost::system::error_code ec; m_Socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); if (ec) LogPrint (eLogDebug, "NTCP2: Couldn't shutdown socket: ", ec.message ()); m_Socket.close (); transports.PeerDisconnected (shared_from_this ()); m_Server.RemoveNTCP2Session (shared_from_this ()); m_SendQueue.clear (); LogPrint (eLogDebug, "NTCP2: session terminated"); } } void NTCP2Session::TerminateByTimeout () { SendTerminationAndTerminate (eNTCP2IdleTimeout); } void NTCP2Session::Done () { m_Server.GetService ().post (std::bind (&NTCP2Session::Terminate, shared_from_this ())); } void NTCP2Session::Established () { m_IsEstablished = true; m_Establisher.reset (nullptr); SetTerminationTimeout (NTCP2_TERMINATION_TIMEOUT); transports.PeerConnected (shared_from_this ()); } void NTCP2Session::CreateNonce (uint64_t seqn, uint8_t * nonce) { memset (nonce, 0, 4); htole64buf (nonce + 4, seqn); } void NTCP2Session::KeyDerivationFunctionDataPhase () { uint8_t k[64]; i2p::crypto::HKDF (m_Establisher->GetCK (), nullptr, 0, "", k); // k_ab, k_ba = HKDF(ck, zerolen) memcpy (m_Kab, k, 32); memcpy (m_Kba, k + 32, 32); uint8_t master[32]; i2p::crypto::HKDF (m_Establisher->GetCK (), nullptr, 0, "ask", master, 32); // ask_master = HKDF(ck, zerolen, info="ask") uint8_t h[39]; memcpy (h, m_Establisher->GetH (), 32); memcpy (h + 32, "siphash", 7); i2p::crypto::HKDF (master, h, 39, "", master, 32); // sip_master = HKDF(ask_master, h || "siphash") i2p::crypto::HKDF (master, nullptr, 0, "", k); // sipkeys_ab, sipkeys_ba = HKDF(sip_master, zerolen) memcpy (m_Sipkeysab, k, 32); memcpy (m_Sipkeysba, k + 32, 32); } void NTCP2Session::SendSessionRequest () { m_Establisher->CreateSessionRequestMessage (); // send message boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionRequestBuffer, m_Establisher->m_SessionRequestBufferLen), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleSessionRequestSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } void NTCP2Session::HandleSessionRequestSent (const boost::system::error_code& ecode, std::size_t bytes_transferred) { (void) bytes_transferred; if (ecode) { LogPrint (eLogWarning, "NTCP2: couldn't send SessionRequest message: ", ecode.message ()); Terminate (); } else { m_Establisher->m_SessionCreatedBuffer = new uint8_t[287]; // TODO: determine actual max size // we receive first 64 bytes (32 Y, and 32 ChaCha/Poly frame) first boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionCreatedBuffer, 64), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleSessionCreatedReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } } void NTCP2Session::HandleSessionRequestReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred) { (void) bytes_transferred; if (ecode) { LogPrint (eLogWarning, "NTCP2: SessionRequest read error: ", ecode.message ()); Terminate (); } else { LogPrint (eLogDebug, "NTCP2: SessionRequest received ", bytes_transferred); uint16_t paddingLen = 0; if (m_Establisher->ProcessSessionRequestMessage (paddingLen)) { if (paddingLen > 0) { if (paddingLen <= 287 - 64) // session request is 287 bytes max { boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionRequestBuffer + 64, paddingLen), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleSessionRequestPaddingReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } else { LogPrint (eLogWarning, "NTCP2: SessionRequest padding length ", (int)paddingLen, " is too long"); Terminate (); } } else SendSessionCreated (); } else Terminate (); } } void NTCP2Session::HandleSessionRequestPaddingReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred) { if (ecode) { LogPrint (eLogWarning, "NTCP2: SessionRequest padding read error: ", ecode.message ()); Terminate (); } else SendSessionCreated (); } void NTCP2Session::SendSessionCreated () { m_Establisher->CreateSessionCreatedMessage (); // send message boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionCreatedBuffer, m_Establisher->m_SessionCreatedBufferLen), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleSessionCreatedSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } void NTCP2Session::HandleSessionCreatedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred) { if (ecode) { LogPrint (eLogWarning, "NTCP2: SessionCreated read error: ", ecode.message ()); Terminate (); } else { LogPrint (eLogDebug, "NTCP2: SessionCreated received ", bytes_transferred); uint16_t paddingLen = 0; if (m_Establisher->ProcessSessionCreatedMessage (paddingLen)) { if (paddingLen > 0) { if (paddingLen <= 287 - 64) // session created is 287 bytes max { boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionCreatedBuffer + 64, paddingLen), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleSessionCreatedPaddingReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } else { LogPrint (eLogWarning, "NTCP2: SessionCreated padding length ", (int)paddingLen, " is too long"); Terminate (); } } else SendSessionConfirmed (); } else Terminate (); } } void NTCP2Session::HandleSessionCreatedPaddingReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred) { if (ecode) { LogPrint (eLogWarning, "NTCP2: SessionCreated padding read error: ", ecode.message ()); Terminate (); } else { m_Establisher->m_SessionCreatedBufferLen += bytes_transferred; SendSessionConfirmed (); } } void NTCP2Session::SendSessionConfirmed () { uint8_t nonce[12]; CreateNonce (1, nonce); // set nonce to 1 m_Establisher->CreateSessionConfirmedMessagePart1 (nonce); memset (nonce, 0, 12); // set nonce back to 0 m_Establisher->CreateSessionConfirmedMessagePart2 (nonce); // send message boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionConfirmedBuffer, m_Establisher->m3p2Len + 48), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleSessionConfirmedSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } void NTCP2Session::HandleSessionConfirmedSent (const boost::system::error_code& ecode, std::size_t bytes_transferred) { (void) bytes_transferred; if (ecode) { LogPrint (eLogWarning, "NTCP2: couldn't send SessionConfirmed message: ", ecode.message ()); Terminate (); } else { LogPrint (eLogDebug, "NTCP2: SessionConfirmed sent"); KeyDerivationFunctionDataPhase (); // Alice data phase keys m_SendKey = m_Kab; m_ReceiveKey = m_Kba; SetSipKeys (m_Sipkeysab, m_Sipkeysba); memcpy (m_ReceiveIV.buf, m_Sipkeysba + 16, 8); memcpy (m_SendIV.buf, m_Sipkeysab + 16, 8); Established (); ReceiveLength (); // TODO: remove // m_SendQueue.push_back (CreateDeliveryStatusMsg (1)); // SendQueue (); } } void NTCP2Session::HandleSessionCreatedSent (const boost::system::error_code& ecode, std::size_t bytes_transferred) { (void) bytes_transferred; if (ecode) { LogPrint (eLogWarning, "NTCP2: couldn't send SessionCreated message: ", ecode.message ()); Terminate (); } else { LogPrint (eLogDebug, "NTCP2: SessionCreated sent"); m_Establisher->m_SessionConfirmedBuffer = new uint8_t[m_Establisher->m3p2Len + 48]; boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionConfirmedBuffer, m_Establisher->m3p2Len + 48), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleSessionConfirmedReceived , shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } } void NTCP2Session::HandleSessionConfirmedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred) { if (ecode) { LogPrint (eLogWarning, "NTCP2: SessionConfirmed read error: ", ecode.message ()); Terminate (); } else { LogPrint (eLogDebug, "NTCP2: SessionConfirmed received"); // part 1 uint8_t nonce[12]; CreateNonce (1, nonce); if (m_Establisher->ProcessSessionConfirmedMessagePart1 (nonce)) { // part 2 std::vector<uint8_t> buf(m_Establisher->m3p2Len - 16); // -MAC memset (nonce, 0, 12); // set nonce to 0 again if (m_Establisher->ProcessSessionConfirmedMessagePart2 (nonce, buf.data ())) { KeyDerivationFunctionDataPhase (); // Bob data phase keys m_SendKey = m_Kba; m_ReceiveKey = m_Kab; SetSipKeys (m_Sipkeysba, m_Sipkeysab); memcpy (m_ReceiveIV.buf, m_Sipkeysab + 16, 8); memcpy (m_SendIV.buf, m_Sipkeysba + 16, 8); // payload // process RI if (buf[0] != eNTCP2BlkRouterInfo) { LogPrint (eLogWarning, "NTCP2: unexpected block ", (int)buf[0], " in SessionConfirmed"); Terminate (); return; } auto size = bufbe16toh (buf.data () + 1); if (size > buf.size () - 3) { LogPrint (eLogError, "NTCP2: Unexpected RouterInfo size ", size, " in SessionConfirmed"); Terminate (); return; } // TODO: check flag i2p::data::RouterInfo ri (buf.data () + 4, size - 1); // 1 byte block type + 2 bytes size + 1 byte flag if (ri.IsUnreachable ()) { LogPrint (eLogError, "NTCP2: Signature verification failed in SessionConfirmed"); SendTerminationAndTerminate (eNTCP2RouterInfoSignatureVerificationFail); return; } if (i2p::util::GetMillisecondsSinceEpoch () > ri.GetTimestamp () + i2p::data::NETDB_MIN_EXPIRATION_TIMEOUT*1000LL) // 90 minutes { LogPrint (eLogError, "NTCP2: RouterInfo is too old in SessionConfirmed"); SendTerminationAndTerminate (eNTCP2Message3Error); return; } auto addr = ri.GetNTCP2AddressWithStaticKey (m_Establisher->m_RemoteStaticKey); if (!addr) { LogPrint (eLogError, "NTCP2: No NTCP2 address wth static key found in SessionConfirmed"); Terminate (); return; } i2p::data::netdb.PostI2NPMsg (CreateI2NPMessage (eI2NPDummyMsg, buf.data () + 3, size)); // TODO: should insert ri and not parse it twice // TODO: process options // ready to communicate auto existing = i2p::data::netdb.FindRouter (ri.GetRouterIdentity ()->GetIdentHash ()); // check if exists already SetRemoteIdentity (existing ? existing->GetRouterIdentity () : ri.GetRouterIdentity ()); if (m_Server.AddNTCP2Session (shared_from_this (), true)) { Established (); ReceiveLength (); } else Terminate (); } else Terminate (); } else Terminate (); } } void NTCP2Session::SetSipKeys (const uint8_t * sendSipKey, const uint8_t * receiveSipKey) { #if OPENSSL_SIPHASH m_SendSipKey = EVP_PKEY_new_raw_private_key (EVP_PKEY_SIPHASH, nullptr, sendSipKey, 16); m_SendMDCtx = EVP_MD_CTX_create (); EVP_PKEY_CTX *ctx = nullptr; EVP_DigestSignInit (m_SendMDCtx, &ctx, nullptr, nullptr, m_SendSipKey); EVP_PKEY_CTX_ctrl (ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, nullptr); m_ReceiveSipKey = EVP_PKEY_new_raw_private_key (EVP_PKEY_SIPHASH, nullptr, receiveSipKey, 16); m_ReceiveMDCtx = EVP_MD_CTX_create (); ctx = nullptr; EVP_DigestSignInit (m_ReceiveMDCtx, &ctx, NULL, NULL, m_ReceiveSipKey); EVP_PKEY_CTX_ctrl (ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, nullptr); #else m_SendSipKey = sendSipKey; m_ReceiveSipKey = receiveSipKey; #endif } void NTCP2Session::ClientLogin () { m_Establisher->CreateEphemeralKey (); SendSessionRequest (); } void NTCP2Session::ServerLogin () { m_Establisher->CreateEphemeralKey (); m_Establisher->m_SessionRequestBuffer = new uint8_t[287]; // 287 bytes max for now boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionRequestBuffer, 64), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleSessionRequestReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } void NTCP2Session::ReceiveLength () { if (IsTerminated ()) return; #ifdef __linux__ const int one = 1; setsockopt(m_Socket.native_handle(), IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one)); #endif boost::asio::async_read (m_Socket, boost::asio::buffer(&m_NextReceivedLen, 2), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleReceivedLength, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } void NTCP2Session::HandleReceivedLength (const boost::system::error_code& ecode, std::size_t bytes_transferred) { if (ecode) { if (ecode != boost::asio::error::operation_aborted) LogPrint (eLogWarning, "NTCP2: receive length read error: ", ecode.message ()); Terminate (); } else { #if OPENSSL_SIPHASH EVP_DigestSignInit (m_ReceiveMDCtx, nullptr, nullptr, nullptr, nullptr); EVP_DigestSignUpdate (m_ReceiveMDCtx, m_ReceiveIV.buf, 8); size_t l = 8; EVP_DigestSignFinal (m_ReceiveMDCtx, m_ReceiveIV.buf, &l); #else i2p::crypto::Siphash<8> (m_ReceiveIV.buf, m_ReceiveIV.buf, 8, m_ReceiveSipKey); #endif // m_NextReceivedLen comes from the network in BigEndian m_NextReceivedLen = be16toh (m_NextReceivedLen) ^ le16toh (m_ReceiveIV.key); LogPrint (eLogDebug, "NTCP2: received length ", m_NextReceivedLen); if (m_NextReceivedLen >= 16) { if (m_NextReceivedBuffer) delete[] m_NextReceivedBuffer; m_NextReceivedBuffer = new uint8_t[m_NextReceivedLen]; boost::system::error_code ec; size_t moreBytes = m_Socket.available(ec); if (!ec && moreBytes >= m_NextReceivedLen) { // read and process message immediately if available moreBytes = boost::asio::read (m_Socket, boost::asio::buffer(m_NextReceivedBuffer, m_NextReceivedLen), boost::asio::transfer_all (), ec); HandleReceived (ec, moreBytes); } else Receive (); } else { LogPrint (eLogError, "NTCP2: received length ", m_NextReceivedLen, " is too short"); Terminate (); } } } void NTCP2Session::Receive () { if (IsTerminated ()) return; #ifdef __linux__ const int one = 1; setsockopt(m_Socket.native_handle(), IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one)); #endif boost::asio::async_read (m_Socket, boost::asio::buffer(m_NextReceivedBuffer, m_NextReceivedLen), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } void NTCP2Session::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred) { if (ecode) { if (ecode != boost::asio::error::operation_aborted) LogPrint (eLogWarning, "NTCP2: receive read error: ", ecode.message ()); Terminate (); } else { m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch (); m_NumReceivedBytes += bytes_transferred + 2; // + length i2p::transport::transports.UpdateReceivedBytes (bytes_transferred); uint8_t nonce[12]; CreateNonce (m_ReceiveSequenceNumber, nonce); m_ReceiveSequenceNumber++; if (i2p::crypto::AEADChaCha20Poly1305 (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, m_NextReceivedBuffer, m_NextReceivedLen, false)) { LogPrint (eLogDebug, "NTCP2: received message decrypted"); ProcessNextFrame (m_NextReceivedBuffer, m_NextReceivedLen-16); delete[] m_NextReceivedBuffer; m_NextReceivedBuffer = nullptr; // we don't need received buffer anymore ReceiveLength (); } else { LogPrint (eLogWarning, "NTCP2: Received AEAD verification failed "); SendTerminationAndTerminate (eNTCP2DataPhaseAEADFailure); } } } void NTCP2Session::ProcessNextFrame (const uint8_t * frame, size_t len) { size_t offset = 0; while (offset < len) { uint8_t blk = frame[offset]; offset++; auto size = bufbe16toh (frame + offset); offset += 2; LogPrint (eLogDebug, "NTCP2: Block type ", (int)blk, " of size ", size); if (size > len) { LogPrint (eLogError, "NTCP2: Unexpected block length ", size); break; } switch (blk) { case eNTCP2BlkDateTime: LogPrint (eLogDebug, "NTCP2: datetime"); break; case eNTCP2BlkOptions: LogPrint (eLogDebug, "NTCP2: options"); break; case eNTCP2BlkRouterInfo: { LogPrint (eLogDebug, "NTCP2: RouterInfo flag=", (int)frame[offset]); i2p::data::netdb.PostI2NPMsg (CreateI2NPMessage (eI2NPDummyMsg, frame + offset, size)); break; } case eNTCP2BlkI2NPMessage: { LogPrint (eLogDebug, "NTCP2: I2NP"); if (size > I2NP_MAX_MESSAGE_SIZE) { LogPrint (eLogError, "NTCP2: I2NP block is too long ", size); break; } auto nextMsg = NewI2NPMessage (size); nextMsg->Align (12); // for possible tunnel msg nextMsg->len = nextMsg->offset + size + 7; // 7 more bytes for full I2NP header memcpy (nextMsg->GetNTCP2Header (), frame + offset, size); nextMsg->FromNTCP2 (); m_Handler.PutNextMessage (nextMsg); break; } case eNTCP2BlkTermination: if (size >= 9) { LogPrint (eLogDebug, "NTCP2: termination. reason=", (int)(frame[offset + 8])); Terminate (); } else LogPrint (eLogWarning, "NTCP2: Unexpected termination block size ", size); break; case eNTCP2BlkPadding: LogPrint (eLogDebug, "NTCP2: padding"); break; default: LogPrint (eLogWarning, "NTCP2: Unknown block type ", (int)blk); } offset += size; } m_Handler.Flush (); } void NTCP2Session::SetNextSentFrameLength (size_t frameLen, uint8_t * lengthBuf) { #if OPENSSL_SIPHASH EVP_DigestSignInit (m_SendMDCtx, nullptr, nullptr, nullptr, nullptr); EVP_DigestSignUpdate (m_SendMDCtx, m_SendIV.buf, 8); size_t l = 8; EVP_DigestSignFinal (m_SendMDCtx, m_SendIV.buf, &l); #else i2p::crypto::Siphash<8> (m_SendIV.buf, m_SendIV.buf, 8, m_SendSipKey); #endif // length must be in BigEndian htobe16buf (lengthBuf, frameLen ^ le16toh (m_SendIV.key)); LogPrint (eLogDebug, "NTCP2: sent length ", frameLen); } void NTCP2Session::SendI2NPMsgs (std::vector<std::shared_ptr<I2NPMessage> >& msgs) { if (msgs.empty () || IsTerminated ()) return; size_t totalLen = 0; std::vector<std::pair<uint8_t *, size_t> > encryptBufs; std::vector<boost::asio::const_buffer> bufs; std::shared_ptr<I2NPMessage> first; uint8_t * macBuf = nullptr; for (auto& it: msgs) { it->ToNTCP2 (); auto buf = it->GetNTCP2Header (); auto len = it->GetNTCP2Length (); // block header buf -= 3; buf[0] = eNTCP2BlkI2NPMessage; // blk htobe16buf (buf + 1, len); // size len += 3; totalLen += len; encryptBufs.push_back ( {buf, len} ); if (&it == &msgs.front ()) // first message { // allocate two bytes for length buf -= 2; len += 2; first = it; } if (&it == &msgs.back () && it->len + 16 < it->maxLen) // last message { // if it's long enough we add padding and MAC to it // create padding block auto paddingLen = CreatePaddingBlock (totalLen, buf + len, it->maxLen - it->len - 16); if (paddingLen) { encryptBufs.push_back ( {buf + len, paddingLen} ); len += paddingLen; totalLen += paddingLen; } macBuf = buf + len; // allocate 16 bytes for MAC len += 16; } bufs.push_back (boost::asio::buffer (buf, len)); } if (!macBuf) // last block was not enough for MAC { // allocate send buffer m_NextSendBuffer = new uint8_t[287]; // can be any size > 16, we just allocate 287 frequently // crate padding block auto paddingLen = CreatePaddingBlock (totalLen, m_NextSendBuffer, 287 - 16); // and padding block to encrypt and send if (paddingLen) encryptBufs.push_back ( {m_NextSendBuffer, paddingLen} ); bufs.push_back (boost::asio::buffer (m_NextSendBuffer, paddingLen + 16)); macBuf = m_NextSendBuffer + paddingLen; totalLen += paddingLen; } uint8_t nonce[12]; CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++; i2p::crypto::AEADChaCha20Poly1305Encrypt (encryptBufs, m_SendKey, nonce, macBuf); // encrypt buffers SetNextSentFrameLength (totalLen + 16, first->GetNTCP2Header () - 5); // frame length right before first block // send buffers m_IsSending = true; boost::asio::async_write (m_Socket, bufs, boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleI2NPMsgsSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, msgs)); } void NTCP2Session::HandleI2NPMsgsSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, std::vector<std::shared_ptr<I2NPMessage> > msgs) { HandleNextFrameSent (ecode, bytes_transferred); // msgs get destroyed here } void NTCP2Session::EncryptAndSendNextBuffer (size_t payloadLen) { if (IsTerminated ()) { delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr; return; } // encrypt uint8_t nonce[12]; CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++; i2p::crypto::AEADChaCha20Poly1305Encrypt ({ {m_NextSendBuffer + 2, payloadLen} }, m_SendKey, nonce, m_NextSendBuffer + payloadLen + 2); SetNextSentFrameLength (payloadLen + 16, m_NextSendBuffer); // send m_IsSending = true; boost::asio::async_write (m_Socket, boost::asio::buffer (m_NextSendBuffer, payloadLen + 16 + 2), boost::asio::transfer_all (), std::bind(&NTCP2Session::HandleNextFrameSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); } void NTCP2Session::HandleNextFrameSent (const boost::system::error_code& ecode, std::size_t bytes_transferred) { m_IsSending = false; delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr; if (ecode) { if (ecode != boost::asio::error::operation_aborted) LogPrint (eLogWarning, "NTCP2: Couldn't send frame ", ecode.message ()); Terminate (); } else { m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch (); m_NumSentBytes += bytes_transferred; i2p::transport::transports.UpdateSentBytes (bytes_transferred); LogPrint (eLogDebug, "NTCP2: Next frame sent ", bytes_transferred); if (m_LastActivityTimestamp > m_NextRouterInfoResendTime) { m_NextRouterInfoResendTime += NTCP2_ROUTERINFO_RESEND_INTERVAL + rand ()%NTCP2_ROUTERINFO_RESEND_INTERVAL_THRESHOLD; SendRouterInfo (); } else SendQueue (); } } void NTCP2Session::SendQueue () { if (!m_SendQueue.empty ()) { std::vector<std::shared_ptr<I2NPMessage> > msgs; size_t s = 0; while (!m_SendQueue.empty ()) { auto msg = m_SendQueue.front (); size_t len = msg->GetNTCP2Length (); if (s + len + 3 <= NTCP2_UNENCRYPTED_FRAME_MAX_SIZE) // 3 bytes block header { msgs.push_back (msg); s += (len + 3); m_SendQueue.pop_front (); } else if (len + 3 > NTCP2_UNENCRYPTED_FRAME_MAX_SIZE) { LogPrint (eLogError, "NTCP2: I2NP message of size ", len, " can't be sent. Dropped"); m_SendQueue.pop_front (); } else break; } SendI2NPMsgs (msgs); } } size_t NTCP2Session::CreatePaddingBlock (size_t msgLen, uint8_t * buf, size_t len) { if (len < 3) return 0; len -= 3; if (msgLen < 256) msgLen = 256; // for short message padding should not be always zero size_t paddingSize = (msgLen*NTCP2_MAX_PADDING_RATIO)/100; if (msgLen + paddingSize + 3 > NTCP2_UNENCRYPTED_FRAME_MAX_SIZE) paddingSize = NTCP2_UNENCRYPTED_FRAME_MAX_SIZE - msgLen -3; if (paddingSize > len) paddingSize = len; if (paddingSize) paddingSize = rand () % paddingSize; buf[0] = eNTCP2BlkPadding; // blk htobe16buf (buf + 1, paddingSize); // size memset (buf + 3, 0, paddingSize); return paddingSize + 3; } void NTCP2Session::SendRouterInfo () { if (!IsEstablished ()) return; auto riLen = i2p::context.GetRouterInfo ().GetBufferLen (); size_t payloadLen = riLen + 4; // 3 bytes block header + 1 byte RI flag m_NextSendBuffer = new uint8_t[payloadLen + 16 + 2 + 64]; // up to 64 bytes padding m_NextSendBuffer[2] = eNTCP2BlkRouterInfo; htobe16buf (m_NextSendBuffer + 3, riLen + 1); // size m_NextSendBuffer[5] = 0; // flag memcpy (m_NextSendBuffer + 6, i2p::context.GetRouterInfo ().GetBuffer (), riLen); // padding block auto paddingSize = CreatePaddingBlock (payloadLen, m_NextSendBuffer + 2 + payloadLen, 64); payloadLen += paddingSize; // encrypt and send EncryptAndSendNextBuffer (payloadLen); } void NTCP2Session::SendTermination (NTCP2TerminationReason reason) { if (!m_SendKey || !m_SendSipKey) return; m_NextSendBuffer = new uint8_t[49]; // 49 = 12 bytes message + 16 bytes MAC + 2 bytes size + up to 19 padding block // termination block m_NextSendBuffer[2] = eNTCP2BlkTermination; m_NextSendBuffer[3] = 0; m_NextSendBuffer[4] = 9; // 9 bytes block size htobe64buf (m_NextSendBuffer + 5, m_ReceiveSequenceNumber); m_NextSendBuffer[13] = (uint8_t)reason; // padding block auto paddingSize = CreatePaddingBlock (12, m_NextSendBuffer + 14, 19); // encrypt and send EncryptAndSendNextBuffer (paddingSize + 12); } void NTCP2Session::SendTerminationAndTerminate (NTCP2TerminationReason reason) { SendTermination (reason); m_Server.GetService ().post (std::bind (&NTCP2Session::Terminate, shared_from_this ())); // let termination message go } void NTCP2Session::SendI2NPMessages (const std::vector<std::shared_ptr<I2NPMessage> >& msgs) { m_Server.GetService ().post (std::bind (&NTCP2Session::PostI2NPMessages, shared_from_this (), msgs)); } void NTCP2Session::PostI2NPMessages (std::vector<std::shared_ptr<I2NPMessage> > msgs) { if (m_IsTerminated) return; for (auto it: msgs) m_SendQueue.push_back (it); if (!m_IsSending) SendQueue (); else if (m_SendQueue.size () > NTCP2_MAX_OUTGOING_QUEUE_SIZE) { LogPrint (eLogWarning, "NTCP2: outgoing messages queue size to ", GetIdentHashBase64(), " exceeds ", NTCP2_MAX_OUTGOING_QUEUE_SIZE); Terminate (); } } void NTCP2Session::SendLocalRouterInfo () { if (!IsOutgoing ()) // we send it in SessionConfirmed m_Server.GetService ().post (std::bind (&NTCP2Session::SendRouterInfo, shared_from_this ())); } NTCP2Server::NTCP2Server (): RunnableServiceWithWork ("NTCP2"), m_TerminationTimer (GetService ()), m_ProxyType(eNoProxy), m_Resolver(GetService ()) { } NTCP2Server::~NTCP2Server () { Stop (); } void NTCP2Server::Start () { if (!IsRunning ()) { StartIOService (); if(UsingProxy()) { LogPrint(eLogInfo, "NTCP2: Using proxy to connect to peers"); // TODO: resolve proxy until it is resolved boost::asio::ip::tcp::resolver::query q(m_ProxyAddress, std::to_string(m_ProxyPort)); boost::system::error_code e; auto itr = m_Resolver.resolve(q, e); if(e) LogPrint(eLogError, "NTCP2: Failed to resolve proxy ", e.message()); else { m_ProxyEndpoint.reset (new boost::asio::ip::tcp::endpoint(*itr)); if (m_ProxyEndpoint) LogPrint(eLogDebug, "NTCP2: m_ProxyEndpoint ", *m_ProxyEndpoint); } } else LogPrint(eLogInfo, "NTCP2: Proxy is not used"); // start acceptors auto& addresses = context.GetRouterInfo ().GetAddresses (); for (const auto& address: addresses) { if (!address) continue; if (address->IsPublishedNTCP2 () && address->port) { if (address->host.is_v4()) { try { auto ep = m_Address4 ? boost::asio::ip::tcp::endpoint (m_Address4->address(), address->port): boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), address->port); m_NTCP2Acceptor.reset (new boost::asio::ip::tcp::acceptor (GetService (), ep)); } catch ( std::exception & ex ) { LogPrint(eLogError, "NTCP2: Failed to bind to v4 port ", address->port, ex.what()); ThrowFatal ("Unable to start IPv4 NTCP2 transport at port ", address->port, ": ", ex.what ()); continue; } LogPrint (eLogInfo, "NTCP2: Start listening v4 TCP port ", address->port); auto conn = std::make_shared<NTCP2Session>(*this); m_NTCP2Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAccept, this, conn, std::placeholders::_1)); } else if (address->host.is_v6() && (context.SupportsV6 () || context.SupportsMesh ())) { m_NTCP2V6Acceptor.reset (new boost::asio::ip::tcp::acceptor (GetService ())); try { m_NTCP2V6Acceptor->open (boost::asio::ip::tcp::v6()); m_NTCP2V6Acceptor->set_option (boost::asio::ip::v6_only (true)); m_NTCP2V6Acceptor->set_option (boost::asio::socket_base::reuse_address (true)); m_NTCP2V6Acceptor->bind (boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), address->port)); m_NTCP2V6Acceptor->listen (); LogPrint (eLogInfo, "NTCP2: Start listening v6 TCP port ", address->port); auto conn = std::make_shared<NTCP2Session> (*this); m_NTCP2V6Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAcceptV6, this, conn, std::placeholders::_1)); } catch ( std::exception & ex ) { LogPrint(eLogError, "NTCP2: failed to bind to v6 port ", address->port, ": ", ex.what()); ThrowFatal ("Unable to start IPv6 NTCP2 transport at port ", address->port, ": ", ex.what ()); continue; } } } } ScheduleTermination (); } } void NTCP2Server::Stop () { { // we have to copy it because Terminate changes m_NTCP2Sessions auto ntcpSessions = m_NTCP2Sessions; for (auto& it: ntcpSessions) it.second->Terminate (); for (auto& it: m_PendingIncomingSessions) it->Terminate (); } m_NTCP2Sessions.clear (); if (IsRunning ()) { m_TerminationTimer.cancel (); m_ProxyEndpoint = nullptr; } StopIOService (); } bool NTCP2Server::AddNTCP2Session (std::shared_ptr<NTCP2Session> session, bool incoming) { if (!session) return false; if (incoming) m_PendingIncomingSessions.remove (session); if (!session->GetRemoteIdentity ()) return false; auto& ident = session->GetRemoteIdentity ()->GetIdentHash (); auto it = m_NTCP2Sessions.find (ident); if (it != m_NTCP2Sessions.end ()) { LogPrint (eLogWarning, "NTCP2: session to ", ident.ToBase64 (), " already exists"); if (incoming) // replace by new session it->second->Terminate (); else return false; } m_NTCP2Sessions.insert (std::make_pair (ident, session)); return true; } void NTCP2Server::RemoveNTCP2Session (std::shared_ptr<NTCP2Session> session) { if (session && session->GetRemoteIdentity ()) m_NTCP2Sessions.erase (session->GetRemoteIdentity ()->GetIdentHash ()); } std::shared_ptr<NTCP2Session> NTCP2Server::FindNTCP2Session (const i2p::data::IdentHash& ident) { auto it = m_NTCP2Sessions.find (ident); if (it != m_NTCP2Sessions.end ()) return it->second; return nullptr; } void NTCP2Server::Connect(std::shared_ptr<NTCP2Session> conn) { if (!conn || conn->GetRemoteEndpoint ().address ().is_unspecified ()) { LogPrint (eLogError, "NTCP2: Can't connect to unspecified address"); return; } LogPrint (eLogDebug, "NTCP2: Connecting to ", conn->GetRemoteEndpoint ()); GetService ().post([this, conn]() { if (this->AddNTCP2Session (conn)) { auto timer = std::make_shared<boost::asio::deadline_timer>(GetService ()); auto timeout = NTCP2_CONNECT_TIMEOUT * 5; conn->SetTerminationTimeout(timeout * 2); timer->expires_from_now (boost::posix_time::seconds(timeout)); timer->async_wait ([conn, timeout](const boost::system::error_code& ecode) { if (ecode != boost::asio::error::operation_aborted) { LogPrint (eLogInfo, "NTCP2: Not connected in ", timeout, " seconds"); conn->Terminate (); } }); // bind to local address std::shared_ptr<boost::asio::ip::tcp::endpoint> localAddress; if (conn->GetRemoteEndpoint ().address ().is_v6 ()) { if (i2p::util::net::IsYggdrasilAddress (conn->GetRemoteEndpoint ().address ())) localAddress = m_YggdrasilAddress; else localAddress = m_Address6; conn->GetSocket ().open (boost::asio::ip::tcp::v6 ()); } else { localAddress = m_Address4; conn->GetSocket ().open (boost::asio::ip::tcp::v4 ()); } if (localAddress) { boost::system::error_code ec; conn->GetSocket ().bind (*localAddress, ec); if (ec) LogPrint (eLogError, "NTCP2: can't bind to ", localAddress->address ().to_string (), ": ", ec.message ()); } conn->GetSocket ().async_connect (conn->GetRemoteEndpoint (), std::bind (&NTCP2Server::HandleConnect, this, std::placeholders::_1, conn, timer)); } else conn->Terminate (); }); } void NTCP2Server::HandleConnect (const boost::system::error_code& ecode, std::shared_ptr<NTCP2Session> conn, std::shared_ptr<boost::asio::deadline_timer> timer) { timer->cancel (); if (ecode) { LogPrint (eLogInfo, "NTCP2: Connect error ", ecode.message ()); conn->Terminate (); } else { LogPrint (eLogDebug, "NTCP2: Connected to ", conn->GetRemoteEndpoint ()); conn->ClientLogin (); } } void NTCP2Server::HandleAccept (std::shared_ptr<NTCP2Session> conn, const boost::system::error_code& error) { if (!error) { boost::system::error_code ec; auto ep = conn->GetSocket ().remote_endpoint(ec); if (!ec) { LogPrint (eLogDebug, "NTCP2: Connected from ", ep); if (conn) { conn->SetRemoteEndpoint (ep); conn->ServerLogin (); m_PendingIncomingSessions.push_back (conn); conn = nullptr; } } else LogPrint (eLogError, "NTCP2: Connected from error ", ec.message ()); } else LogPrint (eLogError, "NTCP2: Accept error ", error.message ()); if (error != boost::asio::error::operation_aborted) { if (!conn) // connection is used, create new one conn = std::make_shared<NTCP2Session> (*this); else // reuse failed conn->Close (); m_NTCP2Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAccept, this, conn, std::placeholders::_1)); } } void NTCP2Server::HandleAcceptV6 (std::shared_ptr<NTCP2Session> conn, const boost::system::error_code& error) { if (!error) { boost::system::error_code ec; auto ep = conn->GetSocket ().remote_endpoint(ec); if (!ec) { LogPrint (eLogDebug, "NTCP2: Connected from ", ep); if (conn) { conn->SetRemoteEndpoint (ep); conn->ServerLogin (); m_PendingIncomingSessions.push_back (conn); } } else LogPrint (eLogError, "NTCP2: Connected from error ", ec.message ()); } if (error != boost::asio::error::operation_aborted) { conn = std::make_shared<NTCP2Session> (*this); m_NTCP2V6Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAcceptV6, this, conn, std::placeholders::_1)); } } void NTCP2Server::ScheduleTermination () { m_TerminationTimer.expires_from_now (boost::posix_time::seconds(NTCP2_TERMINATION_CHECK_TIMEOUT)); m_TerminationTimer.async_wait (std::bind (&NTCP2Server::HandleTerminationTimer, this, std::placeholders::_1)); } void NTCP2Server::HandleTerminationTimer (const boost::system::error_code& ecode) { if (ecode != boost::asio::error::operation_aborted) { auto ts = i2p::util::GetSecondsSinceEpoch (); // established for (auto& it: m_NTCP2Sessions) if (it.second->IsTerminationTimeoutExpired (ts)) { auto session = it.second; LogPrint (eLogDebug, "NTCP2: No activity for ", session->GetTerminationTimeout (), " seconds"); session->TerminateByTimeout (); // it doesn't change m_NTCP2Session right a way } // pending for (auto it = m_PendingIncomingSessions.begin (); it != m_PendingIncomingSessions.end ();) { if ((*it)->IsEstablished () || (*it)->IsTerminationTimeoutExpired (ts)) { (*it)->Terminate (); it = m_PendingIncomingSessions.erase (it); // established of expired } else if ((*it)->IsTerminated ()) it = m_PendingIncomingSessions.erase (it); // already terminated else it++; } ScheduleTermination (); } } void NTCP2Server::ConnectWithProxy (std::shared_ptr<NTCP2Session> conn) { if(!m_ProxyEndpoint) return; if (!conn || conn->GetRemoteEndpoint ().address ().is_unspecified ()) { LogPrint (eLogError, "NTCP2: Can't connect to unspecified address"); return; } GetService().post([this, conn]() { if (this->AddNTCP2Session (conn)) { auto timer = std::make_shared<boost::asio::deadline_timer>(GetService()); auto timeout = NTCP2_CONNECT_TIMEOUT * 5; conn->SetTerminationTimeout(timeout * 2); timer->expires_from_now (boost::posix_time::seconds(timeout)); timer->async_wait ([conn, timeout](const boost::system::error_code& ecode) { if (ecode != boost::asio::error::operation_aborted) { LogPrint (eLogInfo, "NTCP2: Not connected in ", timeout, " seconds"); conn->Terminate (); } }); conn->GetSocket ().async_connect (*m_ProxyEndpoint, std::bind (&NTCP2Server::HandleProxyConnect, this, std::placeholders::_1, conn, timer)); } }); } void NTCP2Server::UseProxy(ProxyType proxytype, const std::string& addr, uint16_t port, const std::string& user, const std::string& pass) { m_ProxyType = proxytype; m_ProxyAddress = addr; m_ProxyPort = port; if (m_ProxyType == eHTTPProxy ) m_ProxyAuthorization = i2p::http::CreateBasicAuthorizationString (user, pass); } void NTCP2Server::HandleProxyConnect(const boost::system::error_code& ecode, std::shared_ptr<NTCP2Session> conn, std::shared_ptr<boost::asio::deadline_timer> timer) { if (ecode) { LogPrint(eLogWarning, "NTCP2: failed to connect to proxy ", ecode.message()); timer->cancel(); conn->Terminate(); return; } switch (m_ProxyType) { case eSocksProxy: { // TODO: support username/password auth etc static const uint8_t buff[3] = {0x05, 0x01, 0x00}; boost::asio::async_write(conn->GetSocket(), boost::asio::buffer(buff, 3), boost::asio::transfer_all(), [] (const boost::system::error_code & ec, std::size_t transferred) { (void) transferred; if(ec) { LogPrint(eLogWarning, "NTCP2: socks5 write error ", ec.message()); } }); auto readbuff = std::make_shared<std::vector<uint8_t> >(2); boost::asio::async_read(conn->GetSocket(), boost::asio::buffer(readbuff->data (), 2), [this, readbuff, timer, conn](const boost::system::error_code & ec, std::size_t transferred) { if(ec) { LogPrint(eLogError, "NTCP2: socks5 read error ", ec.message()); timer->cancel(); conn->Terminate(); return; } else if(transferred == 2) { if((*readbuff)[1] == 0x00) { AfterSocksHandshake(conn, timer); return; } else if ((*readbuff)[1] == 0xff) { LogPrint(eLogError, "NTCP2: socks5 proxy rejected authentication"); timer->cancel(); conn->Terminate(); return; } LogPrint(eLogError, "NTCP2:", (int)(*readbuff)[1]); } LogPrint(eLogError, "NTCP2: socks5 server gave invalid response"); timer->cancel(); conn->Terminate(); }); break; } case eHTTPProxy: { auto& ep = conn->GetRemoteEndpoint (); i2p::http::HTTPReq req; req.method = "CONNECT"; req.version ="HTTP/1.1"; if(ep.address ().is_v6 ()) req.uri = "[" + ep.address ().to_string() + "]:" + std::to_string(ep.port ()); else req.uri = ep.address ().to_string() + ":" + std::to_string(ep.port ()); if (!m_ProxyAuthorization.empty ()) req.AddHeader("Proxy-Authorization", m_ProxyAuthorization); boost::asio::streambuf writebuff; std::ostream out(&writebuff); out << req.to_string(); boost::asio::async_write(conn->GetSocket(), writebuff.data(), boost::asio::transfer_all(), [](const boost::system::error_code & ec, std::size_t transferred) { (void) transferred; if(ec) LogPrint(eLogError, "NTCP2: http proxy write error ", ec.message()); }); boost::asio::streambuf * readbuff = new boost::asio::streambuf; boost::asio::async_read_until(conn->GetSocket(), *readbuff, "\r\n\r\n", [readbuff, timer, conn] (const boost::system::error_code & ec, std::size_t transferred) { if(ec) { LogPrint(eLogError, "NTCP2: http proxy read error ", ec.message()); timer->cancel(); conn->Terminate(); } else { readbuff->commit(transferred); i2p::http::HTTPRes res; if(res.parse(boost::asio::buffer_cast<const char*>(readbuff->data()), readbuff->size()) > 0) { if(res.code == 200) { timer->cancel(); conn->ClientLogin(); delete readbuff; return; } else LogPrint(eLogError, "NTCP2: http proxy rejected request ", res.code); } else LogPrint(eLogError, "NTCP2: http proxy gave malformed response"); timer->cancel(); conn->Terminate(); delete readbuff; } }); break; } default: LogPrint(eLogError, "NTCP2: unknown proxy type, invalid state"); } } void NTCP2Server::AfterSocksHandshake(std::shared_ptr<NTCP2Session> conn, std::shared_ptr<boost::asio::deadline_timer> timer) { // build request size_t sz = 6; // header + port auto buff = std::make_shared<std::vector<int8_t> >(256); auto readbuff = std::make_shared<std::vector<int8_t> >(256); (*buff)[0] = 0x05; (*buff)[1] = 0x01; (*buff)[2] = 0x00; auto& ep = conn->GetRemoteEndpoint (); if(ep.address ().is_v4 ()) { (*buff)[3] = 0x01; auto addrbytes = ep.address ().to_v4().to_bytes(); sz += 4; memcpy(buff->data () + 4, addrbytes.data(), 4); } else if (ep.address ().is_v6 ()) { (*buff)[3] = 0x04; auto addrbytes = ep.address ().to_v6().to_bytes(); sz += 16; memcpy(buff->data () + 4, addrbytes.data(), 16); } else { // We mustn't really fall here because all connections are made to IP addresses LogPrint(eLogError, "NTCP2: Tried to connect to unexpected address via proxy"); return; } htobe16buf(buff->data () + sz - 2, ep.port ()); boost::asio::async_write(conn->GetSocket(), boost::asio::buffer(buff->data (), sz), boost::asio::transfer_all(), [buff](const boost::system::error_code & ec, std::size_t written) { if(ec) { LogPrint(eLogError, "NTCP2: failed to write handshake to socks proxy ", ec.message()); return; } }); boost::asio::async_read(conn->GetSocket(), boost::asio::buffer(readbuff->data (), 10), [timer, conn, sz, readbuff](const boost::system::error_code & e, std::size_t transferred) { if(e) { LogPrint(eLogError, "NTCP2: socks proxy read error ", e.message()); } else if(transferred == sz) { if((*readbuff)[1] == 0x00) { timer->cancel(); conn->ClientLogin(); return; } } timer->cancel(); conn->Terminate(); }); } void NTCP2Server::SetLocalAddress (const boost::asio::ip::address& localAddress) { auto addr = std::make_shared<boost::asio::ip::tcp::endpoint>(boost::asio::ip::tcp::endpoint(localAddress, 0)); if (localAddress.is_v6 ()) { if (i2p::util::net::IsYggdrasilAddress (localAddress)) m_YggdrasilAddress = addr; else m_Address6 = addr; } else m_Address4 = addr; } } }
; A014020: Inverse of 11th cyclotomic polynomial. ; 1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0 lpb $0,1 sub $0,11 lpe mov $1,$0 sub $1,2 bin $1,$0
; ; Generic pseudo graphics routines for text-only platforms ; Version for the 2x3 graphics symbols ; ; Written by Stefano Bodrato 19/12/2006 ; ; ; Clears graph screen. ; ; ; $Id: clsgraph.asm,v 1.5 2017-01-02 22:57:59 aralbrec Exp $ ; INCLUDE "graphics/grafix.inc" SECTION code_clib PUBLIC cleargraphics PUBLIC _cleargraphics EXTERN base_graphics .cleargraphics ._cleargraphics ld hl,(base_graphics) ld bc,maxx*maxy/6-1 .clean ld (hl),blankch inc hl dec bc ld a,b or c jr nz,clean ret
; A056791: Weight of binary expansion of n + length of binary expansion of n. ; 1,2,3,4,4,5,5,6,5,6,6,7,6,7,7,8,6,7,7,8,7,8,8,9,7,8,8,9,8,9,9,10,7,8,8,9,8,9,9,10,8,9,9,10,9,10,10,11,8,9,9,10,9,10,10,11,9,10,10,11,10,11,11,12,8,9,9,10,9,10,10,11,9,10,10,11,10,11,11,12,9,10,10,11,10,11,11 mov $2,$0 lpb $0 add $0,1 div $2,2 sub $0,$2 lpe mov $1,$0 add $1,1
; A063494: a(n) = (2*n - 1)*(7*n^2 - 7*n + 3)/3. ; Submitted by Jon Maiga ; 1,17,75,203,429,781,1287,1975,2873,4009,5411,7107,9125,11493,14239,17391,20977,25025,29563,34619,40221,46397,53175,60583,68649,77401,86867,97075,108053,119829,132431,145887,160225,175473,191659,208811,226957,246125,266343,287639,310041,333577,358275,384163,411269,439621,469247,500175,532433,566049,601051,637467,675325,714653,755479,797831,841737,887225,934323,983059,1033461,1085557,1139375,1194943,1252289,1311441,1372427,1435275,1500013,1566669,1635271,1705847,1778425,1853033,1929699,2008451 mul $0,2 add $0,2 mov $1,$0 bin $0,3 mul $0,7 add $0,$1 add $0,$1 sub $0,4 div $0,2 add $0,1
; A265021: Sum of fifth powers of the first n even numbers. ; 0,32,1056,8832,41600,141600,390432,928256,1976832,3866400,7066400,12220032,20182656,32064032,49274400,73574400,107128832,152564256,213030432,292265600,394665600,525356832,690273056,896236032,1151040000,1463540000,1843744032,2302909056,2853640832,3509997600,4287597600,5203730432,6277472256,7529804832,8983738400,10664438400,12599356032,14818362656,17353888032,20241062400,23517862400,27225260832,31407380256,36111650432,41388969600,47293869600,53884684832,61223725056,69377452032,78416660000,88416660000,99457468032,111623997056,125006252832,139699533600,155804633600,173428050432,192682196256,213685612832,236563190400,261446390400,288473472032,317789722656,349547692032,383907430400,421036730400,461111372832,504315376256,550841250432,600890253600,654672653600,712407992832,774325357056,840663648032,911671860000,987609360000,1068746172032,1155363265056,1247752844832,1346218649600,1451076249600,1562653350432,1681290100256,1807339400832,1941167222400,2083152922400,2233689568032,2393184262656,2562058476032,2740748378400,2929705178400,3129395464832,3340301552256,3562921830432,3797771117600,4045381017600,4306300280832,4581095169056,4870349824032,5174666640000,5494666640000,5830989856032,6184295713056,6555263416832,6944592345600,7353002445600,7781234630432,8230051184256,8700236168832,9192595834400,9707959034400,10247177644032,10811126982656,11400706240032,12016838906400,12660473206400,13332582536832,14034165908256,14766248390432,15529881561600,16326143961600,17156141548832,18021008161056,18921905980032,19860026000000,20836588500000,21852843520032,22910071341056,24009582968832,25152720621600,26340858221600,27575401890432,28857790448256,30189495916832,31572024026400,33006914726400,34495742700032,36040117882656,37641685984032,39302129014400,41023165814400,42806552588832,44654083444256,46567590930432,48548946585600,50600061485600,52722886796832,54919414333056,57191677116032,59541749940000,61971749940000,64483837164032,67080215149056,69763131500832,72534878477600,75397793577600,78354260130432,81406707892256,84557613644832,87809501798400,91164944998400,94626564736032,98197031962656,101879067708032,105675443702400,109588983002400,113622560620832,117779104160256,122061594450432,126473066189600,131016608589600,135695366024832,140512538685056,145471383232032,150575213460000,155827400960000,161231375788032,166790627137056,172508704012832,178389215913600,184435833513600,190652289350432,197042378516256,203609959352832,210358954150400,217293349850400,224417198752032,231734619222656,239249796412032,246966982970400,254890499770400,263024736632832,271374153056256,279943278950432,288736715373600,297759135273600,307015284232832,316509981217056,326248119328032,336234666560000,346474666560000,356973239392032,367735582305056,378766970504832,390072757929600,401658378029600,413529344550432,425691252320256,438149778040832,450910681082400,463979804282400,477363074748032,491066504662656,505096192096032,519458321818400,534159166118400,549205085624832,564602530132256,580358039430432,596478244137600,612969866537600,629839721420832,647094716929056,664741855404032,682788234240000,701241046740000,720107582976032,739395230653056,759111475976832,779263904525600,799860202125600,820908155730432,842415654304256,864390689708832,886841357594400,909775858294400,933202497724032,957129688282656,981565949760032,1006519910246400,1032000307046400,1058015987596832,1084575910388256,1111689145890432,1139364877481600,1167612402381600,1196441132588832,1225860595821056,1255880436460032,1286510416500000 mov $1,$0 add $1,1 mov $2,$0 add $2,$0 mul $1,$2 mov $3,$1 pow $1,2 sub $1,$3 mul $1,$3 div $1,48 mul $1,32
* Sprite size * * Mode 4 * +------|-----+ * |aaaaaaaaaaaa| * |aaggggggggaa| * |aaggggggggaa| * -aaggaaaaaaaa- * |aaggaaggggaa| * |aaggaaggggaa| * |aaaaaaaaaaaa| * +------|-----+ * section sprite xdef mes_size include 'dev8_keys_sysspr' mes_size dc.b 0,sp.wsize end
// Dexforce_DF_Source.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include "solution.h" #include "../Firmware/camera_param.h" #include "../cmd/getopt.h" const char* help_info = "Examples:\n\ \n\ 1.Capture:\n\ test.exe --capture --ip 192.168.x.x --patterns ./patterns_data --calib ./param.txt --pointcloud ./pointcloud_data\n\ \n\ 2.Read:\n\ test.exe --read --patterns ./patterns_data --calib ./param.txt --pointcloud ./pointcloud_data\n\ \n\ "; extern int optind, opterr, optopt; extern char* optarg; enum opt_set { IP, CAPTURE, READ, PATTERNS, CALIB, POINTCLOUD, HELP }; static struct option long_options[] = { {"ip",required_argument,NULL,IP}, {"capture",no_argument,NULL,CAPTURE}, {"read",no_argument,NULL,READ}, {"patterns", required_argument, NULL, PATTERNS}, {"calib", required_argument, NULL, CALIB}, {"pointcloud", required_argument, NULL, POINTCLOUD}, {"help",no_argument,NULL,HELP}, }; const char* camera_ip; const char* patterns_path; const char* calib_path; const char* pointcloud_path; int command = HELP; void capture(); void read(); const char* camera_id; const char* path; int main(int argc, char* argv[]) { int c = 0; while (EOF != (c = getopt_long(argc, argv, "i:h", long_options, NULL))) { switch (c) { case IP: camera_ip = optarg; break; case PATTERNS: patterns_path = optarg; break; case CALIB: calib_path = optarg; break; case POINTCLOUD: pointcloud_path = optarg; break; case '?': printf("unknow option:%c\n", optopt); break; default: command = c; break; } } switch (command) { case HELP: printf(help_info); break; case CAPTURE: capture(); break; case READ: read(); break; default: break; } /*************************************************************************************************/ } void capture() { struct CameraCalibParam calibration_param_; DfSolution solution_machine_; std::vector<cv::Mat> patterns_; bool ret = solution_machine_.captureMixedVariableWavelengthPatterns(camera_ip, patterns_); if (ret) { solution_machine_.savePatterns(patterns_path, patterns_); } ret = solution_machine_.getCameraCalibData(camera_ip, calibration_param_); if (ret) { solution_machine_.saveCameraCalibData(calib_path, calibration_param_); } else { std::cout << "Get Camera Calib Data Failure!"; } solution_machine_.reconstructMixedVariableWavelengthPatternsBaseXYSR(patterns_, calibration_param_, pointcloud_path); } void read() { struct CameraCalibParam calibration_param_; DfSolution solution_machine_; std::vector<cv::Mat> patterns_; bool ret = solution_machine_.readImages(patterns_path, patterns_); if (!ret) { std::cout << "Read Image Error!"; } ret = solution_machine_.readCameraCalibData(calib_path, calibration_param_); if (!ret) { std::cout << "Read Calib Param Error!" << std::endl; } solution_machine_.reconstructMixedVariableWavelengthPatternsBaseXYSR(patterns_, calibration_param_,pointcloud_path); }
; A021803: Decimal expansion of 1/799. ; 0,0,1,2,5,1,5,6,4,4,5,5,5,6,9,4,6,1,8,2,7,2,8,4,1,0,5,1,3,1,4,1,4,2,6,7,8,3,4,7,9,3,4,9,1,8,6,4,8,3,1,0,3,8,7,9,8,4,9,8,1,2,2,6,5,3,3,1,6,6,4,5,8,0,7,2,5,9,0,7,3,8,4,2,3,0,2,8,7,8,5,9,8,2,4,7,8,0,9 add $0,1 mov $2,10 pow $2,$0 mov $0,$2 div $0,799 mod $0,10
/**************************************************************************** * * Copyright (c) 2013-2020 PX4 Development Team. 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 PX4 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. * ****************************************************************************/ /** * @file accelerometer_calibration.cpp * * Implementation of accelerometer calibration. * * Transform acceleration vector to true orientation, scale and offset * * ===== Model ===== * accel_corr = accel_T * (accel_raw - accel_offs) * * accel_corr[3] - fully corrected acceleration vector in body frame * accel_T[3][3] - accelerometers transform matrix, rotation and scaling transform * accel_raw[3] - raw acceleration vector * accel_offs[3] - acceleration offset vector * * ===== Calibration ===== * * Reference vectors * accel_corr_ref[6][3] = [ g 0 0 ] // nose up * | -g 0 0 | // nose down * | 0 g 0 | // left side down * | 0 -g 0 | // right side down * | 0 0 g | // on back * [ 0 0 -g ] // level * accel_raw_ref[6][3] * * accel_corr_ref[i] = accel_T * (accel_raw_ref[i] - accel_offs), i = 0...5 * * 6 reference vectors * 3 axes = 18 equations * 9 (accel_T) + 3 (accel_offs) = 12 unknown constants * * Find accel_offs * * accel_offs[i] = (accel_raw_ref[i*2][i] + accel_raw_ref[i*2+1][i]) / 2 * * Find accel_T * * 9 unknown constants * need 9 equations -> use 3 of 6 measurements -> 3 * 3 = 9 equations * * accel_corr_ref[i*2] = accel_T * (accel_raw_ref[i*2] - accel_offs), i = 0...2 * * Solve separate system for each row of accel_T: * * accel_corr_ref[j*2][i] = accel_T[i] * (accel_raw_ref[j*2] - accel_offs), j = 0...2 * * A * x = b * * x = [ accel_T[0][i] ] * | accel_T[1][i] | * [ accel_T[2][i] ] * * b = [ accel_corr_ref[0][i] ] // One measurement per side is enough * | accel_corr_ref[2][i] | * [ accel_corr_ref[4][i] ] * * a[i][j] = accel_raw_ref[i][j] - accel_offs[j], i = 0;2;4, j = 0...2 * * Matrix A is common for all three systems: * A = [ a[0][0] a[0][1] a[0][2] ] * | a[2][0] a[2][1] a[2][2] | * [ a[4][0] a[4][1] a[4][2] ] * * x = A^-1 * b * * accel_T = A^-1 * g * g = 9.80665 * * ===== Rotation ===== * * Calibrating using model: * accel_corr = accel_T_r * (rot * accel_raw - accel_offs_r) * * Actual correction: * accel_corr = rot * accel_T * (accel_raw - accel_offs) * * Known: accel_T_r, accel_offs_r, rot * Unknown: accel_T, accel_offs * * Solution: * accel_T_r * (rot * accel_raw - accel_offs_r) = rot * accel_T * (accel_raw - accel_offs) * rot^-1 * accel_T_r * (rot * accel_raw - accel_offs_r) = accel_T * (accel_raw - accel_offs) * rot^-1 * accel_T_r * rot * accel_raw - rot^-1 * accel_T_r * accel_offs_r = accel_T * accel_raw - accel_T * accel_offs) * => accel_T = rot^-1 * accel_T_r * rot * => accel_offs = rot^-1 * accel_offs_r * * @author Anton Babushkin <anton.babushkin@me.com> */ #include "accelerometer_calibration.h" #include "calibration_messages.h" #include "calibration_routines.h" #include "commander_helper.h" #include "factory_calibration_storage.h" #include <px4_platform_common/defines.h> #include <px4_platform_common/posix.h> #include <px4_platform_common/time.h> #include <drivers/drv_hrt.h> #include <lib/sensor_calibration/Accelerometer.hpp> #include <lib/sensor_calibration/Utilities.hpp> #include <lib/mathlib/mathlib.h> #include <lib/geo/geo.h> #include <matrix/math.hpp> #include <lib/conversion/rotation.h> #include <lib/parameters/param.h> #include <lib/systemlib/err.h> #include <lib/systemlib/mavlink_log.h> #include <uORB/Subscription.hpp> #include <uORB/SubscriptionBlocking.hpp> #include <uORB/SubscriptionMultiArray.hpp> #include <uORB/topics/sensor_accel.h> #include <uORB/topics/vehicle_attitude.h> using namespace matrix; using namespace time_literals; static constexpr char sensor_name[] {"accel"}; static constexpr unsigned MAX_ACCEL_SENS = 4; /// Data passed to calibration worker routine struct accel_worker_data_s { orb_advert_t *mavlink_log_pub{nullptr}; unsigned done_count{0}; float accel_ref[MAX_ACCEL_SENS][detect_orientation_side_count][3] {}; float accel_temperature_ref[MAX_ACCEL_SENS] {NAN, NAN, NAN, NAN}; }; // Read specified number of accelerometer samples, calculate average and dispersion. static calibrate_return read_accelerometer_avg(float (&accel_avg)[MAX_ACCEL_SENS][detect_orientation_side_count][3], float (&accel_temperature_avg)[MAX_ACCEL_SENS], unsigned orient, unsigned samples_num) { Vector3f accel_sum[MAX_ACCEL_SENS] {}; float temperature_sum[MAX_ACCEL_SENS] {NAN, NAN, NAN, NAN}; unsigned counts[MAX_ACCEL_SENS] {}; unsigned errcount = 0; // sensor thermal corrections uORB::Subscription sensor_correction_sub{ORB_ID(sensor_correction)}; sensor_correction_s sensor_correction{}; sensor_correction_sub.copy(&sensor_correction); uORB::SubscriptionBlocking<sensor_accel_s> accel_sub[MAX_ACCEL_SENS] { {ORB_ID(sensor_accel), 0, 0}, {ORB_ID(sensor_accel), 0, 1}, {ORB_ID(sensor_accel), 0, 2}, {ORB_ID(sensor_accel), 0, 3}, }; /* use the first sensor to pace the readout, but do per-sensor counts */ while (counts[0] < samples_num) { if (accel_sub[0].updatedBlocking(100000)) { for (unsigned accel_index = 0; accel_index < MAX_ACCEL_SENS; accel_index++) { sensor_accel_s arp; while (accel_sub[accel_index].update(&arp)) { // fetch optional thermal offset corrections in sensor/board frame Vector3f offset{0, 0, 0}; sensor_correction_sub.update(&sensor_correction); if (sensor_correction.timestamp > 0 && arp.device_id != 0) { for (uint8_t correction_index = 0; correction_index < MAX_ACCEL_SENS; correction_index++) { if (sensor_correction.accel_device_ids[correction_index] == arp.device_id) { switch (correction_index) { case 0: offset = Vector3f{sensor_correction.accel_offset_0}; break; case 1: offset = Vector3f{sensor_correction.accel_offset_1}; break; case 2: offset = Vector3f{sensor_correction.accel_offset_2}; break; case 3: offset = Vector3f{sensor_correction.accel_offset_3}; break; } } } } accel_sum[accel_index] += Vector3f{arp.x, arp.y, arp.z} - offset; counts[accel_index]++; if (!PX4_ISFINITE(temperature_sum[accel_index])) { // set first valid value temperature_sum[accel_index] = (arp.temperature * counts[accel_index]); } else { temperature_sum[accel_index] += arp.temperature; } } } } else { errcount++; continue; } if (errcount > samples_num / 10) { return calibrate_return_error; } } // rotate sensor measurements from sensor to body frame using board rotation matrix const Dcmf board_rotation = calibration::GetBoardRotationMatrix(); for (unsigned s = 0; s < MAX_ACCEL_SENS; s++) { accel_sum[s] = board_rotation * accel_sum[s]; } for (unsigned s = 0; s < MAX_ACCEL_SENS; s++) { const Vector3f avg{accel_sum[s] / counts[s]}; avg.copyTo(accel_avg[s][orient]); accel_temperature_avg[s] = temperature_sum[s] / counts[s]; } return calibrate_return_ok; } static calibrate_return accel_calibration_worker(detect_orientation_return orientation, void *data) { static constexpr unsigned samples_num = 750; accel_worker_data_s *worker_data = (accel_worker_data_s *)(data); calibration_log_info(worker_data->mavlink_log_pub, "[cal] Hold still, measuring %s side", detect_orientation_str(orientation)); read_accelerometer_avg(worker_data->accel_ref, worker_data->accel_temperature_ref, orientation, samples_num); // check accel for (unsigned accel_index = 0; accel_index < MAX_ACCEL_SENS; accel_index++) { switch (orientation) { case ORIENTATION_TAIL_DOWN: // [ g, 0, 0 ] if (worker_data->accel_ref[accel_index][ORIENTATION_TAIL_DOWN][0] < 0.f) { calibration_log_emergency(worker_data->mavlink_log_pub, "[cal] accel %d invalid X-axis, check rotation", accel_index); return calibrate_return_error; } break; case ORIENTATION_NOSE_DOWN: // [ -g, 0, 0 ] if (worker_data->accel_ref[accel_index][ORIENTATION_NOSE_DOWN][0] > 0.f) { calibration_log_emergency(worker_data->mavlink_log_pub, "[cal] accel %d invalid X-axis, check rotation", accel_index); return calibrate_return_error; } break; case ORIENTATION_LEFT: // [ 0, g, 0 ] if (worker_data->accel_ref[accel_index][ORIENTATION_LEFT][1] < 0.f) { calibration_log_emergency(worker_data->mavlink_log_pub, "[cal] accel %d invalid Y-axis, check rotation", accel_index); return calibrate_return_error; } break; case ORIENTATION_RIGHT: // [ 0, -g, 0 ] if (worker_data->accel_ref[accel_index][ORIENTATION_RIGHT][1] > 0.f) { calibration_log_emergency(worker_data->mavlink_log_pub, "[cal] accel %d invalid Y-axis, check rotation", accel_index); return calibrate_return_error; } break; case ORIENTATION_UPSIDE_DOWN: // [ 0, 0, g ] if (worker_data->accel_ref[accel_index][ORIENTATION_UPSIDE_DOWN][2] < 0.f) { calibration_log_emergency(worker_data->mavlink_log_pub, "[cal] accel %d invalid Z-axis, check rotation", accel_index); return calibrate_return_error; } break; case ORIENTATION_RIGHTSIDE_UP: // [ 0, 0, -g ] if (worker_data->accel_ref[accel_index][ORIENTATION_RIGHTSIDE_UP][2] > 0.f) { calibration_log_emergency(worker_data->mavlink_log_pub, "[cal] accel %d invalid Z-axis, check rotation", accel_index); return calibrate_return_error; } break; default: break; } } calibration_log_info(worker_data->mavlink_log_pub, "[cal] %s side result: [%.3f %.3f %.3f]", detect_orientation_str(orientation), (double)worker_data->accel_ref[0][orientation][0], (double)worker_data->accel_ref[0][orientation][1], (double)worker_data->accel_ref[0][orientation][2]); worker_data->done_count++; calibration_log_info(worker_data->mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 17 * worker_data->done_count); return calibrate_return_ok; } int do_accel_calibration(orb_advert_t *mavlink_log_pub) { calibration_log_info(mavlink_log_pub, CAL_QGC_STARTED_MSG, sensor_name); calibration::Accelerometer calibrations[MAX_ACCEL_SENS] {}; unsigned active_sensors = 0; for (uint8_t cur_accel = 0; cur_accel < MAX_ACCEL_SENS; cur_accel++) { uORB::SubscriptionData<sensor_accel_s> accel_sub{ORB_ID(sensor_accel), cur_accel}; if (accel_sub.advertised() && (accel_sub.get().device_id != 0) && (accel_sub.get().timestamp > 0)) { calibrations[cur_accel].set_device_id(accel_sub.get().device_id); active_sensors++; } else { calibrations[cur_accel].Reset(); } } if (active_sensors == 0) { calibration_log_critical(mavlink_log_pub, CAL_ERROR_SENSOR_MSG); return PX4_ERROR; } FactoryCalibrationStorage factory_storage; if (factory_storage.open() != PX4_OK) { calibration_log_critical(mavlink_log_pub, "ERROR: cannot open calibration storage"); return PX4_ERROR; } /* measure and calculate offsets & scales */ accel_worker_data_s worker_data{}; worker_data.mavlink_log_pub = mavlink_log_pub; bool data_collected[detect_orientation_side_count] {}; if (calibrate_from_orientation(mavlink_log_pub, data_collected, accel_calibration_worker, &worker_data, false) == calibrate_return_ok) { const Dcmf board_rotation = calibration::GetBoardRotationMatrix(); const Dcmf board_rotation_t = board_rotation.transpose(); bool param_save = false; bool failed = true; for (unsigned i = 0; i < MAX_ACCEL_SENS; i++) { if (i < active_sensors) { // calculate offsets Vector3f offset{}; // X offset: average X from TAIL_DOWN + NOSE_DOWN const Vector3f accel_tail_down{worker_data.accel_ref[i][ORIENTATION_TAIL_DOWN]}; const Vector3f accel_nose_down{worker_data.accel_ref[i][ORIENTATION_NOSE_DOWN]}; offset(0) = (accel_tail_down(0) + accel_nose_down(0)) * 0.5f; // Y offset: average Y from LEFT + RIGHT const Vector3f accel_left{worker_data.accel_ref[i][ORIENTATION_LEFT]}; const Vector3f accel_right{worker_data.accel_ref[i][ORIENTATION_RIGHT]}; offset(1) = (accel_left(1) + accel_right(1)) * 0.5f; // Z offset: average Z from UPSIDE_DOWN + RIGHTSIDE_UP const Vector3f accel_upside_down{worker_data.accel_ref[i][ORIENTATION_UPSIDE_DOWN]}; const Vector3f accel_rightside_up{worker_data.accel_ref[i][ORIENTATION_RIGHTSIDE_UP]}; offset(2) = (accel_upside_down(2) + accel_rightside_up(2)) * 0.5f; // transform matrix Matrix3f mat_A; mat_A.row(0) = accel_tail_down - offset; mat_A.row(1) = accel_left - offset; mat_A.row(2) = accel_upside_down - offset; // calculate inverse matrix for A: simplify matrices mult because b has only one non-zero element == g at index i const Matrix3f accel_T = mat_A.I() * CONSTANTS_ONE_G; // update calibration const Vector3f accel_offs_rotated{board_rotation_t *offset}; calibrations[i].set_offset(accel_offs_rotated); const Matrix3f accel_T_rotated{board_rotation_t *accel_T * board_rotation}; calibrations[i].set_scale(accel_T_rotated.diag()); calibrations[i].set_temperature(worker_data.accel_temperature_ref[i]); #if defined(DEBUD_BUILD) PX4_INFO("accel %d: offset", i); offset.print(); PX4_INFO("accel %d: bT * offset", i); accel_offs_rotated.print(); PX4_INFO("accel %d: mat_A", i); mat_A.print(); PX4_INFO("accel %d: accel_T", i); accel_T.print(); PX4_INFO("accel %d: bT * accel_T * b", i); accel_T_rotated.print(); #endif // DEBUD_BUILD calibrations[i].PrintStatus(); if (calibrations[i].ParametersSave(i, true)) { param_save = true; failed = false; } else { failed = true; calibration_log_critical(mavlink_log_pub, "calibration save failed"); break; } } } if (!failed && factory_storage.store() != PX4_OK) { failed = true; } if (param_save) { param_notify_changes(); } if (!failed) { calibration_log_info(mavlink_log_pub, CAL_QGC_DONE_MSG, sensor_name); px4_usleep(600000); // give this message enough time to propagate return PX4_OK; } } calibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, sensor_name); px4_usleep(600000); // give this message enough time to propagate return PX4_ERROR; } int do_accel_calibration_quick(orb_advert_t *mavlink_log_pub) { #if !defined(CONSTRAINED_FLASH) PX4_INFO("Accelerometer quick calibration"); bool param_save = false; bool failed = true; FactoryCalibrationStorage factory_storage; if (factory_storage.open() != PX4_OK) { calibration_log_critical(mavlink_log_pub, "ERROR: cannot open calibration storage"); return PX4_ERROR; } // sensor thermal corrections (optional) uORB::Subscription sensor_correction_sub{ORB_ID(sensor_correction)}; sensor_correction_s sensor_correction{}; sensor_correction_sub.copy(&sensor_correction); uORB::SubscriptionMultiArray<sensor_accel_s, MAX_ACCEL_SENS> accel_subs{ORB_ID::sensor_accel}; /* use the first sensor to pace the readout, but do per-sensor counts */ for (unsigned accel_index = 0; accel_index < MAX_ACCEL_SENS; accel_index++) { sensor_accel_s arp{}; Vector3f accel_sum{}; float temperature_sum{NAN}; unsigned count = 0; while (accel_subs[accel_index].update(&arp)) { // fetch optional thermal offset corrections in sensor/board frame if ((arp.timestamp > 0) && (arp.device_id != 0)) { Vector3f offset{0, 0, 0}; if (sensor_correction.timestamp > 0) { for (uint8_t correction_index = 0; correction_index < MAX_ACCEL_SENS; correction_index++) { if (sensor_correction.accel_device_ids[correction_index] == arp.device_id) { switch (correction_index) { case 0: offset = Vector3f{sensor_correction.accel_offset_0}; break; case 1: offset = Vector3f{sensor_correction.accel_offset_1}; break; case 2: offset = Vector3f{sensor_correction.accel_offset_2}; break; case 3: offset = Vector3f{sensor_correction.accel_offset_3}; break; } } } } const Vector3f accel{Vector3f{arp.x, arp.y, arp.z} - offset}; if (count > 0) { const Vector3f diff{accel - (accel_sum / count)}; if (diff.norm() < 1.f) { accel_sum += Vector3f{arp.x, arp.y, arp.z} - offset; count++; if (!PX4_ISFINITE(temperature_sum)) { // set first valid value temperature_sum = (arp.temperature * count); } else { temperature_sum += arp.temperature; } } } else { accel_sum = accel; temperature_sum = arp.temperature; count = 1; } } } if ((count > 0) && (arp.device_id != 0)) { bool calibrated = false; const Vector3f accel_avg = accel_sum / count; const float temperature_avg = temperature_sum / count; Vector3f offset{0.f, 0.f, 0.f}; uORB::SubscriptionData<vehicle_attitude_s> attitude_sub{ORB_ID(vehicle_attitude)}; attitude_sub.update(); if (attitude_sub.advertised() && attitude_sub.get().timestamp != 0) { // use vehicle_attitude if available const vehicle_attitude_s &att = attitude_sub.get(); const matrix::Quatf q{att.q}; const Vector3f accel_ref = q.conjugate_inversed(Vector3f{0.f, 0.f, -CONSTANTS_ONE_G}); // sanity check angle between acceleration vectors const float angle = AxisAnglef(Quatf(accel_avg, accel_ref)).angle(); if (angle <= math::radians(10.f)) { offset = accel_avg - accel_ref; calibrated = true; } } if (!calibrated) { // otherwise simply normalize to gravity and remove offset Vector3f accel{accel_avg}; accel.normalize(); accel = accel * CONSTANTS_ONE_G; offset = accel_avg - accel; calibrated = true; } calibration::Accelerometer calibration{arp.device_id}; if (!calibrated || (offset.norm() > CONSTANTS_ONE_G) || !PX4_ISFINITE(offset(0)) || !PX4_ISFINITE(offset(1)) || !PX4_ISFINITE(offset(2))) { PX4_ERR("accel %d quick calibrate failed", accel_index); } else { calibration.set_offset(offset); calibration.set_temperature(temperature_avg); if (calibration.ParametersSave(accel_index)) { calibration.PrintStatus(); param_save = true; failed = false; } else { failed = true; calibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, "calibration save failed"); break; } } } } if (!failed && factory_storage.store() != PX4_OK) { failed = true; } if (param_save) { param_notify_changes(); } if (!failed) { return PX4_OK; } #endif // !CONSTRAINED_FLASH return PX4_ERROR; }
object_const_def ; object_event constants const DARKCAVEBLACKTHORNENTRANCE_PHARMACIST const DARKCAVEBLACKTHORNENTRANCE_POKE_BALL1 const DARKCAVEBLACKTHORNENTRANCE_POKE_BALL2 DarkCaveBlackthornEntrance_MapScripts: db 0 ; scene scripts db 0 ; callbacks DarkCaveBlackthornEntrancePharmacistScript: faceplayer opentext checkevent EVENT_GOT_BLACKGLASSES_IN_DARK_CAVE iftrue .GotBlackglasses writetext DarkCaveBlackthornEntrancePharmacistText1 buttonsound verbosegiveitem BLACKGLASSES iffalse .PackFull setevent EVENT_GOT_BLACKGLASSES_IN_DARK_CAVE .GotBlackglasses: writetext DarkCaveBlackthornEntrancePharmacistText2 waitbutton .PackFull: closetext end DarkCaveBlackthornEntranceRevive: itemball REVIVE DarkCaveBlackthornEntranceTMSnore: tmhmball TM_SNORE DarkCaveBlackthornEntrancePharmacistText1: text "Whoa! You startled" line "me there!" para "I had my BLACK-" line "GLASSES on, so I" para "didn't notice you" line "at all." para "What am I doing" line "here?" para "Hey, don't you" line "worry about it." para "I'll give you a" line "pair of BLACK-" cont "GLASSES, so forget" cont "you saw me, OK?" done DarkCaveBlackthornEntrancePharmacistText2: text "BLACKGLASSES ups" line "the power of dark-" cont "type moves." done DarkCaveBlackthornEntrance_MapEvents: db 0, 0 ; filler db 2 ; warp events warp_event 23, 3, ROUTE_45, 1 warp_event 3, 25, DARK_CAVE_VIOLET_ENTRANCE, 2 db 0 ; coord events db 0 ; bg events db 3 ; object events object_event 7, 3, SPRITE_PHARMACIST, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, DarkCaveBlackthornEntrancePharmacistScript, -1 object_event 21, 24, SPRITE_POKE_BALL, SPRITEMOVEDATA_STILL, 0, 0, -1, -1, 0, OBJECTTYPE_ITEMBALL, 0, DarkCaveBlackthornEntranceRevive, EVENT_DARK_CAVE_BLACKTHORN_ENTRANCE_REVIVE object_event 7, 22, SPRITE_POKE_BALL, SPRITEMOVEDATA_STILL, 0, 0, -1, -1, 0, OBJECTTYPE_TMHMBALL, 0, DarkCaveBlackthornEntranceTMSnore, EVENT_DARK_CAVE_BLACKTHORN_ENTRANCE_TM_SNORE
/* //@HEADER // ************************************************************************ // // KokkosKernels 0.9: Linear Algebra and Graph Kernels // Copyright 2017 Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // 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 Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Siva Rajamanickam (srajama@sandia.gov) // // ************************************************************************ //@HEADER */ #define KOKKOSKERNELS_IMPL_COMPILE_LIBRARY true #include "KokkosKernels_config.h" #if defined (KOKKOSKERNELS_INST_DOUBLE) \ && defined (KOKKOSKERNELS_INST_LAYOUTLEFT) \ && defined (KOKKOSKERNELS_INST_EXECSPACE_OPENMP) \ && defined (KOKKOSKERNELS_INST_MEMSPACE_HBWSPACE) \ && defined (KOKKOSKERNELS_INST_MEMSPACE_HBWSPACE) \ && defined (KOKKOSKERNELS_INST_ORDINAL_INT64_T) \ && defined (KOKKOSKERNELS_INST_OFFSET_INT) #include "KokkosSparse_gauss_seidel_spec.hpp" namespace KokkosSparse { namespace Impl { KOKKOSSPARSE_GAUSS_SEIDEL_SYMBOLIC_ETI_SPEC_INST(double, int64_t, int, Kokkos::LayoutLeft, Kokkos::OpenMP, Kokkos::Experimental::HBWSpace, Kokkos::Experimental::HBWSpace) } // Impl } // KokkosSparse #endif
; DE1ROM: 128KB PRG-ROM + 64KB CHR-ROM ; http://bootgod.dyndns.org:7777/search.php?keywords=DE1ROM&kwtype=pcb ; DE1ROM uses Nintendo's clone of a Tengen 800030. (See also: Mapper 064) ;------------------------------------------------------------------------------; ; DE1ROM mirroring is like MMC3; mapper controlled. ; %0000 = Horizontal ; %0001 = Vertical MIRRORING = %0001 ; Mapper 206 (DE1ROM) iNES header .byte "NES",$1A .byte $08 ; 8x 16K PRG banks .byte $08 ; 8x 8K CHR-ROM banks .byte $E0|MIRRORING ; flags 6 .byte $C0 ; flags 7 .byte $00 ; no PRG RAM .dsb 7, $00 ; clear the remaining bytes
#include<bits/stdc++.h> using namespace std; const int N = 20, T = 4e5 + 9; int dp[1 << N], n; string s[N]; int len[N], p[N][T], mn[N][T]; vector<int> v[N][T + T]; int yo(int mask, int sum) { if (mask == (1 << n) - 1) return 0; int &ret = dp[mask]; if (ret != -1) { return ret; } ret = 0; for (int i = 0; i < n; i++) { if (~mask >> i & 1) { if (mn[i][len[i]] >= -sum) { ret = max(ret, (int)v[i][-sum + T].size() + yo(mask | (1 << i), sum + p[i][len[i]])); } else { int l = 1, r = len[i], cur = 0; while (l <= r) { int mid = l + r >> 1; if (mn[i][mid] >= -sum) { cur = mid; l = mid + 1; } else { r = mid - 1; } } auto &w = v[i][-sum + T]; int cnt = upper_bound(w.begin(), w.end(), cur) - w.begin(); ret = max(ret, cnt); } } } return ret; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n; for (int i = 0; i < n; i++) { cin >> s[i]; len[i] = s[i].size(); s[i] = "0" + s[i]; mn[i][0] = T; for (int j = 1; j <= len[i]; j++) { p[i][j] = p[i][j - 1] + (s[i][j] == '(' ? 1 : -1); mn[i][j] = min(mn[i][j - 1], p[i][j]); v[i][p[i][j] + T].push_back(j); } } memset(dp, -1, sizeof dp); cout << yo(0, 0) << '\n'; return 0; }
; A164591: a(n) = ((4 + sqrt(18))*(4 + sqrt(8))^n + (4 - sqrt(18))*(4 - sqrt(8))^n)/8 . ; 1,7,48,328,2240,15296,104448,713216,4870144,33255424,227082240,1550614528,10588258304,72301150208,493703135232,3371215880192,23020101959680,157191088635904,1073367893409792,7329414438191104,50048372358250496 add $0,1 mov $1,2 mov $2,1 lpb $0 sub $0,1 mul $2,8 add $2,1 sub $2,$1 add $1,$2 lpe mul $1,8 sub $1,71 div $1,64 add $1,1
global fast_memcpy ; void mempcy(char *dst, char *src, int n) fast_memcpy: pushfd pushad mov ebx,[esp + 36 + 12] ; mov ebx, _nSize$ cmp ebx, 0 jbe end_mcpy ; mov edi, _dest$ mov edi, [esp + 36 + 4] ; mov esi, _src$ mov esi, [esp + 8 + 36] cld mov edx, esi neg edx and edx, 15 cmp edx, ebx jle unaligned_copy mov edx, ebx unaligned_copy: mov ecx, edx rep movsb sub ebx, edx jz end_mcpy mov ecx, ebx shr ecx, 7 jz mc_fl loop1: movaps XMM0, [esi] movaps XMM1, [esi+10h] movaps XMM2, [esi+20h] movaps XMM3, [esi+30h] movaps XMM4, [esi+40h] movaps XMM5, [esi+50h] movaps XMM6, [esi+60h] movaps XMM7, [esi+70h] movups [edi], XMM0 movups [edi+10h], XMM1 movups [edi+20h], XMM2 movups [edi+30h], XMM3 movups [edi+40h], XMM4 movups [edi+50h], XMM5 movups [edi+60h], XMM6 movups [edi+70h], XMM7 add esi, 80h add edi, 80h dec ecx jnz loop1 mc_fl: and ebx, 7fH jz end_mcpy mov ecx, ebx rep movsb end_mcpy: popad popfd ret
.global s_prepare_buffers s_prepare_buffers: push %r15 push %r8 push %r9 push %rbp push %rbx push %rdi lea addresses_normal_ht+0x1cc36, %rbx nop nop nop nop and $12019, %rbp mov (%rbx), %r15d sub $42632, %r8 lea addresses_UC_ht+0x8ff6, %r9 nop nop nop add %rbp, %rbp movups (%r9), %xmm7 vpextrq $1, %xmm7, %rdi nop nop nop nop sub %rbp, %rbp pop %rdi pop %rbx pop %rbp pop %r9 pop %r8 pop %r15 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r14 push %r15 push %r8 push %rdx // Store lea addresses_A+0x18c36, %r14 nop nop nop nop xor %r8, %r8 movl $0x51525354, (%r14) nop nop nop nop cmp %r14, %r14 // Load lea addresses_D+0x1436, %rdx nop nop add %r11, %r11 movaps (%rdx), %xmm5 vpextrq $1, %xmm5, %r10 nop nop dec %r14 // Store lea addresses_D+0x1436, %r10 nop nop nop add %r15, %r15 movw $0x5152, (%r10) and $51626, %rdx // Store lea addresses_D+0x3db6, %r8 add %rdx, %rdx movl $0x51525354, (%r8) nop nop xor %r14, %r14 // Store lea addresses_D+0xd2b6, %rdx nop nop nop nop nop dec %r12 movl $0x51525354, (%rdx) nop nop nop inc %r14 // Load lea addresses_US+0x1a436, %r14 nop nop nop add %rdx, %rdx mov (%r14), %r8 nop xor %r12, %r12 // Store lea addresses_RW+0x17366, %r8 nop nop sub %r12, %r12 mov $0x5152535455565758, %rdx movq %rdx, (%r8) nop nop nop nop nop dec %rdx // Store lea addresses_RW+0x1ac36, %r12 xor $28476, %r10 movb $0x51, (%r12) nop nop xor %r12, %r12 // Store lea addresses_PSE+0x13036, %r11 xor $46732, %r14 movl $0x51525354, (%r11) nop cmp %r15, %r15 // Store lea addresses_normal+0x16836, %r10 nop nop nop and %r14, %r14 mov $0x5152535455565758, %r15 movq %r15, %xmm3 movups %xmm3, (%r10) xor %r15, %r15 // Load mov $0x41372c0000000c36, %r11 nop nop nop and %r10, %r10 vmovups (%r11), %ymm6 vextracti128 $1, %ymm6, %xmm6 vpextrq $1, %xmm6, %r8 nop cmp %r10, %r10 // Faulty Load lea addresses_D+0x1436, %r15 cmp %rdx, %rdx movb (%r15), %r14b lea oracles, %r8 and $0xff, %r14 shlq $12, %r14 mov (%r8,%r14,1), %r14 pop %rdx pop %r8 pop %r15 pop %r14 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 8, 'NT': True, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_A', 'same': False, 'AVXalign': False, 'congruent': 9}} {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_D', 'same': True, 'AVXalign': True, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_D', 'same': True, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 4}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 2}} {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_US', 'same': False, 'AVXalign': False, 'congruent': 10}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': True, 'type': 'addresses_RW', 'same': False, 'AVXalign': False, 'congruent': 3}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_RW', 'same': False, 'AVXalign': False, 'congruent': 11}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 8}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 9}} {'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 9}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_D', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 3}} {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 5}} {'52': 5} 52 52 52 52 52 */
/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 3.0 Module * ------------------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Drawing tests. *//*--------------------------------------------------------------------*/ #include "es3fDrawTests.hpp" #include "glsDrawTest.hpp" #include "tcuRenderTarget.hpp" #include "sglrGLContext.hpp" #include "glwEnums.hpp" #include "deRandom.hpp" #include "deStringUtil.hpp" #include "deUniquePtr.hpp" #include "deSTLUtil.hpp" #include <set> namespace deqp { namespace gles3 { namespace Functional { namespace { enum TestIterationType { TYPE_DRAW_COUNT, // !< test with 1, 5, and 25 primitives TYPE_INSTANCE_COUNT, // !< test with 1, 4, and 11 instances TYPE_INDEX_RANGE, // !< test with index range of [0, 23], [23, 40], and [5, 5] TYPE_LAST }; static void addTestIterations (gls::DrawTest* test, const gls::DrawTestSpec& baseSpec, TestIterationType type) { gls::DrawTestSpec spec(baseSpec); if (type == TYPE_DRAW_COUNT) { spec.primitiveCount = 1; test->addIteration(spec, "draw count = 1"); spec.primitiveCount = 5; test->addIteration(spec, "draw count = 5"); spec.primitiveCount = 25; test->addIteration(spec, "draw count = 25"); } else if (type == TYPE_INSTANCE_COUNT) { spec.instanceCount = 1; test->addIteration(spec, "instance count = 1"); spec.instanceCount = 4; test->addIteration(spec, "instance count = 4"); spec.instanceCount = 11; test->addIteration(spec, "instance count = 11"); } else if (type == TYPE_INDEX_RANGE) { spec.indexMin = 0; spec.indexMax = 23; test->addIteration(spec, "index range = [0, 23]"); spec.indexMin = 23; spec.indexMax = 40; test->addIteration(spec, "index range = [23, 40]"); // Only makes sense with points if (spec.primitive == gls::DrawTestSpec::PRIMITIVE_POINTS) { spec.indexMin = 5; spec.indexMax = 5; test->addIteration(spec, "index range = [5, 5]"); } } else DE_ASSERT(false); } static void genBasicSpec (gls::DrawTestSpec& spec, gls::DrawTestSpec::DrawMethod method) { spec.apiType = glu::ApiType::es(3,0); spec.primitive = gls::DrawTestSpec::PRIMITIVE_TRIANGLES; spec.primitiveCount = 5; spec.drawMethod = method; spec.indexType = gls::DrawTestSpec::INDEXTYPE_LAST; spec.indexPointerOffset = 0; spec.indexStorage = gls::DrawTestSpec::STORAGE_LAST; spec.first = 0; spec.indexMin = 0; spec.indexMax = 0; spec.instanceCount = 1; spec.attribs.resize(2); spec.attribs[0].inputType = gls::DrawTestSpec::INPUTTYPE_FLOAT; spec.attribs[0].outputType = gls::DrawTestSpec::OUTPUTTYPE_VEC2; spec.attribs[0].storage = gls::DrawTestSpec::STORAGE_BUFFER; spec.attribs[0].usage = gls::DrawTestSpec::USAGE_STATIC_DRAW; spec.attribs[0].componentCount = 4; spec.attribs[0].offset = 0; spec.attribs[0].stride = 0; spec.attribs[0].normalize = false; spec.attribs[0].instanceDivisor = 0; spec.attribs[0].useDefaultAttribute = false; spec.attribs[1].inputType = gls::DrawTestSpec::INPUTTYPE_FLOAT; spec.attribs[1].outputType = gls::DrawTestSpec::OUTPUTTYPE_VEC2; spec.attribs[1].storage = gls::DrawTestSpec::STORAGE_BUFFER; spec.attribs[1].usage = gls::DrawTestSpec::USAGE_STATIC_DRAW; spec.attribs[1].componentCount = 2; spec.attribs[1].offset = 0; spec.attribs[1].stride = 0; spec.attribs[1].normalize = false; spec.attribs[1].instanceDivisor = 0; spec.attribs[1].useDefaultAttribute = false; } class AttributeGroup : public TestCaseGroup { public: AttributeGroup (Context& context, const char* name, const char* descr, gls::DrawTestSpec::DrawMethod drawMethod, gls::DrawTestSpec::Primitive primitive, gls::DrawTestSpec::IndexType indexType, gls::DrawTestSpec::Storage indexStorage); ~AttributeGroup (void); void init (void); private: gls::DrawTestSpec::DrawMethod m_method; gls::DrawTestSpec::Primitive m_primitive; gls::DrawTestSpec::IndexType m_indexType; gls::DrawTestSpec::Storage m_indexStorage; }; AttributeGroup::AttributeGroup (Context& context, const char* name, const char* descr, gls::DrawTestSpec::DrawMethod drawMethod, gls::DrawTestSpec::Primitive primitive, gls::DrawTestSpec::IndexType indexType, gls::DrawTestSpec::Storage indexStorage) : TestCaseGroup (context, name, descr) , m_method (drawMethod) , m_primitive (primitive) , m_indexType (indexType) , m_indexStorage (indexStorage) { } AttributeGroup::~AttributeGroup (void) { } void AttributeGroup::init (void) { // select test type const bool instanced = (m_method == gls::DrawTestSpec::DRAWMETHOD_DRAWARRAYS_INSTANCED) || (m_method == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_INSTANCED); const bool ranged = (m_method == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED); const TestIterationType testType = (instanced) ? (TYPE_INSTANCE_COUNT) : ((ranged) ? (TYPE_INDEX_RANGE) : (TYPE_DRAW_COUNT)); // Single attribute { gls::DrawTest* test = new gls::DrawTest(m_testCtx, m_context.getRenderContext(), "single_attribute", "Single attribute array."); gls::DrawTestSpec spec; spec.apiType = glu::ApiType::es(3,0); spec.primitive = m_primitive; spec.primitiveCount = 5; spec.drawMethod = m_method; spec.indexType = m_indexType; spec.indexPointerOffset = 0; spec.indexStorage = m_indexStorage; spec.first = 0; spec.indexMin = 0; spec.indexMax = 0; spec.instanceCount = 1; spec.attribs.resize(1); spec.attribs[0].inputType = gls::DrawTestSpec::INPUTTYPE_FLOAT; spec.attribs[0].outputType = gls::DrawTestSpec::OUTPUTTYPE_VEC2; spec.attribs[0].storage = gls::DrawTestSpec::STORAGE_BUFFER; spec.attribs[0].usage = gls::DrawTestSpec::USAGE_STATIC_DRAW; spec.attribs[0].componentCount = 2; spec.attribs[0].offset = 0; spec.attribs[0].stride = 0; spec.attribs[0].normalize = false; spec.attribs[0].instanceDivisor = 0; spec.attribs[0].useDefaultAttribute = false; addTestIterations(test, spec, testType); this->addChild(test); } // Multiple attribute { gls::DrawTest* test = new gls::DrawTest(m_testCtx, m_context.getRenderContext(), "multiple_attributes", "Multiple attribute arrays."); gls::DrawTestSpec spec; spec.apiType = glu::ApiType::es(3,0); spec.primitive = m_primitive; spec.primitiveCount = 5; spec.drawMethod = m_method; spec.indexType = m_indexType; spec.indexPointerOffset = 0; spec.indexStorage = m_indexStorage; spec.first = 0; spec.indexMin = 0; spec.indexMax = 0; spec.instanceCount = 1; spec.attribs.resize(2); spec.attribs[0].inputType = gls::DrawTestSpec::INPUTTYPE_FLOAT; spec.attribs[0].outputType = gls::DrawTestSpec::OUTPUTTYPE_VEC2; spec.attribs[0].storage = gls::DrawTestSpec::STORAGE_BUFFER; spec.attribs[0].usage = gls::DrawTestSpec::USAGE_STATIC_DRAW; spec.attribs[0].componentCount = 4; spec.attribs[0].offset = 0; spec.attribs[0].stride = 0; spec.attribs[0].normalize = false; spec.attribs[0].instanceDivisor = 0; spec.attribs[0].useDefaultAttribute = false; spec.attribs[1].inputType = gls::DrawTestSpec::INPUTTYPE_FLOAT; spec.attribs[1].outputType = gls::DrawTestSpec::OUTPUTTYPE_VEC2; spec.attribs[1].storage = gls::DrawTestSpec::STORAGE_BUFFER; spec.attribs[1].usage = gls::DrawTestSpec::USAGE_STATIC_DRAW; spec.attribs[1].componentCount = 2; spec.attribs[1].offset = 0; spec.attribs[1].stride = 0; spec.attribs[1].normalize = false; spec.attribs[1].instanceDivisor = 0; spec.attribs[1].useDefaultAttribute = false; addTestIterations(test, spec, testType); this->addChild(test); } // Multiple attribute, second one divided { gls::DrawTest* test = new gls::DrawTest(m_testCtx, m_context.getRenderContext(), "instanced_attributes", "Instanced attribute array."); gls::DrawTestSpec spec; spec.apiType = glu::ApiType::es(3,0); spec.primitive = m_primitive; spec.primitiveCount = 5; spec.drawMethod = m_method; spec.indexType = m_indexType; spec.indexPointerOffset = 0; spec.indexStorage = m_indexStorage; spec.first = 0; spec.indexMin = 0; spec.indexMax = 0; spec.instanceCount = 1; spec.attribs.resize(3); spec.attribs[0].inputType = gls::DrawTestSpec::INPUTTYPE_FLOAT; spec.attribs[0].outputType = gls::DrawTestSpec::OUTPUTTYPE_VEC2; spec.attribs[0].storage = gls::DrawTestSpec::STORAGE_BUFFER; spec.attribs[0].usage = gls::DrawTestSpec::USAGE_STATIC_DRAW; spec.attribs[0].componentCount = 4; spec.attribs[0].offset = 0; spec.attribs[0].stride = 0; spec.attribs[0].normalize = false; spec.attribs[0].instanceDivisor = 0; spec.attribs[0].useDefaultAttribute = false; // Add another position component so the instances wont be drawn on each other spec.attribs[1].inputType = gls::DrawTestSpec::INPUTTYPE_FLOAT; spec.attribs[1].outputType = gls::DrawTestSpec::OUTPUTTYPE_VEC2; spec.attribs[1].storage = gls::DrawTestSpec::STORAGE_BUFFER; spec.attribs[1].usage = gls::DrawTestSpec::USAGE_STATIC_DRAW; spec.attribs[1].componentCount = 2; spec.attribs[1].offset = 0; spec.attribs[1].stride = 0; spec.attribs[1].normalize = false; spec.attribs[1].instanceDivisor = 1; spec.attribs[1].useDefaultAttribute = false; spec.attribs[1].additionalPositionAttribute = true; // Instanced color spec.attribs[2].inputType = gls::DrawTestSpec::INPUTTYPE_FLOAT; spec.attribs[2].outputType = gls::DrawTestSpec::OUTPUTTYPE_VEC2; spec.attribs[2].storage = gls::DrawTestSpec::STORAGE_BUFFER; spec.attribs[2].usage = gls::DrawTestSpec::USAGE_STATIC_DRAW; spec.attribs[2].componentCount = 3; spec.attribs[2].offset = 0; spec.attribs[2].stride = 0; spec.attribs[2].normalize = false; spec.attribs[2].instanceDivisor = 1; spec.attribs[2].useDefaultAttribute = false; addTestIterations(test, spec, testType); this->addChild(test); } // Multiple attribute, second one default { gls::DrawTest* test = new gls::DrawTest(m_testCtx, m_context.getRenderContext(), "default_attribute", "Attribute specified with glVertexAttrib*."); gls::DrawTestSpec spec; spec.apiType = glu::ApiType::es(3,0); spec.primitive = m_primitive; spec.primitiveCount = 5; spec.drawMethod = m_method; spec.indexType = m_indexType; spec.indexPointerOffset = 0; spec.indexStorage = m_indexStorage; spec.first = 0; spec.indexMin = 0; spec.indexMax = 20; // \note addTestIterations is not called for the spec, so we must ensure [indexMin, indexMax] is a good range spec.instanceCount = 1; spec.attribs.resize(2); spec.attribs[0].inputType = gls::DrawTestSpec::INPUTTYPE_FLOAT; spec.attribs[0].outputType = gls::DrawTestSpec::OUTPUTTYPE_VEC2; spec.attribs[0].storage = gls::DrawTestSpec::STORAGE_BUFFER; spec.attribs[0].usage = gls::DrawTestSpec::USAGE_STATIC_DRAW; spec.attribs[0].componentCount = 2; spec.attribs[0].offset = 0; spec.attribs[0].stride = 0; spec.attribs[0].normalize = false; spec.attribs[0].instanceDivisor = 0; spec.attribs[0].useDefaultAttribute = false; struct IOPair { gls::DrawTestSpec::InputType input; gls::DrawTestSpec::OutputType output; int componentCount; } iopairs[] = { { gls::DrawTestSpec::INPUTTYPE_FLOAT, gls::DrawTestSpec::OUTPUTTYPE_VEC2, 4 }, { gls::DrawTestSpec::INPUTTYPE_FLOAT, gls::DrawTestSpec::OUTPUTTYPE_VEC4, 2 }, { gls::DrawTestSpec::INPUTTYPE_INT, gls::DrawTestSpec::OUTPUTTYPE_IVEC3, 4 }, { gls::DrawTestSpec::INPUTTYPE_UNSIGNED_INT, gls::DrawTestSpec::OUTPUTTYPE_UVEC2, 4 }, }; for (int ioNdx = 0; ioNdx < DE_LENGTH_OF_ARRAY(iopairs); ++ioNdx) { const std::string desc = gls::DrawTestSpec::inputTypeToString(iopairs[ioNdx].input) + de::toString(iopairs[ioNdx].componentCount) + " to " + gls::DrawTestSpec::outputTypeToString(iopairs[ioNdx].output); spec.attribs[1].inputType = iopairs[ioNdx].input; spec.attribs[1].outputType = iopairs[ioNdx].output; spec.attribs[1].storage = gls::DrawTestSpec::STORAGE_BUFFER; spec.attribs[1].usage = gls::DrawTestSpec::USAGE_STATIC_DRAW; spec.attribs[1].componentCount = iopairs[ioNdx].componentCount; spec.attribs[1].offset = 0; spec.attribs[1].stride = 0; spec.attribs[1].normalize = false; spec.attribs[1].instanceDivisor = 0; spec.attribs[1].useDefaultAttribute = true; test->addIteration(spec, desc.c_str()); } this->addChild(test); } } class IndexGroup : public TestCaseGroup { public: IndexGroup (Context& context, const char* name, const char* descr, gls::DrawTestSpec::DrawMethod drawMethod); ~IndexGroup (void); void init (void); private: gls::DrawTestSpec::DrawMethod m_method; }; IndexGroup::IndexGroup (Context& context, const char* name, const char* descr, gls::DrawTestSpec::DrawMethod drawMethod) : TestCaseGroup (context, name, descr) , m_method (drawMethod) { } IndexGroup::~IndexGroup (void) { } void IndexGroup::init (void) { struct IndexTest { gls::DrawTestSpec::Storage storage; gls::DrawTestSpec::IndexType type; bool aligned; int offsets[3]; }; const IndexTest tests[] = { { gls::DrawTestSpec::STORAGE_USER, gls::DrawTestSpec::INDEXTYPE_BYTE, true, { 0, 1, -1 } }, { gls::DrawTestSpec::STORAGE_USER, gls::DrawTestSpec::INDEXTYPE_SHORT, true, { 0, 2, -1 } }, { gls::DrawTestSpec::STORAGE_USER, gls::DrawTestSpec::INDEXTYPE_INT, true, { 0, 4, -1 } }, { gls::DrawTestSpec::STORAGE_USER, gls::DrawTestSpec::INDEXTYPE_SHORT, false, { 1, 3, -1 } }, { gls::DrawTestSpec::STORAGE_USER, gls::DrawTestSpec::INDEXTYPE_INT, false, { 2, 3, -1 } }, { gls::DrawTestSpec::STORAGE_BUFFER, gls::DrawTestSpec::INDEXTYPE_BYTE, true, { 0, 1, -1 } }, { gls::DrawTestSpec::STORAGE_BUFFER, gls::DrawTestSpec::INDEXTYPE_SHORT, true, { 0, 2, -1 } }, { gls::DrawTestSpec::STORAGE_BUFFER, gls::DrawTestSpec::INDEXTYPE_INT, true, { 0, 4, -1 } }, { gls::DrawTestSpec::STORAGE_BUFFER, gls::DrawTestSpec::INDEXTYPE_SHORT, false, { 1, 3, -1 } }, { gls::DrawTestSpec::STORAGE_BUFFER, gls::DrawTestSpec::INDEXTYPE_INT, false, { 2, 3, -1 } }, }; gls::DrawTestSpec spec; tcu::TestCaseGroup* userPtrGroup = new tcu::TestCaseGroup(m_testCtx, "user_ptr", "user pointer"); tcu::TestCaseGroup* unalignedUserPtrGroup = new tcu::TestCaseGroup(m_testCtx, "unaligned_user_ptr", "unaligned user pointer"); tcu::TestCaseGroup* bufferGroup = new tcu::TestCaseGroup(m_testCtx, "buffer", "buffer"); tcu::TestCaseGroup* unalignedBufferGroup = new tcu::TestCaseGroup(m_testCtx, "unaligned_buffer", "unaligned buffer"); genBasicSpec(spec, m_method); this->addChild(userPtrGroup); this->addChild(unalignedUserPtrGroup); this->addChild(bufferGroup); this->addChild(unalignedBufferGroup); for (int testNdx = 0; testNdx < DE_LENGTH_OF_ARRAY(tests); ++testNdx) { const IndexTest& indexTest = tests[testNdx]; tcu::TestCaseGroup* group = (indexTest.storage == gls::DrawTestSpec::STORAGE_USER) ? ((indexTest.aligned) ? (userPtrGroup) : (unalignedUserPtrGroup)) : ((indexTest.aligned) ? (bufferGroup) : (unalignedBufferGroup)); const std::string name = std::string("index_") + gls::DrawTestSpec::indexTypeToString(indexTest.type); const std::string desc = std::string("index ") + gls::DrawTestSpec::indexTypeToString(indexTest.type) + " in " + gls::DrawTestSpec::storageToString(indexTest.storage); de::MovePtr<gls::DrawTest> test (new gls::DrawTest(m_testCtx, m_context.getRenderContext(), name.c_str(), desc.c_str())); spec.indexType = indexTest.type; spec.indexStorage = indexTest.storage; for (int iterationNdx = 0; iterationNdx < DE_LENGTH_OF_ARRAY(indexTest.offsets) && indexTest.offsets[iterationNdx] != -1; ++iterationNdx) { const std::string iterationDesc = std::string("offset ") + de::toString(indexTest.offsets[iterationNdx]); spec.indexPointerOffset = indexTest.offsets[iterationNdx]; test->addIteration(spec, iterationDesc.c_str()); } if (spec.isCompatibilityTest() != gls::DrawTestSpec::COMPATIBILITY_UNALIGNED_OFFSET && spec.isCompatibilityTest() != gls::DrawTestSpec::COMPATIBILITY_UNALIGNED_STRIDE) group->addChild(test.release()); } } class FirstGroup : public TestCaseGroup { public: FirstGroup (Context& context, const char* name, const char* descr, gls::DrawTestSpec::DrawMethod drawMethod); ~FirstGroup (void); void init (void); private: gls::DrawTestSpec::DrawMethod m_method; }; FirstGroup::FirstGroup (Context& context, const char* name, const char* descr, gls::DrawTestSpec::DrawMethod drawMethod) : TestCaseGroup (context, name, descr) , m_method (drawMethod) { } FirstGroup::~FirstGroup (void) { } void FirstGroup::init (void) { const int firsts[] = { 1, 3, 17 }; gls::DrawTestSpec spec; genBasicSpec(spec, m_method); for (int firstNdx = 0; firstNdx < DE_LENGTH_OF_ARRAY(firsts); ++firstNdx) { const std::string name = std::string("first_") + de::toString(firsts[firstNdx]); const std::string desc = std::string("first ") + de::toString(firsts[firstNdx]); gls::DrawTest* test = new gls::DrawTest(m_testCtx, m_context.getRenderContext(), name.c_str(), desc.c_str()); spec.first = firsts[firstNdx]; addTestIterations(test, spec, TYPE_DRAW_COUNT); this->addChild(test); } } class MethodGroup : public TestCaseGroup { public: MethodGroup (Context& context, const char* name, const char* descr, gls::DrawTestSpec::DrawMethod drawMethod); ~MethodGroup (void); void init (void); private: gls::DrawTestSpec::DrawMethod m_method; }; MethodGroup::MethodGroup (Context& context, const char* name, const char* descr, gls::DrawTestSpec::DrawMethod drawMethod) : TestCaseGroup (context, name, descr) , m_method (drawMethod) { } MethodGroup::~MethodGroup (void) { } void MethodGroup::init (void) { const bool indexed = (m_method == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS) || (m_method == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_INSTANCED) || (m_method == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED); const bool hasFirst = (m_method == gls::DrawTestSpec::DRAWMETHOD_DRAWARRAYS) || (m_method == gls::DrawTestSpec::DRAWMETHOD_DRAWARRAYS_INSTANCED); const gls::DrawTestSpec::Primitive primitive[] = { gls::DrawTestSpec::PRIMITIVE_POINTS, gls::DrawTestSpec::PRIMITIVE_TRIANGLES, gls::DrawTestSpec::PRIMITIVE_TRIANGLE_FAN, gls::DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP, gls::DrawTestSpec::PRIMITIVE_LINES, gls::DrawTestSpec::PRIMITIVE_LINE_STRIP, gls::DrawTestSpec::PRIMITIVE_LINE_LOOP }; if (hasFirst) { // First-tests this->addChild(new FirstGroup(m_context, "first", "First tests", m_method)); } if (indexed) { // Index-tests if (m_method != gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED) this->addChild(new IndexGroup(m_context, "indices", "Index tests", m_method)); } for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(primitive); ++ndx) { const std::string name = gls::DrawTestSpec::primitiveToString(primitive[ndx]); const std::string desc = gls::DrawTestSpec::primitiveToString(primitive[ndx]); this->addChild(new AttributeGroup(m_context, name.c_str(), desc.c_str(), m_method, primitive[ndx], gls::DrawTestSpec::INDEXTYPE_SHORT, gls::DrawTestSpec::STORAGE_BUFFER)); } } class GridProgram : public sglr::ShaderProgram { public: GridProgram (void); void shadeVertices (const rr::VertexAttrib* inputs, rr::VertexPacket* const* packets, const int numPackets) const; void shadeFragments (rr::FragmentPacket* packets, const int numPackets, const rr::FragmentShadingContext& context) const; }; GridProgram::GridProgram (void) : sglr::ShaderProgram(sglr::pdec::ShaderProgramDeclaration() << sglr::pdec::VertexAttribute("a_position", rr::GENERICVECTYPE_FLOAT) << sglr::pdec::VertexAttribute("a_offset", rr::GENERICVECTYPE_FLOAT) << sglr::pdec::VertexAttribute("a_color", rr::GENERICVECTYPE_FLOAT) << sglr::pdec::VertexToFragmentVarying(rr::GENERICVECTYPE_FLOAT) << sglr::pdec::FragmentOutput(rr::GENERICVECTYPE_FLOAT) << sglr::pdec::VertexSource("#version 300 es\n" "in highp vec4 a_position;\n" "in highp vec4 a_offset;\n" "in highp vec4 a_color;\n" "out mediump vec4 v_color;\n" "void main(void)\n" "{\n" " gl_Position = a_position + a_offset;\n" " v_color = a_color;\n" "}\n") << sglr::pdec::FragmentSource( "#version 300 es\n" "layout(location = 0) out mediump vec4 dEQP_FragColor;\n" "in mediump vec4 v_color;\n" "void main(void)\n" "{\n" " dEQP_FragColor = v_color;\n" "}\n")) { } void GridProgram::shadeVertices (const rr::VertexAttrib* inputs, rr::VertexPacket* const* packets, const int numPackets) const { for (int ndx = 0; ndx < numPackets; ++ndx) { packets[ndx]->position = rr::readVertexAttribFloat(inputs[0], packets[ndx]->instanceNdx, packets[ndx]->vertexNdx) + rr::readVertexAttribFloat(inputs[1], packets[ndx]->instanceNdx, packets[ndx]->vertexNdx); packets[ndx]->outputs[0] = rr::readVertexAttribFloat(inputs[2], packets[ndx]->instanceNdx, packets[ndx]->vertexNdx); } } void GridProgram::shadeFragments (rr::FragmentPacket* packets, const int numPackets, const rr::FragmentShadingContext& context) const { for (int packetNdx = 0; packetNdx < numPackets; ++packetNdx) for (int fragNdx = 0; fragNdx < 4; ++fragNdx) rr::writeFragmentOutput(context, packetNdx, fragNdx, 0, rr::readTriangleVarying<float>(packets[packetNdx], context, 0, fragNdx)); } class InstancedGridRenderTest : public TestCase { public: InstancedGridRenderTest (Context& context, const char* name, const char* desc, int gridSide, bool useIndices); ~InstancedGridRenderTest (void); IterateResult iterate (void); private: void renderTo (sglr::Context& ctx, sglr::ShaderProgram& program, tcu::Surface& dst); bool verifyImage (const tcu::Surface& image); const int m_gridSide; const bool m_useIndices; }; InstancedGridRenderTest::InstancedGridRenderTest (Context& context, const char* name, const char* desc, int gridSide, bool useIndices) : TestCase (context, name, desc) , m_gridSide (gridSide) , m_useIndices (useIndices) { } InstancedGridRenderTest::~InstancedGridRenderTest (void) { } InstancedGridRenderTest::IterateResult InstancedGridRenderTest::iterate (void) { const int renderTargetWidth = de::min(1024, m_context.getRenderTarget().getWidth()); const int renderTargetHeight = de::min(1024, m_context.getRenderTarget().getHeight()); sglr::GLContext ctx (m_context.getRenderContext(), m_testCtx.getLog(), sglr::GLCONTEXT_LOG_CALLS | sglr::GLCONTEXT_LOG_PROGRAMS, tcu::IVec4(0, 0, renderTargetWidth, renderTargetHeight)); tcu::Surface surface (renderTargetWidth, renderTargetHeight); GridProgram program; // render renderTo(ctx, program, surface); // verify image if (verifyImage(surface)) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Incorrect rendering result"); return STOP; } void InstancedGridRenderTest::renderTo (sglr::Context& ctx, sglr::ShaderProgram& program, tcu::Surface& dst) { const tcu::Vec4 green (0, 1, 0, 1); const tcu::Vec4 yellow (1, 1, 0, 1); deUint32 positionBuf = 0; deUint32 offsetBuf = 0; deUint32 colorBuf = 0; deUint32 indexBuf = 0; deUint32 programID = ctx.createProgram(&program); deInt32 posLocation = ctx.getAttribLocation(programID, "a_position"); deInt32 offsetLocation = ctx.getAttribLocation(programID, "a_offset"); deInt32 colorLocation = ctx.getAttribLocation(programID, "a_color"); float cellW = 2.0f / m_gridSide; float cellH = 2.0f / m_gridSide; const tcu::Vec4 vertexPositions[] = { tcu::Vec4(0, 0, 0, 1), tcu::Vec4(cellW, 0, 0, 1), tcu::Vec4(0, cellH, 0, 1), tcu::Vec4(0, cellH, 0, 1), tcu::Vec4(cellW, 0, 0, 1), tcu::Vec4(cellW, cellH, 0, 1), }; const deUint16 indices[] = { 0, 4, 3, 2, 1, 5 }; std::vector<tcu::Vec4> offsets; for (int x = 0; x < m_gridSide; ++x) for (int y = 0; y < m_gridSide; ++y) offsets.push_back(tcu::Vec4(x * cellW - 1.0f, y * cellW - 1.0f, 0, 0)); std::vector<tcu::Vec4> colors; for (int x = 0; x < m_gridSide; ++x) for (int y = 0; y < m_gridSide; ++y) colors.push_back(((x + y) % 2 == 0) ? (green) : (yellow)); ctx.genBuffers(1, &positionBuf); ctx.bindBuffer(GL_ARRAY_BUFFER, positionBuf); ctx.bufferData(GL_ARRAY_BUFFER, sizeof(vertexPositions), vertexPositions, GL_STATIC_DRAW); ctx.vertexAttribPointer(posLocation, 4, GL_FLOAT, GL_FALSE, 0, DE_NULL); ctx.vertexAttribDivisor(posLocation, 0); ctx.enableVertexAttribArray(posLocation); ctx.genBuffers(1, &offsetBuf); ctx.bindBuffer(GL_ARRAY_BUFFER, offsetBuf); ctx.bufferData(GL_ARRAY_BUFFER, offsets.size() * sizeof(tcu::Vec4), &offsets[0], GL_STATIC_DRAW); ctx.vertexAttribPointer(offsetLocation, 4, GL_FLOAT, GL_FALSE, 0, DE_NULL); ctx.vertexAttribDivisor(offsetLocation, 1); ctx.enableVertexAttribArray(offsetLocation); ctx.genBuffers(1, &colorBuf); ctx.bindBuffer(GL_ARRAY_BUFFER, colorBuf); ctx.bufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(tcu::Vec4), &colors[0], GL_STATIC_DRAW); ctx.vertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, 0, DE_NULL); ctx.vertexAttribDivisor(colorLocation, 1); ctx.enableVertexAttribArray(colorLocation); if (m_useIndices) { ctx.genBuffers(1, &indexBuf); ctx.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuf); ctx.bufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); } ctx.clearColor(0, 0, 0, 1); ctx.clear(GL_COLOR_BUFFER_BIT); ctx.viewport(0, 0, dst.getWidth(), dst.getHeight()); ctx.useProgram(programID); if (m_useIndices) ctx.drawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, DE_NULL, m_gridSide * m_gridSide); else ctx.drawArraysInstanced(GL_TRIANGLES, 0, 6, m_gridSide * m_gridSide); ctx.useProgram(0); if (m_useIndices) ctx.deleteBuffers(1, &indexBuf); ctx.deleteBuffers(1, &colorBuf); ctx.deleteBuffers(1, &offsetBuf); ctx.deleteBuffers(1, &positionBuf); ctx.deleteProgram(programID); ctx.finish(); ctx.readPixels(dst, 0, 0, dst.getWidth(), dst.getHeight()); glu::checkError(ctx.getError(), "", __FILE__, __LINE__); } bool InstancedGridRenderTest::verifyImage (const tcu::Surface& image) { // \note the green/yellow pattern is only for clarity. The test will only verify that all instances were drawn by looking for anything non-green/yellow. using tcu::TestLog; const tcu::RGBA green (0, 255, 0, 255); const tcu::RGBA yellow (255, 255, 0, 255); const int colorThreshold = 20; tcu::Surface error (image.getWidth(), image.getHeight()); bool isOk = true; for (int y = 1; y < image.getHeight()-1; y++) for (int x = 1; x < image.getWidth()-1; x++) { const tcu::RGBA pixel = image.getPixel(x, y); bool pixelOk = true; // Any pixel with !(G ~= 255) is faulty (not a linear combinations of green and yellow) if (de::abs(pixel.getGreen() - 255) > colorThreshold) pixelOk = false; // Any pixel with !(B ~= 0) is faulty (not a linear combinations of green and yellow) if (de::abs(pixel.getBlue() - 0) > colorThreshold) pixelOk = false; error.setPixel(x, y, (pixelOk) ? (tcu::RGBA(0, 255, 0, 255)) : (tcu::RGBA(255, 0, 0, 255))); isOk = isOk && pixelOk; } if (!isOk) { tcu::TestLog& log = m_testCtx.getLog(); log << TestLog::Message << "Image verification failed." << TestLog::EndMessage; log << TestLog::ImageSet("Verfication result", "Result of rendering") << TestLog::Image("Result", "Result", image) << TestLog::Image("ErrorMask", "Error mask", error) << TestLog::EndImageSet; } else { tcu::TestLog& log = m_testCtx.getLog(); log << TestLog::ImageSet("Verfication result", "Result of rendering") << TestLog::Image("Result", "Result", image) << TestLog::EndImageSet; } return isOk; } class InstancingGroup : public TestCaseGroup { public: InstancingGroup (Context& context, const char* name, const char* descr); ~InstancingGroup (void); void init (void); }; InstancingGroup::InstancingGroup (Context& context, const char* name, const char* descr) : TestCaseGroup (context, name, descr) { } InstancingGroup::~InstancingGroup (void) { } void InstancingGroup::init (void) { const int gridWidths[] = { 2, 5, 10, 32, 100, }; // drawArrays for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(gridWidths); ++ndx) { const std::string name = std::string("draw_arrays_instanced_grid_") + de::toString(gridWidths[ndx]) + "x" + de::toString(gridWidths[ndx]); const std::string desc = std::string("DrawArraysInstanced, Grid size ") + de::toString(gridWidths[ndx]) + "x" + de::toString(gridWidths[ndx]); this->addChild(new InstancedGridRenderTest(m_context, name.c_str(), desc.c_str(), gridWidths[ndx], false)); } // drawElements for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(gridWidths); ++ndx) { const std::string name = std::string("draw_elements_instanced_grid_") + de::toString(gridWidths[ndx]) + "x" + de::toString(gridWidths[ndx]); const std::string desc = std::string("DrawElementsInstanced, Grid size ") + de::toString(gridWidths[ndx]) + "x" + de::toString(gridWidths[ndx]); this->addChild(new InstancedGridRenderTest(m_context, name.c_str(), desc.c_str(), gridWidths[ndx], true)); } } class RandomGroup : public TestCaseGroup { public: RandomGroup (Context& context, const char* name, const char* descr); ~RandomGroup (void); void init (void); }; template <int SIZE> struct UniformWeightArray { float weights[SIZE]; UniformWeightArray (void) { for (int i=0; i<SIZE; ++i) weights[i] = 1.0f; } }; RandomGroup::RandomGroup (Context& context, const char* name, const char* descr) : TestCaseGroup (context, name, descr) { } RandomGroup::~RandomGroup (void) { } void RandomGroup::init (void) { const int numAttempts = 300; static const int attribCounts[] = { 1, 2, 5 }; static const float attribWeights[] = { 30, 10, 1 }; static const int primitiveCounts[] = { 1, 5, 64 }; static const float primitiveCountWeights[] = { 20, 10, 1 }; static const int indexOffsets[] = { 0, 7, 13 }; static const float indexOffsetWeights[] = { 20, 20, 1 }; static const int firsts[] = { 0, 7, 13 }; static const float firstWeights[] = { 20, 20, 1 }; static const int instanceCounts[] = { 1, 2, 16, 17 }; static const float instanceWeights[] = { 20, 10, 5, 1 }; static const int indexMins[] = { 0, 1, 3, 8 }; static const int indexMaxs[] = { 4, 8, 128, 257 }; static const float indexWeights[] = { 50, 50, 50, 50 }; static const int offsets[] = { 0, 1, 5, 12 }; static const float offsetWeights[] = { 50, 10, 10, 10 }; static const int strides[] = { 0, 7, 16, 17 }; static const float strideWeights[] = { 50, 10, 10, 10 }; static const int instanceDivisors[] = { 0, 1, 3, 129 }; static const float instanceDivisorWeights[]= { 70, 30, 10, 10 }; static const gls::DrawTestSpec::Primitive primitives[] = { gls::DrawTestSpec::PRIMITIVE_POINTS, gls::DrawTestSpec::PRIMITIVE_TRIANGLES, gls::DrawTestSpec::PRIMITIVE_TRIANGLE_FAN, gls::DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP, gls::DrawTestSpec::PRIMITIVE_LINES, gls::DrawTestSpec::PRIMITIVE_LINE_STRIP, gls::DrawTestSpec::PRIMITIVE_LINE_LOOP }; const UniformWeightArray<DE_LENGTH_OF_ARRAY(primitives)> primitiveWeights; static const gls::DrawTestSpec::DrawMethod drawMethods[] = { gls::DrawTestSpec::DRAWMETHOD_DRAWARRAYS, gls::DrawTestSpec::DRAWMETHOD_DRAWARRAYS_INSTANCED, gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS, gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED, gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_INSTANCED }; const UniformWeightArray<DE_LENGTH_OF_ARRAY(drawMethods)> drawMethodWeights; static const gls::DrawTestSpec::IndexType indexTypes[] = { gls::DrawTestSpec::INDEXTYPE_BYTE, gls::DrawTestSpec::INDEXTYPE_SHORT, gls::DrawTestSpec::INDEXTYPE_INT, }; const UniformWeightArray<DE_LENGTH_OF_ARRAY(indexTypes)> indexTypeWeights; static const gls::DrawTestSpec::Storage storages[] = { gls::DrawTestSpec::STORAGE_USER, gls::DrawTestSpec::STORAGE_BUFFER, }; const UniformWeightArray<DE_LENGTH_OF_ARRAY(storages)> storageWeights; static const gls::DrawTestSpec::InputType inputTypes[] = { gls::DrawTestSpec::INPUTTYPE_FLOAT, gls::DrawTestSpec::INPUTTYPE_FIXED, gls::DrawTestSpec::INPUTTYPE_BYTE, gls::DrawTestSpec::INPUTTYPE_SHORT, gls::DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE, gls::DrawTestSpec::INPUTTYPE_UNSIGNED_SHORT, gls::DrawTestSpec::INPUTTYPE_INT, gls::DrawTestSpec::INPUTTYPE_UNSIGNED_INT, gls::DrawTestSpec::INPUTTYPE_HALF, gls::DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10, gls::DrawTestSpec::INPUTTYPE_INT_2_10_10_10, }; const UniformWeightArray<DE_LENGTH_OF_ARRAY(inputTypes)> inputTypeWeights; static const gls::DrawTestSpec::OutputType outputTypes[] = { gls::DrawTestSpec::OUTPUTTYPE_FLOAT, gls::DrawTestSpec::OUTPUTTYPE_VEC2, gls::DrawTestSpec::OUTPUTTYPE_VEC3, gls::DrawTestSpec::OUTPUTTYPE_VEC4, gls::DrawTestSpec::OUTPUTTYPE_INT, gls::DrawTestSpec::OUTPUTTYPE_UINT, gls::DrawTestSpec::OUTPUTTYPE_IVEC2, gls::DrawTestSpec::OUTPUTTYPE_IVEC3, gls::DrawTestSpec::OUTPUTTYPE_IVEC4, gls::DrawTestSpec::OUTPUTTYPE_UVEC2, gls::DrawTestSpec::OUTPUTTYPE_UVEC3, gls::DrawTestSpec::OUTPUTTYPE_UVEC4, }; const UniformWeightArray<DE_LENGTH_OF_ARRAY(outputTypes)> outputTypeWeights; static const gls::DrawTestSpec::Usage usages[] = { gls::DrawTestSpec::USAGE_DYNAMIC_DRAW, gls::DrawTestSpec::USAGE_STATIC_DRAW, gls::DrawTestSpec::USAGE_STREAM_DRAW, gls::DrawTestSpec::USAGE_STREAM_READ, gls::DrawTestSpec::USAGE_STREAM_COPY, gls::DrawTestSpec::USAGE_STATIC_READ, gls::DrawTestSpec::USAGE_STATIC_COPY, gls::DrawTestSpec::USAGE_DYNAMIC_READ, gls::DrawTestSpec::USAGE_DYNAMIC_COPY, }; const UniformWeightArray<DE_LENGTH_OF_ARRAY(usages)> usageWeights; static const deUint32 blacklistedCases[]= { 544, //!< extremely narrow triangle }; std::set<deUint32> insertedHashes; size_t insertedCount = 0; for (int ndx = 0; ndx < numAttempts; ++ndx) { de::Random random(0xc551393 + ndx); // random does not depend on previous cases int attributeCount = random.chooseWeighted<int, const int*, const float*>(DE_ARRAY_BEGIN(attribCounts), DE_ARRAY_END(attribCounts), attribWeights); gls::DrawTestSpec spec; spec.apiType = glu::ApiType::es(3,0); spec.primitive = random.chooseWeighted<gls::DrawTestSpec::Primitive> (DE_ARRAY_BEGIN(primitives), DE_ARRAY_END(primitives), primitiveWeights.weights); spec.primitiveCount = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(primitiveCounts), DE_ARRAY_END(primitiveCounts), primitiveCountWeights); spec.drawMethod = random.chooseWeighted<gls::DrawTestSpec::DrawMethod> (DE_ARRAY_BEGIN(drawMethods), DE_ARRAY_END(drawMethods), drawMethodWeights.weights); spec.indexType = random.chooseWeighted<gls::DrawTestSpec::IndexType> (DE_ARRAY_BEGIN(indexTypes), DE_ARRAY_END(indexTypes), indexTypeWeights.weights); spec.indexPointerOffset = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(indexOffsets), DE_ARRAY_END(indexOffsets), indexOffsetWeights); spec.indexStorage = random.chooseWeighted<gls::DrawTestSpec::Storage> (DE_ARRAY_BEGIN(storages), DE_ARRAY_END(storages), storageWeights.weights); spec.first = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(firsts), DE_ARRAY_END(firsts), firstWeights); spec.indexMin = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(indexMins), DE_ARRAY_END(indexMins), indexWeights); spec.indexMax = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(indexMaxs), DE_ARRAY_END(indexMaxs), indexWeights); spec.instanceCount = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(instanceCounts), DE_ARRAY_END(instanceCounts), instanceWeights); // check spec is legal if (!spec.valid()) continue; for (int attrNdx = 0; attrNdx < attributeCount;) { bool valid; gls::DrawTestSpec::AttributeSpec attribSpec; attribSpec.inputType = random.chooseWeighted<gls::DrawTestSpec::InputType> (DE_ARRAY_BEGIN(inputTypes), DE_ARRAY_END(inputTypes), inputTypeWeights.weights); attribSpec.outputType = random.chooseWeighted<gls::DrawTestSpec::OutputType> (DE_ARRAY_BEGIN(outputTypes), DE_ARRAY_END(outputTypes), outputTypeWeights.weights); attribSpec.storage = random.chooseWeighted<gls::DrawTestSpec::Storage> (DE_ARRAY_BEGIN(storages), DE_ARRAY_END(storages), storageWeights.weights); attribSpec.usage = random.chooseWeighted<gls::DrawTestSpec::Usage> (DE_ARRAY_BEGIN(usages), DE_ARRAY_END(usages), usageWeights.weights); attribSpec.componentCount = random.getInt(1, 4); attribSpec.offset = random.chooseWeighted<int, const int*, const float*>(DE_ARRAY_BEGIN(offsets), DE_ARRAY_END(offsets), offsetWeights); attribSpec.stride = random.chooseWeighted<int, const int*, const float*>(DE_ARRAY_BEGIN(strides), DE_ARRAY_END(strides), strideWeights); attribSpec.normalize = random.getBool(); attribSpec.instanceDivisor = random.chooseWeighted<int, const int*, const float*>(DE_ARRAY_BEGIN(instanceDivisors), DE_ARRAY_END(instanceDivisors), instanceDivisorWeights); attribSpec.useDefaultAttribute = random.getBool(); // check spec is legal valid = attribSpec.valid(spec.apiType); // we do not want interleaved elements. (Might result in some weird floating point values) if (attribSpec.stride && attribSpec.componentCount * gls::DrawTestSpec::inputTypeSize(attribSpec.inputType) > attribSpec.stride) valid = false; // try again if not valid if (valid) { spec.attribs.push_back(attribSpec); ++attrNdx; } } // Do not collapse all vertex positions to a single positions if (spec.primitive != gls::DrawTestSpec::PRIMITIVE_POINTS) spec.attribs[0].instanceDivisor = 0; // Is render result meaningful? { // Only one vertex if (spec.drawMethod == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED && spec.indexMin == spec.indexMax && spec.primitive != gls::DrawTestSpec::PRIMITIVE_POINTS) continue; if (spec.attribs[0].useDefaultAttribute && spec.primitive != gls::DrawTestSpec::PRIMITIVE_POINTS) continue; // Triangle only on one axis if (spec.primitive == gls::DrawTestSpec::PRIMITIVE_TRIANGLES || spec.primitive == gls::DrawTestSpec::PRIMITIVE_TRIANGLE_FAN || spec.primitive == gls::DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP) { if (spec.attribs[0].componentCount == 1) continue; if (spec.attribs[0].outputType == gls::DrawTestSpec::OUTPUTTYPE_FLOAT || spec.attribs[0].outputType == gls::DrawTestSpec::OUTPUTTYPE_INT || spec.attribs[0].outputType == gls::DrawTestSpec::OUTPUTTYPE_UINT) continue; if (spec.drawMethod == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED && (spec.indexMax - spec.indexMin) < 2) continue; } } // Add case { deUint32 hash = spec.hash(); for (int attrNdx = 0; attrNdx < attributeCount; ++attrNdx) hash = (hash << 2) ^ (deUint32)spec.attribs[attrNdx].hash(); if (insertedHashes.find(hash) == insertedHashes.end()) { // Only properly aligned and not blacklisted cases if (spec.isCompatibilityTest() != gls::DrawTestSpec::COMPATIBILITY_UNALIGNED_OFFSET && spec.isCompatibilityTest() != gls::DrawTestSpec::COMPATIBILITY_UNALIGNED_STRIDE && !de::contains(DE_ARRAY_BEGIN(blacklistedCases), DE_ARRAY_END(blacklistedCases), hash)) { this->addChild(new gls::DrawTest(m_testCtx, m_context.getRenderContext(), spec, de::toString(insertedCount).c_str(), spec.getDesc().c_str())); } insertedHashes.insert(hash); ++insertedCount; } } } } } // anonymous DrawTests::DrawTests (Context& context) : TestCaseGroup(context, "draw", "Drawing tests") { } DrawTests::~DrawTests (void) { } void DrawTests::init (void) { // Basic { const gls::DrawTestSpec::DrawMethod basicMethods[] = { gls::DrawTestSpec::DRAWMETHOD_DRAWARRAYS, gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS, gls::DrawTestSpec::DRAWMETHOD_DRAWARRAYS_INSTANCED, gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_INSTANCED, gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED, }; for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(basicMethods); ++ndx) { const std::string name = gls::DrawTestSpec::drawMethodToString(basicMethods[ndx]); const std::string desc = gls::DrawTestSpec::drawMethodToString(basicMethods[ndx]); this->addChild(new MethodGroup(m_context, name.c_str(), desc.c_str(), basicMethods[ndx])); } } // extreme instancing this->addChild(new InstancingGroup(m_context, "instancing", "draw tests with a large instance count.")); // Random this->addChild(new RandomGroup(m_context, "random", "random draw commands.")); } } // Functional } // gles3 } // deqp
; A000005: d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n. ; 1,2,2,3,2,4,2,4,3,4,2,6,2,4,4,5,2,6,2,6,4,4,2,8,3,4,4,6,2,8,2,6,4,4,4,9,2,4,4,8,2,8,2,6,6,4,2,10,3,6,4,6,2,8,4,8,4,4,2,12,2,4,6,7,4,8,2,6,4,8,2,12,2,4,6,6,4,8,2,10,5,4,2,12,4,4,4,8,2,12,4,6,4,4,4,12,2,6,6,9,2,8,2,8,8,4,2,12,2,8,4,10,2,8,4,6,6,4,4,16,3,4,4,6,4,12,2,8,4,8,2,12,4,4,8,8,2,8,2,12,4,4,4,15,4,4,6,6,2,12,2,8,6,8,4,12,2,4,4,12,4,10,2,6,8,4,2,16,3,8,6,6,2,8,6,10,4,4,2,18,2,8,4,8,4,8,4,6,8,8,2,14,2,4,8,9,2,12,2,12,4,4,4,12,4,4,6,10,4,16,2,6,4,4,4,16,4,4,4,12,4,8,2,12,9,4,2,12,2,8,8,8,2,12,4,6,4,8,2,20,2,6,6,6,6,8,4,8,4,8 add $0,1 mov $2,$0 lpb $2,1 mov $3,$0 lpb $3,1 mov $4,$3 trn $3,$2 lpe add $4,1 lpb $4,1 add $1,1 trn $4,$2 lpe sub $1,1 sub $2,1 lpe
extern m7_ippsSHA256Init:function extern n8_ippsSHA256Init:function extern y8_ippsSHA256Init:function extern e9_ippsSHA256Init:function extern l9_ippsSHA256Init:function extern n0_ippsSHA256Init:function extern k0_ippsSHA256Init:function extern ippcpJumpIndexForMergedLibs extern ippcpSafeInit:function segment .data align 8 dq .Lin_ippsSHA256Init .Larraddr_ippsSHA256Init: dq m7_ippsSHA256Init dq n8_ippsSHA256Init dq y8_ippsSHA256Init dq e9_ippsSHA256Init dq l9_ippsSHA256Init dq n0_ippsSHA256Init dq k0_ippsSHA256Init segment .text global ippsSHA256Init:function (ippsSHA256Init.LEndippsSHA256Init - ippsSHA256Init) .Lin_ippsSHA256Init: db 0xf3, 0x0f, 0x1e, 0xfa call ippcpSafeInit wrt ..plt align 16 ippsSHA256Init: db 0xf3, 0x0f, 0x1e, 0xfa mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc] movsxd rax, dword [rax] lea r11, [rel .Larraddr_ippsSHA256Init] mov r11, qword [r11+rax*8] jmp r11 .LEndippsSHA256Init:
; Disassembled code
/* * cv_image_deblurring.cpp - iterative blind deblurring * * Copyright (c) 2016-2017 Intel Corporation * * 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. * * Author: Andrey Parfenov <a1994ndrey@gmail.com> * Author: Wind Yuan <feng.yuan@intel.com> */ #include "cv_wiener_filter.h" namespace XCam { CVWienerFilter::CVWienerFilter () : CVBaseClass () { _helpers = new CVImageProcessHelper (); } void CVWienerFilter::wiener_filter (const cv::Mat &blurred_image, const cv::Mat &known, cv::Mat &unknown, float noise_power) { int image_w = blurred_image.size ().width; int image_h = blurred_image.size ().height; cv::Mat y_ft; _helpers->compute_dft (blurred_image, y_ft); cv::Mat padded = cv::Mat::zeros (image_h, image_w, CV_32FC1); int padx = padded.cols - known.cols; int pady = padded.rows - known.rows; cv::copyMakeBorder (known, padded, 0, pady, 0, padx, cv::BORDER_CONSTANT, cv::Scalar::all(0)); cv::Mat padded_ft; _helpers->compute_dft (padded, padded_ft); cv::Mat temp_unknown; cv::Mat unknown_ft[2]; unknown_ft[0] = cv::Mat::zeros (image_h, image_w, CV_32FC1); unknown_ft[1] = cv::Mat::zeros (image_h, image_w, CV_32FC1); cv::Mat denominator; cv::Mat denominator_splitted[] = {cv::Mat::zeros (blurred_image.size (), CV_32FC1), cv::Mat::zeros (blurred_image.size (), CV_32FC1)}; cv::mulSpectrums (padded_ft, padded_ft, denominator, 0, true); cv::split (denominator, denominator_splitted); denominator_splitted[0] = denominator_splitted[0] (cv::Rect (0, 0, blurred_image.cols, blurred_image.rows)); denominator_splitted[0] += cv::Scalar (noise_power); cv::Mat numerator; cv::Mat numerator_splitted[] = {cv::Mat::zeros (blurred_image.size (), CV_32FC1), cv::Mat::zeros (blurred_image.size (), CV_32FC1)}; cv::mulSpectrums (y_ft, padded_ft, numerator, 0, true); cv::split (numerator, numerator_splitted); numerator_splitted[0] = numerator_splitted[0] (cv::Rect (0, 0, blurred_image.cols, blurred_image.rows)); numerator_splitted[1] = numerator_splitted[1] (cv::Rect (0, 0, blurred_image.cols, blurred_image.rows)); cv::divide (numerator_splitted[0], denominator_splitted[0], unknown_ft[0]); cv::divide (numerator_splitted[1], denominator_splitted[0], unknown_ft[1]); _helpers->compute_idft (unknown_ft, temp_unknown); unknown = temp_unknown.clone(); } }
; A085820: Possible two-digit endings of primes (with leading zeros). ; 1,3,7,9,11,13,17,19,21,23,27,29,31,33,37,39,41,43,47,49,51,53,57,59,61,63,67,69,71,73,77,79,81,83,87,89,91,93,97,99 mov $1,$0 mul $1,5 add $1,2 div $1,4 mul $1,2 add $1,1
SECTION code_clib SECTION code_stdio PUBLIC __stdio_recv_input_raw_read EXTERN STDIO_MSG_READ EXTERN l_jpix ; ALL HIGH LEVEL STDIO INPUT PASSES THROUGH __STDIO_RECV_INPUT_RAW_* ; EXCEPT FOR VFSCANF. THIS ENSURES STREAM STATE IS CORRECTLY MAINTAINED __stdio_recv_input_raw_read: ; Driver reads a block of bytes from the stream and writes to buffer ; ; enter : ix = FILE * ; bc = max_length = number of chars to read from stream ; de = void *buffer = destination buffer ; ; exit : ix = FILE * ; de = void *buffer_ptr = address of byte following last written ; a = on error: 0 for stream error, -1 for eof ; bc'= number of bytes successfully read from stream ; ; carry set on error or eof, stream state set appropriately bit 3,(ix+3) jr nz, immediate_stream_error bit 4,(ix+3) jr nz, immediate_eof_error ld a,b or c jr z, len_zero ; if length is zero bit 0,(ix+4) jr z, _no_ungetc_rd ; if no unget char available ld a,(ix+6) ; a = unget char res 0,(ix+4) ; consume the unget char ld (de),a ; write char to buffer inc de dec bc ld a,b or c jr z, len_one call _no_ungetc_rd exx inc bc exx ret _no_ungetc_rd: ld a,STDIO_MSG_READ push bc exx pop hl call l_jpix ld a,l exx ret nc ; if no error ; stream error or eof ? inc a dec a jr z, stream_error ; eof set 4,(ix+3) ; set stream state to eof ret stream_error: set 3,(ix+3) ; set stream state to error ret len_one: exx ld bc,1 exx ret immediate_stream_error: xor a scf jr len_zero immediate_eof_error: ld a,$ff scf len_zero: exx ld bc,0 exx ret
; A008651: Molien series of binary icosahedral group. ; 1,0,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,2,1,1,1,1,1,2,1,1,1,2,1,2,1,1,2,2,1,2,1,2,2,2,1,2,2,2,2,2,1,3,2,2,2,2,2,3,2,2,2,3,2,3,2,2,3,3,2,3,2,3,3,3,2,3,3,3,3,3,2,4,3,3,3,3,3,4,3,3,3 mov $2,$0 seq $0,106006 ; [n/2] + [n/3] + [n/5]. sub $2,1 sub $0,$2
#include <ros/ros.h> #include <visualization_msgs/Marker.h> #include "nav_msgs/Odometry.h" #include <complex> //Positions and thresholds float pickUp[3] = {3.0, 5.0, 1.0}; float dropOff[3] = {-1.0, 0.0, 1.0}; float thresh[2] = {0.3, 0.01}; //Flags bool atPickUp = false; bool atDropOff = false; bool pickUpDone = false; bool dropOffDone = false; void chatterCallback(const nav_msgs::Odometry::ConstPtr& msg) { //Pick up if (std::abs(pickUp[0] -msg->pose.pose.position.x) < thresh[0] && std::abs(pickUp[1] -msg->pose.pose.position.y) < thresh[0] && std::abs(pickUp[2] -msg->pose.pose.orientation.w) < thresh[1]) { if(!atPickUp) { atPickUp = true; } }else{atPickUp = false;} //Drop off if (std::abs(dropOff[0] -msg->pose.pose.position.x) < thresh[0] && std::abs(dropOff[1] -msg->pose.pose.position.y) < thresh[0] && std::abs(dropOff[2] -msg->pose.pose.orientation.w) < thresh[1]) { if(!atDropOff) { atDropOff = true; } }else{atDropOff = false;} } int main( int argc, char** argv ) { ROS_INFO("Main"); ros::init(argc, argv, "add_markers"); ros::NodeHandle n; ros::Rate r(1); ros::Publisher marker_pub = n.advertise<visualization_msgs::Marker>("visualization_marker", 1); ros::Subscriber odom_sub = n.subscribe("odom", 1000, chatterCallback); // Set our initial shape type to be a cube uint32_t shape = visualization_msgs::Marker::CUBE; while (ros::ok()) { visualization_msgs::Marker marker; // Set the frame ID and timestamp. See the TF tutorials for information on these. marker.header.frame_id = "map"; marker.header.stamp = ros::Time::now(); // Set the namespace and id for this marker. This serves to create a unique ID // Any marker sent with the same namespace and id will overwrite the old one marker.ns = "basic_shapes"; marker.id = 0; // Set the marker type. Initially this is CUBE, and cycles between that and SPHERE, ARROW, and CYLINDER marker.type = shape; // Set the marker action. Options are ADD, DELETE, and new in ROS Indigo: 3 (DELETEALL) marker.action = visualization_msgs::Marker::ADD; // Set the pose of the marker. This is a full 6DOF pose relative to the frame/time specified in the header marker.pose.position.x = pickUp[0]; marker.pose.position.y = pickUp[1]; marker.pose.position.z = 0; marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = pickUp[2]; // Set the scale of the marker -- 1x1x1 here means 1m on a side marker.scale.x = 0.5; marker.scale.y = 0.5; marker.scale.z = 0.5; // Set the color -- be sure to set alpha to something non-zero! marker.color.r = 1.0f; marker.color.g = 0.0f; marker.color.b = 0.0f; marker.color.a = 1.0; marker.lifetime = ros::Duration(); // Publish the marker while (marker_pub.getNumSubscribers() < 1) { if (!ros::ok()) { return 0; } ROS_WARN_ONCE("Please create a subscriber to the marker"); sleep(1); } marker_pub.publish(marker); ROS_INFO("Pick-up marker displayed------------"); ROS_INFO("Pick-up marker displayed atPickUp %d ", atPickUp); //Wait for Pick-Up while(!atPickUp) { ros::spinOnce(); } if(atPickUp && !pickUpDone) { marker.action = visualization_msgs::Marker::DELETE; marker_pub.publish(marker); ROS_INFO("Pick-up marker removed"); pickUpDone = true; } //Wait for Drop-Off while(!atDropOff) { ros::spinOnce(); } if(atDropOff && !dropOffDone) { marker.pose.position.x = dropOff[0]; marker.pose.position.y = dropOff[1]; marker.pose.orientation.w = dropOff[2];; marker.action = visualization_msgs::Marker::ADD; marker_pub.publish(marker); ROS_INFO("Drop-off marker displayed"); dropOffDone = true; ros::Duration(10.0).sleep(); } return 0; } }
; IP Version section version xdef ip_vmess xdef ip_vmend xdef ip_vers ; V1.00 Initial version ip_vers equ '1.00' ip_vmess dc.w 'QPC IP devices V' dc.l ip_vers dc.b ' ',$a ip_vmend ds.w 0 end
#include "hongyulib.h" double variance(string infile) { double var; ifstream myfile; myfile.open(infile.c_str()); int file_num = count_file_num(infile); int count; double sum; if(file_num == 0) { puts("ERROR read in file has 0 points!"); return 0; } double data[file_num]; for(count = 0; count < file_num; count++) { myfile >> data[count]; //fscanf(in,"%lf", &data[count]); } // get the average sum = 0; for(count = 0; count < file_num; count++) { if(data[count] != data[count]) { puts("ERROR read in data has nan!"); data[count] = 0; } sum +=data[count]; } double avg = sum/file_num; //printf("variance func: file num is %d avf is %lf \n", file_num, avg); for(count = 0; count < file_num; count++) { var += (data[count] - avg ) * ( data[count] - avg ); } var = var / file_num; return var; }
; A349317: Triangle T(n,k): T(n,k) = 1 if gcd(n, k) > 1, else 0. ; Submitted by Jamie Morken(s3) ; 0,0,1,0,0,1,0,1,0,1,0,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,1,1,0 mov $1,2 lpb $0 add $2,1 sub $0,$2 lpe add $0,1 lpb $0 add $2,1 gcd $0,$2 sub $0,$1 mov $1,1 lpe mov $0,$1 mod $0,2
db DEX_HORSEA ; pokedex id db 30, 40, 70, 60, 70 ; hp atk def spd spc db WATER, WATER ; type db 225 ; catch rate db 83 ; base exp INCBIN "gfx/pokemon/front/horsea.pic", 0, 1 ; sprite dimensions dw HorseaPicFront, HorseaPicBack db BUBBLE, NO_MOVE, NO_MOVE, NO_MOVE ; level 1 learnset db GROWTH_MEDIUM_FAST ; growth rate ; tm/hm learnset tmhm TOXIC, TAKE_DOWN, DOUBLE_EDGE, BUBBLEBEAM, WATER_GUN, \ ICE_BEAM, BLIZZARD, RAGE, MIMIC, DOUBLE_TEAM, \ BIDE, SWIFT, SKULL_BASH, REST, SUBSTITUTE, \ SURF ; end db 0 ; padding
; A008676: Expansion of 1/((1-x^3)*(1-x^5)). ; 1,0,0,1,0,1,1,0,1,1,1,1,1,1,1,2,1,1,2,1,2,2,1,2,2,2,2,2,2,2,3,2,2,3,2,3,3,2,3,3,3,3,3,3,3,4,3,3,4,3,4,4,3,4,4,4,4,4,4,4,5,4,4,5,4,5,5,4,5,5,5,5,5,5,5,6,5,5,6,5,6,6,5,6,6,6,6,6,6,6,7,6,6,7,6,7,7,6,7,7,7,7,7,7,7,8,7,7,8,7,8,8,7,8,8,8,8,8,8,8,9,8,8,9,8,9,9,8,9,9,9,9,9,9,9,10,9,9,10,9,10,10,9,10,10,10,10,10,10,10,11,10,10,11,10,11,11,10,11,11,11,11,11,11,11,12,11,11,12,11,12,12,11,12,12,12,12,12,12,12,13,12,12,13,12,13,13,12,13,13,13,13,13,13,13,14,13,13,14,13,14,14,13,14,14,14,14,14,14,14,15,14,14,15,14,15,15,14,15,15,15,15,15,15,15,16,15,15,16,15,16,16,15,16,16,16,16,16,16,16,17,16,16,17,16,17,17,16,17,17 mov $2,$0 mul $0,2 add $0,1 lpb $0 sub $0,4 trn $0,1 add $3,1 trn $3,$2 trn $2,3 lpe add $1,$3
#ifndef WIGWAG_POLICIES_LIFE_ASSURANCE_POLICIES_HPP #define WIGWAG_POLICIES_LIFE_ASSURANCE_POLICIES_HPP // Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com> // // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <wigwag/policies/life_assurance/intrusive_life_tokens.hpp> #include <wigwag/policies/life_assurance/none.hpp> #include <wigwag/policies/life_assurance/single_threaded.hpp> namespace wigwag { namespace life_assurance { using default_ = intrusive_life_tokens; }} #endif
// Copyright (c) 2014 Dropbox, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "runtime/objmodel.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <memory> #include <stdint.h> #include "asm_writing/icinfo.h" #include "asm_writing/rewriter.h" #include "codegen/codegen.h" #include "codegen/compvars.h" #include "codegen/irgen/hooks.h" #include "codegen/llvm_interpreter.h" #include "codegen/parser.h" #include "codegen/type_recording.h" #include "core/ast.h" #include "core/options.h" #include "core/stats.h" #include "core/types.h" #include "gc/collector.h" #include "gc/heap.h" #include "runtime/capi.h" #include "runtime/classobj.h" #include "runtime/float.h" #include "runtime/generator.h" #include "runtime/iterobject.h" #include "runtime/types.h" #include "runtime/util.h" #define BOX_CLS_OFFSET ((char*)&(((Box*)0x01)->cls) - (char*)0x1) #define HCATTRS_HCLS_OFFSET ((char*)&(((HCAttrs*)0x01)->hcls) - (char*)0x1) #define HCATTRS_ATTRS_OFFSET ((char*)&(((HCAttrs*)0x01)->attr_list) - (char*)0x1) #define ATTRLIST_ATTRS_OFFSET ((char*)&(((HCAttrs::AttrList*)0x01)->attrs) - (char*)0x1) #define ATTRLIST_KIND_OFFSET ((char*)&(((HCAttrs::AttrList*)0x01)->gc_header.kind_id) - (char*)0x1) #define INSTANCEMETHOD_FUNC_OFFSET ((char*)&(((BoxedInstanceMethod*)0x01)->func) - (char*)0x1) #define INSTANCEMETHOD_OBJ_OFFSET ((char*)&(((BoxedInstanceMethod*)0x01)->obj) - (char*)0x1) #define BOOL_B_OFFSET ((char*)&(((BoxedBool*)0x01)->b) - (char*)0x1) #define INT_N_OFFSET ((char*)&(((BoxedInt*)0x01)->n) - (char*)0x1) namespace pyston { // TODO should centralize all of these: static const std::string _call_str("__call__"), _new_str("__new__"), _init_str("__init__"), _get_str("__get__"); static const std::string _getattr_str("__getattr__"); static const std::string _getattribute_str("__getattribute__"); struct GetattrRewriteArgs { Rewriter* rewriter; RewriterVarUsage obj; Location destination; bool call_done_guarding; bool out_success; RewriterVarUsage out_rtn; bool obj_hcls_guarded; GetattrRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, Location destination, bool call_done_guarding) : rewriter(rewriter), obj(std::move(obj)), destination(destination), call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()), obj_hcls_guarded(false) {} ~GetattrRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { obj.ensureDoneUsing(); } }; struct SetattrRewriteArgs { Rewriter* rewriter; RewriterVarUsage obj, attrval; bool call_done_guarding; bool out_success; SetattrRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, RewriterVarUsage&& attrval, bool call_done_guarding) : rewriter(rewriter), obj(std::move(obj)), attrval(std::move(attrval)), call_done_guarding(call_done_guarding), out_success(false) {} ~SetattrRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { obj.ensureDoneUsing(); } }; struct DelattrRewriteArgs { Rewriter* rewriter; RewriterVarUsage obj; bool call_done_guarding; bool out_success; DelattrRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, bool call_done_guarding) : rewriter(rewriter), obj(std::move(obj)), call_done_guarding(call_done_guarding), out_success(false) {} ~DelattrRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { obj.ensureDoneUsing(); } }; struct LenRewriteArgs { Rewriter* rewriter; RewriterVarUsage obj; Location destination; bool call_done_guarding; bool out_success; RewriterVarUsage out_rtn; LenRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, Location destination, bool call_done_guarding) : rewriter(rewriter), obj(std::move(obj)), destination(destination), call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()) {} ~LenRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { obj.ensureDoneUsing(); } }; struct CallRewriteArgs { Rewriter* rewriter; RewriterVarUsage obj; RewriterVarUsage arg1, arg2, arg3, args; bool func_guarded; bool args_guarded; Location destination; bool call_done_guarding; bool out_success; RewriterVarUsage out_rtn; CallRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& obj, Location destination, bool call_done_guarding) : rewriter(rewriter), obj(std::move(obj)), arg1(RewriterVarUsage::empty()), arg2(RewriterVarUsage::empty()), arg3(RewriterVarUsage::empty()), args(RewriterVarUsage::empty()), func_guarded(false), args_guarded(false), destination(destination), call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()) {} ~CallRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { obj.ensureDoneUsing(); arg1.ensureDoneUsing(); arg2.ensureDoneUsing(); arg3.ensureDoneUsing(); args.ensureDoneUsing(); } }; struct BinopRewriteArgs { Rewriter* rewriter; RewriterVarUsage lhs, rhs; Location destination; bool call_done_guarding; bool out_success; RewriterVarUsage out_rtn; BinopRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& lhs, RewriterVarUsage&& rhs, Location destination, bool call_done_guarding) : rewriter(rewriter), lhs(std::move(lhs)), rhs(std::move(rhs)), destination(destination), call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()) {} ~BinopRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { lhs.ensureDoneUsing(); rhs.ensureDoneUsing(); } }; struct CompareRewriteArgs { Rewriter* rewriter; RewriterVarUsage lhs, rhs; Location destination; bool call_done_guarding; bool out_success; RewriterVarUsage out_rtn; CompareRewriteArgs(Rewriter* rewriter, RewriterVarUsage&& lhs, RewriterVarUsage&& rhs, Location destination, bool call_done_guarding) : rewriter(rewriter), lhs(std::move(lhs)), rhs(std::move(rhs)), destination(destination), call_done_guarding(call_done_guarding), out_success(false), out_rtn(RewriterVarUsage::empty()) {} ~CompareRewriteArgs() { if (!out_success) { ensureAllDone(); } } void ensureAllDone() { lhs.ensureDoneUsing(); rhs.ensureDoneUsing(); } }; Box* runtimeCallInternal(Box* obj, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names); static Box* (*runtimeCallInternal0)(Box*, CallRewriteArgs*, ArgPassSpec) = (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec))runtimeCallInternal; static Box* (*runtimeCallInternal1)(Box*, CallRewriteArgs*, ArgPassSpec, Box*) = (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec, Box*))runtimeCallInternal; static Box* (*runtimeCallInternal2)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*) = (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*))runtimeCallInternal; static Box* (*runtimeCallInternal3)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*) = (Box * (*)(Box*, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*))runtimeCallInternal; static Box* (*typeCallInternal1)(BoxedFunction*, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box*) = (Box * (*)(BoxedFunction*, CallRewriteArgs*, ArgPassSpec, Box*))typeCallInternal; static Box* (*typeCallInternal2)(BoxedFunction*, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box*, Box*) = (Box * (*)(BoxedFunction*, CallRewriteArgs*, ArgPassSpec, Box*, Box*))typeCallInternal; static Box* (*typeCallInternal3)(BoxedFunction*, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box*, Box*, Box*) = (Box * (*)(BoxedFunction*, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*))typeCallInternal; bool checkClass(LookupScope scope) { return (scope & CLASS_ONLY) != 0; } bool checkInst(LookupScope scope) { return (scope & INST_ONLY) != 0; } static Box* (*callattrInternal0)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec) = (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec))callattrInternal; static Box* (*callattrInternal1)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*) = (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*))callattrInternal; static Box* (*callattrInternal2)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*) = (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*))callattrInternal; static Box* (*callattrInternal3)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*) = (Box * (*)(Box*, const std::string*, LookupScope, CallRewriteArgs*, ArgPassSpec, Box*, Box*, Box*))callattrInternal; size_t PyHasher::operator()(Box* b) const { if (b->cls == str_cls) { std::hash<std::string> H; return H(static_cast<BoxedString*>(b)->s); } BoxedInt* i = hash(b); assert(sizeof(size_t) == sizeof(i->n)); size_t rtn = i->n; return rtn; } bool PyEq::operator()(Box* lhs, Box* rhs) const { if (lhs->cls == rhs->cls) { if (lhs->cls == str_cls) { return static_cast<BoxedString*>(lhs)->s == static_cast<BoxedString*>(rhs)->s; } } // TODO fix this Box* cmp = compareInternal(lhs, rhs, AST_TYPE::Eq, NULL); assert(cmp->cls == bool_cls); BoxedBool* b = static_cast<BoxedBool*>(cmp); bool rtn = b->b; return rtn; } bool PyLt::operator()(Box* lhs, Box* rhs) const { // TODO fix this Box* cmp = compareInternal(lhs, rhs, AST_TYPE::Lt, NULL); assert(cmp->cls == bool_cls); BoxedBool* b = static_cast<BoxedBool*>(cmp); bool rtn = b->b; return rtn; } extern "C" bool softspace(Box* b, bool newval) { assert(b); if (isSubclass(b->cls, file_cls)) { bool& ss = static_cast<BoxedFile*>(b)->softspace; bool r = ss; ss = newval; return r; } bool r; Box* gotten = b->getattr("softspace"); if (!gotten) { r = 0; } else { r = nonzero(gotten); } b->setattr("softspace", boxInt(newval), NULL); return r; } extern "C" void my_assert(bool b) { assert(b); } extern "C" bool isSubclass(BoxedClass* child, BoxedClass* parent) { // TODO the class is allowed to override this using __subclasscheck__ while (child) { if (child == parent) return true; child = child->base; } return false; } extern "C" void assertFail(BoxedModule* inModule, Box* msg) { if (msg) { BoxedString* tostr = str(msg); raiseExcHelper(AssertionError, "%s", tostr->s.c_str()); } else { raiseExcHelper(AssertionError, NULL); } } extern "C" void assertNameDefined(bool b, const char* name, BoxedClass* exc_cls, bool local_var_msg) { if (!b) { if (local_var_msg) raiseExcHelper(exc_cls, "local variable '%s' referenced before assignment", name); else raiseExcHelper(exc_cls, "name '%s' is not defined", name); } } extern "C" void raiseAttributeErrorStr(const char* typeName, const char* attr) { raiseExcHelper(AttributeError, "'%s' object has no attribute '%s'", typeName, attr); } extern "C" void raiseAttributeError(Box* obj, const char* attr) { if (obj->cls == type_cls) { // Slightly different error message: raiseExcHelper(AttributeError, "type object '%s' has no attribute '%s'", getNameOfClass(static_cast<BoxedClass*>(obj))->c_str(), attr); } else { raiseAttributeErrorStr(getTypeName(obj)->c_str(), attr); } } extern "C" void raiseNotIterableError(const char* typeName) { raiseExcHelper(TypeError, "'%s' object is not iterable", typeName); } static void _checkUnpackingLength(i64 expected, i64 given) { if (given == expected) return; if (given > expected) raiseExcHelper(ValueError, "too many values to unpack"); else { if (given == 1) raiseExcHelper(ValueError, "need more than %ld value to unpack", given); else raiseExcHelper(ValueError, "need more than %ld values to unpack", given); } } extern "C" Box** unpackIntoArray(Box* obj, int64_t expected_size) { assert(expected_size > 0); if (obj->cls == tuple_cls) { BoxedTuple* t = static_cast<BoxedTuple*>(obj); _checkUnpackingLength(expected_size, t->elts.size()); return &t->elts[0]; } if (obj->cls == list_cls) { BoxedList* l = static_cast<BoxedList*>(obj); _checkUnpackingLength(expected_size, l->size); return &l->elts->elts[0]; } BoxedTuple::GCVector elts; for (auto e : obj->pyElements()) { elts.push_back(e); if (elts.size() > expected_size) break; } _checkUnpackingLength(expected_size, elts.size()); return &elts[0]; } PyObject* Py_CallPythonNew(PyTypeObject* self, PyObject* args, PyObject* kwds) { try { Py_FatalError("this function is untested"); Box* new_attr = typeLookup(self, _new_str, NULL); assert(new_attr); new_attr = processDescriptor(new_attr, None, self); return runtimeCallInternal(new_attr, NULL, ArgPassSpec(1, 0, true, true), self, args, kwds, NULL, NULL); } catch (Box* e) { abort(); } } PyObject* Py_CallPythonCall(PyObject* self, PyObject* args, PyObject* kwds) { try { Py_FatalError("this function is untested"); return runtimeCallInternal(self, NULL, ArgPassSpec(0, 0, true, true), args, kwds, NULL, NULL, NULL); } catch (Box* e) { abort(); } } void BoxedClass::freeze() { assert(!is_constant); assert(getattr("__name__")); // otherwise debugging will be very hard // This will probably share a lot in common with Py_TypeReady: if (!tp_new) { this->tp_new = &Py_CallPythonNew; } else if (tp_new != Py_CallPythonNew) { ASSERT(0, "need to set __new__?"); } if (!tp_call) { this->tp_call = &Py_CallPythonCall; } else if (tp_call != Py_CallPythonCall) { ASSERT(0, "need to set __call__?"); } is_constant = true; } BoxedClass::BoxedClass(BoxedClass* metaclass, BoxedClass* base, gcvisit_func gc_visit, int attrs_offset, int instance_size, bool is_user_defined) : BoxVar(metaclass, 0), base(base), gc_visit(gc_visit), attrs_offset(attrs_offset), is_constant(false), is_user_defined(is_user_defined) { // Zero out the CPython tp_* slots: memset(&tp_name, 0, (char*)(&tp_version_tag + 1) - (char*)(&tp_name)); tp_basicsize = instance_size; if (metaclass == NULL) { assert(type_cls == NULL); } else { assert(isSubclass(metaclass, type_cls)); } assert(tp_dealloc == NULL); if (gc_visit == NULL) { assert(base); this->gc_visit = base->gc_visit; } assert(this->gc_visit); if (!base) { assert(object_cls == nullptr); // we're constructing 'object' // Will have to add __base__ = None later } else { assert(object_cls); if (base->attrs_offset) RELEASE_ASSERT(attrs_offset == base->attrs_offset, ""); assert(tp_basicsize >= base->tp_basicsize); } if (base && cls && str_cls) giveAttr("__base__", base); assert(tp_basicsize % sizeof(void*) == 0); // Not critical I suppose, but probably signals a bug if (attrs_offset) { assert(tp_basicsize >= attrs_offset + sizeof(HCAttrs)); assert(attrs_offset % sizeof(void*) == 0); // Not critical I suppose, but probably signals a bug } if (!is_user_defined) gc::registerPermanentRoot(this); } std::string getFullNameOfClass(BoxedClass* cls) { Box* b = cls->getattr("__name__"); assert(b); ASSERT(b->cls == str_cls, "%p", b->cls); BoxedString* name = static_cast<BoxedString*>(b); b = cls->getattr("__module__"); if (!b) return name->s; assert(b); if (b->cls != str_cls) return name->s; BoxedString* module = static_cast<BoxedString*>(b); return module->s + "." + name->s; } std::string getFullTypeName(Box* o) { return getFullNameOfClass(o->cls); } extern "C" const std::string* getNameOfClass(BoxedClass* cls) { Box* b = cls->getattr("__name__"); assert(b); ASSERT(b->cls == str_cls, "%p", b->cls); BoxedString* sb = static_cast<BoxedString*>(b); return &sb->s; } extern "C" const std::string* getTypeName(Box* o) { return getNameOfClass(o->cls); } HiddenClass* HiddenClass::getOrMakeChild(const std::string& attr) { std::unordered_map<std::string, HiddenClass*>::iterator it = children.find(attr); if (it != children.end()) return it->second; static StatCounter num_hclses("num_hidden_classes"); num_hclses.log(); HiddenClass* rtn = new HiddenClass(this); this->children[attr] = rtn; rtn->attr_offsets[attr] = attr_offsets.size(); return rtn; } /** * del attr from current HiddenClass, pertain the orders of remaining attrs */ HiddenClass* HiddenClass::delAttrToMakeHC(const std::string& attr) { int idx = getOffset(attr); assert(idx >= 0); std::vector<std::string> new_attrs(attr_offsets.size() - 1); for (auto it = attr_offsets.begin(); it != attr_offsets.end(); ++it) { if (it->second < idx) new_attrs[it->second] = it->first; else if (it->second > idx) { new_attrs[it->second - 1] = it->first; } } // TODO we can first locate the parent HiddenClass of the deleted // attribute and hence avoid creation of its ancestors. HiddenClass* cur = root_hcls; for (const auto& attr : new_attrs) { cur = cur->getOrMakeChild(attr); } return cur; } Box::Box(BoxedClass* cls) : cls(cls) { // if (TRACK_ALLOCATIONS) { // int id = Stats::getStatId("allocated_" + *getNameOfClass(c)); // Stats::log(id); //} // the only way cls should be NULL is if we're creating the type_cls // object itself: if (cls == NULL) { ASSERT(type_cls == NULL, "should pass a non-null cls here"); } else { } } HCAttrs* Box::getAttrsPtr() { assert(cls->instancesHaveAttrs()); char* p = reinterpret_cast<char*>(this); p += cls->attrs_offset; return reinterpret_cast<HCAttrs*>(p); } Box* Box::getattr(const std::string& attr, GetattrRewriteArgs* rewrite_args) { // Have to guard on the memory layout of this object. // Right now, guard on the specific Python-class, which in turn // specifies the C structure. // In the future, we could create another field (the flavor?) // that also specifies the structure and can include multiple // classes. // Only matters if we end up getting multiple classes with the same // structure (ex user class) and the same hidden classes, because // otherwise the guard will fail anyway.; if (rewrite_args) { rewrite_args->obj.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)cls); rewrite_args->out_success = true; } if (!cls->instancesHaveAttrs()) { if (rewrite_args) { rewrite_args->obj.setDoneUsing(); if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); } return NULL; } HCAttrs* attrs = getAttrsPtr(); HiddenClass* hcls = attrs->hcls; if (rewrite_args) { if (!rewrite_args->obj_hcls_guarded) rewrite_args->obj.addAttrGuard(cls->attrs_offset + HCATTRS_HCLS_OFFSET, (intptr_t)hcls); if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); } int offset = hcls->getOffset(attr); if (offset == -1) { if (rewrite_args) { rewrite_args->obj.setDoneUsing(); } return NULL; } if (rewrite_args) { // TODO using the output register as the temporary makes register allocation easier // since we don't need to clobber a register, but does it make the code slower? RewriterVarUsage attrs = rewrite_args->obj.getAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET, RewriterVarUsage::Kill, Location::any()); rewrite_args->out_rtn = attrs.getAttr(offset * sizeof(Box*) + ATTRLIST_ATTRS_OFFSET, RewriterVarUsage::Kill, Location::any()); } Box* rtn = attrs->attr_list->attrs[offset]; return rtn; } void Box::setattr(const std::string& attr, Box* val, SetattrRewriteArgs* rewrite_args) { assert(cls->instancesHaveAttrs()); assert(gc::isValidGCObject(val)); // Have to guard on the memory layout of this object. // Right now, guard on the specific Python-class, which in turn // specifies the C structure. // In the future, we could create another field (the flavor?) // that also specifies the structure and can include multiple // classes. // Only matters if we end up getting multiple classes with the same // structure (ex user class) and the same hidden classes, because // otherwise the guard will fail anyway.; if (rewrite_args) rewrite_args->obj.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)cls); static const std::string none_str("None"); RELEASE_ASSERT(attr != none_str || this == builtins_module, "can't assign to None"); HCAttrs* attrs = getAttrsPtr(); HiddenClass* hcls = attrs->hcls; int numattrs = hcls->attr_offsets.size(); int offset = hcls->getOffset(attr); if (rewrite_args) { rewrite_args->obj.addAttrGuard(cls->attrs_offset + HCATTRS_HCLS_OFFSET, (intptr_t)hcls); if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); // rewrite_args->rewriter->addDecision(offset == -1 ? 1 : 0); } if (offset >= 0) { assert(offset < numattrs); Box* prev = attrs->attr_list->attrs[offset]; attrs->attr_list->attrs[offset] = val; if (rewrite_args) { RewriterVarUsage r_hattrs = rewrite_args->obj.getAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET, RewriterVarUsage::Kill, Location::any()); r_hattrs.setAttr(offset * sizeof(Box*) + ATTRLIST_ATTRS_OFFSET, std::move(rewrite_args->attrval)); r_hattrs.setDoneUsing(); rewrite_args->out_success = true; } return; } assert(offset == -1); HiddenClass* new_hcls = hcls->getOrMakeChild(attr); // TODO need to make sure we don't need to rearrange the attributes assert(new_hcls->attr_offsets[attr] == numattrs); #ifndef NDEBUG for (const auto& p : hcls->attr_offsets) { assert(new_hcls->attr_offsets[p.first] == p.second); } #endif RewriterVarUsage r_new_array2(RewriterVarUsage::empty()); int new_size = sizeof(HCAttrs::AttrList) + sizeof(Box*) * (numattrs + 1); if (numattrs == 0) { attrs->attr_list = (HCAttrs::AttrList*)gc_alloc(new_size, gc::GCKind::UNTRACKED); if (rewrite_args) { RewriterVarUsage r_newsize = rewrite_args->rewriter->loadConst(new_size, Location::forArg(0)); RewriterVarUsage r_kind = rewrite_args->rewriter->loadConst((int)gc::GCKind::UNTRACKED, Location::forArg(1)); r_new_array2 = rewrite_args->rewriter->call(false, (void*)gc::gc_alloc, std::move(r_newsize), std::move(r_kind)); } } else { attrs->attr_list = (HCAttrs::AttrList*)gc::gc_realloc(attrs->attr_list, new_size); if (rewrite_args) { RewriterVarUsage r_oldarray = rewrite_args->obj.getAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET, RewriterVarUsage::NoKill, Location::forArg(0)); RewriterVarUsage r_newsize = rewrite_args->rewriter->loadConst(new_size, Location::forArg(1)); r_new_array2 = rewrite_args->rewriter->call(false, (void*)gc::gc_realloc, std::move(r_oldarray), std::move(r_newsize)); } } // Don't set the new hcls until after we do the allocation for the new attr_list; // that allocation can cause a collection, and we want the collector to always // see a consistent state between the hcls and the attr_list attrs->hcls = new_hcls; if (rewrite_args) { r_new_array2.setAttr(numattrs * sizeof(Box*) + ATTRLIST_ATTRS_OFFSET, std::move(rewrite_args->attrval)); rewrite_args->obj.setAttr(cls->attrs_offset + HCATTRS_ATTRS_OFFSET, std::move(r_new_array2)); RewriterVarUsage r_hcls = rewrite_args->rewriter->loadConst((intptr_t)new_hcls); rewrite_args->obj.setAttr(cls->attrs_offset + HCATTRS_HCLS_OFFSET, std::move(r_hcls)); rewrite_args->obj.setDoneUsing(); rewrite_args->out_success = true; } attrs->attr_list->attrs[numattrs] = val; } Box* typeLookup(BoxedClass* cls, const std::string& attr, GetattrRewriteArgs* rewrite_args) { Box* val; if (rewrite_args) { assert(!rewrite_args->out_success); RewriterVarUsage obj_saved = rewrite_args->obj.addUse(); bool call_done_guarding = rewrite_args->call_done_guarding; rewrite_args->call_done_guarding = false; val = cls->getattr(attr, rewrite_args); assert(rewrite_args->out_success); if (!val and cls->base) { rewrite_args->out_success = false; rewrite_args->obj = obj_saved.getAttr(offsetof(BoxedClass, base), RewriterVarUsage::Kill); val = typeLookup(cls->base, attr, rewrite_args); } else { obj_saved.setDoneUsing(); } if (call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); return val; } else { val = cls->getattr(attr, NULL); if (!val and cls->base) return typeLookup(cls->base, attr, NULL); return val; } } bool isNondataDescriptorInstanceSpecialCase(Box* descr) { return descr->cls == function_cls || descr->cls == method_cls; } Box* nondataDescriptorInstanceSpecialCases(GetattrRewriteArgs* rewrite_args, Box* obj, Box* descr, RewriterVarUsage& r_descr, bool for_call, bool* should_bind_out) { // Special case: non-data descriptor: function if (descr->cls == function_cls || descr->cls == method_cls) { if (!for_call) { if (rewrite_args) { // can't guard after because we make this call... the call is trivial enough // that we can probably work around it if it's important, but otherwise, if // this triggers, just abort rewriting, I guess assert(rewrite_args->call_done_guarding); rewrite_args->rewriter->setDoneGuarding(); rewrite_args->out_rtn = rewrite_args->rewriter->call(false, (void*)boxInstanceMethod, std::move(rewrite_args->obj), std::move(r_descr)); rewrite_args->out_success = true; } return boxInstanceMethod(obj, descr); } else { if (rewrite_args) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); rewrite_args->out_rtn = std::move(r_descr); rewrite_args->out_success = true; } *should_bind_out = true; return descr; } } return NULL; } Box* descriptorClsSpecialCases(GetattrRewriteArgs* rewrite_args, BoxedClass* cls, Box* descr, RewriterVarUsage& r_descr, bool for_call, bool* should_bind_out) { // Special case: functions if (descr->cls == function_cls || descr->cls == method_cls) { if (rewrite_args) r_descr.addAttrGuard(BOX_CLS_OFFSET, (uint64_t)descr->cls); if (!for_call && descr->cls == function_cls) { if (rewrite_args) { assert(rewrite_args->call_done_guarding); rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); // return an unbound instancemethod rewrite_args->out_rtn = rewrite_args->rewriter->call(false, (void*)boxUnboundInstanceMethod, std::move(r_descr)); rewrite_args->out_success = true; } return boxUnboundInstanceMethod(descr); } if (rewrite_args) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); rewrite_args->out_success = true; rewrite_args->out_rtn = std::move(r_descr); } // leave should_bind_out set to false return descr; } // Special case: member descriptor if (descr->cls == member_cls) { if (rewrite_args) r_descr.addAttrGuard(BOX_CLS_OFFSET, (uint64_t)descr->cls); if (rewrite_args) { assert(rewrite_args->call_done_guarding); rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); // Actually just return val (it's a descriptor but only // has special behaviour for instance lookups - see below) rewrite_args->out_rtn = std::move(r_descr); rewrite_args->out_success = true; } return descr; } return NULL; } Box* dataDescriptorInstanceSpecialCases(GetattrRewriteArgs* rewrite_args, Box* obj, Box* descr, RewriterVarUsage& r_descr, bool for_call, bool* should_bind_out) { // Special case: data descriptor: member descriptor if (descr->cls == member_cls) { BoxedMemberDescriptor* member_desc = static_cast<BoxedMemberDescriptor*>(descr); // TODO should also have logic to raise a type error if type of obj is wrong if (rewrite_args) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); r_descr.setDoneUsing(); } switch (member_desc->type) { case BoxedMemberDescriptor::OBJECT: { assert(member_desc->offset % sizeof(Box*) == 0); Box* rtn = reinterpret_cast<Box**>(obj)[member_desc->offset / sizeof(Box*)]; RELEASE_ASSERT(rtn, ""); if (rewrite_args) { rewrite_args->out_rtn = rewrite_args->obj.getAttr( member_desc->offset, RewriterVarUsage::KillFlag::Kill, rewrite_args->destination); rewrite_args->out_success = true; } return rtn; } case BoxedMemberDescriptor::BYTE: { // TODO rewriter stuff for these other cases as well rewrite_args = NULL; int8_t rtn = reinterpret_cast<int8_t*>(obj)[member_desc->offset]; return boxInt(rtn); } case BoxedMemberDescriptor::BOOL: { rewrite_args = NULL; bool rtn = reinterpret_cast<bool*>(obj)[member_desc->offset]; return boxBool(rtn); } case BoxedMemberDescriptor::INT: { rewrite_args = NULL; int rtn = reinterpret_cast<int*>(obj)[member_desc->offset / sizeof(int)]; return boxInt(rtn); } case BoxedMemberDescriptor::FLOAT: { rewrite_args = NULL; double rtn = reinterpret_cast<double*>(obj)[member_desc->offset / sizeof(double)]; return boxFloat(rtn); } default: RELEASE_ASSERT(0, "%d", member_desc->type); } } return NULL; } inline Box* getclsattr_internal(Box* obj, const std::string& attr, GetattrRewriteArgs* rewrite_args) { return getattrInternalGeneral(obj, attr, rewrite_args, /* cls_only */ true, /* for_call */ false, NULL); } extern "C" Box* getclsattr(Box* obj, const char* attr) { static StatCounter slowpath_getclsattr("slowpath_getclsattr"); slowpath_getclsattr.log(); Box* gotten; #if 0 std::unique_ptr<Rewriter> rewriter(Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, 1, "getclsattr")); if (rewriter.get()) { //rewriter->trap(); GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0)); gotten = getclsattr_internal(obj, attr, &rewrite_args, NULL); if (rewrite_args.out_success && gotten) { rewrite_args.out_rtn.move(-1); rewriter->commit(); } #else std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "getclsattr")); if (rewriter.get()) { // rewriter->trap(); GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), true); gotten = getclsattr_internal(obj, attr, &rewrite_args); if (rewrite_args.out_success && gotten) { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } #endif } else { gotten = getclsattr_internal(obj, attr, NULL); } RELEASE_ASSERT(gotten, "%s:%s", getTypeName(obj)->c_str(), attr); return gotten; } // Does a simple call of the descriptor's __get__ if it exists; // this function is useful for custom getattribute implementations that already know whether the descriptor // came from the class or not. Box* processDescriptorOrNull(Box* obj, Box* inst, Box* owner) { Box* descr_r = callattrInternal(obj, &_get_str, LookupScope::CLASS_ONLY, NULL, ArgPassSpec(2), inst, owner, NULL, NULL, NULL); return descr_r; } Box* processDescriptor(Box* obj, Box* inst, Box* owner) { Box* descr_r = processDescriptorOrNull(obj, inst, owner); if (descr_r) return descr_r; return obj; } static Box* (*runtimeCall0)(Box*, ArgPassSpec) = (Box * (*)(Box*, ArgPassSpec))runtimeCall; static Box* (*runtimeCall1)(Box*, ArgPassSpec, Box*) = (Box * (*)(Box*, ArgPassSpec, Box*))runtimeCall; static Box* (*runtimeCall2)(Box*, ArgPassSpec, Box*, Box*) = (Box * (*)(Box*, ArgPassSpec, Box*, Box*))runtimeCall; static Box* (*runtimeCall3)(Box*, ArgPassSpec, Box*, Box*, Box*) = (Box * (*)(Box*, ArgPassSpec, Box*, Box*, Box*))runtimeCall; Box* getattrInternalGeneral(Box* obj, const std::string& attr, GetattrRewriteArgs* rewrite_args, bool cls_only, bool for_call, bool* should_bind_out) { if (for_call) { *should_bind_out = false; } if (obj->cls == closure_cls) { Box* val = NULL; if (rewrite_args) { GetattrRewriteArgs hrewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), rewrite_args->destination, false); val = obj->getattr(attr, &hrewrite_args); if (!hrewrite_args.out_success) { rewrite_args = NULL; } else if (val) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->out_rtn = std::move(hrewrite_args.out_rtn); rewrite_args->out_success = true; rewrite_args->obj.setDoneUsing(); return val; } } else { val = obj->getattr(attr, NULL); if (val) { return val; } } // If val doesn't exist, then we move up to the parent closure // TODO closures should get their own treatment, but now just piggy-back on the // normal hidden-class IC logic. // Can do better since we don't need to guard on the cls (always going to be closure) BoxedClosure* closure = static_cast<BoxedClosure*>(obj); if (closure->parent) { if (rewrite_args) { rewrite_args->obj = rewrite_args->obj.getAttr(offsetof(BoxedClosure, parent), RewriterVarUsage::NoKill); if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); } return getattrInternal(closure->parent, attr, rewrite_args); } raiseExcHelper(NameError, "free variable '%s' referenced before assignment in enclosing scope", attr.c_str()); } if (!cls_only) { // Don't need to pass icentry args, since we special-case __getattribtue__ and __getattr__ to use // invalidation rather than guards // TODO since you changed this to typeLookup you need to guard Box* getattribute = typeLookup(obj->cls, "__getattribute__", NULL); if (getattribute) { // TODO this is a good candidate for interning? Box* boxstr = boxString(attr); Box* rtn = runtimeCall2(getattribute, ArgPassSpec(2), obj, boxstr); return rtn; } if (rewrite_args) { rewrite_args->rewriter->addDependenceOn(obj->cls->dependent_icgetattrs); } } // Handle descriptor logic here. // A descriptor is either a data descriptor or a non-data descriptor. // data descriptors define both __get__ and __set__. non-data descriptors // only define __get__. Rules are different for the two types, which means // that even though __get__ is the one we might call, we still have to check // if __set__ exists. // If __set__ exists, it's a data descriptor, and it takes precedence over // the instance attribute. // Otherwise, it's non-data, and we only call __get__ if the instance // attribute doesn't exist. // In the cls_only case, we ignore the instance attribute // (so we don't have to check if __set__ exists at all) // Look up the class attribute (called `descr` here because it might // be a descriptor). Box* descr = NULL; RewriterVarUsage r_descr(RewriterVarUsage::empty()); if (rewrite_args) { RewriterVarUsage r_obj_cls = rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any()); GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_obj_cls), rewrite_args->destination, false); descr = typeLookup(obj->cls, attr, &grewrite_args); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (descr) { r_descr = std::move(grewrite_args.out_rtn); } } else { descr = typeLookup(obj->cls, attr, NULL); } // Check if it's a data descriptor Box* _get_ = NULL; RewriterVarUsage r_get(RewriterVarUsage::empty()); if (descr) { if (rewrite_args) r_descr.addAttrGuard(BOX_CLS_OFFSET, (uint64_t)descr->cls); // Special-case data descriptors (e.g., member descriptors) Box* res = dataDescriptorInstanceSpecialCases(rewrite_args, obj, descr, r_descr, for_call, should_bind_out); if (res) { return res; } // Let's only check if __get__ exists if it's not a special case // nondata descriptor. The nondata case is handled below, but // we can immediately know to skip this part if it's one of the // special case nondata descriptors. if (!isNondataDescriptorInstanceSpecialCase(descr)) { // Check if __get__ exists if (rewrite_args) { RewriterVarUsage r_descr_cls = r_descr.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any()); GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_descr_cls), Location::any(), false); _get_ = typeLookup(descr->cls, _get_str, &grewrite_args); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (_get_) { r_get = std::move(grewrite_args.out_rtn); } } else { _get_ = typeLookup(descr->cls, _get_str, NULL); } // As an optimization, don't check for __set__ if we're in cls_only mode, since it won't matter. if (_get_ && !cls_only) { // Check if __set__ exists Box* _set_ = NULL; if (rewrite_args) { RewriterVarUsage r_descr_cls = r_descr.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any()); GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_descr_cls), Location::any(), false); _set_ = typeLookup(descr->cls, "__set__", &grewrite_args); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (_set_) { grewrite_args.out_rtn.setDoneUsing(); } } else { _set_ = typeLookup(descr->cls, "__set__", NULL); } // Call __get__(descr, obj, obj->cls) if (_set_) { // this could happen for the callattr path... if (rewrite_args && !rewrite_args->call_done_guarding) rewrite_args = NULL; Box* res; if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_get), rewrite_args->destination, rewrite_args->call_done_guarding); crewrite_args.arg1 = std::move(r_descr); crewrite_args.arg2 = rewrite_args->obj.addUse(); crewrite_args.arg3 = rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::Kill, Location::any()); res = runtimeCallInternal(_get_, &crewrite_args, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL); if (!crewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_success = true; rewrite_args->out_rtn = std::move(crewrite_args.out_rtn); } } else { r_descr.ensureDoneUsing(); r_get.ensureDoneUsing(); res = runtimeCallInternal(_get_, NULL, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL); } return res; } } } } if (!cls_only) { if (obj->cls != type_cls) { // Look up the val in the object's dictionary and if you find it, return it. Box* val; RewriterVarUsage r_val(RewriterVarUsage::empty()); if (rewrite_args) { GetattrRewriteArgs hrewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), rewrite_args->destination, false); val = obj->getattr(attr, &hrewrite_args); if (!hrewrite_args.out_success) { rewrite_args = NULL; } else if (val) { r_val = std::move(hrewrite_args.out_rtn); } } else { val = obj->getattr(attr, NULL); } if (val) { if (rewrite_args) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); rewrite_args->out_rtn = std::move(r_val); rewrite_args->out_success = true; } r_descr.ensureDoneUsing(); r_get.ensureDoneUsing(); return val; } } else { // More complicated when obj is a type // We have to look up the attr in the entire // class hierarchy, and we also have to check if it is a descriptor, // in addition to the data/nondata descriptor logic. // (in CPython, see type_getattro in typeobject.c) Box* val; RewriterVarUsage r_val(RewriterVarUsage::empty()); if (rewrite_args) { GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), rewrite_args->destination, false); val = typeLookup(static_cast<BoxedClass*>(obj), attr, &grewrite_args); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (val) { r_val = std::move(grewrite_args.out_rtn); } } else { val = typeLookup(static_cast<BoxedClass*>(obj), attr, NULL); } if (val) { r_get.ensureDoneUsing(); r_descr.ensureDoneUsing(); Box* res = descriptorClsSpecialCases(rewrite_args, static_cast<BoxedClass*>(obj), val, r_val, for_call, should_bind_out); if (res) { return res; } // Lookup __get__ RewriterVarUsage r_get(RewriterVarUsage::empty()); Box* local_get; if (rewrite_args) { RewriterVarUsage r_val_cls = r_val.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::NoKill, Location::any()); GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, std::move(r_val_cls), Location::any(), false); local_get = typeLookup(val->cls, _get_str, &grewrite_args); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (local_get) { r_get = std::move(grewrite_args.out_rtn); } } else { local_get = typeLookup(val->cls, _get_str, NULL); } // Call __get__(val, None, obj) if (local_get) { Box* res; // this could happen for the callattr path... if (rewrite_args && !rewrite_args->call_done_guarding) rewrite_args = NULL; if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_get), rewrite_args->destination, rewrite_args->call_done_guarding); crewrite_args.arg1 = std::move(r_val); crewrite_args.arg2 = rewrite_args->rewriter->loadConst((intptr_t)None, Location::any()); crewrite_args.arg3 = std::move(rewrite_args->obj); res = runtimeCallInternal(local_get, &crewrite_args, ArgPassSpec(3), val, None, obj, NULL, NULL); if (!crewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_success = true; rewrite_args->out_rtn = std::move(crewrite_args.out_rtn); } } else { r_val.ensureDoneUsing(); r_get.ensureDoneUsing(); res = runtimeCallInternal(local_get, NULL, ArgPassSpec(3), val, None, obj, NULL, NULL); } return res; } // If there was no local __get__, just return val if (rewrite_args) { if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->obj.setDoneUsing(); rewrite_args->out_rtn = std::move(r_val); rewrite_args->out_success = true; } else { r_val.ensureDoneUsing(); } return val; } } } // If descr and __get__ exist, then call __get__ if (descr) { // Special cases first Box* res = nondataDescriptorInstanceSpecialCases(rewrite_args, obj, descr, r_descr, for_call, should_bind_out); if (res) { return res; } // We looked up __get__ above. If we found it, call it and return // the result. if (_get_) { // this could happen for the callattr path... if (rewrite_args && !rewrite_args->call_done_guarding) rewrite_args = NULL; Box* res; if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_get), rewrite_args->destination, rewrite_args->call_done_guarding); crewrite_args.arg1 = std::move(r_descr); crewrite_args.arg2 = rewrite_args->obj.addUse(); crewrite_args.arg3 = rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::Kill, Location::any()); res = runtimeCallInternal(_get_, &crewrite_args, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL); if (!crewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_success = true; rewrite_args->out_rtn = std::move(crewrite_args.out_rtn); } } else { r_descr.ensureDoneUsing(); r_get.ensureDoneUsing(); res = runtimeCallInternal(_get_, NULL, ArgPassSpec(3), descr, obj, obj->cls, NULL, NULL); } return res; } // Otherwise, just return descr. if (rewrite_args) { rewrite_args->obj.setDoneUsing(); if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); rewrite_args->out_rtn = std::move(r_descr); rewrite_args->out_success = true; } return descr; } // Finally, check __getattr__ if (!cls_only) { // Don't need to pass icentry args, since we special-case __getattribute__ and __getattr__ to use // invalidation rather than guards rewrite_args = NULL; Box* getattr = typeLookup(obj->cls, "__getattr__", NULL); if (getattr) { Box* boxstr = boxString(attr); Box* rtn = runtimeCall2(getattr, ArgPassSpec(2), obj, boxstr); if (rewrite_args) rewrite_args->out_rtn.ensureDoneUsing(); return rtn; } if (rewrite_args) { rewrite_args->rewriter->addDependenceOn(obj->cls->dependent_icgetattrs); } } if (rewrite_args) { rewrite_args->obj.ensureDoneUsing(); rewrite_args->out_success = true; } return NULL; } Box* getattrInternal(Box* obj, const std::string& attr, GetattrRewriteArgs* rewrite_args) { return getattrInternalGeneral(obj, attr, rewrite_args, /* cls_only */ false, /* for_call */ false, NULL); } extern "C" Box* getattr(Box* obj, const char* attr) { static StatCounter slowpath_getattr("slowpath_getattr"); slowpath_getattr.log(); if (VERBOSITY() >= 2) { #if !DISABLE_STATS std::string per_name_stat_name = "getattr__" + std::string(attr); int id = Stats::getStatId(per_name_stat_name); Stats::log(id); #endif } if (strcmp(attr, "__dict__") == 0) { if (obj->cls->instancesHaveAttrs()) return makeAttrWrapper(obj); } std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "getattr")); Box* val; if (rewriter.get()) { Location dest; TypeRecorder* recorder = rewriter->getTypeRecorder(); if (recorder) dest = Location::forArg(1); else dest = rewriter->getReturnDestination(); GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), dest, true); val = getattrInternal(obj, attr, &rewrite_args); // should make sure getattrInternal calls finishes using obj itself // if it is successful if (!rewrite_args.out_success) rewrite_args.obj.ensureDoneUsing(); if (rewrite_args.out_success && val) { if (recorder) { RewriterVarUsage record_rtn = rewriter->call( false, (void*)recordType, rewriter->loadConst((intptr_t)recorder, Location::forArg(0)), std::move(rewrite_args.out_rtn)); rewriter->commitReturning(std::move(record_rtn)); recordType(recorder, val); } else { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } } } else { val = getattrInternal(obj, attr, NULL); } if (val) { return val; } raiseAttributeError(obj, attr); } void setattrInternal(Box* obj, const std::string& attr, Box* val, SetattrRewriteArgs* rewrite_args) { assert(gc::isValidGCObject(val)); // Lookup a descriptor Box* descr = NULL; RewriterVarUsage r_descr(RewriterVarUsage::empty()); // TODO probably check that the cls is user-defined or something like that // (figure out exactly what) // (otherwise no need to check descriptor logic) if (rewrite_args) { RewriterVarUsage r_cls = rewrite_args->obj.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::KillFlag::NoKill, Location::any()); GetattrRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_cls), rewrite_args->rewriter->getReturnDestination(), false); descr = typeLookup(obj->cls, attr, &crewrite_args); if (!crewrite_args.out_success) { rewrite_args = NULL; } else if (descr) { r_descr = std::move(crewrite_args.out_rtn); } } else { descr = typeLookup(obj->cls, attr, NULL); } if (isSubclass(obj->cls, type_cls)) { BoxedClass* self = static_cast<BoxedClass*>(obj); if (attr == _getattr_str || attr == _getattribute_str) { // Will have to embed the clear in the IC, so just disable the patching for now: rewrite_args = NULL; // TODO should put this clearing behavior somewhere else, since there are probably more // cases in which we want to do it. self->dependent_icgetattrs.invalidateAll(); } if (attr == "__base__" && self->getattr("__base__")) raiseExcHelper(TypeError, "readonly attribute"); if (attr == "__new__") { self->tp_new = &Py_CallPythonNew; // TODO update subclasses rewrite_args = NULL; } if (attr == "__call__") { self->tp_call = &Py_CallPythonCall; // TODO update subclasses rewrite_args = NULL; } } Box* _set_ = NULL; RewriterVarUsage r_set(RewriterVarUsage::empty()); if (descr) { if (rewrite_args) { RewriterVarUsage r_cls = r_descr.getAttr(BOX_CLS_OFFSET, RewriterVarUsage::KillFlag::NoKill, Location::any()); GetattrRewriteArgs trewrite_args(rewrite_args->rewriter, std::move(r_cls), Location::any(), false); _set_ = typeLookup(descr->cls, "__set__", &trewrite_args); if (!trewrite_args.out_success) { rewrite_args = NULL; } else if (_set_) { r_set = std::move(trewrite_args.out_rtn); } } else { _set_ = typeLookup(descr->cls, "__set__", NULL); } } // If `descr` has __set__ (thus making it a descriptor) we should call // __set__ with `val` rather than directly calling setattr if (descr && _set_) { if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(r_set), Location::any(), rewrite_args->call_done_guarding); crewrite_args.arg1 = std::move(r_descr); crewrite_args.arg2 = std::move(rewrite_args->obj); crewrite_args.arg3 = std::move(rewrite_args->attrval); runtimeCallInternal(_set_, &crewrite_args, ArgPassSpec(3), descr, obj, val, NULL, NULL); if (crewrite_args.out_success) { crewrite_args.out_rtn.setDoneUsing(); rewrite_args->out_success = true; } } else { runtimeCallInternal(_set_, NULL, ArgPassSpec(3), descr, obj, val, NULL, NULL); } } else { r_descr.ensureDoneUsing(); r_set.ensureDoneUsing(); obj->setattr(attr, val, rewrite_args); } } extern "C" void setattr(Box* obj, const char* attr, Box* attr_val) { assert(strcmp(attr, "__class__") != 0); static StatCounter slowpath_setattr("slowpath_setattr"); slowpath_setattr.log(); if (!obj->cls->instancesHaveAttrs()) { raiseAttributeError(obj, attr); } if (obj->cls == type_cls) { BoxedClass* cobj = static_cast<BoxedClass*>(obj); if (!isUserDefined(cobj)) { raiseExcHelper(TypeError, "can't set attributes of built-in/extension type '%s'", getNameOfClass(cobj)->c_str()); } } std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "setattr")); if (rewriter.get()) { // rewriter->trap(); SetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getArg(2), true); setattrInternal(obj, attr, attr_val, &rewrite_args); if (rewrite_args.out_success) { rewriter->commit(); } else { rewrite_args.obj.ensureDoneUsing(); rewrite_args.attrval.ensureDoneUsing(); } } else { setattrInternal(obj, attr, attr_val, NULL); } } bool isUserDefined(BoxedClass* cls) { return cls->is_user_defined; // return cls->hasattrs && (cls != function_cls && cls != type_cls) && !cls->is_constant; } extern "C" bool nonzero(Box* obj) { static StatCounter slowpath_nonzero("slowpath_nonzero"); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 1, "nonzero")); RewriterVarUsage r_obj(RewriterVarUsage::empty()); if (rewriter.get()) { r_obj = std::move(rewriter->getArg(0)); // rewriter->trap(); r_obj.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)obj->cls); rewriter->setDoneGuarding(); } if (obj->cls == bool_cls) { if (rewriter.get()) { RewriterVarUsage b = r_obj.getAttr(BOOL_B_OFFSET, RewriterVarUsage::KillFlag::Kill, rewriter->getReturnDestination()); rewriter->commitReturning(std::move(b)); } BoxedBool* bool_obj = static_cast<BoxedBool*>(obj); return bool_obj->b; } else if (obj->cls == int_cls) { if (rewriter.get()) { // TODO should do: // test %rsi, %rsi // setne %al RewriterVarUsage n = r_obj.getAttr(INT_N_OFFSET, RewriterVarUsage::KillFlag::Kill, rewriter->getReturnDestination()); RewriterVarUsage b = n.toBool(RewriterVarUsage::KillFlag::Kill, rewriter->getReturnDestination()); rewriter->commitReturning(std::move(b)); } BoxedInt* int_obj = static_cast<BoxedInt*>(obj); return int_obj->n != 0; } else if (obj->cls == float_cls) { if (rewriter.get()) { RewriterVarUsage b = rewriter->call(false, (void*)floatNonzeroUnboxed, std::move(r_obj)); rewriter->commitReturning(std::move(b)); } return static_cast<BoxedFloat*>(obj)->d != 0; } else if (obj->cls == none_cls) { if (rewriter.get()) { r_obj.setDoneUsing(); RewriterVarUsage b = rewriter->loadConst(0, rewriter->getReturnDestination()); rewriter->commitReturning(std::move(b)); } return false; } if (rewriter.get()) { r_obj.setDoneUsing(); } // FIXME we have internal functions calling this method; // instead, we should break this out into an external and internal function. // slowpath_* counters are supposed to count external calls; putting it down // here gets a better representation of that. // TODO move internal callers to nonzeroInternal, and log *all* calls to nonzero slowpath_nonzero.log(); // int id = Stats::getStatId("slowpath_nonzero_" + *getTypeName(obj)); // Stats::log(id); // go through descriptor logic Box* func = getclsattr_internal(obj, "__nonzero__", NULL); if (func == NULL) { ASSERT(isUserDefined(obj->cls) || obj->cls == classobj_cls, "%s.__nonzero__", getTypeName(obj)->c_str()); // TODO return true; } Box* r = runtimeCall0(func, ArgPassSpec(0)); if (r->cls == bool_cls) { BoxedBool* b = static_cast<BoxedBool*>(r); bool rtn = b->b; return rtn; } else if (r->cls == int_cls) { BoxedInt* b = static_cast<BoxedInt*>(r); bool rtn = b->n != 0; return rtn; } else { raiseExcHelper(TypeError, "__nonzero__ should return bool or int, returned %s", getTypeName(r)->c_str()); } } extern "C" BoxedString* str(Box* obj) { static StatCounter slowpath_str("slowpath_str"); slowpath_str.log(); if (obj->cls != str_cls) { static const std::string str_str("__str__"); obj = callattrInternal(obj, &str_str, CLASS_ONLY, NULL, ArgPassSpec(0), NULL, NULL, NULL, NULL, NULL); } if (obj->cls != str_cls) { raiseExcHelper(TypeError, "__str__ did not return a string!"); } return static_cast<BoxedString*>(obj); } extern "C" BoxedString* repr(Box* obj) { static StatCounter slowpath_repr("slowpath_repr"); slowpath_repr.log(); static const std::string repr_str("__repr__"); obj = callattrInternal(obj, &repr_str, CLASS_ONLY, NULL, ArgPassSpec(0), NULL, NULL, NULL, NULL, NULL); if (obj->cls != str_cls) { raiseExcHelper(TypeError, "__repr__ did not return a string!"); } return static_cast<BoxedString*>(obj); } extern "C" BoxedString* reprOrNull(Box* obj) { try { Box* r = repr(obj); assert(r->cls == str_cls); // this should be checked by repr() return static_cast<BoxedString*>(r); } catch (Box* b) { return nullptr; } } extern "C" BoxedString* strOrNull(Box* obj) { try { BoxedString* r = str(obj); return static_cast<BoxedString*>(r); } catch (Box* b) { return nullptr; } } extern "C" bool isinstance(Box* obj, Box* cls, int64_t flags) { bool false_on_noncls = (flags & 0x1); if (cls->cls == tuple_cls) { auto t = static_cast<BoxedTuple*>(cls); for (auto c : t->elts) { if (isinstance(obj, c, flags)) return true; } return false; } if (cls->cls == classobj_cls) { if (!isSubclass(obj->cls, instance_cls)) return false; return instanceIsinstance(static_cast<BoxedInstance*>(obj), static_cast<BoxedClassobj*>(cls)); } if (!false_on_noncls) { assert(cls->cls == type_cls); } else { if (cls->cls != type_cls) return false; } BoxedClass* ccls = static_cast<BoxedClass*>(cls); // TODO the class is allowed to override this using __instancecheck__ return isSubclass(obj->cls, ccls); } extern "C" BoxedInt* hash(Box* obj) { static StatCounter slowpath_hash("slowpath_hash"); slowpath_hash.log(); // goes through descriptor logic Box* hash = getclsattr_internal(obj, "__hash__", NULL); if (hash == NULL) { ASSERT(isUserDefined(obj->cls), "%s.__hash__", getTypeName(obj)->c_str()); // TODO not the best way to handle this... return static_cast<BoxedInt*>(boxInt((i64)obj)); } Box* rtn = runtimeCall0(hash, ArgPassSpec(0)); if (rtn->cls != int_cls) { raiseExcHelper(TypeError, "an integer is required"); } return static_cast<BoxedInt*>(rtn); } extern "C" BoxedInt* lenInternal(Box* obj, LenRewriteArgs* rewrite_args) { Box* rtn; static std::string attr_str("__len__"); if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(rewrite_args->obj), rewrite_args->destination, rewrite_args->call_done_guarding); rtn = callattrInternal0(obj, &attr_str, CLASS_ONLY, &crewrite_args, ArgPassSpec(0)); if (!crewrite_args.out_success) rewrite_args = NULL; else if (rtn) rewrite_args->out_rtn = std::move(crewrite_args.out_rtn); } else { rtn = callattrInternal0(obj, &attr_str, CLASS_ONLY, NULL, ArgPassSpec(0)); } if (rtn == NULL) { raiseExcHelper(TypeError, "object of type '%s' has no len()", getTypeName(obj)->c_str()); } if (rtn->cls != int_cls) { raiseExcHelper(TypeError, "an integer is required"); } if (rewrite_args) rewrite_args->out_success = true; return static_cast<BoxedInt*>(rtn); } extern "C" BoxedInt* len(Box* obj) { static StatCounter slowpath_len("slowpath_len"); slowpath_len.log(); return lenInternal(obj, NULL); } extern "C" i64 unboxedLen(Box* obj) { static StatCounter slowpath_unboxedlen("slowpath_unboxedlen"); slowpath_unboxedlen.log(); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 1, "unboxedLen")); BoxedInt* lobj; RewriterVarUsage r_boxed(RewriterVarUsage::empty()); if (rewriter.get()) { // rewriter->trap(); LenRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), true); lobj = lenInternal(obj, &rewrite_args); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else r_boxed = std::move(rewrite_args.out_rtn); } else { lobj = lenInternal(obj, NULL); } assert(lobj->cls == int_cls); i64 rtn = lobj->n; if (rewriter.get()) { RewriterVarUsage rtn = std::move(r_boxed.getAttr(INT_N_OFFSET, RewriterVarUsage::KillFlag::Kill, Location(assembler::RAX))); rewriter->commitReturning(std::move(rtn)); } return rtn; } extern "C" void dump(void* p) { printf("\n"); bool is_gc = (gc::global_heap.getAllocationFromInteriorPointer(p) != NULL); if (!is_gc) { printf("non-gc memory\n"); return; } gc::GCAllocation* al = gc::GCAllocation::fromUserData(p); if (al->kind_id == gc::GCKind::UNTRACKED) { printf("gc-untracked object\n"); return; } if (al->kind_id == gc::GCKind::CONSERVATIVE) { printf("conservatively-scanned object object\n"); return; } if (al->kind_id == gc::GCKind::PYTHON) { printf("Python object\n"); Box* b = (Box*)p; printf("Class: %s\n", getFullTypeName(b).c_str()); if (isSubclass(b->cls, type_cls)) { printf("Type name: %s\n", getFullNameOfClass(static_cast<BoxedClass*>(b)).c_str()); } if (isSubclass(b->cls, str_cls)) { printf("String value: %s\n", static_cast<BoxedString*>(b)->s.c_str()); } if (isSubclass(b->cls, tuple_cls)) { printf("%ld elements\n", static_cast<BoxedTuple*>(b)->elts.size()); } return; } RELEASE_ASSERT(0, "%d", (int)al->kind_id); } // For rewriting purposes, this function assumes that nargs will be constant. // That's probably fine for some uses (ex binops), but otherwise it should be guarded on beforehand. extern "C" Box* callattrInternal(Box* obj, const std::string* attr, LookupScope scope, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { int npassed_args = argspec.totalPassed(); if (rewrite_args && !rewrite_args->args_guarded) { // TODO duplication with runtime_call // TODO should know which args don't need to be guarded, ex if we're guaranteed that they // already fit, either since the type inferencer could determine that, // or because they only need to fit into an UNKNOWN slot. if (npassed_args >= 1) rewrite_args->arg1.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg1->cls); if (npassed_args >= 2) rewrite_args->arg2.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg2->cls); if (npassed_args >= 3) rewrite_args->arg3.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg3->cls); if (npassed_args > 3) { for (int i = 3; i < npassed_args; i++) { // TODO if there are a lot of args (>16), might be better to increment a pointer // rather index them directly? RewriterVarUsage v = rewrite_args->args.getAttr((i - 3) * sizeof(Box*), RewriterVarUsage::KillFlag::NoKill, Location::any()); v.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)args[i - 3]->cls); v.setDoneUsing(); } } } // right now I don't think this is ever called with INST_ONLY? assert(scope != INST_ONLY); // Look up the argument. Pass in the arguments to getattrInternalGeneral or getclsattr_general // that will shortcut functions by not putting them into instancemethods bool should_bind; Box* val; RewriterVarUsage r_val(RewriterVarUsage::empty()); if (rewrite_args) { GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), Location::any(), false); val = getattrInternalGeneral(obj, *attr, &grewrite_args, scope == CLASS_ONLY, true, &should_bind); if (!grewrite_args.out_success) { rewrite_args = NULL; } else if (val) { r_val = std::move(grewrite_args.out_rtn); } } else { val = getattrInternalGeneral(obj, *attr, NULL, scope == CLASS_ONLY, true, &should_bind); } if (val == NULL) { if (rewrite_args) { rewrite_args->arg1.ensureDoneUsing(); rewrite_args->arg2.ensureDoneUsing(); rewrite_args->arg3.ensureDoneUsing(); rewrite_args->args.ensureDoneUsing(); rewrite_args->out_success = true; rewrite_args->obj.setDoneUsing(); } return val; } if (should_bind) { if (rewrite_args) { r_val.addGuard((int64_t)val); } // TODO copy from runtimeCall // TODO these two branches could probably be folded together (the first one is becoming // a subset of the second) if (npassed_args <= 2) { Box* rtn; if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_val), rewrite_args->destination, rewrite_args->call_done_guarding); srewrite_args.arg1 = std::move(rewrite_args->obj); // should be no-ops: if (npassed_args >= 1) srewrite_args.arg2 = std::move(rewrite_args->arg1); if (npassed_args >= 2) srewrite_args.arg3 = std::move(rewrite_args->arg2); srewrite_args.func_guarded = true; srewrite_args.args_guarded = true; rtn = runtimeCallInternal(val, &srewrite_args, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), obj, arg1, arg2, NULL, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); } } else { rtn = runtimeCallInternal(val, NULL, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), obj, arg1, arg2, NULL, keyword_names); } if (rewrite_args) rewrite_args->out_success = true; return rtn; } else { int alloca_size = sizeof(Box*) * (npassed_args + 1 - 3); Box** new_args = (Box**)alloca(alloca_size); new_args[0] = arg3; memcpy(new_args + 1, args, (npassed_args - 3) * sizeof(Box*)); Box* rtn; if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_val), rewrite_args->destination, rewrite_args->call_done_guarding); srewrite_args.arg1 = std::move(rewrite_args->obj); srewrite_args.arg2 = std::move(rewrite_args->arg1); srewrite_args.arg3 = std::move(rewrite_args->arg2); srewrite_args.args = rewrite_args->rewriter->allocateAndCopyPlus1( std::move(rewrite_args->arg3), npassed_args == 3 ? RewriterVarUsage::empty() : std::move(rewrite_args->args), npassed_args - 3); srewrite_args.args_guarded = true; srewrite_args.func_guarded = true; rtn = runtimeCallInternal(val, &srewrite_args, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), obj, arg1, arg2, new_args, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); rewrite_args->out_success = true; } } else { rtn = runtimeCallInternal(val, NULL, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), obj, arg1, arg2, new_args, keyword_names); } return rtn; } } else { if (rewrite_args) { rewrite_args->obj.setDoneUsing(); } Box* rtn; if (val->cls != function_cls && val->cls != instancemethod_cls) { rewrite_args = NULL; r_val.ensureDoneUsing(); } if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_val), rewrite_args->destination, rewrite_args->call_done_guarding); if (npassed_args >= 1) srewrite_args.arg1 = std::move(rewrite_args->arg1); if (npassed_args >= 2) srewrite_args.arg2 = std::move(rewrite_args->arg2); if (npassed_args >= 3) srewrite_args.arg3 = std::move(rewrite_args->arg3); if (npassed_args >= 4) srewrite_args.args = std::move(rewrite_args->args); srewrite_args.args_guarded = true; rtn = runtimeCallInternal(val, &srewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); } } else { rtn = runtimeCallInternal(val, NULL, argspec, arg1, arg2, arg3, args, keyword_names); } if (!rtn) { raiseExcHelper(TypeError, "'%s' object is not callable", getTypeName(val)->c_str()); } if (rewrite_args) rewrite_args->out_success = true; return rtn; } } extern "C" Box* callattr(Box* obj, const std::string* attr, bool clsonly, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { int npassed_args = argspec.totalPassed(); static StatCounter slowpath_callattr("slowpath_callattr"); slowpath_callattr.log(); assert(attr); int num_orig_args = 4 + std::min(4, npassed_args); if (argspec.num_keywords) num_orig_args++; std::unique_ptr<Rewriter> rewriter(Rewriter::createRewriter( __builtin_extract_return_addr(__builtin_return_address(0)), num_orig_args, "callattr")); Box* rtn; LookupScope scope = clsonly ? CLASS_ONLY : CLASS_OR_INST; if (rewriter.get()) { // TODO feel weird about doing this; it either isn't necessary // or this kind of thing is necessary in a lot more places // rewriter->getArg(3).addGuard(npassed_args); CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(), true); if (npassed_args >= 1) rewrite_args.arg1 = std::move(rewriter->getArg(4)); if (npassed_args >= 2) rewrite_args.arg2 = std::move(rewriter->getArg(5)); if (npassed_args >= 3) rewrite_args.arg3 = std::move(rewriter->getArg(6)); if (npassed_args >= 4) rewrite_args.args = std::move(rewriter->getArg(7)); rtn = callattrInternal(obj, attr, scope, &rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else if (rtn) { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } } else { rtn = callattrInternal(obj, attr, scope, NULL, argspec, arg1, arg2, arg3, args, keyword_names); } if (rtn == NULL) { raiseAttributeError(obj, attr->c_str()); } return rtn; } static inline Box*& getArg(int idx, Box*& arg1, Box*& arg2, Box*& arg3, Box** args) { if (idx == 0) return arg1; if (idx == 1) return arg2; if (idx == 2) return arg3; return args[idx - 3]; } static CompiledFunction* pickVersion(CLFunction* f, int num_output_args, Box* oarg1, Box* oarg2, Box* oarg3, Box** oargs) { LOCK_REGION(codegen_rwlock.asWrite()); CompiledFunction* chosen_cf = NULL; for (CompiledFunction* cf : f->versions) { assert(cf->spec->arg_types.size() == num_output_args); if (cf->spec->rtn_type->llvmType() != UNKNOWN->llvmType()) continue; bool works = true; for (int i = 0; i < num_output_args; i++) { Box* arg = getArg(i, oarg1, oarg2, oarg3, oargs); ConcreteCompilerType* t = cf->spec->arg_types[i]; if ((arg && !t->isFitBy(arg->cls)) || (!arg && t != UNKNOWN)) { works = false; break; } } if (!works) continue; chosen_cf = cf; break; } if (chosen_cf == NULL) { if (f->source == NULL) { // TODO I don't think this should be happening any more? printf("Error: couldn't find suitable function version and no source to recompile!\n"); abort(); } std::vector<ConcreteCompilerType*> arg_types; for (int i = 0; i < num_output_args; i++) { Box* arg = getArg(i, oarg1, oarg2, oarg3, oargs); assert(arg); // only builtin functions can pass NULL args arg_types.push_back(typeFromClass(arg->cls)); } FunctionSpecialization* spec = new FunctionSpecialization(UNKNOWN, arg_types); EffortLevel::EffortLevel new_effort = initialEffort(); // this also pushes the new CompiledVersion to the back of the version list: chosen_cf = compileFunction(f, spec, new_effort, NULL); } return chosen_cf; } static void placeKeyword(const std::vector<AST_expr*>& arg_names, std::vector<bool>& params_filled, const std::string& kw_name, Box* kw_val, Box*& oarg1, Box*& oarg2, Box*& oarg3, Box** oargs, BoxedDict* okwargs) { assert(kw_val); bool found = false; for (int j = 0; j < arg_names.size(); j++) { AST_expr* e = arg_names[j]; if (e->type != AST_TYPE::Name) continue; AST_Name* n = ast_cast<AST_Name>(e); if (n->id == kw_name) { if (params_filled[j]) { raiseExcHelper(TypeError, "<function>() got multiple values for keyword argument '%s'", kw_name.c_str()); } getArg(j, oarg1, oarg2, oarg3, oargs) = kw_val; params_filled[j] = true; found = true; break; } } if (!found) { if (okwargs) { Box*& v = okwargs->d[boxString(kw_name)]; if (v) { raiseExcHelper(TypeError, "<function>() got multiple values for keyword argument '%s'", kw_name.c_str()); } v = kw_val; } else { raiseExcHelper(TypeError, "<function>() got an unexpected keyword argument '%s'", kw_name.c_str()); } } } Box* callFunc(BoxedFunction* func, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { /* * Procedure: * - First match up positional arguments; any extra go to varargs. error if too many. * - Then apply keywords; any extra go to kwargs. error if too many. * - Use defaults to fill in any missing * - error about missing parameters */ static StatCounter slowpath_resolveclfunc("slowpath_callfunc"); slowpath_resolveclfunc.log(); CLFunction* f = func->f; FunctionList& versions = f->versions; int num_output_args = f->numReceivedArgs(); int num_passed_args = argspec.totalPassed(); BoxedClosure* closure = func->closure; if (argspec.has_starargs || argspec.has_kwargs || f->takes_kwargs || func->isGenerator) { rewrite_args = NULL; } // These could be handled: if (argspec.num_keywords) { rewrite_args = NULL; } // TODO Should we guard on the CLFunction or the BoxedFunction? // A single CLFunction could end up forming multiple BoxedFunctions, and we // could emit assembly that handles any of them. But doing this involves some // extra indirection, and it's not clear if that's worth it, since it seems like // the common case will be functions only ever getting a single set of default arguments. bool guard_clfunc = false; assert(!guard_clfunc && "I think there are users that expect the boxedfunction to be guarded"); if (rewrite_args) { assert(rewrite_args->args_guarded && "need to guard args here"); if (!rewrite_args->func_guarded) { if (guard_clfunc) { rewrite_args->obj.addAttrGuard(offsetof(BoxedFunction, f), (intptr_t)f); } else { rewrite_args->obj.addGuard((intptr_t)func); rewrite_args->obj.setDoneUsing(); } } else { rewrite_args->obj.setDoneUsing(); } if (rewrite_args->call_done_guarding) rewrite_args->rewriter->setDoneGuarding(); assert(rewrite_args->rewriter->isDoneGuarding()); // if (guard_clfunc) { // Have to save the defaults array since the object itself will probably get overwritten: // rewrite_args->obj = rewrite_args->obj.move(-2); // r_defaults_array = rewrite_args->obj.getAttr(offsetof(BoxedFunction, defaults), -2); //} } if (rewrite_args) { // We might have trouble if we have more output args than input args, // such as if we need more space to pass defaults. if (num_output_args > 3 && num_output_args > argspec.totalPassed()) { int arg_bytes_required = (num_output_args - 3) * sizeof(Box*); RewriterVarUsage new_args(RewriterVarUsage::empty()); if (rewrite_args->args.isDoneUsing()) { // rewrite_args->args could be empty if there are not more than // 3 input args. new_args = rewrite_args->rewriter->allocate(num_output_args - 3); } else { new_args = rewrite_args->rewriter->allocateAndCopy(std::move(rewrite_args->args), num_output_args - 3); } rewrite_args->args = std::move(new_args); } } std::vector<Box*> varargs; if (argspec.has_starargs) { Box* given_varargs = getArg(argspec.num_args + argspec.num_keywords, arg1, arg2, arg3, args); for (Box* e : given_varargs->pyElements()) { varargs.push_back(e); } } // The "output" args that we will pass to the called function: Box* oarg1 = NULL, * oarg2 = NULL, * oarg3 = NULL; Box** oargs = NULL; if (num_output_args > 3) { int size = (num_output_args - 3) * sizeof(Box*); oargs = (Box**)alloca(size); #ifndef NDEBUG memset(&oargs[0], 0, size); #endif } //// // First, match up positional parameters to positional/varargs: int positional_to_positional = std::min((int)argspec.num_args, f->num_args); for (int i = 0; i < positional_to_positional; i++) { getArg(i, oarg1, oarg2, oarg3, oargs) = getArg(i, arg1, arg2, arg3, args); // we already moved the positional args into position } int varargs_to_positional = std::min((int)varargs.size(), f->num_args - positional_to_positional); for (int i = 0; i < varargs_to_positional; i++) { assert(!rewrite_args && "would need to be handled here"); getArg(i + positional_to_positional, oarg1, oarg2, oarg3, oargs) = varargs[i]; } std::vector<bool> params_filled(num_output_args, false); for (int i = 0; i < positional_to_positional + varargs_to_positional; i++) { params_filled[i] = true; } std::vector<Box*, StlCompatAllocator<Box*> > unused_positional; for (int i = positional_to_positional; i < argspec.num_args; i++) { rewrite_args = NULL; unused_positional.push_back(getArg(i, arg1, arg2, arg3, args)); } for (int i = varargs_to_positional; i < varargs.size(); i++) { rewrite_args = NULL; unused_positional.push_back(varargs[i]); } if (f->takes_varargs) { int varargs_idx = f->num_args; if (rewrite_args) { assert(!unused_positional.size()); // rewrite_args->rewriter->loadConst((intptr_t)EmptyTuple, Location::forArg(varargs_idx)); RewriterVarUsage emptyTupleConst = rewrite_args->rewriter->loadConst( (intptr_t)EmptyTuple, varargs_idx < 3 ? Location::forArg(varargs_idx) : Location::any()); if (varargs_idx == 0) rewrite_args->arg1 = std::move(emptyTupleConst); if (varargs_idx == 1) rewrite_args->arg2 = std::move(emptyTupleConst); if (varargs_idx == 2) rewrite_args->arg3 = std::move(emptyTupleConst); if (varargs_idx >= 3) rewrite_args->args.setAttr((varargs_idx - 3) * sizeof(Box*), std::move(emptyTupleConst)); } Box* ovarargs = new BoxedTuple(std::move(unused_positional)); getArg(varargs_idx, oarg1, oarg2, oarg3, oargs) = ovarargs; } else if (unused_positional.size()) { raiseExcHelper(TypeError, "<function>() takes at most %d argument%s (%d given)", f->num_args, (f->num_args == 1 ? "" : "s"), argspec.num_args + argspec.num_keywords + varargs.size()); } //// // Second, apply any keywords: BoxedDict* okwargs = NULL; if (f->takes_kwargs) { assert(!rewrite_args && "would need to be handled here"); okwargs = new BoxedDict(); getArg(f->num_args + (f->takes_varargs ? 1 : 0), oarg1, oarg2, oarg3, oargs) = okwargs; } const std::vector<AST_expr*>* arg_names = f->source ? f->source->arg_names.args : NULL; if (arg_names == nullptr && argspec.num_keywords && !f->takes_kwargs) { raiseExcHelper(TypeError, "<function @%p>() doesn't take keyword arguments", f->versions[0]->code); } if (argspec.num_keywords) assert(argspec.num_keywords == keyword_names->size()); for (int i = 0; i < argspec.num_keywords; i++) { assert(!rewrite_args && "would need to be handled here"); int arg_idx = i + argspec.num_args; Box* kw_val = getArg(arg_idx, arg1, arg2, arg3, args); if (!arg_names) { assert(okwargs); okwargs->d[boxStringPtr((*keyword_names)[i])] = kw_val; continue; } assert(arg_names); placeKeyword(*arg_names, params_filled, *(*keyword_names)[i], kw_val, oarg1, oarg2, oarg3, oargs, okwargs); } if (argspec.has_kwargs) { assert(!rewrite_args && "would need to be handled here"); Box* kwargs = getArg(argspec.num_args + argspec.num_keywords + (argspec.has_starargs ? 1 : 0), arg1, arg2, arg3, args); RELEASE_ASSERT(kwargs->cls == dict_cls, "haven't implemented this for non-dicts"); BoxedDict* d_kwargs = static_cast<BoxedDict*>(kwargs); for (auto& p : d_kwargs->d) { if (p.first->cls != str_cls) raiseExcHelper(TypeError, "<function>() keywords must be strings"); BoxedString* s = static_cast<BoxedString*>(p.first); if (arg_names) { placeKeyword(*arg_names, params_filled, s->s, p.second, oarg1, oarg2, oarg3, oargs, okwargs); } else { assert(okwargs); Box*& v = okwargs->d[p.first]; if (v) { raiseExcHelper(TypeError, "<function>() got multiple values for keyword argument '%s'", s->s.c_str()); } v = p.second; } } } // Fill with defaults: for (int i = 0; i < f->num_args - f->num_defaults; i++) { if (params_filled[i]) continue; // TODO not right error message raiseExcHelper(TypeError, "<function>() did not get a value for positional argument %d", i); } RewriterVarUsage r_defaults_array(RewriterVarUsage::empty()); if (guard_clfunc) { r_defaults_array = rewrite_args->obj.getAttr(offsetof(BoxedFunction, defaults), RewriterVarUsage::KillFlag::Kill, Location::any()); } for (int i = f->num_args - f->num_defaults; i < f->num_args; i++) { if (params_filled[i]) continue; int default_idx = i + f->num_defaults - f->num_args; Box* default_obj = func->defaults->elts[default_idx]; if (rewrite_args) { int offset = offsetof(std::remove_pointer<decltype(BoxedFunction::defaults)>::type, elts) + sizeof(Box*) * default_idx; if (guard_clfunc) { // If we just guarded on the CLFunction, then we have to emit assembly // to fetch the values from the defaults array: if (i < 3) { RewriterVarUsage r_default = r_defaults_array.getAttr(offset, RewriterVarUsage::KillFlag::NoKill, Location::forArg(i)); if (i == 0) rewrite_args->arg1 = std::move(r_default); if (i == 1) rewrite_args->arg2 = std::move(r_default); if (i == 2) rewrite_args->arg3 = std::move(r_default); } else { RewriterVarUsage r_default = r_defaults_array.getAttr(offset, RewriterVarUsage::KillFlag::Kill, Location::any()); rewrite_args->args.setAttr((i - 3) * sizeof(Box*), std::move(r_default)); } } else { // If we guarded on the BoxedFunction, which has a constant set of defaults, // we can embed the default arguments directly into the instructions. if (i < 3) { RewriterVarUsage r_default = rewrite_args->rewriter->loadConst((intptr_t)default_obj, Location::any()); if (i == 0) rewrite_args->arg1 = std::move(r_default); if (i == 1) rewrite_args->arg2 = std::move(r_default); if (i == 2) rewrite_args->arg3 = std::move(r_default); } else { RewriterVarUsage r_default = rewrite_args->rewriter->loadConst((intptr_t)default_obj, Location::any()); rewrite_args->args.setAttr((i - 3) * sizeof(Box*), std::move(r_default)); } } } getArg(i, oarg1, oarg2, oarg3, oargs) = default_obj; } // special handling for generators: // the call to function containing a yield should just create a new generator object. Box* res; if (func->isGenerator) { res = createGenerator(func, oarg1, oarg2, oarg3, oargs); } else { res = callCLFunc(f, rewrite_args, num_output_args, closure, NULL, oarg1, oarg2, oarg3, oargs); } return res; } Box* callCLFunc(CLFunction* f, CallRewriteArgs* rewrite_args, int num_output_args, BoxedClosure* closure, BoxedGenerator* generator, Box* oarg1, Box* oarg2, Box* oarg3, Box** oargs) { CompiledFunction* chosen_cf = pickVersion(f, num_output_args, oarg1, oarg2, oarg3, oargs); assert(chosen_cf->is_interpreted == (chosen_cf->code == NULL)); if (chosen_cf->is_interpreted) { return interpretFunction(chosen_cf->func, num_output_args, closure, generator, oarg1, oarg2, oarg3, oargs); } if (rewrite_args) { rewrite_args->rewriter->addDependenceOn(chosen_cf->dependent_callsites); std::vector<RewriterVarUsage> arg_vec; // TODO this kind of embedded reference needs to be tracked by the GC somehow? // Or maybe it's ok, since we've guarded on the function object? if (closure) arg_vec.push_back(std::move(rewrite_args->rewriter->loadConst((intptr_t)closure, Location::forArg(0)))); if (num_output_args >= 1) arg_vec.push_back(std::move(rewrite_args->arg1)); if (num_output_args >= 2) arg_vec.push_back(std::move(rewrite_args->arg2)); if (num_output_args >= 3) arg_vec.push_back(std::move(rewrite_args->arg3)); if (num_output_args >= 4) arg_vec.push_back(std::move(rewrite_args->args)); rewrite_args->out_rtn = rewrite_args->rewriter->call(true, (void*)chosen_cf->call, std::move(arg_vec)); rewrite_args->out_success = true; } if (closure && generator) return chosen_cf->closure_generator_call(closure, generator, oarg1, oarg2, oarg3, oargs); else if (closure) return chosen_cf->closure_call(closure, oarg1, oarg2, oarg3, oargs); else if (generator) return chosen_cf->generator_call(generator, oarg1, oarg2, oarg3, oargs); else return chosen_cf->call(oarg1, oarg2, oarg3, oargs); } Box* runtimeCallInternal(Box* obj, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { int npassed_args = argspec.totalPassed(); if (obj->cls != function_cls && obj->cls != instancemethod_cls) { Box* rtn; if (rewrite_args) { // TODO is this ok? // rewrite_args->rewriter->trap(); rtn = callattrInternal(obj, &_call_str, CLASS_ONLY, rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); } else { rtn = callattrInternal(obj, &_call_str, CLASS_ONLY, NULL, argspec, arg1, arg2, arg3, args, keyword_names); } if (!rtn) raiseExcHelper(TypeError, "'%s' object is not callable", getTypeName(obj)->c_str()); return rtn; } if (rewrite_args) { if (!rewrite_args->args_guarded) { // TODO should know which args don't need to be guarded, ex if we're guaranteed that they // already fit, either since the type inferencer could determine that, // or because they only need to fit into an UNKNOWN slot. if (npassed_args >= 1) rewrite_args->arg1.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg1->cls); if (npassed_args >= 2) rewrite_args->arg2.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg2->cls); if (npassed_args >= 3) rewrite_args->arg3.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)arg3->cls); for (int i = 3; i < npassed_args; i++) { RewriterVarUsage v = rewrite_args->args.getAttr((i - 3) * sizeof(Box*), RewriterVarUsage::KillFlag::NoKill, Location::any()); v.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)args[i - 3]->cls); v.setDoneUsing(); } rewrite_args->args_guarded = true; } rewrite_args->rewriter->addDecision(obj->cls == function_cls ? 1 : 0); } if (obj->cls == function_cls) { BoxedFunction* f = static_cast<BoxedFunction*>(obj); // Some functions are sufficiently important that we want them to be able to patchpoint themselves; // they can do this by setting the "internal_callable" field: CLFunction::InternalCallable callable = f->f->internal_callable; if (callable == NULL) { callable = callFunc; } Box* res = callable(f, rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); return res; } else if (obj->cls == instancemethod_cls) { // TODO it's dumb but I should implement patchpoints here as well // duplicated with callattr BoxedInstanceMethod* im = static_cast<BoxedInstanceMethod*>(obj); if (rewrite_args && !rewrite_args->func_guarded) { rewrite_args->obj.addAttrGuard(INSTANCEMETHOD_FUNC_OFFSET, (intptr_t)im->func); } // Guard on which type of instancemethod (bound or unbound) // That is, if im->obj is NULL, guard on it being NULL // otherwise, guard on it being non-NULL if (rewrite_args) { rewrite_args->obj.addAttrGuard(INSTANCEMETHOD_OBJ_OFFSET, 0, im->obj != NULL); } // TODO guard on im->obj being NULL or not if (im->obj == NULL) { Box* f = im->func; if (rewrite_args) { rewrite_args->func_guarded = true; rewrite_args->args_guarded = true; rewrite_args->obj = rewrite_args->obj.getAttr(INSTANCEMETHOD_FUNC_OFFSET, RewriterVarUsage::Kill, Location::any()); } Box* res = runtimeCallInternal(f, rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); return res; } if (npassed_args <= 2) { Box* rtn; if (rewrite_args) { // Kind of weird that we don't need to give this a valid RewriterVar, but it shouldn't need to access it // (since we've already guarded on the function). // rewriter enforce that we give it one, though CallRewriteArgs srewrite_args(rewrite_args->rewriter, rewrite_args->obj.addUse(), rewrite_args->destination, rewrite_args->call_done_guarding); srewrite_args.arg1 = rewrite_args->obj.getAttr(INSTANCEMETHOD_OBJ_OFFSET, RewriterVarUsage::KillFlag::Kill, Location::any()); srewrite_args.func_guarded = true; srewrite_args.args_guarded = true; if (npassed_args >= 1) srewrite_args.arg2 = std::move(rewrite_args->arg1); if (npassed_args >= 2) srewrite_args.arg3 = std::move(rewrite_args->arg2); rtn = runtimeCallInternal( im->func, &srewrite_args, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), im->obj, arg1, arg2, NULL, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); } } else { rtn = runtimeCallInternal(im->func, NULL, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), im->obj, arg1, arg2, NULL, keyword_names); } if (rewrite_args) rewrite_args->out_success = true; return rtn; } else { Box** new_args = (Box**)alloca(sizeof(Box*) * (npassed_args + 1 - 3)); new_args[0] = arg3; memcpy(new_args + 1, args, (npassed_args - 3) * sizeof(Box*)); Box* rtn = runtimeCall(im->func, ArgPassSpec(argspec.num_args + 1, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs), im->obj, arg1, arg2, new_args, keyword_names); return rtn; } } assert(0); abort(); } extern "C" Box* runtimeCall(Box* obj, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { int npassed_args = argspec.totalPassed(); static StatCounter slowpath_runtimecall("slowpath_runtimecall"); slowpath_runtimecall.log(); int num_orig_args = 2 + std::min(4, npassed_args); if (argspec.num_keywords > 0) { assert(argspec.num_keywords == keyword_names->size()); num_orig_args++; } std::unique_ptr<Rewriter> rewriter(Rewriter::createRewriter( __builtin_extract_return_addr(__builtin_return_address(0)), num_orig_args, "runtimeCall")); Box* rtn; if (rewriter.get()) { // TODO feel weird about doing this; it either isn't necessary // or this kind of thing is necessary in a lot more places // rewriter->getArg(1).addGuard(npassed_args); CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(), true); if (npassed_args >= 1) rewrite_args.arg1 = std::move(rewriter->getArg(2)); if (npassed_args >= 2) rewrite_args.arg2 = std::move(rewriter->getArg(3)); if (npassed_args >= 3) rewrite_args.arg3 = std::move(rewriter->getArg(4)); if (npassed_args >= 4) rewrite_args.args = std::move(rewriter->getArg(5)); rtn = runtimeCallInternal(obj, &rewrite_args, argspec, arg1, arg2, arg3, args, keyword_names); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else if (rtn) { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } } else { rtn = runtimeCallInternal(obj, NULL, argspec, arg1, arg2, arg3, args, keyword_names); } assert(rtn); return rtn; } extern "C" Box* binopInternal(Box* lhs, Box* rhs, int op_type, bool inplace, BinopRewriteArgs* rewrite_args) { // TODO handle the case of the rhs being a subclass of the lhs // this could get really annoying because you can dynamically make one type a subclass // of the other! if (rewrite_args) { // TODO probably don't need to guard on the lhs_cls since it // will get checked no matter what, but the check that should be // removed is probably the later one. // ie we should have some way of specifying what we know about the values // of objects and their attributes, and the attributes' attributes. rewrite_args->lhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)lhs->cls); rewrite_args->rhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)rhs->cls); } Box* irtn = NULL; if (inplace) { std::string iop_name = getInplaceOpName(op_type); if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, rewrite_args->lhs.addUse(), rewrite_args->destination, rewrite_args->call_done_guarding); srewrite_args.arg1 = rewrite_args->rhs.addUse(); srewrite_args.args_guarded = true; irtn = callattrInternal1(lhs, &iop_name, CLASS_ONLY, &srewrite_args, ArgPassSpec(1), rhs); if (!srewrite_args.out_success) { rewrite_args = NULL; } else if (irtn) { if (irtn == NotImplemented) srewrite_args.out_rtn.ensureDoneUsing(); else rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); } } else { irtn = callattrInternal1(lhs, &iop_name, CLASS_ONLY, NULL, ArgPassSpec(1), rhs); } if (irtn) { if (irtn != NotImplemented) { if (rewrite_args) { rewrite_args->lhs.setDoneUsing(); rewrite_args->rhs.setDoneUsing(); rewrite_args->out_success = true; } return irtn; } } } const std::string& op_name = getOpName(op_type); Box* lrtn; if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(rewrite_args->lhs), rewrite_args->destination, rewrite_args->call_done_guarding); srewrite_args.arg1 = std::move(rewrite_args->rhs); lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, &srewrite_args, ArgPassSpec(1), rhs); if (!srewrite_args.out_success) rewrite_args = NULL; else if (lrtn) { if (lrtn == NotImplemented) srewrite_args.out_rtn.ensureDoneUsing(); else rewrite_args->out_rtn = std::move(srewrite_args.out_rtn); } } else { lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, NULL, ArgPassSpec(1), rhs); } if (lrtn) { if (lrtn != NotImplemented) { if (rewrite_args) { rewrite_args->out_success = true; } return lrtn; } } // TODO patch these cases if (rewrite_args) { assert(rewrite_args->out_success == false); rewrite_args = NULL; } std::string rop_name = getReverseOpName(op_type); Box* rrtn = callattrInternal1(rhs, &rop_name, CLASS_ONLY, NULL, ArgPassSpec(1), lhs); if (rrtn != NULL && rrtn != NotImplemented) return rrtn; llvm::StringRef op_sym = getOpSymbol(op_type); const char* op_sym_suffix = ""; if (inplace) { op_sym_suffix = "="; } if (VERBOSITY()) { if (inplace) { std::string iop_name = getInplaceOpName(op_type); if (irtn) fprintf(stderr, "%s has %s, but returned NotImplemented\n", getTypeName(lhs)->c_str(), iop_name.c_str()); else fprintf(stderr, "%s does not have %s\n", getTypeName(lhs)->c_str(), iop_name.c_str()); } if (lrtn) fprintf(stderr, "%s has %s, but returned NotImplemented\n", getTypeName(lhs)->c_str(), op_name.c_str()); else fprintf(stderr, "%s does not have %s\n", getTypeName(lhs)->c_str(), op_name.c_str()); if (rrtn) fprintf(stderr, "%s has %s, but returned NotImplemented\n", getTypeName(rhs)->c_str(), rop_name.c_str()); else fprintf(stderr, "%s does not have %s\n", getTypeName(rhs)->c_str(), rop_name.c_str()); } raiseExcHelper(TypeError, "unsupported operand type(s) for %s%s: '%s' and '%s'", op_sym.data(), op_sym_suffix, getTypeName(lhs)->c_str(), getTypeName(rhs)->c_str()); } extern "C" Box* binop(Box* lhs, Box* rhs, int op_type) { static StatCounter slowpath_binop("slowpath_binop"); slowpath_binop.log(); // static StatCounter nopatch_binop("nopatch_binop"); // int id = Stats::getStatId("slowpath_binop_" + *getTypeName(lhs) + op_name + *getTypeName(rhs)); // Stats::log(id); std::unique_ptr<Rewriter> rewriter((Rewriter*)NULL); // Currently can't patchpoint user-defined binops since we can't assume that just because // resolving it one way right now (ex, using the value from lhs.__add__) means that later // we'll resolve it the same way, even for the same argument types. // TODO implement full resolving semantics inside the rewrite? bool can_patchpoint = !isUserDefined(lhs->cls) && !isUserDefined(rhs->cls); if (can_patchpoint) rewriter.reset( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "binop")); Box* rtn; if (rewriter.get()) { // rewriter->trap(); BinopRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getArg(1), rewriter->getReturnDestination(), true); rtn = binopInternal(lhs, rhs, op_type, false, &rewrite_args); assert(rtn); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } else { rtn = binopInternal(lhs, rhs, op_type, false, NULL); } return rtn; } extern "C" Box* augbinop(Box* lhs, Box* rhs, int op_type) { static StatCounter slowpath_binop("slowpath_binop"); slowpath_binop.log(); // static StatCounter nopatch_binop("nopatch_binop"); // int id = Stats::getStatId("slowpath_binop_" + *getTypeName(lhs) + op_name + *getTypeName(rhs)); // Stats::log(id); std::unique_ptr<Rewriter> rewriter((Rewriter*)NULL); // Currently can't patchpoint user-defined binops since we can't assume that just because // resolving it one way right now (ex, using the value from lhs.__add__) means that later // we'll resolve it the same way, even for the same argument types. // TODO implement full resolving semantics inside the rewrite? bool can_patchpoint = !isUserDefined(lhs->cls) && !isUserDefined(rhs->cls); if (can_patchpoint) rewriter.reset( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "binop")); Box* rtn; if (rewriter.get()) { BinopRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getArg(1), rewriter->getReturnDestination(), true); rtn = binopInternal(lhs, rhs, op_type, true, &rewrite_args); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } } else { rtn = binopInternal(lhs, rhs, op_type, true, NULL); } return rtn; } Box* compareInternal(Box* lhs, Box* rhs, int op_type, CompareRewriteArgs* rewrite_args) { if (op_type == AST_TYPE::Is || op_type == AST_TYPE::IsNot) { bool neg = (op_type == AST_TYPE::IsNot); if (rewrite_args) { rewrite_args->rewriter->setDoneGuarding(); RewriterVarUsage cmpres = rewrite_args->lhs.cmp(neg ? AST_TYPE::NotEq : AST_TYPE::Eq, std::move(rewrite_args->rhs), rewrite_args->destination); rewrite_args->lhs.setDoneUsing(); rewrite_args->out_rtn = rewrite_args->rewriter->call(false, (void*)boxBool, std::move(cmpres)); rewrite_args->out_success = true; } return boxBool((lhs == rhs) ^ neg); } if (op_type == AST_TYPE::In || op_type == AST_TYPE::NotIn) { // TODO do rewrite static const std::string str_contains("__contains__"); Box* contained = callattrInternal1(rhs, &str_contains, CLASS_ONLY, NULL, ArgPassSpec(1), lhs); if (contained == NULL) { static const std::string str_iter("__iter__"); Box* iter = callattrInternal0(rhs, &str_iter, CLASS_ONLY, NULL, ArgPassSpec(0)); if (iter) ASSERT(isUserDefined(rhs->cls), "%s should probably have a __contains__", getTypeName(rhs)->c_str()); RELEASE_ASSERT(iter == NULL, "need to try iterating"); Box* getitem = typeLookup(rhs->cls, "__getitem__", NULL); if (getitem) ASSERT(isUserDefined(rhs->cls), "%s should probably have a __contains__", getTypeName(rhs)->c_str()); RELEASE_ASSERT(getitem == NULL, "need to try old iteration protocol"); raiseExcHelper(TypeError, "argument of type '%s' is not iterable", getTypeName(rhs)->c_str()); } bool b = nonzero(contained); if (op_type == AST_TYPE::NotIn) return boxBool(!b); return boxBool(b); } // Can do the guard checks after the Is/IsNot handling, since that is // irrespective of the object classes if (rewrite_args) { // TODO probably don't need to guard on the lhs_cls since it // will get checked no matter what, but the check that should be // removed is probably the later one. // ie we should have some way of specifying what we know about the values // of objects and their attributes, and the attributes' attributes. rewrite_args->lhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)lhs->cls); rewrite_args->rhs.addAttrGuard(BOX_CLS_OFFSET, (intptr_t)rhs->cls); } const std::string& op_name = getOpName(op_type); Box* lrtn; if (rewrite_args) { CallRewriteArgs crewrite_args(rewrite_args->rewriter, std::move(rewrite_args->lhs), rewrite_args->destination, rewrite_args->call_done_guarding); crewrite_args.arg1 = std::move(rewrite_args->rhs); lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, &crewrite_args, ArgPassSpec(1), rhs); if (!crewrite_args.out_success) rewrite_args = NULL; else if (lrtn) rewrite_args->out_rtn = std::move(crewrite_args.out_rtn); } else { lrtn = callattrInternal1(lhs, &op_name, CLASS_ONLY, NULL, ArgPassSpec(1), rhs); } if (lrtn) { if (lrtn != NotImplemented) { bool can_patchpoint = !isUserDefined(lhs->cls) && !isUserDefined(rhs->cls); if (rewrite_args) { if (can_patchpoint) { rewrite_args->out_success = true; } else { rewrite_args->out_rtn.ensureDoneUsing(); } } return lrtn; } } // TODO patch these cases if (rewrite_args) { rewrite_args->out_rtn.ensureDoneUsing(); assert(rewrite_args->out_success == false); rewrite_args = NULL; } std::string rop_name = getReverseOpName(op_type); Box* rrtn = callattrInternal1(rhs, &rop_name, CLASS_ONLY, NULL, ArgPassSpec(1), lhs); if (rrtn != NULL && rrtn != NotImplemented) return rrtn; if (op_type == AST_TYPE::Eq) return boxBool(lhs == rhs); if (op_type == AST_TYPE::NotEq) return boxBool(lhs != rhs); #ifndef NDEBUG if ((lhs->cls == int_cls || lhs->cls == float_cls || lhs->cls == long_cls) && (rhs->cls == int_cls || rhs->cls == float_cls || rhs->cls == long_cls)) { Py_FatalError("missing comparison between these classes"); } #endif // TODO // According to http://docs.python.org/2/library/stdtypes.html#comparisons // CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects // of the same types that don’t support proper comparison are ordered by their address. if (op_type == AST_TYPE::Gt || op_type == AST_TYPE::GtE || op_type == AST_TYPE::Lt || op_type == AST_TYPE::LtE) { intptr_t cmp1, cmp2; if (lhs->cls == rhs->cls) { cmp1 = (intptr_t)lhs; cmp2 = (intptr_t)rhs; } else { // This isn't really necessary, but try to make sure that numbers get sorted first if (lhs->cls == int_cls || lhs->cls == float_cls) cmp1 = 0; else cmp1 = (intptr_t)lhs->cls; if (rhs->cls == int_cls || rhs->cls == float_cls) cmp2 = 0; else cmp2 = (intptr_t)rhs->cls; } if (op_type == AST_TYPE::Gt) return boxBool(cmp1 > cmp2); if (op_type == AST_TYPE::GtE) return boxBool(cmp1 >= cmp2); if (op_type == AST_TYPE::Lt) return boxBool(cmp1 < cmp2); if (op_type == AST_TYPE::LtE) return boxBool(cmp1 <= cmp2); } RELEASE_ASSERT(0, "%d", op_type); } extern "C" Box* compare(Box* lhs, Box* rhs, int op_type) { static StatCounter slowpath_compare("slowpath_compare"); slowpath_compare.log(); static StatCounter nopatch_compare("nopatch_compare"); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "compare")); Box* rtn; if (rewriter.get()) { // rewriter->trap(); CompareRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), std::move(rewriter->getArg(1)), rewriter->getReturnDestination(), true); rtn = compareInternal(lhs, rhs, op_type, &rewrite_args); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } else { rtn = compareInternal(lhs, rhs, op_type, NULL); } return rtn; } extern "C" Box* unaryop(Box* operand, int op_type) { static StatCounter slowpath_unaryop("slowpath_unaryop"); slowpath_unaryop.log(); const std::string& op_name = getOpName(op_type); Box* attr_func = getclsattr_internal(operand, op_name, NULL); ASSERT(attr_func, "%s.%s", getTypeName(operand)->c_str(), op_name.c_str()); Box* rtn = runtimeCall0(attr_func, ArgPassSpec(0)); return rtn; } extern "C" Box* getitem(Box* value, Box* slice) { // This possibly could just be represented as a single callattr; the only tricky part // are the error messages. // Ex "(1)[1]" and "(1).__getitem__(1)" give different error messages. static StatCounter slowpath_getitem("slowpath_getitem"); slowpath_getitem.log(); static std::string str_getitem("__getitem__"); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "getitem")); Box* rtn; if (rewriter.get()) { CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(), true); rewrite_args.arg1 = std::move(rewriter->getArg(1)); rtn = callattrInternal1(value, &str_getitem, CLASS_ONLY, &rewrite_args, ArgPassSpec(1), slice); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else if (rtn) rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } else { rtn = callattrInternal1(value, &str_getitem, CLASS_ONLY, NULL, ArgPassSpec(1), slice); } if (rtn == NULL) { // different versions of python give different error messages for this: if (PYTHON_VERSION_MAJOR == 2 && PYTHON_VERSION_MINOR < 7) { raiseExcHelper(TypeError, "'%s' object is unsubscriptable", getTypeName(value)->c_str()); // tested on 2.6.6 } else if (PYTHON_VERSION_MAJOR == 2 && PYTHON_VERSION_MINOR == 7 && PYTHON_VERSION_MICRO < 3) { raiseExcHelper(TypeError, "'%s' object is not subscriptable", getTypeName(value)->c_str()); // tested on 2.7.1 } else { // Changed to this in 2.7.3: raiseExcHelper(TypeError, "'%s' object has no attribute '__getitem__'", getTypeName(value)->c_str()); // tested on 2.7.3 } } return rtn; } // target[slice] = value extern "C" void setitem(Box* target, Box* slice, Box* value) { static StatCounter slowpath_setitem("slowpath_setitem"); slowpath_setitem.log(); static std::string str_setitem("__setitem__"); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "setitem")); Box* rtn; if (rewriter.get()) { CallRewriteArgs rewrite_args(rewriter.get(), std::move(rewriter->getArg(0)), rewriter->getReturnDestination(), true); rewrite_args.arg1 = std::move(rewriter->getArg(1)); rewrite_args.arg2 = std::move(rewriter->getArg(2)); rtn = callattrInternal2(target, &str_setitem, CLASS_ONLY, &rewrite_args, ArgPassSpec(2), slice, value); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else if (rtn) rewrite_args.out_rtn.setDoneUsing(); } else { rtn = callattrInternal2(target, &str_setitem, CLASS_ONLY, NULL, ArgPassSpec(2), slice, value); } if (rtn == NULL) { raiseExcHelper(TypeError, "'%s' object does not support item assignment", getTypeName(target)->c_str()); } if (rewriter.get()) { rewriter->commit(); } } // del target[start:end:step] extern "C" void delitem(Box* target, Box* slice) { static StatCounter slowpath_delitem("slowpath_delitem"); slowpath_delitem.log(); static std::string str_delitem("__delitem__"); std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 2, "delitem")); Box* rtn; if (rewriter.get()) { CallRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), true); rewrite_args.arg1 = std::move(rewriter->getArg(1)); rtn = callattrInternal1(target, &str_delitem, CLASS_ONLY, &rewrite_args, ArgPassSpec(1), slice); if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } else if (rtn != NULL) { rewrite_args.out_rtn.setDoneUsing(); } } else { rtn = callattrInternal1(target, &str_delitem, CLASS_ONLY, NULL, ArgPassSpec(1), slice); } if (rtn == NULL) { raiseExcHelper(TypeError, "'%s' object does not support item deletion", getTypeName(target)->c_str()); } if (rewriter.get()) { rewriter->commit(); } } void Box::delattr(const std::string& attr, DelattrRewriteArgs* rewrite_args) { // as soon as the hcls changes, the guard on hidden class won't pass. HCAttrs* attrs = getAttrsPtr(); HiddenClass* hcls = attrs->hcls; HiddenClass* new_hcls = hcls->delAttrToMakeHC(attr); // The order of attributes is pertained as delAttrToMakeHC constructs // the new HiddenClass by invoking getOrMakeChild in the prevous order // of remaining attributes int num_attrs = hcls->attr_offsets.size(); int offset = hcls->getOffset(attr); assert(offset >= 0); Box** start = attrs->attr_list->attrs; memmove(start + offset, start + offset + 1, (num_attrs - offset - 1) * sizeof(Box*)); attrs->hcls = new_hcls; // guarantee the size of the attr_list equals the number of attrs int new_size = sizeof(HCAttrs::AttrList) + sizeof(Box*) * (num_attrs - 1); attrs->attr_list = (HCAttrs::AttrList*)gc::gc_realloc(attrs->attr_list, new_size); } extern "C" void delattr_internal(Box* obj, const std::string& attr, bool allow_custom, DelattrRewriteArgs* rewrite_args) { static const std::string delattr_str("__delattr__"); static const std::string delete_str("__delete__"); // custom __delattr__ if (allow_custom) { Box* delAttr = typeLookup(obj->cls, delattr_str, NULL); if (delAttr != NULL) { Box* boxstr = boxString(attr); Box* rtn = runtimeCall2(delAttr, ArgPassSpec(2), obj, boxstr); return; } } // first check whether the deleting attribute is a descriptor Box* clsAttr = typeLookup(obj->cls, attr, NULL); if (clsAttr != NULL) { Box* delAttr = typeLookup(static_cast<BoxedClass*>(clsAttr->cls), delete_str, NULL); if (delAttr != NULL) { Box* boxstr = boxString(attr); Box* rtn = runtimeCall2(delAttr, ArgPassSpec(2), clsAttr, obj); return; } } // check if the attribute is in the instance's __dict__ Box* attrVal = obj->getattr(attr, NULL); if (attrVal != NULL) { obj->delattr(attr, NULL); } else { // the exception cpthon throws is different when the class contains the attribute if (clsAttr != NULL) { raiseExcHelper(AttributeError, "'%s' object attribute '%s' is read-only", getTypeName(obj)->c_str(), attr.c_str()); } else { raiseAttributeError(obj, attr.c_str()); } } } // del target.attr extern "C" void delattr(Box* obj, const char* attr) { static StatCounter slowpath_delattr("slowpath_delattr"); slowpath_delattr.log(); if (obj->cls == type_cls) { BoxedClass* cobj = static_cast<BoxedClass*>(obj); if (!isUserDefined(cobj)) { raiseExcHelper(TypeError, "can't set attributes of built-in/extension type '%s'\n", getNameOfClass(cobj)->c_str()); } } delattr_internal(obj, attr, true, NULL); } extern "C" Box* getiter(Box* o) { // TODO add rewriting to this? probably want to try to avoid this path though static const std::string iter_str("__iter__"); Box* r = callattrInternal0(o, &iter_str, LookupScope::CLASS_ONLY, NULL, ArgPassSpec(0)); if (r) return r; static const std::string getitem_str("__getitem__"); if (typeLookup(o->cls, getitem_str, NULL)) { return new BoxedSeqIter(o); } raiseExcHelper(TypeError, "'%s' object is not iterable", getTypeName(o)->c_str()); } llvm::iterator_range<BoxIterator> Box::pyElements() { Box* iter = getiter(this); assert(iter); return llvm::iterator_range<BoxIterator>(++BoxIterator(iter), BoxIterator(nullptr)); } // For use on __init__ return values static void assertInitNone(Box* obj) { if (obj != None) { raiseExcHelper(TypeError, "__init__() should return None, not '%s'", getTypeName(obj)->c_str()); } } Box* typeNew(Box* _cls, Box* arg1, Box* arg2, Box** _args) { Box* arg3 = _args[0]; if (!isSubclass(_cls->cls, type_cls)) raiseExcHelper(TypeError, "type.__new__(X): X is not a type object (%s)", getTypeName(_cls)->c_str()); BoxedClass* cls = static_cast<BoxedClass*>(_cls); if (!isSubclass(cls, type_cls)) raiseExcHelper(TypeError, "type.__new__(%s): %s is not a subtype of type", getNameOfClass(cls)->c_str(), getNameOfClass(cls)->c_str()); if (arg2 == NULL) { assert(arg3 == NULL); BoxedClass* rtn = arg1->cls; return rtn; } RELEASE_ASSERT(arg3->cls == dict_cls, "%s", getTypeName(arg3)->c_str()); BoxedDict* attr_dict = static_cast<BoxedDict*>(arg3); RELEASE_ASSERT(arg2->cls == tuple_cls, ""); BoxedTuple* bases = static_cast<BoxedTuple*>(arg2); RELEASE_ASSERT(arg1->cls == str_cls, ""); BoxedString* name = static_cast<BoxedString*>(arg1); BoxedClass* base; if (bases->elts.size() == 0) { bases = new BoxedTuple({ object_cls }); } RELEASE_ASSERT(bases->elts.size() == 1, ""); Box* _base = bases->elts[0]; RELEASE_ASSERT(_base->cls == type_cls, ""); base = static_cast<BoxedClass*>(_base); BoxedClass* made; if (base->instancesHaveAttrs()) { made = new BoxedClass(cls, base, NULL, base->attrs_offset, base->tp_basicsize, true); } else { assert(base->tp_basicsize % sizeof(void*) == 0); made = new BoxedClass(cls, base, NULL, base->tp_basicsize, base->tp_basicsize + sizeof(HCAttrs), true); } made->giveAttr("__module__", boxString(getCurrentModule()->name())); made->giveAttr("__doc__", None); for (const auto& p : attr_dict->d) { assert(p.first->cls == str_cls); made->setattr(static_cast<BoxedString*>(p.first)->s, p.second, NULL); } // Note: make sure to do this after assigning the attrs, since it will overwrite any defined __name__ made->setattr("__name__", name, NULL); // TODO this function (typeNew) should probably call PyType_Ready made->tp_new = base->tp_new; made->tp_alloc = reinterpret_cast<decltype(cls->tp_alloc)>(PyType_GenericAlloc); return made; } Box* typeCallInternal(BoxedFunction* f, CallRewriteArgs* rewrite_args, ArgPassSpec argspec, Box* arg1, Box* arg2, Box* arg3, Box** args, const std::vector<const std::string*>* keyword_names) { int npassed_args = argspec.totalPassed(); static StatCounter slowpath_typecall("slowpath_typecall"); slowpath_typecall.log(); // TODO shouldn't have to redo this argument handling here... if (argspec.has_starargs) { rewrite_args = NULL; assert(argspec.num_args == 0); // doesn't need to be true, but assumed here Box* starargs = arg1; assert(starargs->cls == tuple_cls); BoxedTuple* targs = static_cast<BoxedTuple*>(starargs); int n = targs->elts.size(); if (n >= 1) arg1 = targs->elts[0]; if (n >= 2) arg2 = targs->elts[1]; if (n >= 3) arg3 = targs->elts[2]; if (n >= 4) args = &targs->elts[3]; argspec = ArgPassSpec(n); } Box* _cls = arg1; RewriterVarUsage r_ccls(RewriterVarUsage::empty()); RewriterVarUsage r_new(RewriterVarUsage::empty()); RewriterVarUsage r_init(RewriterVarUsage::empty()); Box* new_attr, *init_attr; if (rewrite_args) { assert(!argspec.has_starargs); assert(argspec.num_args > 0); rewrite_args->obj.setDoneUsing(); // rewrite_args->rewriter->annotate(0); // rewrite_args->rewriter->trap(); r_ccls = std::move(rewrite_args->arg1); // This is probably a duplicate, but it's hard to really convince myself of that. // Need to create a clear contract of who guards on what r_ccls.addGuard((intptr_t)arg1); } if (!isSubclass(_cls->cls, type_cls)) { raiseExcHelper(TypeError, "descriptor '__call__' requires a 'type' object but received an '%s'", getTypeName(_cls)->c_str()); } BoxedClass* cls = static_cast<BoxedClass*>(_cls); if (rewrite_args) { GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, r_ccls.addUse(), rewrite_args->destination, false); // TODO: if tp_new != Py_CallPythonNew, call that instead? new_attr = typeLookup(cls, _new_str, &grewrite_args); if (!grewrite_args.out_success) rewrite_args = NULL; else { assert(new_attr); r_new = std::move(grewrite_args.out_rtn); r_new.addGuard((intptr_t)new_attr); } // Special-case functions to allow them to still rewrite: if (new_attr->cls != function_cls) { Box* descr_r = processDescriptorOrNull(new_attr, None, cls); if (descr_r) { new_attr = descr_r; rewrite_args = NULL; } } } else { new_attr = typeLookup(cls, _new_str, NULL); new_attr = processDescriptor(new_attr, None, cls); } assert(new_attr && "This should always resolve"); if (rewrite_args) { GetattrRewriteArgs grewrite_args(rewrite_args->rewriter, r_ccls.addUse(), rewrite_args->destination, false); init_attr = typeLookup(cls, _init_str, &grewrite_args); if (!grewrite_args.out_success) rewrite_args = NULL; else { if (init_attr) { r_init = std::move(grewrite_args.out_rtn); r_init.addGuard((intptr_t)init_attr); } } } else { init_attr = typeLookup(cls, _init_str, NULL); } // The init_attr should always resolve as well, but doesn't yet Box* made; RewriterVarUsage r_made(RewriterVarUsage::empty()); ArgPassSpec new_argspec = argspec; if (npassed_args > 1 && new_attr == typeLookup(object_cls, _new_str, NULL)) { if (init_attr == typeLookup(object_cls, _init_str, NULL)) { raiseExcHelper(TypeError, objectNewParameterTypeErrorMsg()); } else { new_argspec = ArgPassSpec(1); } } if (rewrite_args) { CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_new), rewrite_args->destination, rewrite_args->call_done_guarding); int new_npassed_args = new_argspec.totalPassed(); if (new_npassed_args >= 1) srewrite_args.arg1 = std::move(r_ccls); if (new_npassed_args >= 2) srewrite_args.arg2 = rewrite_args->arg2.addUse(); if (new_npassed_args >= 3) srewrite_args.arg3 = rewrite_args->arg3.addUse(); if (new_npassed_args >= 4) srewrite_args.args = rewrite_args->args.addUse(); srewrite_args.args_guarded = true; srewrite_args.func_guarded = true; made = runtimeCallInternal(new_attr, &srewrite_args, new_argspec, cls, arg2, arg3, args, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { assert(rewrite_args->rewriter->isDoneGuarding()); r_made = std::move(srewrite_args.out_rtn); } } else { made = runtimeCallInternal(new_attr, NULL, new_argspec, cls, arg2, arg3, args, keyword_names); } assert(made); // Special-case (also a special case in CPython): if we just called type.__new__(arg), don't call __init__ if (cls == type_cls && argspec == ArgPassSpec(2)) return made; // If this is true, not supposed to call __init__: RELEASE_ASSERT(made->cls == cls, "allowed but unsupported (%s vs %s)", getNameOfClass(made->cls)->c_str(), getNameOfClass(cls)->c_str()); if (init_attr && init_attr != typeLookup(object_cls, _init_str, NULL)) { // TODO apply the same descriptor special-casing as in callattr? Box* initrtn; // Attempt to rewrite the basic case: if (rewrite_args && init_attr->cls == function_cls) { // Note: this code path includes the descriptor logic CallRewriteArgs srewrite_args(rewrite_args->rewriter, std::move(r_init), rewrite_args->destination, false); if (npassed_args >= 1) srewrite_args.arg1 = r_made.addUse(); if (npassed_args >= 2) srewrite_args.arg2 = std::move(rewrite_args->arg2); if (npassed_args >= 3) srewrite_args.arg3 = std::move(rewrite_args->arg3); if (npassed_args >= 4) srewrite_args.args = std::move(rewrite_args->args); srewrite_args.args_guarded = true; srewrite_args.func_guarded = true; // initrtn = callattrInternal(cls, &_init_str, INST_ONLY, &srewrite_args, argspec, made, arg2, arg3, args, // keyword_names); initrtn = runtimeCallInternal(init_attr, &srewrite_args, argspec, made, arg2, arg3, args, keyword_names); if (!srewrite_args.out_success) { rewrite_args = NULL; } else { rewrite_args->rewriter->call(false, (void*)assertInitNone, std::move(srewrite_args.out_rtn)) .setDoneUsing(); } } else { init_attr = processDescriptor(init_attr, made, cls); ArgPassSpec init_argspec = argspec; init_argspec.num_args--; int passed = init_argspec.totalPassed(); // If we weren't passed the args array, it's not safe to index into it if (passed <= 2) initrtn = runtimeCallInternal(init_attr, NULL, init_argspec, arg2, arg3, NULL, NULL, keyword_names); else initrtn = runtimeCallInternal(init_attr, NULL, init_argspec, arg2, arg3, args[0], &args[1], keyword_names); } assertInitNone(initrtn); } else { if (new_attr == NULL && npassed_args != 1) { // TODO not npassed args, since the starargs or kwargs could be null raiseExcHelper(TypeError, objectNewParameterTypeErrorMsg()); } } if (rewrite_args) { rewrite_args->out_rtn = std::move(r_made); rewrite_args->out_success = true; } // Some of these might still be in use if rewrite_args was set to NULL r_init.ensureDoneUsing(); r_ccls.ensureDoneUsing(); r_made.ensureDoneUsing(); r_init.ensureDoneUsing(); if (rewrite_args) { rewrite_args->arg2.ensureDoneUsing(); rewrite_args->arg3.ensureDoneUsing(); rewrite_args->args.ensureDoneUsing(); } return made; } Box* typeCall(Box* obj, BoxedList* vararg) { assert(vararg->cls == list_cls); if (vararg->size == 0) return typeCallInternal1(NULL, NULL, ArgPassSpec(1), obj); else if (vararg->size == 1) return typeCallInternal2(NULL, NULL, ArgPassSpec(2), obj, vararg->elts->elts[0]); else if (vararg->size == 2) return typeCallInternal3(NULL, NULL, ArgPassSpec(3), obj, vararg->elts->elts[0], vararg->elts->elts[1]); else abort(); } extern "C" void delGlobal(BoxedModule* m, std::string* name) { if (!m->getattr(*name)) { raiseExcHelper(NameError, "name '%s' is not defined", name->c_str()); } m->delattr(*name, NULL); } extern "C" Box* getGlobal(BoxedModule* m, std::string* name) { static StatCounter slowpath_getglobal("slowpath_getglobal"); slowpath_getglobal.log(); static StatCounter nopatch_getglobal("nopatch_getglobal"); if (VERBOSITY() >= 2) { #if !DISABLE_STATS std::string per_name_stat_name = "getglobal__" + *name; int id = Stats::getStatId(per_name_stat_name); Stats::log(id); #endif } { /* anonymous scope to make sure destructors get run before we err out */ std::unique_ptr<Rewriter> rewriter( Rewriter::createRewriter(__builtin_extract_return_addr(__builtin_return_address(0)), 3, "getGlobal")); Box* r; if (rewriter.get()) { // rewriter->trap(); GetattrRewriteArgs rewrite_args(rewriter.get(), rewriter->getArg(0), rewriter->getReturnDestination(), false); r = m->getattr(*name, &rewrite_args); if (!rewrite_args.obj.isDoneUsing()) { rewrite_args.obj.setDoneUsing(); } if (!rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } if (r) { if (rewriter.get()) { rewriter->setDoneGuarding(); rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } else { rewrite_args.out_rtn.setDoneUsing(); } return r; } } else { r = m->getattr(*name, NULL); nopatch_getglobal.log(); if (r) { return r; } } static StatCounter stat_builtins("getglobal_builtins"); stat_builtins.log(); if ((*name) == "__builtins__") { if (rewriter.get()) { RewriterVarUsage r_rtn = rewriter->loadConst((intptr_t)builtins_module, rewriter->getReturnDestination()); rewriter->setDoneGuarding(); rewriter->commitReturning(std::move(r_rtn)); } return builtins_module; } Box* rtn; if (rewriter.get()) { RewriterVarUsage builtins = rewriter->loadConst((intptr_t)builtins_module, Location::any()); GetattrRewriteArgs rewrite_args(rewriter.get(), std::move(builtins), rewriter->getReturnDestination(), true); rtn = builtins_module->getattr(*name, &rewrite_args); if (!rtn || !rewrite_args.out_success) { rewrite_args.ensureAllDone(); rewriter.reset(NULL); } if (rewriter.get()) { rewriter->commitReturning(std::move(rewrite_args.out_rtn)); } } else { rtn = builtins_module->getattr(*name, NULL); } if (rtn) return rtn; } raiseExcHelper(NameError, "global name '%s' is not defined", name->c_str()); } extern "C" Box* importFrom(Box* _m, const std::string* name) { assert(_m->cls == module_cls); BoxedModule* m = static_cast<BoxedModule*>(_m); Box* r = m->getattr(*name, NULL); if (r) return r; raiseExcHelper(ImportError, "cannot import name %s", name->c_str()); } extern "C" Box* importStar(Box* _from_module, BoxedModule* to_module) { assert(_from_module->cls == module_cls); BoxedModule* from_module = static_cast<BoxedModule*>(_from_module); static std::string all_str("__all__"); static std::string getitem_str("__getitem__"); Box* all = from_module->getattr(all_str); if (all) { Box* all_getitem = typeLookup(all->cls, getitem_str, NULL); if (!all_getitem) raiseExcHelper(TypeError, "'%s' object does not support indexing", getTypeName(all)->c_str()); int idx = 0; while (true) { Box* attr_name; try { attr_name = runtimeCallInternal2(all_getitem, NULL, ArgPassSpec(2), all, boxInt(idx)); } catch (Box* b) { if (b->cls == IndexError) break; throw; } idx++; if (attr_name->cls != str_cls) raiseExcHelper(TypeError, "attribute name must be string, not '%s'", getTypeName(attr_name)->c_str()); BoxedString* casted_attr_name = static_cast<BoxedString*>(attr_name); Box* attr_value = from_module->getattr(casted_attr_name->s); if (!attr_value) raiseExcHelper(AttributeError, "'module' object has no attribute '%s'", casted_attr_name->s.c_str()); to_module->setattr(casted_attr_name->s, attr_value, NULL); } return None; } HCAttrs* module_attrs = from_module->getAttrsPtr(); for (auto& p : module_attrs->hcls->attr_offsets) { if (p.first[0] == '_') continue; to_module->setattr(p.first, module_attrs->attr_list->attrs[p.second], NULL); } return None; } }
; application exit handling routines exit_full: call flash_code_copy exit_cleanup.run relocate exit_cleanup, mpLcdCrsrImage + 500 bit setting_ram_backup,(iy + settings_flag) call nz,flash_clear_backup call lcd_normal call _ClrParserHook call _ClrAppChangeHook call util_setup_shortcuts call _ClrScrn call _HomeUp res useTokensInString,(iy + clockFlags) res onInterrupt,(iy + onFlags) set graphDraw,(iy + graphFlags) ld hl,pixelShadow ld bc,69090 call _MemClear call _ClrTxtShd ; clear text shadow bit 3,(iy + $25) jr z,.no_defrag ld a,cxErase call _NewContext0 ; trigger a defrag as needed .no_defrag: res apdWarmStart,(iy + apdFlags) call _APDSetup call _EnableAPD ; restore apd im 1 ei ld a,kClear jp _JForceCmd ; exit the application for good end relocate
/* * This test verifies interrupt handling using a simple timer model */ lc r100, 0x10000000 // test result output pointer lc r101, halt lc r102, failure lc r103, 0x20000000 // timer: number of pulses (0xFFFFFFFF - infinite) lc r104, 0x20000004 // timer: delay between pulses (in cycles) lc iv0, timer_handler0 lc iv1, timer_handler1 mov cr, 3 // enable interrupts 0 and 1 lc r32, 2000 // cycle counter lc r33, cnt_loop mov r34, 0 // interrupt 0 call counter mov r35, 0 // interrupt 1 call counter sw r104, 100 sw r103, 10 cnt_loop: sub r32, r32, 1 cjmpug r33, r32, 0 // cnt_loop cjmpne r102, r34, 10 // failure cjmpne r102, r35, 4 // failure sw r100, 1 jmp r101 // halt failure: sw r100, 2 halt: hlt jmp r101 // halt timer_handler0: add r34, r34, 1 lc r0, 0x10000004 sw r0, r34 cjmpne irp, r34, 5 // exit interrupt handler if r34!=5 mov cr, 1 // disable interrupt 1 iret timer_handler1: add r35, r35, 1 // Interrupt 1 has lower priority than interrupt 0 and will be called later cjmpne r102, r34, r35 lc r0, 0x10000008 sw r0, r35 iret
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r8 push %rax push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0x1aac9, %r12 nop add $22014, %r8 mov $0x6162636465666768, %r11 movq %r11, %xmm6 movups %xmm6, (%r12) nop nop nop nop nop cmp $45732, %rbx lea addresses_D_ht+0x7115, %r8 nop nop nop and $45808, %r12 mov $0x6162636465666768, %rdx movq %rdx, %xmm6 vmovups %ymm6, (%r8) nop xor %r8, %r8 lea addresses_A_ht+0x6b9, %rdi nop nop nop nop mfence mov (%rdi), %dx nop cmp $14214, %rdi lea addresses_A_ht+0x16139, %rdi nop nop nop nop xor $50151, %rdx mov (%rdi), %bx nop nop nop cmp $52203, %rdi lea addresses_normal_ht+0xf011, %r12 nop inc %rax mov $0x6162636465666768, %rbx movq %rbx, %xmm0 vmovups %ymm0, (%r12) nop nop nop inc %r12 lea addresses_A_ht+0xf539, %rdx nop nop nop nop dec %rax mov $0x6162636465666768, %r12 movq %r12, (%rdx) nop nop nop nop nop add %r8, %r8 lea addresses_D_ht+0x16dc1, %rdx nop nop nop add %r8, %r8 mov (%rdx), %r12d nop nop nop nop sub %r8, %r8 lea addresses_WT_ht+0x18089, %rdi sub %rbx, %rbx mov (%rdi), %ax nop nop xor $56949, %rax lea addresses_normal_ht+0x18951, %r12 nop nop nop nop sub %rdi, %rdi mov (%r12), %bx nop sub %r11, %r11 lea addresses_D_ht+0x10ab9, %rsi lea addresses_A_ht+0x13cb9, %rdi nop nop xor %r12, %r12 mov $11, %rcx rep movsl inc %rcx lea addresses_WT_ht+0x11c0b, %rsi lea addresses_WC_ht+0x108b9, %rdi nop nop nop nop nop inc %rdx mov $10, %rcx rep movsl nop nop nop and %r11, %r11 lea addresses_UC_ht+0x1e2b9, %rdx nop nop cmp %r8, %r8 movw $0x6162, (%rdx) nop nop cmp %rax, %rax lea addresses_UC_ht+0x1e7f9, %r12 nop nop nop dec %rsi vmovups (%r12), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $1, %xmm3, %r8 nop nop nop and %r11, %r11 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rax pop %r8 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r13 push %r14 push %r8 push %rbx push %rcx // Faulty Load lea addresses_US+0x194b9, %rcx nop nop nop and $31566, %rbx mov (%rcx), %r13 lea oracles, %r14 and $0xff, %r13 shlq $12, %r13 mov (%r14,%r13,1), %r13 pop %rcx pop %rbx pop %r8 pop %r14 pop %r13 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_US', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_US', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 4}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 2}} {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 8}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 3}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': True, 'size': 8, 'NT': False, 'same': False, 'congruent': 6}} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 3}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 4}, 'OP': 'LOAD'} {'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 3}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 9}} {'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 4}, 'OP': 'LOAD'} {'00': 4} 00 00 00 00 */
; A017794: Binomial coefficients C(78,n). ; 1,78,3003,76076,1426425,21111090,256851595,2641902120,23446881315,182364632450,1258315963905,7778680504140,43430966148115,220495674290430,1023729916348425,4367914309753280,17198662594653540,62724534168736440,212566476905162380,671262558647881200,1980224548011249540,5469191608792974920,14170178259145435020,34501303587484537440,79065487387985398300,170781452758048460328,348131422929868015284,670475333050116177584,1221222928055568752028,2105556772509601296600,3439076061765682117780 mov $1,78 bin $1,$0 mov $0,$1
; A127948: Triangle, A004736 * A127899. ; 1,0,2,-1,1,3,-2,0,2,4,-3,-1,1,3,5,-4,-2,0,2,4,6,-5,-3,-1,1,3,5,7,-6,-4,-2,0,2,4,6,8,-7,-5,-3,-1,1,3,5,7,9,-8,-6,-4,-2,0,2,4,6,8,10 add $0,1 mul $0,2 mov $1,2 mov $2,-1 lpb $0,1 add $2,$1 sub $0,$2 lpe mov $1,$0
; A286909: Positions of 1 in A286907; complement of A286908. ; 2,4,8,10,14,16,18,22,24,28,30,32,36,38,42,44,48,50,52,56,58,62,64,66,70,72,76,78,82,84,86,90,92,96,98,100,104,106,110,112,114,118,120,124,126,130,132,134,138,140,144,146,148,152,154,158,160,164,166,168,172,174,178,180,182,186,188,192,194,196,200,202,206,208,212,214,216,220,222,226,228,230,234,236,240,242,246,248,250,254,256,260,262,264,268,270,274,276,280,282,284,288,290,294,296,298,302,304,308,310,312,316,318,322,324,328,330,332,336,338,342,344,346,350,352,356,358,362,364,366,370,372,376,378,380,384,386,390,392,394,398,400,404,406,410,412,414,418,420,424,426,428,432,434,438,440,444,446,448,452,454,458,460,462,466,468,472,474,478,480,482,486,488,492,494,496,500,502,506,508,510,514,516,520,522,526,528,530,534,536,540,542,544,548,550,554,556,560,562,564,568,570,574,576,578,582,584,588,590,592,596,598,602,604,608,610,612,616,618,622,624,626,630,632,636,638,642,644,646,650,652,656,658,660,664,666,670,672,674,678,680,684,686,690,692,694,698,700,704,706 add $0,1 pow $0,2 lpb $0,1 add $1,1 sub $0,$1 lpe mul $1,2
;-------------------------------------------------------------------- ; RC2014 UART Routines ; ; Code by Grant Colegate 2017 ; ; See http://rc2014.co.uk for info on the RC2014 homebrew computer. ;-------------------------------------------------------------------- MODULE rc2014_uart SECTION code_user ; Check the UART RX buffer. ; Returns the status in L. public rc2014_rx_ready rc2014_rx_ready: ld h, 0 ld l, 0 rst $18 ret z ld l, 1 ret ; Read a character from the UART. ; Returns the received character in L. public rc2014_rx rc2014_rx: rst $10 ld h, 0 ld l, a ret ; Transmit a character to the UART. ; Transmits the character in L. public rc2014_tx rc2014_tx: ld a, l rst $08 ret ; Print a null terminated string over UART. public rc2014_print rc2014_print: ld a, (hl) cp 0 ret z rst $08 inc hl jr rc2014_print
; A274230: Number of holes in a sheet of paper when you fold it n times and cut off the four corners. ; 0,0,1,3,9,21,49,105,225,465,961,1953,3969,8001,16129,32385,65025,130305,261121,522753,1046529,2094081,4190209,8382465,16769025,33542145,67092481,134193153,268402689,536821761,1073676289,2147385345,4294836225,8589737985,17179607041,34359345153,68718952449,137438167041,274876858369,549754241025,1099509530625,2199020109825,4398042316801,8796086730753,17592177655809,35184359505921,70368727400449,140737463189505,281474943156225,562949903089665,1125899839733761,2251799713021953,4503599493152769,9007199053414401 mov $2,$0 mov $3,$0 lpb $0 sub $0,1 sub $2,1 mov $1,$2 mul $2,2 add $3,1 trn $3,3 sub $2,$3 lpe
/* ** Created by doom on 27/11/18. */ #include <tuple> #include <core/halted_loop.hpp> #include <vga/vga.hpp> #include <keyboard/key_event_recognizer.hpp> #include <keyboard/input_mapper.hpp> using namespace foros; enum syscall_id { write = 0, }; template <typename ...Args> static long syscall(syscall_id id, std::tuple<Args ...> args) { constexpr auto nb_args = sizeof...(Args); if constexpr (nb_args == 6) { asm volatile("mov %0, %%r9"::"r"((long)(std::get<5>(args)))); } if constexpr (nb_args >= 5) { asm volatile("mov %0, %%r8"::"r"((long)(std::get<4>(args)))); } if constexpr (nb_args >= 4) { asm volatile("mov %0, %%rcx"::"r"((long)(std::get<3>(args)))); } if constexpr (nb_args >= 3) { asm volatile("mov %0, %%rdx"::"r"((long)(std::get<2>(args)))); } if constexpr (nb_args >= 2) { asm volatile("mov %0, %%rsi"::"r"((long)(std::get<1>(args)))); } if constexpr (nb_args >= 1) { asm volatile("mov %0, %%rdi"::"r"((long)(std::get<0>(args)))); } long ret; asm volatile( "mov %1, %%rax;" "int $0x80;" "mov %%rax, %0" : "=a"(ret) : "r"((long)id) ); return ret; } static long monitor_write(const char *buf, size_t size) { return syscall(syscall_id::write, std::make_tuple(buf, size)); } void fake_init_main() { monitor_write("hello\n", 6); halted_loop([]() { auto ev_opt = kbd::key_event_recognizer::instance().get_next_event(); while (ev_opt) { auto[ev_code, ev_state] = ev_opt.unwrap(); switch (ev_code) { case kbd::key_code::enter: if (ev_state == kbd::key_state::down) { vga::scrolling_printer() << "\n"; } break; case kbd::key_code::backspace: if (ev_state == kbd::key_state::down) { vga::scrolling_printer() << "\b \b"; } break; default: { auto chr_opt = kbd::input_mapper::instance().add_event(ev_opt.unwrap()); if (chr_opt) { vga::scrolling_printer() << chr_opt.unwrap(); } break; } } ev_opt = kbd::key_event_recognizer::instance().get_next_event(); } }); }
; A124152: a(n) = Fibonacci(6, n). ; 0,8,70,360,1292,3640,8658,18200,34840,61992,104030,166408,255780,380120,548842,772920,1065008,1439560,1912950,2503592,3232060,4121208,5196290,6485080,8017992,9828200,11951758,14427720,17298260,20608792,24408090,28748408,33685600,39279240,45592742,52693480,60652908,69546680,79454770,90461592,102656120,116132008,130987710,147326600,165257092,184892760,206352458,229760440,255246480,282945992,313000150,345556008,380766620,418791160,459795042,503950040,551434408,602433000,657137390,715745992 mov $1,$0 pow $0,2 add $0,1 mul $1,2 mul $1,$0 add $0,2 mul $1,$0 mov $0,$1 div $0,4 mul $0,2
; A025192: a(0)=1; a(n) = 2*3^(n-1) for n >= 1. ; 1,2,6,18,54,162,486,1458,4374,13122,39366,118098,354294,1062882,3188646,9565938,28697814,86093442,258280326,774840978,2324522934,6973568802,20920706406,62762119218,188286357654,564859072962,1694577218886,5083731656658,15251194969974,45753584909922,137260754729766,411782264189298,1235346792567894,3706040377703682,11118121133111046,33354363399333138,100063090197999414,300189270593998242,900567811781994726,2701703435345984178,8105110306037952534,24315330918113857602,72945992754341572806,218837978263024718418,656513934789074155254,1969541804367222465762,5908625413101667397286,17725876239305002191858,53177628717915006575574,159532886153745019726722,478598658461235059180166,1435795975383705177540498,4307387926151115532621494,12922163778453346597864482,38766491335360039793593446,116299474006080119380780338,348898422018240358142341014,1046695266054721074427023042,3140085798164163223281069126,9420257394492489669843207378,28260772183477469009529622134,84782316550432407028588866402,254346949651297221085766599206,763040848953891663257299797618,2289122546861674989771899392854,6867367640585024969315698178562,20602102921755074907947094535686,61806308765265224723841283607058,185418926295795674171523850821174,556256778887387022514571552463522,1668770336662161067543714657390566,5006311009986483202631143972171698,15018933029959449607893431916515094,45056799089878348823680295749545282,135170397269635046471040887248635846,405511191808905139413122661745907538 mov $1,3 pow $1,$0 mul $1,2 sub $1,2 div $1,3 add $1,1 mov $0,$1
; A139738: a(n) = 10^n mod 8^n. ; 0,2,36,488,1808,1696,213568,1611392,16113920,60475904,336323584,5510719488,37927325696,104395350016,3242976755712,14837581512704,148375815127040,920808197849088,9208081978490880,56052022765944832,848750603811160064,3875820019684212736,38758200196842127360,240008049378744860672,3580672114504859910144,26361988179309308674048,263619881793093086740480,1427272998316301692698624,19108433261621533625810944,36341827705542801895718912,982388296698118156406751232,7348002888410421014269263872 mov $1,8 pow $1,$0 mov $2,10 pow $2,$0 mod $2,$1 mov $0,$2
bits 32 movd mm0,eax movd mm0,[foo] movq mm0,[foo] movd mm0,dword [foo] movq mm0,qword [foo] movmskps eax,xmm1 movmskpd eax,xmm1 nop movd xmm0,eax movd xmm0,[foo] movq xmm0,[foo] movd xmm0,dword [foo] movq xmm0,qword [foo] nop bits 64 movd mm0,eax movq mm0,[foo] movd mm0,dword [foo] movq mm0,qword [foo] movq mm0,rax movmskps eax,xmm1 movmskpd eax,xmm1 nop movd xmm0,eax movq xmm0,[foo] movd xmm0,dword [foo] movq xmm0,qword [foo] movq xmm0,rax movmskps rax,xmm1 movmskpd rax,xmm1 nop section .bss foo resq 1
; ; Disk bootstrap for the pc88 ; SECTION BOOTSTRAP EXTERN __DATA_END_tail org $f000 di ld hl,$c000 ld de,$f000 ld bc,512 ldir jp entry console_defn: defb "0,25,0,1",0 entry: xor a ld ($e6a7),a ;Disable cursor call $428b ;Stop cursor blink ld hl,console_defn ; call $7071 ; Console entry call $5f0e ; Text screen area ld a,%00000001 ; Colour, 80 column text mode out ($30),a ; --x- ---- graphics hires ; ---x ---- graphic color yes (1) / no (0) ; ---- x--- graphic display yes (1) / no (0) ; ---- -x-- Basic N (1) / N88 (0) ; ---- --x- RAM select yes (1) / no (0) ; ---- ---x VRAM 200 lines (1) / 400 lines (0) in 1bpp mode ld a,%00111011 ; Hires, 25 row, color graphics mode, graphics on, N88 basic, 64k mode, 200 line resolution out ($31),a xor a ;Disable interrupts out ($E6),a out ($E4),a ld hl,CRT_ORG_CODE ld b, +((__DATA_END_tail - CRT_ORG_CODE) / 256) + 1 ld c,0 ld de,2 ;Start sector 2, track 0 call DISK_Load jp CRT_ORG_CODE ; hl = address ; b = number of sectors ; c = drive ; d = start track ; e = start sectors ;ディスクからデータをロード ; HL: ロードするアドレス ; B: セクタ数 C: ドライブ D: トラック E: セクタ DISK_Load: ld a,$02 ;コマンド 2 Read Data call DISK_SdCmd ld a,b ;セクタ数 1<=sec(s)<=16 cp 17 jr c,load2 ld a,17 ;16を超える場合は 17-StartSector だけ読んで次トラックへ sub e load2: call DISK_SdData1 ld a,c ;ドライブ call DISK_SdData1 ld a,d ;トラック call DISK_SdData1 ld a,e ;セクタ call DISK_SdData1 ld a,$12 ;コマンド 18 Fast Send Data call DISK_SdCmd loop1: push bc ld b,128 ; 128 * 2bytes 受信 loop2: call DISK_RdData2 djnz loop2 ; セクタ内ループ inc e ld a,e cp 17 ; 17に到達->次のトラックへ移行 jr z,next pop bc djnz loop1 ; セクタ数分ループ ret ;次のトラックへ next: inc d ;次のトラックから ld e,1 ;セクタは1から pop bc dec b jr nz,DISK_Load ret ; サブシステムにコマンド送信 ; a=コマンド番号 DISK_SdCmd: push af ld a,%00001111 ;Attention=1 out ($FF),a wait1: in a,($FE) bit 1,a ;Ready for Data? jr z,wait1 ld a,%00001110 ;Attention=0 out ($FF),a jr DISK_SdData1sub ;1バイト送信 DISK_SdData1: push af wait1_1: in a,($FE) bit 1,a ;Ready for Data jr z,wait1_1 DISK_SdData1sub: pop af out ($FD),a ;コマンド ld a,%00001001 ;Data Valid out ($FF),a wait2: in a,($FE) bit 2,a ;Data Accepted? jr z,wait2 ld a,%00001000 ;Data Valid out ($FF),a wait3: in a,($FE) bit 2,a ;Data Accepted? jr nz,wait3 ret ;2バイト受信 DISK_RdData2: ld a,%00001011 ;Ready for Data out ($FF),a wait1_3: in a,($FE) rrca ;Data Valid? jr nc,wait1_3 ld a,%00001010 ;Ready for Data=0 out ($FF),a in a,($FC) ;データ受信 ld (hl),a inc hl ld a,%00001101 ;Data Valid=1 out ($FF),a wait2_1: in a,($FE) rrca jr c,wait2_1 in a,($FC) ld (hl),a inc hl ld a,%00001100 ;Data Accepted out ($FF),a ret
; A304616: a(n) = 81*n^2 - 69*n + 24. ; 24,36,210,546,1044,1704,2526,3510,4656,5964,7434,9066,10860,12816,14934,17214,19656,22260,25026,27954,31044,34296,37710,41286,45024,48924,52986,57210,61596,66144,70854,75726,80760,85956,91314,96834,102516,108360,114366,120534,126864,133356,140010,146826,153804,160944,168246,175710,183336,191124,199074,207186,215460,223896,232494,241254,250176,259260,268506,277914,287484,297216,307110,317166,327384,337764,348306,359010,369876,380904,392094,403446,414960,426636,438474,450474,462636,474960,487446,500094,512904,525876,539010,552306,565764,579384,593166,607110,621216,635484,649914,664506,679260,694176,709254,724494,739896,755460,771186,787074 mov $1,27 mul $1,$0 sub $1,23 mul $1,$0 div $1,2 mul $1,6 add $1,24 mov $0,$1
%include "asm_io.inc" segment .data str1 db "Hello Assembly World!",0 segment .bss segment .text global asm_main asm_main: enter 0,0 pusha mov eax, str1 ;str1 is an address call print_string;print the string at that address call print_nl ;print a new line pusha popa mov eax, 0 leave ret
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, SRI International * 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 SRI International nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Sachin Chitta, Dave Coleman, Mike Lautman */ #include <moveit/move_group_interface/move_group_interface.h> #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <moveit_msgs/DisplayRobotState.h> #include <moveit_msgs/DisplayTrajectory.h> #include <moveit_msgs/AttachedCollisionObject.h> #include <moveit_msgs/CollisionObject.h> #include <moveit_visual_tools/moveit_visual_tools.h> int main(int argc, char** argv) { ros::init(argc, argv, "move_group_interface_tutorial"); ros::NodeHandle node_handle; ros::AsyncSpinner spinner(1); spinner.start(); // BEGIN_TUTORIAL // // Setup // ^^^^^ // // MoveIt! operates on sets of joints called "planning groups" and stores them in an object called // the `JointModelGroup`. Throughout MoveIt! the terms "planning group" and "joint model group" // are used interchangably. static const std::string PLANNING_GROUP = "right_arm"; // The :move_group_interface:`MoveGroup` class can be easily // setup using just the name of the planning group you would like to control and plan for. moveit::planning_interface::MoveGroupInterface move_group(PLANNING_GROUP); // We will use the :planning_scene_interface:`PlanningSceneInterface` // class to add and remove collision objects in our "virtual world" scene moveit::planning_interface::PlanningSceneInterface planning_scene_interface; // Raw pointers are frequently used to refer to the planning group for improved performance. const robot_state::JointModelGroup* joint_model_group = move_group.getCurrentState()->getJointModelGroup(PLANNING_GROUP); // Visualization // ^^^^^^^^^^^^^ // // The package MoveItVisualTools provides many capabilties for visualizing objects, robots, // and trajectories in RViz as well as debugging tools such as step-by-step introspection of a script namespace rvt = rviz_visual_tools; moveit_visual_tools::MoveItVisualTools visual_tools("right_base_link"); visual_tools.deleteAllMarkers(); // Remote control is an introspection tool that allows users to step through a high level script // via buttons and keyboard shortcuts in RViz visual_tools.loadRemoteControl(); // RViz provides many types of markers, in this demo we will use text, cylinders, and spheres Eigen::Affine3d text_pose = Eigen::Affine3d::Identity(); text_pose.translation().z() = 1.75; visual_tools.publishText(text_pose, "MoveGroupInterface Demo", rvt::WHITE, rvt::XLARGE); // Batch publishing is used to reduce the number of messages being sent to RViz for large visualizations visual_tools.trigger(); // Getting Basic Information // ^^^^^^^^^^^^^^^^^^^^^^^^^ // // We can print the name of the reference frame for this robot. ROS_INFO_NAMED("tutorial", "Reference frame: %s", move_group.getPlanningFrame().c_str()); // We can also print the name of the end-effector link for this group. ROS_INFO_NAMED("tutorial", "End effector link: %s", move_group.getEndEffectorLink().c_str()); // Start the demo // ^^^^^^^^^^^^^^^^^^^^^^^^^ visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to start the demo"); // Planning to a Pose goal // ^^^^^^^^^^^^^^^^^^^^^^^ // We can plan a motion for this group to a desired pose for the // end-effector. geometry_msgs::Pose target_pose1; target_pose1.orientation.w = 1.0; target_pose1.position.x = 0.2; target_pose1.position.y = -0.2; target_pose1.position.z = 0.8; move_group.setPoseTarget(target_pose1); // Now, we call the planner to compute the plan and visualize it. // Note that we are just planning, not asking move_group // to actually move the robot. moveit::planning_interface::MoveGroupInterface::Plan my_plan; bool success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS); ROS_INFO_NAMED("tutorial", "Visualizing plan 1 (pose goal) %s", success ? "" : "FAILED"); // Visualizing plans // ^^^^^^^^^^^^^^^^^ // We can also visualize the plan as a line with markers in RViz. ROS_INFO_NAMED("tutorial", "Visualizing plan 1 as trajectory line"); visual_tools.publishAxisLabeled(target_pose1, "pose1"); visual_tools.publishText(text_pose, "Pose Goal", rvt::WHITE, rvt::XLARGE); visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); visual_tools.trigger(); visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue the demo"); // Moving to a pose goal // ^^^^^^^^^^^^^^^^^^^^^ // // Moving to a pose goal is similar to the step above // except we now use the move() function. Note that // the pose goal we had set earlier is still active // and so the robot will try to move to that goal. We will // not use that function in this tutorial since it is // a blocking function and requires a controller to be active // and report success on execution of a trajectory. /* Uncomment below line when working with a real robot */ /* move_group.move(); */ // Planning to a joint-space goal // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // // Let's set a joint space goal and move towards it. This will replace the // pose target we set above. // // To start, we'll create an pointer that references the current robot's state. // RobotState is the object that contains all the current position/velocity/acceleration data. moveit::core::RobotStatePtr current_state = move_group.getCurrentState(); // // Next get the current set of joint values for the group. std::vector<double> joint_group_positions; current_state->copyJointGroupPositions(joint_model_group, joint_group_positions); // Now, let's modify one of the joints, plan to the new joint space goal and visualize the plan. joint_group_positions[0] = -1.0; // radians move_group.setJointValueTarget(joint_group_positions); success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS); ROS_INFO_NAMED("tutorial", "Visualizing plan 2 (joint space goal) %s", success ? "" : "FAILED"); // Visualize the plan in RViz visual_tools.deleteAllMarkers(); visual_tools.publishText(text_pose, "Joint Space Goal", rvt::WHITE, rvt::XLARGE); visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); visual_tools.trigger(); visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue the demo"); // Planning with Path Constraints // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // // Path constraints can easily be specified for a link on the robot. // Let's specify a path constraint and a pose goal for our group. // First define the path constraint. moveit_msgs::OrientationConstraint ocm; ocm.link_name = "right_wrist_3_link"; ocm.header.frame_id = "right_base_link"; ocm.orientation.w = 1.0; ocm.absolute_x_axis_tolerance = 0.1; ocm.absolute_y_axis_tolerance = 0.1; ocm.absolute_z_axis_tolerance = 0.1; ocm.weight = 1.0; // Now, set it as the path constraint for the group. moveit_msgs::Constraints test_constraints; test_constraints.orientation_constraints.push_back(ocm); move_group.setPathConstraints(test_constraints); // We will reuse the old goal that we had and plan to it. // Note that this will only work if the current state already // satisfies the path constraints. So, we need to set the start // state to a new pose. robot_state::RobotState start_state(*move_group.getCurrentState()); geometry_msgs::Pose start_pose2; start_pose2.orientation.w = 1.0; start_pose2.position.x = 0.55; start_pose2.position.y = -0.05; start_pose2.position.z = 0.8; start_state.setFromIK(joint_model_group, start_pose2); move_group.setStartState(start_state); // Now we will plan to the earlier pose target from the new // start state that we have just created. move_group.setPoseTarget(target_pose1); // Planning with constraints can be slow because every sample must call an inverse kinematics solver. // Lets increase the planning time from the default 5 seconds to be sure the planner has enough time to succeed. move_group.setPlanningTime(10.0); success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS); ROS_INFO_NAMED("tutorial", "Visualizing plan 3 (constraints) %s", success ? "" : "FAILED"); // Visualize the plan in RViz visual_tools.deleteAllMarkers(); visual_tools.publishAxisLabeled(start_pose2, "start"); visual_tools.publishAxisLabeled(target_pose1, "goal"); visual_tools.publishText(text_pose, "Constrained Goal", rvt::WHITE, rvt::XLARGE); visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); visual_tools.trigger(); visual_tools.prompt("next step"); // When done with the path constraint be sure to clear it. move_group.clearPathConstraints(); // Since we set the start state we have to clear it before planning other paths move_group.setStartStateToCurrentState(); // Cartesian Paths // ^^^^^^^^^^^^^^^ // You can plan a Cartesian path directly by specifying a list of waypoints // for the end-effector to go through. Note that we are starting // from the new start state above. The initial pose (start state) does not // need to be added to the waypoint list but adding it can help with visualizations geometry_msgs::Pose target_pose3 = move_group.getCurrentPose().pose; std::vector<geometry_msgs::Pose> waypoints; waypoints.push_back(target_pose3); target_pose3.position.z -= 0.2; waypoints.push_back(target_pose3); // down target_pose3.position.y -= 0.2; waypoints.push_back(target_pose3); // right target_pose3.position.z += 0.2; target_pose3.position.y += 0.2; target_pose3.position.x -= 0.2; waypoints.push_back(target_pose3); // up and left // Cartesian motions are frequently needed to be slower for actions such as approach and retreat // grasp motions. Here we demonstrate how to reduce the speed of the robot arm via a scaling factor // of the maxiumum speed of each joint. Note this is not the speed of the end effector point. move_group.setMaxVelocityScalingFactor(0.1); // We want the Cartesian path to be interpolated at a resolution of 1 cm // which is why we will specify 0.01 as the max step in Cartesian // translation. We will specify the jump threshold as 0.0, effectively disabling it. // Warning - disabling the jump threshold while operating real hardware can cause // large unpredictable motions of redundant joints and could be a safety issue moveit_msgs::RobotTrajectory trajectory; const double jump_threshold = 0.0; const double eef_step = 0.01; double fraction = move_group.computeCartesianPath(waypoints, eef_step, jump_threshold, trajectory); ROS_INFO_NAMED("tutorial", "Visualizing plan 4 (Cartesian path) (%.2f%% acheived)", fraction * 100.0); // Visualize the plan in RViz visual_tools.deleteAllMarkers(); visual_tools.publishText(text_pose, "Joint Space Goal", rvt::WHITE, rvt::XLARGE); visual_tools.publishPath(waypoints, rvt::LIME_GREEN, rvt::SMALL); for (std::size_t i = 0; i < waypoints.size(); ++i) visual_tools.publishAxisLabeled(waypoints[i], "pt" + std::to_string(i), rvt::SMALL); visual_tools.trigger(); visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue the demo"); // Adding/Removing Objects and Attaching/Detaching Objects // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // // Define a collision object ROS message. moveit_msgs::CollisionObject collision_object; collision_object.header.frame_id = move_group.getPlanningFrame(); // The id of the object is used to identify it. collision_object.id = "box1"; // Define a box to add to the world. shape_msgs::SolidPrimitive primitive; primitive.type = primitive.BOX; primitive.dimensions.resize(3); primitive.dimensions[0] = 0.4; primitive.dimensions[1] = 0.1; primitive.dimensions[2] = 0.4; // Define a pose for the box (specified relative to frame_id) geometry_msgs::Pose box_pose; box_pose.orientation.w = 1.0; box_pose.position.x = 0.4; box_pose.position.y = -0.2; box_pose.position.z = 1.0; collision_object.primitives.push_back(primitive); collision_object.primitive_poses.push_back(box_pose); collision_object.operation = collision_object.ADD; std::vector<moveit_msgs::CollisionObject> collision_objects; collision_objects.push_back(collision_object); // Now, let's add the collision object into the world ROS_INFO_NAMED("tutorial", "Add an object into the world"); planning_scene_interface.addCollisionObjects(collision_objects); // Show text in RViz of status visual_tools.publishText(text_pose, "Add object", rvt::WHITE, rvt::XLARGE); visual_tools.trigger(); // Wait for MoveGroup to recieve and process the collision object message visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to once the collision object appears in RViz"); // Now when we plan a trajectory it will avoid the obstacle move_group.setStartState(*move_group.getCurrentState()); geometry_msgs::Pose another_pose; another_pose.orientation.w = 1.0; another_pose.position.x = 0.4; another_pose.position.y = -0.4; another_pose.position.z = 0.9; move_group.setPoseTarget(another_pose); success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS); ROS_INFO_NAMED("tutorial", "Visualizing plan 5 (pose goal move around cuboid) %s", success ? "" : "FAILED"); // Visualize the plan in RViz visual_tools.deleteAllMarkers(); visual_tools.publishText(text_pose, "Obstacle Goal", rvt::WHITE, rvt::XLARGE); visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); visual_tools.trigger(); visual_tools.prompt("next step"); // Now, let's attach the collision object to the robot. ROS_INFO_NAMED("tutorial", "Attach the object to the robot"); move_group.attachObject(collision_object.id); // Show text in RViz of status visual_tools.publishText(text_pose, "Object attached to robot", rvt::WHITE, rvt::XLARGE); visual_tools.trigger(); /* Wait for MoveGroup to recieve and process the attached collision object message */ visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to once the collision object attaches to the " "robot"); // Now, let's detach the collision object from the robot. ROS_INFO_NAMED("tutorial", "Detach the object from the robot"); move_group.detachObject(collision_object.id); // Show text in RViz of status visual_tools.publishText(text_pose, "Object dettached from robot", rvt::WHITE, rvt::XLARGE); visual_tools.trigger(); /* Wait for MoveGroup to recieve and process the attached collision object message */ visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to once the collision object detaches to the " "robot"); // Now, let's remove the collision object from the world. ROS_INFO_NAMED("tutorial", "Remove the object from the world"); std::vector<std::string> object_ids; object_ids.push_back(collision_object.id); planning_scene_interface.removeCollisionObjects(object_ids); // Show text in RViz of status visual_tools.publishText(text_pose, "Object removed", rvt::WHITE, rvt::XLARGE); visual_tools.trigger(); /* Wait for MoveGroup to recieve and process the attached collision object message */ visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to once the collision object disapears"); // END_TUTORIAL ros::shutdown(); return 0; }
// -*- C++ -*- //===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14 // XFAIL: dylib-has-no-bad_variant_access && !libcpp-no-exceptions // <variant> // template <class ...Types> class variant; // template <class T> constexpr variant(T&&) noexcept(see below); #include <cassert> #include <string> #include <type_traits> #include <variant> #include <memory> #include "test_macros.h" #include "variant_test_helpers.h" struct Dummy { Dummy() = default; }; struct ThrowsT { ThrowsT(int) noexcept(false) {} }; struct NoThrowT { NoThrowT(int) noexcept(true) {} }; struct AnyConstructible { template <typename T> AnyConstructible(T&&) {} }; struct NoConstructible { NoConstructible() = delete; }; template <class T> struct RValueConvertibleFrom { RValueConvertibleFrom(T&&) {} }; void test_T_ctor_noexcept() { { using V = std::variant<Dummy, NoThrowT>; static_assert(std::is_nothrow_constructible<V, int>::value, ""); } { using V = std::variant<Dummy, ThrowsT>; static_assert(!std::is_nothrow_constructible<V, int>::value, ""); } } void test_T_ctor_sfinae() { { using V = std::variant<long, long long>; static_assert(!std::is_constructible<V, int>::value, "ambiguous"); } { using V = std::variant<std::string, std::string>; static_assert(!std::is_constructible<V, const char *>::value, "ambiguous"); } { using V = std::variant<std::string, void *>; static_assert(!std::is_constructible<V, int>::value, "no matching constructor"); } { using V = std::variant<std::string, float>; static_assert(std::is_constructible<V, int>::value == VariantAllowsNarrowingConversions, "no matching constructor"); } { using V = std::variant<std::unique_ptr<int>, bool>; static_assert(!std::is_constructible<V, std::unique_ptr<char>>::value, "no explicit bool in constructor"); struct X { operator void*(); }; static_assert(!std::is_constructible<V, X>::value, "no boolean conversion in constructor"); static_assert(!std::is_constructible<V, std::false_type>::value, "no converted to bool in constructor"); } { struct X {}; struct Y { operator X(); }; using V = std::variant<X>; static_assert(std::is_constructible<V, Y>::value, "regression on user-defined conversions in constructor"); } { using V = std::variant<AnyConstructible, NoConstructible>; static_assert( !std::is_constructible<V, std::in_place_type_t<NoConstructible>>::value, "no matching constructor"); static_assert(!std::is_constructible<V, std::in_place_index_t<1>>::value, "no matching constructor"); } #if !defined(TEST_VARIANT_HAS_NO_REFERENCES) { using V = std::variant<int, int &&>; static_assert(!std::is_constructible<V, int>::value, "ambiguous"); } { using V = std::variant<int, const int &>; static_assert(!std::is_constructible<V, int>::value, "ambiguous"); } #endif } void test_T_ctor_basic() { { constexpr std::variant<int> v(42); static_assert(v.index() == 0, ""); static_assert(std::get<0>(v) == 42, ""); } { constexpr std::variant<int, long> v(42l); static_assert(v.index() == 1, ""); static_assert(std::get<1>(v) == 42, ""); } #ifndef TEST_VARIANT_ALLOWS_NARROWING_CONVERSIONS { constexpr std::variant<unsigned, long> v(42); static_assert(v.index() == 1, ""); static_assert(std::get<1>(v) == 42, ""); } #endif { std::variant<std::string, bool const> v = "foo"; assert(v.index() == 0); assert(std::get<0>(v) == "foo"); } { std::variant<bool volatile, std::unique_ptr<int>> v = nullptr; assert(v.index() == 1); assert(std::get<1>(v) == nullptr); } { std::variant<bool volatile const, int> v = true; assert(v.index() == 0); assert(std::get<0>(v)); } { std::variant<RValueConvertibleFrom<int>> v1 = 42; assert(v1.index() == 0); int x = 42; std::variant<RValueConvertibleFrom<int>, AnyConstructible> v2 = x; assert(v2.index() == 1); } #if !defined(TEST_VARIANT_HAS_NO_REFERENCES) { using V = std::variant<const int &, int &&, long>; static_assert(std::is_convertible<int &, V>::value, "must be implicit"); int x = 42; V v(x); assert(v.index() == 0); assert(&std::get<0>(v) == &x); } { using V = std::variant<const int &, int &&, long>; static_assert(std::is_convertible<int, V>::value, "must be implicit"); int x = 42; V v(std::move(x)); assert(v.index() == 1); assert(&std::get<1>(v) == &x); } #endif } struct BoomOnAnything { template <class T> constexpr BoomOnAnything(T) { static_assert(!std::is_same<T, T>::value, ""); } }; void test_no_narrowing_check_for_class_types() { using V = std::variant<int, BoomOnAnything>; V v(42); assert(v.index() == 0); assert(std::get<0>(v) == 42); } struct Bar {}; struct Baz {}; void test_construction_with_repeated_types() { using V = std::variant<int, Bar, Baz, int, Baz, int, int>; static_assert(!std::is_constructible<V, int>::value, ""); static_assert(!std::is_constructible<V, Baz>::value, ""); // OK, the selected type appears only once and so it shouldn't // be affected by the duplicate types. static_assert(std::is_constructible<V, Bar>::value, ""); } int main(int, char**) { test_T_ctor_basic(); test_T_ctor_noexcept(); test_T_ctor_sfinae(); test_no_narrowing_check_for_class_types(); test_construction_with_repeated_types(); return 0; }
; A202829: E.g.f.: exp(4*x/(1-3*x)) / sqrt(1-9*x^2). ; Submitted by Jon Maiga ; 1,4,49,676,13225,293764,7890481,236359876,8052729169,300797402500,12388985000401,551925653637604,26614517015830969,1373655853915667716,75803216516463190225,4440662493517062816004,275697752917311709134241,18052104090118575573856516 mov $3,1 lpb $0 mul $1,$0 sub $0,1 mov $2,$3 add $3,$1 mov $1,3 mul $1,$2 sub $3,$1 lpe pow $3,2 mov $0,$3
; A279891: Triangle read by rows, T(n,k) = 2*n, with n>=k>=0. ; 0,2,2,4,4,4,6,6,6,6,8,8,8,8,8,10,10,10,10,10,10,12,12,12,12,12,12,12,14,14,14,14,14,14,14,14,16,16,16,16,16,16,16,16,16,18,18,18,18,18,18,18,18,18,18,20,20,20,20,20,20,20,20,20,20,20,22,22,22,22,22,22,22,22,22,22,22,22 lpb $0 add $1,1 sub $0,$1 lpe mul $1,2 mov $0,$1
db "FIVE STAR@" ; species name db "It is timid and" next "clusters together" next "with others. The" page "fluid secreted by" next "its feet indicates" next "its location.@"
MODULE set_sprite_tile PUBLIC set_sprite_tile PUBLIC _set_sprite_tile SECTION code_driver INCLUDE "target/gb/def/gb_globals.def" ; void __LIB__ set_sprite_tile(uint8_t nb, uint8_t tile) __smallc NONBANKED; set_sprite_tile: _set_sprite_tile: PUSH BC LD HL,sp+6 ; Skip return address and registers LD C,(HL) ; C = nb DEC HL DEC HL LD D,(HL) ; D = tile CALL set_sprite_tile_impl POP BC RET set_sprite_tile_impl: LD HL,OAM+2 ; Calculate origin of sprite info SLA C ; Multiply C by 4 SLA C LD B,0x00 ADD HL,BC LD A,D ; Set sprite number LD (HL),A RET
; stdio_error_edevnf_mc ; 06.2008 aralbrec PUBLIC stdio_error_edevnf_mc EXTERN stdio_errno_mc INCLUDE "../stdio.def" .stdio_error_edevnf_mc ld hl,EDEVNF jp stdio_errno_mc
// Tests calling into arrays of pointers to non-args no-return functions // Commodore 64 PRG executable file .file [name="function-pointer-noarg-call-5.prg", type="prg", segments="Program"] .segmentdef Program [segments="Basic, Code, Data"] .segmentdef Basic [start=$0801] .segmentdef Code [start=$80d] .segmentdef Data [startAfter="Code"] .segment Basic :BasicUpstart(main) .segment Code main: { .label i = 4 .label f = 2 lda #0 sta.z i __b2: // void (*f)() = fns[++i&1] inc.z i // ++i&1 lda #1 and.z i // void (*f)() = fns[++i&1] asl tay lda fns,y sta.z f lda fns+1,y sta.z f+1 // (*f)() jsr icall1 jmp __b2 icall1: jmp (f) } fn2: { .label BG_COLOR = $d021 // (*BG_COLOR)++; inc BG_COLOR // } rts } fn1: { .label BORDER_COLOR = $d020 // (*BORDER_COLOR)++; inc BORDER_COLOR // } rts } .segment Data // declare fns as array 2 of pointer to function (void) returning void fns: .word fn1, fn2
; A344055: a(n) = 2^n * n! * [x^n](exp(2*x) * BesselI(1, x)). ; Submitted by Jon Maiga ; 0,1,8,51,304,1770,10224,58947,340064,1964862,11374000,65966318,383289504,2230877428,13005037920,75923905635,443837331648,2597761611894,15221636471088,89283411393018,524194439193120,3080311943546124,18115458433730592,106618075368243534 mov $2,$0 trn $0,1 seq $0,5572 ; Number of walks on cubic lattice starting and finishing on the xy plane and never going below it. mul $0,$2
; =========== ! xmacro =========== start_21: call COMUCopyCode ld a,end_21-start_21-5 ld (hl),e inc hl ld (hl),d dec hl end_21: ret ; =========== * word =========== start_2a: call COMUCompileCallToSelf call MULTMultiply16 ret ; =========== + xmacro =========== start_2b: call COMUCopyCode ld a,end_2b-start_2b-5 add hl,de end_2b: ret ; =========== +! word =========== start_2b_21: call COMUCompileCallToSelf ld a,(hl) add a,e ld (hl),a inc hl ld a,(hl) adc a,d ld (hl),a dec hl ret ; =========== ++ xmacro =========== start_2b_2b: call COMUCopyCode ld a,end_2b_2b-start_2b_2b-5 inc hl end_2b_2b: ret ; =========== +++ xmacro =========== start_2b_2b_2b: call COMUCopyCode ld a,end_2b_2b_2b-start_2b_2b_2b-5 inc hl inc hl end_2b_2b_2b: ret ; =========== +or word =========== start_2b_6f_72: call COMUCompileCallToSelf ld a,h or d ld h,a ld a,l or e ld l,a ret ; =========== - xmacro =========== start_2d: call COMUCopyCode ld a,end_2d-start_2d-5 ld a,h cpl ld h,a ld a,l cpl ld l,a end_2d: ret ; =========== -- xmacro =========== start_2d_2d: call COMUCopyCode ld a,end_2d_2d-start_2d_2d-5 dec hl end_2d_2d: ret ; =========== --- xmacro =========== start_2d_2d_2d: call COMUCopyCode ld a,end_2d_2d_2d-start_2d_2d_2d-5 dec hl dec hl end_2d_2d_2d: ret ; =========== / word =========== start_2f: call COMUCompileCallToSelf push de call DIVDivideMod16 ex de,hl pop de ret ; =========== /mod word =========== start_2f_6d_6f_64: call COMUCompileCallToSelf call DIVDivideMod16 ex de,hl ret ; =========== 0= word =========== start_30_3d: call COMUCompileCallToSelf ld a,h or l ld hl,$0000 jr nz,__IsNotZero dec hl __IsNotZero: ret ; =========== 1, word =========== start_31_2c: call COMUCompileCallToSelf ld a,l call FARCompileByte ret ; =========== 2* xmacro =========== start_32_2a: call COMUCopyCode ld a,end_32_2a-start_32_2a-5 add hl,hl end_32_2a: ret ; =========== 2, word =========== start_32_2c: call COMUCompileCallToSelf call FARCompileWord ret ; =========== 2/ xmacro =========== start_32_2f: call COMUCopyCode ld a,end_32_2f-start_32_2f-5 sra h rr l end_32_2f: ret ; =========== ; macro =========== start_3b: nop call COMUCopyCode ld a,end_3b-start_3b-6 ret end_3b: ret ; =========== < word =========== start_3c: call COMUCompileCallToSelf ; checking if B < A ld a,h ; signs different ?? xor d jp m,__Less_DiffSigns push de ex de,hl ; HL = B, DE = A sbc hl,de ; calculate B-A, CS if -ve e.g. B < A pop de ld hl,$0000 ; so return 0 if B-A doesn't generate a borrow ret nc dec hl ret __Less_DiffSigns: bit 7,d ; if B bit 7 is set, -ve B must be < A ld hl,$0000 ret z ; so return zero if not set dec hl ret ret ; =========== = word =========== start_3d: call COMUCompileCallToSelf ld a,h ; D = H^D xor d ld h,a ld a,l ; A = L^E | H^D xor e or h ld hl,$0000 ; return 0 if any differences. ret nz dec hl ret ; =========== @ xmacro =========== start_40: call COMUCopyCode ld a,end_40-start_40-5 ld a,(hl) inc hl ld h,(hl) ld l,a end_40: ret ; =========== a>b xmacro =========== start_61_3e_62: call COMUCopyCode ld a,end_61_3e_62-start_61_3e_62-5 ld e,l ld d,h end_61_3e_62: ret ; =========== a>r macro =========== start_61_3e_72: nop call COMUCopyCode ld a,end_61_3e_72-start_61_3e_72-6 push hl end_61_3e_72: ret ; =========== ab>r macro =========== start_61_62_3e_72: nop call COMUCopyCode ld a,end_61_62_3e_72-start_61_62_3e_72-6 push hl push de end_61_62_3e_72: ret ; =========== abs word =========== start_61_62_73: call COMUCompileCallToSelf bit 7,h jp nz,__Negate ret ; =========== and word =========== start_61_6e_64: call COMUCompileCallToSelf ld a,h and d ld h,a ld a,l and e ld l,a ret ; =========== b>a xmacro =========== start_62_3e_61: call COMUCopyCode ld a,end_62_3e_61-start_62_3e_61-5 ld l,e ld h,d end_62_3e_61: ret ; =========== b>r macro =========== start_62_3e_72: nop call COMUCopyCode ld a,end_62_3e_72-start_62_3e_72-6 push de end_62_3e_72: ret ; =========== break macro =========== start_62_72_65_61_6b: nop call COMUCopyCode ld a,end_62_72_65_61_6b-start_62_72_65_61_6b-6 db $DD,$01 end_62_72_65_61_6b: ret ; =========== bswap xmacro =========== start_62_73_77_61_70: call COMUCopyCode ld a,end_62_73_77_61_70-start_62_73_77_61_70-5 ld a,h ld h,l ld l,a end_62_73_77_61_70: ret ; =========== c! xmacro =========== start_63_21: call COMUCopyCode ld a,end_63_21-start_63_21-5 ld (hl),e end_63_21: ret ; =========== c@ xmacro =========== start_63_40: call COMUCopyCode ld a,end_63_40-start_63_40-5 ld l,(hl) ld h,$00 end_63_40: ret ; =========== copy word =========== start_63_6f_70_79: call COMUCompileCallToSelf ; B (DE) = source A (HL) = target ld bc,(Parameter) ; get count ld a,b ; zero check or c jr z,__copyExit push de ; save A/B push hl xor a ; find direction. sbc hl,de ld a,h add hl,de bit 7,a ; if +ve use LDDR jr z,__copy2 ex de,hl ; LDIR etc do (DE) <- (HL) ldir jr __copyExit __copy2: add hl,bc ; add length to HL,DE, swap as LDDR does (DE) <- (HL) ex de,hl add hl,bc dec de ; -1 to point to last byte dec hl lddr __copyExit: pop hl pop de ret ; =========== crunch word =========== start_63_72_75_6e_63_68: call COMUCompileCallToSelf call DICTCrunchDictionary ret ; =========== debug word =========== start_64_65_62_75_67: call COMUCompileCallToSelf call DEBUGShow ret ; =========== fill word =========== start_66_69_6c_6c: call COMUCompileCallToSelf ld bc,(Parameter) ; count to do. ld a,b or c jr z,__fillExit ; if count zero exit. push de push hl __fillLoop: ld (hl),e inc hl dec bc ld a,b or c jr nz,__fillLoop __fillExit: pop hl pop de ret ; =========== h word =========== start_68: call COMUCompileCallToSelf ex de,hl ld hl,Here ret ; =========== halt word =========== start_68_61_6c_74: call COMUCompileCallToSelf __haltz80: db $DD,$00 ; in CSpect emulator exits. di halt jr __haltz80 ret ; =========== here word =========== start_68_65_72_65: call COMUCompileCallToSelf ex de,hl ld hl,(Here) ret ; =========== hex! word =========== start_68_65_78_21: call COMUCompileCallToSelf ; DE = word, HL = pos call GFXWriteHexWord ; write out the word ret ; =========== inkey word =========== start_69_6e_6b_65_79: call COMUCompileCallToSelf ex de,hl call IOScanKeyboard ld l,a ld h,0 ret ; =========== mod word =========== start_6d_6f_64: call COMUCompileCallToSelf push de call DIVDivideMod16 pop de ret ; =========== negate word =========== start_6e_65_67_61_74_65: call COMUCompileCallToSelf __Negate: ld a,h cpl ld h,a ld a,l cpl ld l,a inc hl ret ; =========== or word =========== start_6f_72: call COMUCompileCallToSelf ld a,h xor d ld h,a ld a,l xor e ld l,a ret ; =========== or! word =========== start_6f_72_21: call COMUCompileCallToSelf ld a,(hl) or e ld (hl),a inc hl ld a,(hl) or d ld (hl),a dec hl ret ; =========== p! xmacro =========== start_70_21: call COMUCopyCode ld a,end_70_21-start_70_21-5 ld c,l ld b,h out (c),e end_70_21: ret ; =========== p@ word =========== start_70_40: call COMUCompileCallToSelf ld c,l ld b,h in l,(c) ld h,0 ret ; =========== param! word =========== start_70_61_72_61_6d_21: call COMUCompileCallToSelf ld (Parameter),hl ret ; =========== pop macro =========== start_70_6f_70: nop call COMUCopyCode ld a,end_70_6f_70-start_70_6f_70-6 ex de,hl pop hl end_70_6f_70: ret ; =========== push macro =========== start_70_75_73_68: nop call COMUCopyCode ld a,end_70_75_73_68-start_70_75_73_68-6 push hl end_70_75_73_68: ret ; =========== r>a macro =========== start_72_3e_61: nop call COMUCopyCode ld a,end_72_3e_61-start_72_3e_61-6 pop hl end_72_3e_61: ret ; =========== r>ab macro =========== start_72_3e_61_62: nop call COMUCopyCode ld a,end_72_3e_61_62-start_72_3e_61_62-6 pop de pop hl end_72_3e_61_62: ret ; =========== r>b macro =========== start_72_3e_62: nop call COMUCopyCode ld a,end_72_3e_62-start_72_3e_62-6 pop de end_72_3e_62: ret ; =========== save.memory word =========== start_73_61_76_65_2e_6d_65_6d_6f_72_79: call COMUCompileCallToSelf call SAVEMemory ret ; =========== screen! word =========== start_73_63_72_65_65_6e_21: call COMUCompileCallToSelf call GFXWriteCharacter ret ; =========== screen.mode word =========== start_73_63_72_65_65_6e_2e_6d_6f_64_65: call COMUCompileCallToSelf ld a,l ; set the screen mode to A call GFXMode ret ; =========== swap xmacro =========== start_73_77_61_70: call COMUCopyCode ld a,end_73_77_61_70-start_73_77_61_70-5 ex de,hl ; 2nd now TOS end_73_77_61_70: ret ; =========== sys.info word =========== start_73_79_73_2e_69_6e_66_6f: call COMUCompileCallToSelf ex de,hl ld hl,SystemInformation ret
; void __CALLEE__ sp1_ClearRectInv_callee(struct sp1_Rect *r, uchar colour, uchar tile, uchar rflag) ; 03.2006 aralbrec, Sprite Pack v3.0 ; sinclair spectrum version PUBLIC sp1_ClearRectInv_callee PUBLIC ASMDISP_SP1_CLEARRECTINV_CALLEE EXTERN sp1_GetUpdateStruct_callee, sp1_ClearRect_callee, l_jpix EXTERN ASMDISP_SP1_GETUPDATESTRUCT_CALLEE, ASMDISP_SP1CRSELECT EXTERN SP1V_DISPWIDTH, SP1V_UPDATELISTT .sp1_ClearRectInv_callee pop af pop bc pop hl pop de ld h,e pop de push af ld a,c push hl ex de,hl ld d,(hl) inc hl ld e,(hl) inc hl ld b,(hl) inc hl ld c,(hl) pop hl .asmentry ; Clear a rectangular area on screen, erasing sprites, ; changing tile and changing colour depending on flags. ; Invalidate the area so that it is drawn in the next update. ; ; enter : d = row coord ; e = col coord ; b = width ; c = height ; h = attr ; l = tile ; a = bit 0 set for tiles, bit 1 set for tile colours, bit 2 set for sprites ; uses : af, bc, de, hl, af', ix, iy .SP1ClearRectInv and $07 ret z ; ret if all flags reset push hl call sp1_ClearRect_callee + ASMDISP_SP1CRSELECT ; ix = address of operation code (depending on flags passed in) call sp1_GetUpdateStruct_callee + ASMDISP_SP1_GETUPDATESTRUCT_CALLEE ; hl = & struct update pop de ; d = attr, e = tile ld iy,(SP1V_UPDATELISTT) ; iy = last struct sp1_update in draw queue .rowloop push bc ; save b = width push hl ; save update position .colloop ld a,$80 xor (hl) jp p, alreadyinv ; if this update struct already invalidated, skip ahead ld (hl),a ld (iy+6),h ; store link in last invalidated update struct to this struct update ld (iy+7),l ld a,l ; make this update struct the last one in invalidated list ld iyl,a ; "ld iyl,l" is likely taken as "ld iyl,iyl" ld a,h ld iyh,a .alreadyinv call l_jpix ; apply operation on hl, advance hl to next struct sp1_update to the right djnz colloop pop hl ld bc,10*SP1V_DISPWIDTH add hl,bc pop bc dec c jp nz, rowloop ld (iy+6),0 ld (SP1V_UPDATELISTT),iy ret DEFC ASMDISP_SP1_CLEARRECTINV_CALLEE = asmentry - sp1_ClearRectInv_callee
.byte $00 ; Unknown purpose .byte OBJ_AUTOSCROLL, $00, $03 .byte OBJ_CLOUDSINBGBEGIN, $01, $03 .byte OBJ_CFIRE_ULCANNON, $17, $0F .byte OBJ_FIREJET_LEFT, $18, $0D .byte OBJ_CFIRE_HLCANNON2, $24, $15 .byte OBJ_CFIRE_HLCANNON2, $27, $15 .byte OBJ_CFIRE_BULLETBILL, $2D, $0C .byte OBJ_CFIRE_URCANNON2, $38, $07 .byte OBJ_CFIRE_LLCANNON2, $3C, $08 .byte OBJ_CFIRE_HLCANNON2, $44, $0F .byte OBJ_CFIRE_4WAY, $49, $0A .byte OBJ_CFIRE_URCANNON2, $4E, $0D .byte OBJ_CFIRE_URCANNON2, $5D, $0A .byte OBJ_CFIRE_ULCANNON2, $5F, $10 .byte OBJ_CFIRE_BULLETBILL, $5A, $0E .byte OBJ_CFIRE_URCANNON2, $61, $0A .byte OBJ_CFIRE_ULCANNON2, $62, $10 .byte OBJ_CFIRE_LLCANNON2, $66, $0A .byte OBJ_CFIRE_HLCANNON2, $65, $10 .byte OBJ_CFIRE_LLCANNON2, $6A, $0A .byte OBJ_CFIRE_HLCANNON2, $68, $10 .byte OBJ_CFIRE_BULLETBILL, $70, $0C .byte $FF ; Terminator
#include "vapor/glutil.h" // Must be included first!!! #include "vapor/ShaderProgram.h" #include "vapor/FileUtils.h" #include "vapor/VAssert.h" #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <vapor/Shader.h> #include <vapor/Texture.h> using namespace VAPoR; using std::vector; using std::string; ShaderProgram::Policy ShaderProgram::UniformNotFoundPolicy = ShaderProgram::Policy::Relaxed; ShaderProgram::ShaderProgram() : _linked(false), _successStatus(false) {} ShaderProgram::~ShaderProgram() { if (_id) glDeleteProgram(_id); for (int i = 0; i < _shaders.size(); i++) if (_shaders[i]) delete _shaders[i]; } int ShaderProgram::Link() { if (_linked) { return 1; } _id = glCreateProgram(); VAssert(_id); for (auto it = _shaders.begin(); it != _shaders.end(); it++) { if(*it == nullptr || !(*it)->WasCompilationSuccessful()) { return -1; } glAttachShader(_id, (*it)->GetID()); } glLinkProgram(_id); glGetProgramiv(_id, GL_LINK_STATUS, &_successStatus); _linked = true; for (int i = 0; i < _shaders.size(); i++) delete _shaders[i]; _shaders.clear(); if (!_successStatus) return -1; ComputeSamplerLocations(); return 1; } void ShaderProgram::Bind() { if (WasLinkingSuccessful()) glUseProgram(_id); } bool ShaderProgram::IsBound() const { return _id == GetBoundProgramID(); } void ShaderProgram::UnBind() { glUseProgram(0); } int ShaderProgram::GetBoundProgramID() { int currentlyBoundProgramId; glGetIntegerv(GL_CURRENT_PROGRAM, &currentlyBoundProgramId); return currentlyBoundProgramId; } void ShaderProgram::AddShader(Shader *s) { if (_linked) { SetErrMsg("Program already linked"); return; } _shaders.push_back(s); } int ShaderProgram::AddShaderFromSource(unsigned int type, const char *source) { Shader *s = new Shader(type); int ret = s->CompileFromSource(source); _shaders.push_back(s); return ret; } /* bool ShaderProgram::AddShaderFromFile(unsigned int type, const std::string path) { Shader *s = new Shader(type); bool ret = s->CompileFromSource(FileUtils::ReadFileToString(path)); _shaders.push_back(s); return ret; } */ unsigned int ShaderProgram::GetID() const { return _id; } unsigned int ShaderProgram::WasLinkingSuccessful() const { return _successStatus; } int ShaderProgram::GetAttributeLocation(const std::string &name) const { return glGetAttribLocation(_id, name.c_str()); } int ShaderProgram::GetUniformLocation(const std::string &name) const { return glGetUniformLocation(_id, name.c_str()); } bool ShaderProgram::HasUniform(const std::string &name) const { return GetUniformLocation(name) != -1; } template<typename T> bool ShaderProgram::SetUniform(const std::string &name, const T &value) const { // if ((typeid(T) == typeid(int)) && _samplerLocations.count(name)) printf("%s set to %i\n", name.c_str(), *(int*)((void*)&value)); if (!IsBound()) { VAssert(!"Program not bound"); return false; } const int location = glGetUniformLocation(_id, name.c_str()); if (location == -1) { // printf("Uniform \"%s\" not found\n", name.c_str()); if (UniformNotFoundPolicy == Policy::Strict) VAssert(!"Uniform name not found"); return false; } SetUniform(location, value); return true; } template bool ShaderProgram::SetUniform <int>(const std::string &name, const int &value) const; template bool ShaderProgram::SetUniform <bool>(const std::string &name, const bool &value) const; template bool ShaderProgram::SetUniform <float>(const std::string &name, const float &value) const; template bool ShaderProgram::SetUniform <glm::vec2>(const std::string &name, const glm::vec2 &value) const; template bool ShaderProgram::SetUniform <glm::vec3>(const std::string &name, const glm::vec3 &value) const; template bool ShaderProgram::SetUniform <glm::vec4>(const std::string &name, const glm::vec4 &value) const; template bool ShaderProgram::SetUniform <glm::mat4>(const std::string &name, const glm::mat4 &value) const; template bool ShaderProgram::SetUniform <glm::ivec2>(const std::string &name, const glm::ivec2 &value) const; template bool ShaderProgram::SetUniform <glm::ivec3>(const std::string &name, const glm::ivec3 &value) const; template bool ShaderProgram::SetUniform<vector<float>>(const std::string &name, const vector<float> &value) const; void ShaderProgram::SetUniform(int location, const int &value) const { glUniform1i(location, value); } void ShaderProgram::SetUniform(int location, const float &value) const { glUniform1f(location, value); } void ShaderProgram::SetUniform(int location, const glm::vec2 &value) const { glUniform2fv(location, 1, glm::value_ptr(value)); } void ShaderProgram::SetUniform(int location, const glm::vec3 &value) const { glUniform3fv(location, 1, glm::value_ptr(value)); } void ShaderProgram::SetUniform(int location, const glm::vec4 &value) const { glUniform4fv(location, 1, glm::value_ptr(value)); } void ShaderProgram::SetUniform(int location, const glm::mat4 &value) const { glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(value)); } void ShaderProgram::SetUniform(int location, const glm::ivec2 &value) const { glUniform2iv(location, 1, glm::value_ptr(value)); } void ShaderProgram::SetUniform(int location, const glm::ivec3 &value) const { glUniform3iv(location, 1, glm::value_ptr(value)); } void ShaderProgram::SetUniform(int location, const vector<float> &value) const { glUniform1fv(location, value.size(), value.data()); } template<typename T> void ShaderProgram::SetUniformArray(const std::string &name, int count, const T *values) const { SetUniformArray(GetUniformLocation(name), count, values); } template void ShaderProgram::SetUniformArray <int>(const std::string &name, int count, const int *values) const; template void ShaderProgram::SetUniformArray <float>(const std::string &name, int count, const float *values) const; template void ShaderProgram::SetUniformArray<glm::vec3>(const std::string &name, int count, const glm::vec3 *values) const; template void ShaderProgram::SetUniformArray<glm::vec4>(const std::string &name, int count, const glm::vec4 *values) const; void ShaderProgram::SetUniformArray(int location, int count, const int *values) const { glUniform1iv(location, count, values); } void ShaderProgram::SetUniformArray(int location, int count, const float *values) const { glUniform1fv(location, count, values); } void ShaderProgram::SetUniformArray(int location, int count, const glm::vec3 *values) const { glUniform3fv(location, count, (float *)values); } void ShaderProgram::SetUniformArray(int location, int count, const glm::vec4 *values) const { glUniform4fv(location, count, (float *)values); } template<typename T> bool ShaderProgram::SetSampler(const std::string &name, const T &value) const { auto itr = _samplerLocations.find(name); if (itr == _samplerLocations.end()) return false; int textureUnit = itr->second; glActiveTexture(GL_TEXTURE0 + textureUnit); value.Bind(); SetUniform(name, textureUnit); glActiveTexture(GL_TEXTURE0); return true; } template bool ShaderProgram::SetSampler <Texture1D> (const std::string &name, const Texture1D &value) const; template bool ShaderProgram::SetSampler <Texture2D> (const std::string &name, const Texture2D &value) const; template bool ShaderProgram::SetSampler <Texture3D> (const std::string &name, const Texture3D &value) const; template bool ShaderProgram::SetSampler <Texture2DArray>(const std::string &name, const Texture2DArray &value) const; std::string ShaderProgram::GetLog() const { if (_linked) { char buf[512]; glGetProgramInfoLog(_id, 512, NULL, buf); return std::string(buf); } else { if (_shaders.empty()) return "Cannot linked because there are no shaders"; else return "Cannot link because shader failed to compile"; } } void ShaderProgram::PrintUniforms() const { GLint count; GLint size; GLenum type; char name[64]; int nameLength; glGetProgramiv(_id, GL_ACTIVE_UNIFORMS, &count); for (int i = 0; i < count; i++) { glGetActiveUniform(_id, i, 64, &nameLength, &size, &type, name); printf("%s %s\n", GLTypeToString(type), name); } } void ShaderProgram::ComputeSamplerLocations() { GLint count; GLint size; GLenum type; char name[128]; int nameLength; int samplerId = 1; // Starting at 1 fixes some super weird GL bug glGetProgramiv(_id, GL_ACTIVE_UNIFORMS, &count); for (int i = 0; i < count; i++) { glGetActiveUniform(_id, i, 128, &nameLength, &size, &type, name); if (IsGLTypeSampler(type)) _samplerLocations[string(name)] = samplerId++; } VAssert(samplerId <= GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1); } const char *ShaderProgram::GLTypeToString(const unsigned int type) { switch (type) { case GL_FLOAT: return "float"; case GL_FLOAT_VEC2: return "vec2"; case GL_FLOAT_VEC3: return "vec3"; case GL_FLOAT_VEC4: return "vec4"; case GL_DOUBLE: return "double"; case GL_DOUBLE_VEC2: return "dvec2"; case GL_DOUBLE_VEC3: return "dvec3"; case GL_DOUBLE_VEC4: return "dvec4"; case GL_INT: return "int"; case GL_INT_VEC2: return "ivec2"; case GL_INT_VEC3: return "ivec3"; case GL_INT_VEC4: return "ivec4"; case GL_UNSIGNED_INT: return "unsigned int"; case GL_UNSIGNED_INT_VEC2: return "uvec2"; case GL_UNSIGNED_INT_VEC3: return "uvec3"; case GL_UNSIGNED_INT_VEC4: return "uvec4"; case GL_BOOL: return "bool"; case GL_BOOL_VEC2: return "bvec2"; case GL_BOOL_VEC3: return "bvec3"; case GL_BOOL_VEC4: return "bvec4"; case GL_FLOAT_MAT2: return "mat2"; case GL_FLOAT_MAT3: return "mat3"; case GL_FLOAT_MAT4: return "mat4"; case GL_FLOAT_MAT2x3: return "mat2x3"; case GL_FLOAT_MAT2x4: return "mat2x4"; case GL_FLOAT_MAT3x2: return "mat3x2"; case GL_FLOAT_MAT3x4: return "mat3x4"; case GL_FLOAT_MAT4x2: return "mat4x2"; case GL_FLOAT_MAT4x3: return "mat4x3"; case GL_DOUBLE_MAT2: return "dmat2"; case GL_DOUBLE_MAT3: return "dmat3"; case GL_DOUBLE_MAT4: return "dmat4"; case GL_DOUBLE_MAT2x3: return "dmat2x3"; case GL_DOUBLE_MAT2x4: return "dmat2x4"; case GL_DOUBLE_MAT3x2: return "dmat3x2"; case GL_DOUBLE_MAT3x4: return "dmat3x4"; case GL_DOUBLE_MAT4x2: return "dmat4x2"; case GL_DOUBLE_MAT4x3: return "dmat4x3"; case GL_SAMPLER_1D: return "sampler1D"; case GL_SAMPLER_2D: return "sampler2D"; case GL_SAMPLER_3D: return "sampler3D"; case GL_SAMPLER_CUBE: return "samplerCube"; case GL_SAMPLER_1D_SHADOW: return "sampler1DShadow"; case GL_SAMPLER_2D_SHADOW: return "sampler2DShadow"; case GL_SAMPLER_1D_ARRAY: return "sampler1DArray"; case GL_SAMPLER_2D_ARRAY: return "sampler2DArray"; case GL_SAMPLER_1D_ARRAY_SHADOW: return "sampler1DArrayShadow"; case GL_SAMPLER_2D_ARRAY_SHADOW: return "sampler2DArrayShadow"; case GL_SAMPLER_2D_MULTISAMPLE: return "sampler2DMS"; case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: return "sampler2DMSArray"; case GL_SAMPLER_CUBE_SHADOW: return "samplerCubeShadow"; case GL_SAMPLER_BUFFER: return "samplerBuffer"; case GL_SAMPLER_2D_RECT: return "sampler2DRect"; case GL_SAMPLER_2D_RECT_SHADOW: return "sampler2DRectShadow"; case GL_INT_SAMPLER_1D: return "isampler1D"; case GL_INT_SAMPLER_2D: return "isampler2D"; case GL_INT_SAMPLER_3D: return "isampler3D"; case GL_INT_SAMPLER_CUBE: return "isamplerCube"; case GL_INT_SAMPLER_1D_ARRAY: return "isampler1DArray"; case GL_INT_SAMPLER_2D_ARRAY: return "isampler2DArray"; case GL_INT_SAMPLER_2D_MULTISAMPLE: return "isampler2DMS"; case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: return "isampler2DMSArray"; case GL_INT_SAMPLER_BUFFER: return "isamplerBuffer"; case GL_INT_SAMPLER_2D_RECT: return "isampler2DRect"; case GL_UNSIGNED_INT_SAMPLER_1D: return "usampler1D"; case GL_UNSIGNED_INT_SAMPLER_2D: return "usampler2D"; case GL_UNSIGNED_INT_SAMPLER_3D: return "usampler3D"; case GL_UNSIGNED_INT_SAMPLER_CUBE: return "usamplerCube"; case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: return "usampler2DArray"; case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: return "usampler2DArray"; case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: return "usampler2DMS"; case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: return "usampler2DMSArray"; case GL_UNSIGNED_INT_SAMPLER_BUFFER: return "usamplerBuffer"; case GL_UNSIGNED_INT_SAMPLER_2D_RECT: return "usampler2DRect"; #ifdef GL_IMAGE_1D case GL_IMAGE_1D: return "image1D"; case GL_IMAGE_2D: return "image2D"; case GL_IMAGE_3D: return "image3D"; case GL_IMAGE_2D_RECT: return "image2DRect"; case GL_IMAGE_CUBE: return "imageCube"; case GL_IMAGE_BUFFER: return "imageBuffer"; case GL_IMAGE_1D_ARRAY: return "image1DArray"; case GL_IMAGE_2D_ARRAY: return "image2DArray"; case GL_IMAGE_2D_MULTISAMPLE: return "image2DMS"; case GL_IMAGE_2D_MULTISAMPLE_ARRAY: return "image2DMSArray"; case GL_INT_IMAGE_1D: return "iimage1D"; case GL_INT_IMAGE_2D: return "iimage2D"; case GL_INT_IMAGE_3D: return "iimage3D"; case GL_INT_IMAGE_2D_RECT: return "iimage2DRect"; case GL_INT_IMAGE_CUBE: return "iimageCube"; case GL_INT_IMAGE_BUFFER: return "iimageBuffer"; case GL_INT_IMAGE_1D_ARRAY: return "iimage1DArray"; case GL_INT_IMAGE_2D_ARRAY: return "iimage2DArray"; case GL_INT_IMAGE_2D_MULTISAMPLE: return "iimage2DMS"; case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY: return "iimage2DMSArray"; case GL_UNSIGNED_INT_IMAGE_1D: return "uimage1D"; case GL_UNSIGNED_INT_IMAGE_2D: return "uimage2D"; case GL_UNSIGNED_INT_IMAGE_3D: return "uimage3D"; case GL_UNSIGNED_INT_IMAGE_2D_RECT: return "uimage2DRect"; case GL_UNSIGNED_INT_IMAGE_CUBE: return "uimageCube"; case GL_UNSIGNED_INT_IMAGE_BUFFER: return "uimageBuffer"; case GL_UNSIGNED_INT_IMAGE_1D_ARRAY: return "uimage1DArray"; case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: return "uimage2DArray"; case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: return "uimage2DMS"; case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: return "uimage2DMSArray"; case GL_UNSIGNED_INT_ATOMIC_COUNTER: return "atomic_uint"; #endif default: return "INVALID ENUM"; } } bool ShaderProgram::IsGLTypeSampler(const unsigned int type) { switch (type) { case GL_SAMPLER_1D: case GL_SAMPLER_2D: case GL_SAMPLER_3D: case GL_SAMPLER_CUBE: case GL_SAMPLER_1D_SHADOW: case GL_SAMPLER_2D_SHADOW: case GL_SAMPLER_1D_ARRAY: case GL_SAMPLER_2D_ARRAY: case GL_SAMPLER_1D_ARRAY_SHADOW: case GL_SAMPLER_2D_ARRAY_SHADOW: case GL_SAMPLER_2D_MULTISAMPLE: case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: case GL_SAMPLER_CUBE_SHADOW: case GL_SAMPLER_BUFFER: case GL_SAMPLER_2D_RECT: case GL_SAMPLER_2D_RECT_SHADOW: case GL_INT_SAMPLER_1D: case GL_INT_SAMPLER_2D: case GL_INT_SAMPLER_3D: case GL_INT_SAMPLER_CUBE: case GL_INT_SAMPLER_1D_ARRAY: case GL_INT_SAMPLER_2D_ARRAY: case GL_INT_SAMPLER_2D_MULTISAMPLE: case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case GL_INT_SAMPLER_BUFFER: case GL_INT_SAMPLER_2D_RECT: case GL_UNSIGNED_INT_SAMPLER_1D: case GL_UNSIGNED_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_CUBE: case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: case GL_UNSIGNED_INT_SAMPLER_BUFFER: case GL_UNSIGNED_INT_SAMPLER_2D_RECT: return true; default: return false; } } SmartShaderProgram::SmartShaderProgram(ShaderProgram *program) : _program(program) { if (_program) _program->Bind(); } SmartShaderProgram::~SmartShaderProgram() { if (_program) _program->UnBind(); } bool SmartShaderProgram::IsValid() const { return _program; }
AREA |.text|, CODE, READONLY GLOBAL |rust_psm_stack_direction| ALIGN 4 |rust_psm_stack_direction| PROC orr w0, wzr, #2 ret ENDP GLOBAL |rust_psm_stack_pointer| ALIGN 4 |rust_psm_stack_pointer| PROC mov x0, sp ret ENDP GLOBAL |rust_psm_replace_stack| ALIGN 4 |rust_psm_replace_stack| PROC mov sp, x2 br x1 ENDP GLOBAL |rust_psm_on_stack| ALIGN 4 |rust_psm_on_stack| PROC stp x29, x30, [sp, #-16]! mov x29, sp mov sp, x3 blr x2 mov sp, x29 ldp x29, x30, [sp], #16 ret ENDP END
Music_ChampionBattle: musicheader 3, 1, Music_ChampionBattle_Ch1 musicheader 1, 2, Music_ChampionBattle_Ch2 musicheader 1, 3, Music_ChampionBattle_Ch3 Music_ChampionBattle_Ch1: tempo 98 volume $77 dutycycle $3 tone $0002 vibrato $12, $15 notetype $c, $b2 octave 2 note A#, 8 note A#, 8 note A#, 8 note A#, 4 intensity $b7 note B_, 4 Music_ChampionBattle_branch_ea9e2: callchannel Music_ChampionBattle_branch_eaaee octave 3 note D#, 4 loopchannel 2, Music_ChampionBattle_branch_ea9e2 callchannel Music_ChampionBattle_branch_eaaee octave 3 note E_, 4 Music_ChampionBattle_branch_ea9f0: callchannel Music_ChampionBattle_branch_eaafc loopchannel 3, Music_ChampionBattle_branch_ea9f0 callchannel Music_ChampionBattle_branch_eab06 Music_ChampionBattle_branch_ea9fa: callchannel Music_ChampionBattle_branch_eaafc loopchannel 7, Music_ChampionBattle_branch_ea9fa callchannel Music_ChampionBattle_branch_eab06 intensity $b2 note A#, 2 note A#, 2 intensity $b7 octave 3 note D#, 4 intensity $b2 octave 2 note A#, 2 note A#, 2 intensity $b7 octave 3 note E_, 4 intensity $b2 octave 2 note A#, 2 note A#, 2 intensity $b7 octave 3 note F#, 4 intensity $b2 octave 2 note A#, 2 note A#, 2 intensity $b7 octave 3 note G#, 4 intensity $a0 note A#, 8 octave 2 note A#, 8 octave 3 note B_, 12 intensity $b2 note A#, 1 note B_, 1 octave 4 note C_, 1 note C#, 1 Music_ChampionBattle_branch_eaa35: callchannel Music_ChampionBattle_branch_eab0f note E_, 2 note E_, 2 intensity $b7 note F#, 4 Music_ChampionBattle_branch_eaa3d: intensity $b2 note E_, 2 note E_, 2 intensity $b7 note G#, 4 loopchannel 2, Music_ChampionBattle_branch_eaa3d intensity $b2 note E_, 2 note E_, 2 intensity $b7 note B_, 4 callchannel Music_ChampionBattle_branch_eab0f note E_, 2 note E_, 2 intensity $b7 note F#, 4 intensity $b2 note E_, 2 note E_, 2 intensity $b7 note G#, 4 intensity $b2 note E_, 2 note E_, 2 intensity $b7 note B_, 4 intensity $b2 note E_, 2 note E_, 2 intensity $b7 octave 4 note E_, 4 callchannel Music_ChampionBattle_branch_eab24 note B_, 4 note G#, 4 callchannel Music_ChampionBattle_branch_eab24 octave 4 note D_, 4 note D_, 4 intensity $a0 octave 3 note A#, 8 octave 2 note A#, 8 octave 3 note F#, 8 octave 2 note F#, 8 intensity $60 note B_, 16 intensity $70 note B_, 16 intensity $80 octave 3 note C#, 16 intensity $a0 note D#, 16 intensity $b4 octave 4 note F#, 4 note F_, 4 note E_, 4 note D#, 4 note D_, 4 note C#, 4 note F#, 4 note F#, 4 note F#, 4 note F_, 4 note E_, 4 note D#, 4 note F#, 2 note G#, 2 note D#, 2 note E_, 2 note F#, 4 note F#, 4 note __, 16 intensity $90 octave 3 note F#, 8 intensity $b4 note E_, 4 note E_, 4 intensity $90 note D#, 16 note C#, 16 Music_ChampionBattle_branch_eaab1: intensity $b2 octave 2 note A#, 2 note A#, 2 intensity $b7 octave 3 note D#, 4 loopchannel 4, Music_ChampionBattle_branch_eaab1 Music_ChampionBattle_branch_eaabe: intensity $b2 note C_, 2 note C_, 2 intensity $b7 note D#, 4 loopchannel 2, Music_ChampionBattle_branch_eaabe intensity $b2 note C_, 2 note C_, 2 intensity $b7 note F#, 4 intensity $b2 note C_, 2 note C_, 2 intensity $b7 note G#, 4 callchannel Music_ChampionBattle_branch_eab31 octave 3 note D#, 2 note D#, 2 intensity $b7 note B_, 4 callchannel Music_ChampionBattle_branch_eab31 octave 3 note D#, 2 note D#, 2 intensity $b7 octave 4 note D_, 4 loopchannel 0, Music_ChampionBattle_branch_eaa35 Music_ChampionBattle_branch_eaaee: intensity $b2 octave 2 note A#, 2 note A#, 6 note A#, 2 note A#, 6 note A#, 2 note A#, 6 note A#, 2 note A#, 2 intensity $b7 endchannel Music_ChampionBattle_branch_eaafc: intensity $b2 octave 2 note A#, 2 note A#, 2 intensity $b7 octave 3 note D#, 4 endchannel Music_ChampionBattle_branch_eab06: intensity $b2 octave 2 note A#, 2 note A#, 2 intensity $b7 note B_, 4 endchannel Music_ChampionBattle_branch_eab0f: intensity $b5 octave 3 note D#, 2 note A#, 2 note D#, 2 note F#, 4 note F_, 2 note E_, 2 note B_, 2 note F#, 2 note A#, 2 note F_, 2 note A_, 2 note E_, 2 note G#, 2 note D#, 2 note G_, 2 intensity $b2 endchannel Music_ChampionBattle_branch_eab24: intensity $b2 octave 3 note A#, 2 note A#, 4 note A#, 4 note A#, 4 note A#, 4 note A#, 4 note A#, 2 intensity $b7 endchannel Music_ChampionBattle_branch_eab31: intensity $b2 note D#, 2 note D#, 2 intensity $b7 note A#, 4 intensity $b2 note D#, 2 note D#, 2 intensity $b7 note B_, 4 intensity $b2 note D#, 2 note D#, 2 intensity $b7 octave 4 note C#, 4 intensity $b2 endchannel Music_ChampionBattle_Ch2: dutycycle $3 vibrato $8, $36 tone $0001 notetype $c, $c2 octave 3 note D#, 8 note D#, 8 note D#, 8 note D#, 4 intensity $c7 note D_, 4 callchannel Music_ChampionBattle_branch_eac4f note A#, 4 callchannel Music_ChampionBattle_branch_eac4f note B_, 4 callchannel Music_ChampionBattle_branch_eac4f octave 4 note C#, 4 callchannel Music_ChampionBattle_branch_eac5c note D_, 4 callchannel Music_ChampionBattle_branch_eac5c note F_, 4 callchannel Music_ChampionBattle_branch_eac5c note D_, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 note A#, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 note B_, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 octave 4 note C_, 4 intensity $c2 octave 3 note D#, 2 note D#, 2 intensity $c7 octave 4 note C#, 4 note D#, 8 octave 3 note D#, 8 octave 4 note E_, 8 intensity $3c note E_, 8 Music_ChampionBattle_branch_eab9d: intensity $c5 note D#, 6 octave 3 note A#, 6 octave 4 note D#, 2 note D_, 2 note C#, 4 note C_, 4 octave 3 note B_, 4 note A#, 4 intensity $c7 note B_, 8 octave 4 note E_, 8 intensity $c2 octave 3 note G#, 2 note G#, 2 intensity $c7 note B_, 4 intensity $c2 note G#, 2 note G#, 2 intensity $c7 octave 4 note C#, 4 intensity $c5 note D#, 6 octave 3 note A#, 6 octave 4 note D#, 2 note D_, 2 note C#, 4 note C_, 4 octave 3 note B_, 4 note A#, 2 note B_, 2 intensity $c7 octave 4 note E_, 8 note G#, 8 note E_, 8 note B_, 8 callchannel Music_ChampionBattle_branch_eac79 note E_, 4 note E_, 4 callchannel Music_ChampionBattle_branch_eac79 note F#, 4 note F#, 4 intensity $c7 note D#, 8 octave 3 note D#, 8 octave 4 note C#, 8 octave 3 note C#, 8 intensity $b0 note D#, 16 note D#, 16 note F_, 16 note F#, 16 intensity $c4 Music_ChampionBattle_branch_eabef: octave 5 note D#, 4 note D_, 4 note C#, 4 note C_, 4 note D#, 2 note D_, 2 note C#, 2 note C_, 2 octave 4 note B_, 4 note B_, 4 loopchannel 2, Music_ChampionBattle_branch_eabef intensity $b0 octave 3 note D#, 16 note B_, 16 note A#, 16 note G#, 16 intensity $c2 note D#, 2 note D#, 2 intensity $c7 note A#, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 note B_, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 note A#, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 note A_, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 note A#, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 note B_, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 octave 4 note C#, 4 intensity $c2 octave 3 note D#, 2 note D#, 2 intensity $c7 octave 4 note D_, 4 intensity $b0 note D#, 8 note E_, 8 note F#, 8 note E_, 8 note D#, 8 note E_, 8 note F#, 8 note G#, 8 loopchannel 0, Music_ChampionBattle_branch_eab9d Music_ChampionBattle_branch_eac4f: intensity $c2 note D#, 2 note D#, 6 note D#, 2 note D#, 6 note D#, 2 note D#, 6 note D#, 2 note D#, 2 intensity $c7 endchannel Music_ChampionBattle_branch_eac5c: intensity $c2 octave 3 note D#, 2 note D#, 2 intensity $c7 note A#, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 note B_, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 note A#, 4 intensity $c2 note D#, 2 note D#, 2 intensity $c7 endchannel Music_ChampionBattle_branch_eac79: intensity $c1 note D#, 2 note D#, 4 note D#, 4 note D#, 4 note D#, 4 note D#, 4 note D#, 2 intensity $c5 endchannel Music_ChampionBattle_Ch3: notetype $c, $14 Music_ChampionBattle_branch_eac88: octave 3 note D#, 1 note __, 7 loopchannel 3, Music_ChampionBattle_branch_eac88 note D#, 1 note __, 3 note E_, 4 callchannel Music_ChampionBattle_branch_ead61 callchannel Music_ChampionBattle_branch_ead61 callchannel Music_ChampionBattle_branch_ead61 callchannel Music_ChampionBattle_branch_ead6f note D_, 4 callchannel Music_ChampionBattle_branch_ead6f note A_, 4 callchannel Music_ChampionBattle_branch_ead6f note D_, 4 note D#, 1 note __, 1 note D#, 1 note __, 1 note A#, 4 note D#, 1 note __, 1 note D#, 1 note __, 1 note A#, 4 note D#, 1 note __, 1 note D#, 1 note __, 1 note B_, 4 note D#, 1 note __, 1 note D#, 1 note __, 1 octave 4 note C#, 4 note D#, 8 octave 3 note D#, 8 note B_, 4 note G_, 2 note B_, 2 note F#, 2 note A#, 2 note F_, 2 note A_, 2 Music_ChampionBattle_branch_eacc6: note D#, 2 note A#, 2 loopchannel 8, Music_ChampionBattle_branch_eacc6 Music_ChampionBattle_branch_eaccc: note E_, 2 note B_, 2 loopchannel 5, Music_ChampionBattle_branch_eaccc note E_, 2 octave 4 note C_, 2 octave 3 note A_, 2 note B_, 2 note G_, 2 note A_, 2 Music_ChampionBattle_branch_eacda: note D#, 2 note A#, 2 loopchannel 8, Music_ChampionBattle_branch_eacda Music_ChampionBattle_branch_eace0: note E_, 2 note B_, 2 loopchannel 8, Music_ChampionBattle_branch_eace0 callchannel Music_ChampionBattle_branch_ead83 octave 3 note D#, 2 note E_, 2 note D#, 2 note E_, 2 note D#, 2 octave 4 note D_, 2 note C#, 2 note C_, 2 callchannel Music_ChampionBattle_branch_ead83 octave 3 note D#, 2 note A#, 2 note D#, 2 note A#, 2 note D#, 2 octave 4 note D_, 2 note C#, 2 note C_, 2 octave 3 note A#, 8 note D#, 8 note B_, 8 note D#, 8 Music_ChampionBattle_branch_ead05: note D#, 2 note F#, 2 loopchannel 16, Music_ChampionBattle_branch_ead05 callchannel Music_ChampionBattle_branch_ead8e octave 3 note E_, 2 note B_, 2 octave 4 note D#, 2 note E_, 2 note F#, 2 octave 3 note B_, 2 octave 4 note D#, 2 note E_, 2 callchannel Music_ChampionBattle_branch_ead8e Music_ChampionBattle_branch_ead1d: octave 3 note E_, 2 note B_, 2 loopchannel 4, Music_ChampionBattle_branch_ead1d Music_ChampionBattle_branch_ead24: note D#, 2 note A#, 2 loopchannel 5, Music_ChampionBattle_branch_ead24 note B_, 2 octave 4 note D#, 2 octave 3 note D#, 2 note __, 2 note D#, 2 note __, 2 Music_ChampionBattle_branch_ead32: note E_, 2 note B_, 2 loopchannel 5, Music_ChampionBattle_branch_ead32 octave 4 note C#, 2 note E_, 2 octave 3 note E_, 2 note __, 2 note E_, 2 note __, 2 Music_ChampionBattle_branch_ead40: note D#, 2 note G#, 2 loopchannel 8, Music_ChampionBattle_branch_ead40 Music_ChampionBattle_branch_ead46: note D#, 2 note A#, 2 loopchannel 7, Music_ChampionBattle_branch_ead46 note B_, 2 note A#, 2 Music_ChampionBattle_branch_ead4e: octave 3 note D#, 2 note A#, 2 octave 4 note D_, 2 note D#, 2 loopchannel 7, Music_ChampionBattle_branch_ead4e note C#, 2 octave 3 note B_, 2 note A#, 2 note G#, 2 loopchannel 0, Music_ChampionBattle_branch_eacc6 Music_ChampionBattle_branch_ead61: note D#, 1 note __, 1 note D#, 1 note __, 5 loopchannel 3, Music_ChampionBattle_branch_ead61 note D#, 1 note __, 1 note D#, 1 note __, 1 note B_, 4 endchannel Music_ChampionBattle_branch_ead6f: note D#, 1 note __, 1 note D#, 1 note __, 1 note A#, 4 note D#, 1 note __, 1 note D#, 1 note __, 1 note B_, 4 note D#, 1 note __, 1 note D#, 1 note __, 1 note A#, 4 note D#, 1 note __, 1 note D#, 1 note __, 1 endchannel Music_ChampionBattle_branch_ead83: octave 3 note D#, 2 note F#, 2 note D#, 2 note F#, 2 note D#, 2 octave 4 note D_, 2 note C#, 2 note C_, 2 endchannel Music_ChampionBattle_branch_ead8e: octave 3 note E_, 2 note B_, 2 note E_, 2 note B_, 2 note E_, 2 note B_, 2 octave 4 note D#, 2 note E_, 2 endchannel
SECTION code_clib PUBLIC nmi_init PUBLIC _nmi_init EXTERN asm_nmi_handler EXTERN l_push_di EXTERN l_pop_ei nmi_init: _nmi_init: ld hl,asm_nmi_handler ld ($ff7f),hl ld a,195 ld ($ff7e),a ret
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/files/file_path.h" #include "base/pickle.h" #include "extensions/common/user_script.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace extensions { static const int kAllSchemes = URLPattern::SCHEME_HTTP | URLPattern::SCHEME_HTTPS | URLPattern::SCHEME_FILE | URLPattern::SCHEME_FTP | URLPattern::SCHEME_CHROMEUI; TEST(ExtensionUserScriptTest, Glob_HostString) { UserScript script; script.add_glob("*mail.google.com*"); script.add_glob("*mail.yahoo.com*"); script.add_glob("*mail.msn.com*"); EXPECT_TRUE(script.MatchesURL(GURL("http://mail.google.com"))); EXPECT_TRUE(script.MatchesURL(GURL("http://mail.google.com/foo"))); EXPECT_TRUE(script.MatchesURL(GURL("https://mail.google.com/foo"))); EXPECT_TRUE(script.MatchesURL(GURL("ftp://mail.google.com/foo"))); EXPECT_TRUE(script.MatchesURL(GURL("http://woo.mail.google.com/foo"))); EXPECT_TRUE(script.MatchesURL(GURL("http://mail.yahoo.com/bar"))); EXPECT_TRUE(script.MatchesURL(GURL("http://mail.msn.com/baz"))); EXPECT_FALSE(script.MatchesURL(GURL("http://www.hotmail.com"))); script.add_exclude_glob("*foo*"); EXPECT_TRUE(script.MatchesURL(GURL("http://mail.google.com"))); EXPECT_FALSE(script.MatchesURL(GURL("http://mail.google.com/foo"))); } TEST(ExtensionUserScriptTest, Glob_TrailingSlash) { UserScript script; script.add_glob("*mail.google.com/"); // GURL normalizes the URL to have a trailing "/" EXPECT_TRUE(script.MatchesURL(GURL("http://mail.google.com"))); EXPECT_TRUE(script.MatchesURL(GURL("http://mail.google.com/"))); EXPECT_FALSE(script.MatchesURL(GURL("http://mail.google.com/foo"))); } TEST(ExtensionUserScriptTest, Glob_TrailingSlashStar) { UserScript script; script.add_glob("http://mail.google.com/*"); // GURL normalizes the URL to have a trailing "/" EXPECT_TRUE(script.MatchesURL(GURL("http://mail.google.com"))); EXPECT_TRUE(script.MatchesURL(GURL("http://mail.google.com/foo"))); EXPECT_FALSE(script.MatchesURL(GURL("https://mail.google.com/foo"))); } TEST(ExtensionUserScriptTest, Glob_Star) { UserScript script; script.add_glob("*"); EXPECT_TRUE(script.MatchesURL(GURL("http://foo.com/bar"))); EXPECT_TRUE(script.MatchesURL(GURL("http://hot.com/dog"))); EXPECT_TRUE(script.MatchesURL(GURL("https://hot.com/dog"))); EXPECT_TRUE(script.MatchesURL(GURL("file:///foo/bar"))); EXPECT_TRUE(script.MatchesURL(GURL("file://localhost/foo/bar"))); } TEST(ExtensionUserScriptTest, Glob_StringAnywhere) { UserScript script; script.add_glob("*foo*"); EXPECT_TRUE(script.MatchesURL(GURL("http://foo.com/bar"))); EXPECT_TRUE(script.MatchesURL(GURL("http://baz.org/foo/bar"))); EXPECT_FALSE(script.MatchesURL(GURL("http://baz.org"))); } TEST(ExtensionUserScriptTest, UrlPattern) { URLPattern pattern(kAllSchemes); ASSERT_EQ(URLPattern::PARSE_SUCCESS, pattern.Parse("http://*/foo*")); UserScript script; script.add_url_pattern(pattern); EXPECT_TRUE(script.MatchesURL(GURL("http://monkey.com/foobar"))); EXPECT_FALSE(script.MatchesURL(GURL("http://monkey.com/hotdog"))); // NOTE: URLPattern is tested more extensively in url_pattern_unittest.cc. } TEST(ExtensionUserScriptTest, ExcludeUrlPattern) { UserScript script; URLPattern pattern(kAllSchemes); ASSERT_EQ(URLPattern::PARSE_SUCCESS, pattern.Parse("http://*.nytimes.com/*")); script.add_url_pattern(pattern); URLPattern exclude(kAllSchemes); ASSERT_EQ(URLPattern::PARSE_SUCCESS, exclude.Parse("*://*/*business*")); script.add_exclude_url_pattern(exclude); EXPECT_TRUE(script.MatchesURL(GURL("http://www.nytimes.com/health"))); EXPECT_FALSE(script.MatchesURL(GURL("http://www.nytimes.com/business"))); EXPECT_TRUE(script.MatchesURL(GURL("http://business.nytimes.com"))); } TEST(ExtensionUserScriptTest, UrlPatternAndIncludeGlobs) { UserScript script; URLPattern pattern(kAllSchemes); ASSERT_EQ(URLPattern::PARSE_SUCCESS, pattern.Parse("http://*.nytimes.com/*")); script.add_url_pattern(pattern); script.add_glob("*nytimes.com/???s/*"); EXPECT_TRUE(script.MatchesURL(GURL("http://www.nytimes.com/arts/1.html"))); EXPECT_TRUE(script.MatchesURL(GURL("http://www.nytimes.com/jobs/1.html"))); EXPECT_FALSE(script.MatchesURL(GURL("http://www.nytimes.com/sports/1.html"))); } TEST(ExtensionUserScriptTest, UrlPatternAndExcludeGlobs) { UserScript script; URLPattern pattern(kAllSchemes); ASSERT_EQ(URLPattern::PARSE_SUCCESS, pattern.Parse("http://*.nytimes.com/*")); script.add_url_pattern(pattern); script.add_exclude_glob("*science*"); EXPECT_TRUE(script.MatchesURL(GURL("http://www.nytimes.com"))); EXPECT_FALSE(script.MatchesURL(GURL("http://science.nytimes.com"))); EXPECT_FALSE(script.MatchesURL(GURL("http://www.nytimes.com/science"))); } TEST(ExtensionUserScriptTest, UrlPatternGlobInteraction) { // If there are both, match intersection(union(globs), union(urlpatterns)). UserScript script; URLPattern pattern(kAllSchemes); ASSERT_EQ(URLPattern::PARSE_SUCCESS,pattern.Parse("http://www.google.com/*")); script.add_url_pattern(pattern); script.add_glob("*bar*"); // No match, because it doesn't match the glob. EXPECT_FALSE(script.MatchesURL(GURL("http://www.google.com/foo"))); script.add_exclude_glob("*baz*"); // No match, because it matches the exclude glob. EXPECT_FALSE(script.MatchesURL(GURL("http://www.google.com/baz"))); // Match, because it matches the glob, doesn't match the exclude glob. EXPECT_TRUE(script.MatchesURL(GURL("http://www.google.com/bar"))); // Try with just a single exclude glob. script.clear_globs(); EXPECT_TRUE(script.MatchesURL(GURL("http://www.google.com/foo"))); // Try with no globs or exclude globs. script.clear_exclude_globs(); EXPECT_TRUE(script.MatchesURL(GURL("http://www.google.com/foo"))); } TEST(ExtensionUserScriptTest, Pickle) { URLPattern pattern1(kAllSchemes); URLPattern pattern2(kAllSchemes); URLPattern exclude1(kAllSchemes); URLPattern exclude2(kAllSchemes); ASSERT_EQ(URLPattern::PARSE_SUCCESS, pattern1.Parse("http://*/foo*")); ASSERT_EQ(URLPattern::PARSE_SUCCESS, pattern2.Parse("http://bar/baz*")); ASSERT_EQ(URLPattern::PARSE_SUCCESS, exclude1.Parse("*://*/*bar")); ASSERT_EQ(URLPattern::PARSE_SUCCESS, exclude2.Parse("https://*/*")); UserScript script1; script1.js_scripts().push_back(UserScript::File( base::FilePath(FILE_PATH_LITERAL("c:\\foo\\")), base::FilePath(FILE_PATH_LITERAL("foo.user.js")), GURL("chrome-extension://abc/foo.user.js"))); script1.css_scripts().push_back(UserScript::File( base::FilePath(FILE_PATH_LITERAL("c:\\foo\\")), base::FilePath(FILE_PATH_LITERAL("foo.user.css")), GURL("chrome-extension://abc/foo.user.css"))); script1.css_scripts().push_back(UserScript::File( base::FilePath(FILE_PATH_LITERAL("c:\\foo\\")), base::FilePath(FILE_PATH_LITERAL("foo2.user.css")), GURL("chrome-extension://abc/foo2.user.css"))); script1.set_run_location(UserScript::DOCUMENT_START); script1.add_url_pattern(pattern1); script1.add_url_pattern(pattern2); script1.add_exclude_url_pattern(exclude1); script1.add_exclude_url_pattern(exclude2); Pickle pickle; script1.Pickle(&pickle); PickleIterator iter(pickle); UserScript script2; script2.Unpickle(pickle, &iter); EXPECT_EQ(1U, script2.js_scripts().size()); EXPECT_EQ(script1.js_scripts()[0].url(), script2.js_scripts()[0].url()); EXPECT_EQ(2U, script2.css_scripts().size()); for (size_t i = 0; i < script2.js_scripts().size(); ++i) { EXPECT_EQ(script1.css_scripts()[i].url(), script2.css_scripts()[i].url()); } ASSERT_EQ(script1.globs().size(), script2.globs().size()); for (size_t i = 0; i < script1.globs().size(); ++i) { EXPECT_EQ(script1.globs()[i], script2.globs()[i]); } ASSERT_EQ(script1.url_patterns(), script2.url_patterns()); ASSERT_EQ(script1.exclude_url_patterns(), script2.exclude_url_patterns()); } TEST(ExtensionUserScriptTest, Defaults) { UserScript script; ASSERT_EQ(UserScript::DOCUMENT_IDLE, script.run_location()); } } // namespace extensions
txt_commander DB "COMMANDER",0 txt_inventory DB "INVENTORY",0 txt_present_system DB "Present System :",0 txt_hyperspace_system DB "Hyperspace System:",0 txt_condition DB "Condition :",0 txt_fuel DB "Fuel :",0 txt_cash DB "Cash :",0 txt_legal_status DB "Legal Status:",0 txt_rating DB "Rating :",0 txt_equipment DB "EQUIPMENT:",0 txt_fuel_level DB "00.0 Light Years",0 txt_cash_amount DB "XXXXXXXXXX",0 txt_cash_decimal DB "." txt_cash_fraction DB "X Cr",0 txt_status_colour equ $FF print_boiler_text_l2: ; ">print_boilder_text hl = text structure, b = message count" BoilerTextLoop: push bc ; Save Message Count loop value ld c,(hl) ; Get Row into b inc hl ld b,(hl) ; Get Col into b inc hl ld e,(hl) ; Get text address Lo into E inc hl ld d,(hl) ; Get text address Hi into E inc hl push hl ; Save present HL to stack as this is the address for the next message ex de,hl ; now hl = address of text data ld e,txt_status_colour MMUSelectLayer2 call l1_print_at pop hl pop bc djnz BoilerTextLoop ret print_boiler_text: ; ">print_boilder_text hl = text structure, b = message count" .BoilerTextLoop: push bc ; Save Message Count loop value ld c,(hl) ; Get Row into b inc hl ld b,(hl) ; Get Col into b inc hl ld e,(hl) ; Get text address Lo into E inc hl ld d,(hl) ; Get text address Hi into E inc hl push hl ; Save present HL to stack as this is the address for the next message ex de,hl ; now hl = address of text data ld e,txt_status_colour push bc pop de call l1_print_at pop hl pop bc djnz .BoilerTextLoop ret GetFuelLevel: INCLUDE "Menus/get_fuel_level_inlineinclude.asm" GetCash: ld hl,(Cash) ex de,hl ld ix,(Cash+2) ld iy,txt_cash_amount call DispDEIXtoIY ; This will write out with 0 termination after last digit .ShiftDecimalDigit: ld a,(IY+0) ;Push last digit to post decimal ld (txt_cash_fraction),a .UpdateInteger: ld hl,txt_cash_amount+1 ; Now was there only 1 digit ld a,(hl) ; if so we leave it alone so its "0.0" cp 0 ret z ld (IY),0 ; Else we erase last digit as it went to fraction ret
;; ;; Copyright (c) 2018-2022, Intel Corporation ;; ;; 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 "include/os.asm" %include "include/memcpy.asm" %include "include/clear_regs.asm" %include "include/cet.inc" %include "include/error.inc" ;;; Routines to do 128/256 bit CFB AES encrypt/decrypt operations on one block only. ;;; It processes only one buffer at a time. ;;; It is designed to manage partial blocks of DOCSIS 3.1 SEC BPI ;; In System V AMD64 ABI ;; callee saves: RBX, RBP, R12-R15 ;; Windows x64 ABI ;; callee saves: RBX, RBP, RDI, RSI, RSP, R12-R15 ;; ;; Registers: RAX RBX RCX RDX RBP RSI RDI R8 R9 R10 R11 R12 R13 R14 R15 ;; ----------------------------------------------------------- ;; Windows clobbers: RAX R9 R10 R11 ;; Windows preserves: RBX RCX RDX RBP RSI RDI R8 R12 R13 R14 R15 ;; ----------------------------------------------------------- ;; Linux clobbers: RAX R9 R10 ;; Linux preserves: RBX RCX RDX RBP RSI RDI R8 R11 R12 R13 R14 R15 ;; ----------------------------------------------------------- ;; ;; Linux/Windows clobbers: xmm0 ;; %ifdef LINUX %define arg1 rdi %define arg2 rsi %define arg3 rdx %define arg4 rcx %define arg5 r8 %else %define arg1 rcx %define arg2 rdx %define arg3 r8 %define arg4 r9 %define arg5 [rsp + 5*8] %endif %define OUT arg1 %define IN arg2 %define IV arg3 %define KEYS arg4 %ifdef LINUX %define LEN arg5 %else %define LEN2 arg5 %define LEN r11 %endif %define TMP0 rax %define TMP1 r10 %define XDATA xmm0 %define XIN xmm1 mksection .text %macro do_cfb 1 %define %%NROUNDS %1 %ifndef LINUX mov LEN, LEN2 %endif %ifdef SAFE_PARAM IMB_ERR_CHECK_RESET cmp IV, 0 jz %%cfb_error cmp KEYS, 0 jz %%cfb_error cmp LEN, 0 jz %%skip_in_out_check cmp OUT, 0 jz %%cfb_error cmp IN, 0 jz %%cfb_error jmp %%cfb_no_error %%cfb_error: IMB_ERR_CHECK_START rax IMB_ERR_CHECK_NULL IV, rax, IMB_ERR_NULL_IV IMB_ERR_CHECK_NULL KEYS, rax, IMB_ERR_NULL_EXP_KEY IMB_ERR_CHECK_ZERO LEN, rax, IMB_ERR_CIPH_LEN IMB_ERR_CHECK_NULL OUT, rax, IMB_ERR_NULL_DST IMB_ERR_CHECK_NULL IN, rax, IMB_ERR_NULL_SRC IMB_ERR_CHECK_END rax jmp %%exit_cfb %%cfb_no_error: %%skip_in_out_check: %endif simd_load_avx_16 XIN, IN, LEN ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; vmovdqu XDATA, [IV] ; IV (or next to last block) vpxor XDATA, [KEYS + 16*0] ; 0. ARK %assign i 16 %rep %%NROUNDS vaesenc XDATA, [KEYS + i] ; ENC %assign i (i+16) %endrep vaesenclast XDATA, [KEYS + i] vpxor XDATA, XIN ; plaintext/ciphertext XOR block cipher encryption simd_store_avx OUT, XDATA, LEN, TMP0, TMP1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %ifdef SAFE_DATA ;; XDATA and XIN are the only scratch SIMD registers used clear_xmms_avx XDATA, XIN clear_scratch_gps_asm %endif %%exit_cfb: %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; void aes_cfb_128_one(void *out, void *in, void *iv, void *keys, uint64_t len) ;; arg 1: OUT : addr to put clear/cipher text out ;; arg 2: IN : addr to take cipher/clear text from ;; arg 3: IV : initialization vector ;; arg 4: KEYS: pointer to expanded keys structure (16 byte aligned) ;; arg 5: LEN: length of the text to encrypt/decrypt (valid range is 0 to 16) ;; ;; AES CFB128 one block encrypt/decrypt implementation. ;; The function doesn't update IV. The result of operation can be found in OUT. ;; ;; It is primarily designed to process partial block of ;; DOCSIS 3.1 AES Packet PDU Encryption (I.10) ;; ;; It process up to one block only (up to 16 bytes). ;; ;; It makes sure not to read more than LEN bytes from IN and ;; not to store more than LEN bytes to OUT. MKGLOBAL(aes_cfb_128_one_avx,function,) MKGLOBAL(aes_cfb_128_one_avx2,function,) MKGLOBAL(aes_cfb_128_one_avx512,function,) align 32 aes_cfb_128_one_avx: aes_cfb_128_one_avx2: aes_cfb_128_one_avx512: endbranch64 do_cfb 9 ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; void aes_cfb_256_one(void *out, void *in, void *iv, void *keys, uint64_t len) ;; arg 1: OUT : addr to put clear/cipher text out ;; arg 2: IN : addr to take cipher/clear text from ;; arg 3: IV : initialization vector ;; arg 4: KEYS: pointer to expanded keys structure (16 byte aligned) ;; arg 5: LEN: length of the text to encrypt/decrypt (valid range is 0 to 16) ;; ;; AES CFB256 one block encrypt/decrypt implementation. ;; The function doesn't update IV. The result of operation can be found in OUT. ;; ;; It is primarily designed to process partial block of ;; DOCSIS 3.1 AES Packet PDU Encryption (I.10) ;; ;; It process up to one block only (up to 16 bytes). ;; ;; It makes sure not to read more than LEN bytes from IN and ;; not to store more than LEN bytes to OUT. MKGLOBAL(aes_cfb_256_one_avx,function,) MKGLOBAL(aes_cfb_256_one_avx2,function,) MKGLOBAL(aes_cfb_256_one_avx512,function,) align 32 aes_cfb_256_one_avx: aes_cfb_256_one_avx2: aes_cfb_256_one_avx512: do_cfb 13 ret mksection stack-noexec