text
stringlengths
1
1.05M
;/* Revision history since 5.0 Golden: ; * ; * M013 SHK 10/02/91 Zero out BX before we make the call to detect mouse ; * mouse version numbers. ; */ ;/* ; * Microsoft Confidential ; * Copyright (C) Microsoft Corporation 1991 ; * All Rights Reserved. ; */ ?WIN = 0 ;Not windows; ?PLM = 1 ;DO use pl/m include cmacros.inc DOSARENA STRUC Signature db ? Owner dw ? Paragraphs dw ? Special db 3 dup(?) OwnerName db 8 dup(?) DOSARENA ENDS sBegin data sEnd data sBegin code assumes cs, code assumes ds, data ;;;RETURNS The mouse version , ;;;major in hibyte, minor in lobyte cProc MouseVersion, PUBLIC , <si,di,ds,es> cBegin MouseVersion xor bx,bx ; M013 older mouse versions may not set version, so ; zero here so we can detect "unknown" version mov ax,0024h ;Get Mouse Information int 33h xchg ax,bx cEnd MouseVersion is_system_chain db 0 myUmbLinkState dw ? ;;; DetectLogitech ;;; FUNCTION ;;; detects the presence (in memory!) of a Logitech Mouse driver ;;; RETURNS ;;; if Logitech detected (numbers are binary) : ;;; dh = 0 ;;; dl = major version ;;; ah = minor version ;;; al = incremental version ;;; eg: Logitech version 5.01 -> dx=0005h:ax=0001h ;;; if Not detected ;;; dx:ax = 0 ;;; EFFECTS ;;; Temporarily links in UMBs, scans all memory arenas ;;; ALGORITHM ;;; ;;; Link in UMBS, scan ALL memory arenas more name "MOUSE". Scan ;;; all "MOUSE" arenas for the sequence "LOGITECH MOUSE DRIVER VX.XX" ;;; cProc DetectLogitech , PUBLIC,<si,di,ds,es> cBegin DetectLogitech ;;; We must link in the UMBs for this search, since ;;; the mouse driver might be in a UMB! ;;; first save state mov ax,5802h ; Get link state; output in ax int 21h mov WORD PTR cs:myUmbLinkState,ax ; Save link state for restoration ;;; now set state (umbs linked in) mov ax,5803h ; link/unlink UMBs bx = 0 is unlink, mov bx,1 ; bx =1 is link int 21h ;;; Get DOS memory arena pointer just above DBP mov AH,52h ; "undocumented" int 21h ; ES:BX --> first DBP sub bx,4 ; ARENA HEAD POINTER is now in es:bx les bx,es:[bx] ; first arena -> es:bx mov ax,es ; ax is temporary segment saver ;;; loop through all arenas... nextarena: ;;; We use the same code to walk through regular arenas and ;;; system arenas, regular arena chains end with signature 'Z' ;;; while system arenas end with 'F' mov cl,es:[bx].Signature ; current arena the arena list tail? cmp cl,'F' ; 'F' means we were in a system list je end_system_chain cmp cl,'Z' ; 'Z' means there are no more arenas je endofarenas1 cmp cl, 'M' ; sanity check--> valid je arena_valid ; regular arenas are id 'M' cmp cl, 'D' ; and system arenas are id 'D' je arena_valid jmp short endofarenas1 ; invalid arenas! arena_valid: ;;; check for special system type of arena (UMBs,devices) cmp es:[bx].owner,08h ; system arenas have owner of 08h jne find_a_regular_mouse_arena cmp WORD PTR es:[bx].ownername,'DS' ; system arenas have owner name of SD jne find_a_regular_mouse_arena ;;; here we set up for walking a system arena (UMB,device lists) cmp cs:is_system_chain,0 ; if we are already in a system arena, je start_system_chain ; something weird is going on fall through! ;;; restore setup for walking regular arena chains end_system_chain: dec cs:is_system_chain ; no longer in a system chain pop ax ; restore registers saved at chain start pop bx ; pop es ; es:bx points to next arena jmp short find_a_regular_mouse_arena ;continue arena walking endofarenas1: jmp endofarenas ; jump out of range, this is intermediate start_system_chain: ;;; here we setup for walking system chain inc cs:is_system_chain ; remember we are in a special chain push es ; remember current arena push bx ; is es:bx, as well as segment in ax push ax add bx,16 ; system arena head starts at first ; segment in this regular arena ; fall through to generic search code find_a_regular_mouse_arena: ;;;es:bx -> arena header cmp WORD PTR es:[bx].OwnerName[0],'OM' ; is owner "MOUSE"? jne continue_chain ; note we are doing cmp WORD PTR es:[bx].OwnerName[2],'SU' ; double byte compares! jne continue_chain cmp BYTE PTR es:[bx].OwnerName[4],'E' jne continue_chain ;; found a MOUSE ARENA mov di,bx ; get pointer to memory block mov CX, es:[bx].paragraphs ; lengths is in paragraphs shl cx,1 ; we need bytes shl cx,1 ; mul by 16 shl cx,1 shl cx,1 cld ; don't forget! continue_this_scan: ;;; scanning for "LOGITECH MOUSE DRIVER VX.XX" in this es:di memory block ;;; 012345678901234567890123456 mov dx,ax mov AX,'OL' repne scasw or cx,cx mov ax,dx jz continue_chain cmp WORD PTR es:[di],'IG' jne continue_this_scan cmp WORD PTR es:[di+2],'ET' jne continue_this_scan cmp WORD PTR es:[di+4],'HC' jne continue_this_scan cmp WORD PTR es:[di+6],'M ' jne continue_this_scan ;;; note we don't check for "OUSE DRIVER", just too much cmp WORD PTR es:[di+19],'V ' jne continue_this_scan ;;; found the signature, now get the version after the "V" ;;; WARNING assumes D.DD as version format, but we already ;;; checked "real" version for less than 6.23 so we probably ;;; wouldn't get here... mov dl,BYTE PTR es:[di+21] ; ascii major version mov ah,BYTE PTR es:[di+23] ; ascii minor version mov al,BYTE PTR es:[di+24] ; ascii incremental version mov dh,'0' ; binarize the numbers ... sub dl,dh sub ah,dh sub al,dh xor dh,dh ; note dh = 0 on return! jmp short DetectLogictechReturn ; clean up and get out! continue_chain: ;;; this arena has not logitech, go to next mov es,ax ; restore arena segment add ax,es:[bx].paragraphs ; skip the memory block to next arena inc ax ; one paragraph for last header mov es,ax ; save arena segment in ax jmp nextarena ; ready to search again endofarenas: ;;; If we get here, we did not find a logitech signature ;;; in a "MOUSE" owned arena xor ax,ax xor dx,dx DetectLogictechReturn: ;;; if we were in a system chain, we need to clean up ;;; the stuff (es,bx,ax = 6 bytes) we saved on the stack cmp cs:is_system_chain,0 je no_cleanup add sp,6 no_cleanup: ;;; we now need to restore the UMB link state push ax ; don't toast return value! ;;; now re-set umb link state mov ax,5803h ;link/unlink UMBs bx = 0 is unlink,bx =1 is link mov bx,cs:myUmbLinkState int 21h pop ax ;; restore return value cEnd DetectLogictech sEnd code end  
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include <string> #include "functional_test_utils/skip_tests_config.hpp" std::vector<std::string> disabledTestPatterns() { return { // Issue 26268 ".*ConcatLayerTest.*axis=0.*", // Not supported activation types ".*ActivationLayerTest\\.CompareWithRefs/Tanh.*netPRC=FP32.*", ".*ActivationLayerTest\\.CompareWithRefs/Exp.*netPRC=FP32.*", ".*ActivationLayerTest\\.CompareWithRefs/Log.*netPRC=FP32.*", ".*ActivationLayerTest\\.CompareWithRefs/Sigmoid.*netPRC=FP32.*", ".*ActivationLayerTest\\.CompareWithRefs/Relu.*netPRC=FP32.*", // TODO: currently this tests are not applicable to myriadPlugin ".*Behavior.*ExecGraphTests.*" }; }
VermilionGymObject: db $3 ; border block db $2 ; warps db $11, $4, $3, $ff db $11, $5, $3, $ff db $0 ; signs db $5 ; objects object SPRITE_SURGE, $5, $1, STAY, DOWN, $1, OPP_LT_SURGE, $1 object SPRITE_BLACK_HAIR_BOY_2, $9, $6, STAY, LEFT, $2, OPP_ENGINEER, $1 object SPRITE_BLACK_HAIR_BOY_2, $3, $8, STAY, LEFT, $3, OPP_ROCKER, $1 object SPRITE_SAILOR, $0, $a, STAY, RIGHT, $4, OPP_SAILOR, $8 object SPRITE_GYM_HELPER, $4, $e, STAY, DOWN, $5 ; person ; warp-to EVENT_DISP VERMILION_GYM_WIDTH, $11, $4 EVENT_DISP VERMILION_GYM_WIDTH, $11, $5
// // Created by Sam on 11/11/2018. // #include <catch.hpp> #include <string> #include <pybind11/embed.h> namespace py = pybind11; TEST_CASE("Embedded interpreter") { py::scoped_interpreter guard{}; try { SECTION("Correct Python Version") { auto correctVersion = "3.6.6"; auto sys = py::module::import("sys"); auto version_info = sys.attr("version_info"); int major = version_info.attr("major").cast<int>(); int minor = version_info.attr("minor").cast<int>(); int micro = version_info.attr("micro").cast<int>(); auto version = std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(micro); REQUIRE(version == correctVersion); } SECTION("Import module") { py::module::import("sys").attr("path").cast<py::list>().append("../src/Python"); auto game = py::module::import("Game"); } } catch (const py::error_already_set &e) { FAIL_CHECK(e.what()); } catch (const std::runtime_error &e) { FAIL_CHECK(e.what()); } }
Start: NOP JMP Start HLT
SECTION code_fp_math48 PUBLIC _lgamma_fastcall EXTERN cm48_sdcciy_lgamma_fastcall defc _lgamma_fastcall = cm48_sdcciy_lgamma_fastcall
SECTION code_clib SECTION code_l_sdcc PUBLIC ____sdcc_ll_sub_hlix_deix_bc EXTERN ____sdcc_ll_sub_de_bc_hl ____sdcc_ll_sub_hlix_deix_bc: push bc IFDEF __SDCC_IX push ix pop bc ELSE push iy pop bc ENDIF add hl,bc ex de,hl add hl,bc ex (sp),hl pop bc jp ____sdcc_ll_sub_de_bc_hl
; A131229: Numbers congruent to {1,7} mod 10. ; 1,7,11,17,21,27,31,37,41,47,51,57,61,67,71,77,81,87,91,97,101,107,111,117,121,127,131,137,141,147,151,157,161,167,171,177,181,187,191,197,201,207,211,217,221,227,231,237,241,247,251,257,261,267,271,277,281 mov $1,$0 mod $0,2 mul $1,5 add $0,$1 add $0,1
db "ROCK SNAKE@" ; species name db "As it digs through" next "the ground, it" next "absorbs many hard" page "objects. This is" next "what makes its" next "body so solid.@"
// Copyright 2018 The Fuchsia 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 "garnet/bin/iquery/formatters/json.h" #include <rapidjson/prettywriter.h> #include "garnet/bin/iquery/utils.h" #include "lib/inspect/hierarchy.h" #include "third_party/cobalt/util/crypto_util/base64.h" namespace iquery { namespace { using cobalt::crypto::Base64Encode; template <typename WriterType, typename ArrayType> void FormatArray(WriterType& writer, const ArrayType& array) { auto buckets = array.GetBuckets(); if (buckets.size() != 0) { writer->StartObject(); writer->String("buckets"); writer->StartArray(); for (const auto& bucket : buckets) { writer->StartObject(); writer->String("floor"); writer->String(FormatNumericValue(bucket.floor)); writer->String("upper_bound"); writer->String(FormatNumericValue(bucket.upper_limit)); writer->String("count"); writer->String(FormatNumericValue(bucket.count)); writer->EndObject(); } writer->EndArray(); writer->EndObject(); } else { writer->StartArray(); for (const auto& val : array.value()) { writer->String(FormatNumericValue(val)); } writer->EndArray(); } } template <typename WriterType> void FormatMetricValue(WriterType& writer, const inspect::hierarchy::Metric& metric) { switch (metric.format()) { case inspect::hierarchy::MetricFormat::INT_ARRAY: FormatArray(writer, metric.Get<inspect::hierarchy::IntArray>()); break; case inspect::hierarchy::MetricFormat::UINT_ARRAY: FormatArray(writer, metric.Get<inspect::hierarchy::UIntArray>()); break; case inspect::hierarchy::MetricFormat::DOUBLE_ARRAY: FormatArray(writer, metric.Get<inspect::hierarchy::DoubleArray>()); break; default: writer->String(FormatNumericMetricValue(metric)); } } // Create the appropriate Json exporter according to the given options. // NOTE(donoso): For some reason, rapidjson decided that while Writer is a class // PrettyWriter inherits from, it is *not* a virtual interface. // This means I cannot pass a Writer pointer around and get each // writer to do it's thing, which is what I expected. // Eventually this class will have to become a dispatcher that // passes the writer to a templatized version of FormatCat, Ls // and Find. template <typename OutputStream> std::unique_ptr<rapidjson::PrettyWriter<OutputStream>> GetJsonWriter( OutputStream& os, const Options&) { // NOTE(donosoc): When json formatter options are given, create the // appropriate json writer and configure it here. return std::make_unique<rapidjson::PrettyWriter<OutputStream>>(os); } // FormatFind ------------------------------------------------------------------ std::string FormatFind(const Options& options, const std::vector<inspect::ObjectSource>& results) { rapidjson::StringBuffer sb; auto writer = GetJsonWriter(sb, options); writer->StartArray(); for (const auto& entry_point : results) { entry_point.VisitObjectsInHierarchy( [&](const std::vector<std::string>& path, const inspect::ObjectHierarchy& hierarchy) { writer->String(FormatPath(options.path_format, entry_point.FormatRelativePath(path), hierarchy.node().name())); }); } writer->EndArray(); return sb.GetString(); } // FormatLs -------------------------------------------------------------------- std::string FormatLs(const Options& options, const std::vector<inspect::ObjectSource>& results) { rapidjson::StringBuffer sb; auto writer = GetJsonWriter(sb, options); writer->StartArray(); for (const auto& entry_point : results) { const auto& hierarchy = entry_point.GetRootHierarchy(); for (const auto& child : hierarchy.children()) { writer->String( FormatPath(options.path_format, entry_point.FormatRelativePath({child.node().name()}), child.node().name())); } } writer->EndArray(); return sb.GetString(); } // FormatCat ------------------------------------------------------------------- template <typename OutputStream> void RecursiveFormatCat(rapidjson::PrettyWriter<OutputStream>* writer, const Options& options, const inspect::ObjectSource& entry_point, const inspect::ObjectHierarchy& root) { writer->StartObject(); // Properties. for (const auto& property : root.node().properties()) { writer->String(FormatStringBase64Fallback(property.name())); switch (property.format()) { case inspect::hierarchy::PropertyFormat::STRING: writer->String(FormatStringBase64Fallback( property.Get<inspect::hierarchy::StringProperty>().value())); break; case inspect::hierarchy::PropertyFormat::BYTES: { auto& val = property.Get<inspect::hierarchy::ByteVectorProperty>().value(); writer->String(FormatStringBase64Fallback( {reinterpret_cast<const char*>(val.data()), val.size()})); break; } default: FXL_LOG(WARNING) << "Failed to format unknown type for " << property.name(); writer->String("<Unknown type, format failed>"); break; } } // Metrics. for (const auto& metric : root.node().metrics()) { writer->String(FormatStringBase64Fallback(metric.name())); FormatMetricValue(writer, metric); } for (const auto& child : root.children()) { writer->String(child.node().name()); RecursiveFormatCat(writer, options, entry_point, child); } writer->EndObject(); } std::string FormatCat(const Options& options, const std::vector<inspect::ObjectSource>& results) { rapidjson::StringBuffer sb; auto writer = GetJsonWriter(sb, options); writer->StartArray(); for (const auto& entry_point : results) { writer->StartObject(); writer->String("path"); // The "path" field always ignored the object's name in JSON output. writer->String(FormatPath(options.path_format, entry_point.FormatRelativePath(), entry_point.FormatRelativePath())); writer->String("contents"); writer->StartObject(); writer->String(entry_point.GetRootHierarchy().node().name()); RecursiveFormatCat(writer.get(), options, entry_point, entry_point.GetRootHierarchy()); writer->EndObject(); writer->EndObject(); } writer->EndArray(); return sb.GetString(); } } // namespace std::string JsonFormatter::Format( const Options& options, const std::vector<inspect::ObjectSource>& results) { switch (options.mode) { case Options::Mode::CAT: return FormatCat(options, results); case Options::Mode::FIND: return FormatFind(options, results); case Options::Mode::LS: return FormatLs(options, results); case Options::Mode::UNSET: { FXL_LOG(ERROR) << "Unset Mode"; return ""; } } } } // namespace iquery
/* * Copyright 2011 The LibYuv Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "libyuv/planar_functions.h" #include <string.h> // for memset() #include "libyuv/cpu_id.h" #ifdef HAVE_JPEG #include "libyuv/mjpeg_decoder.h" #endif #include "source/row.h" #ifdef __cplusplus namespace libyuv { extern "C" { #endif // Copy a plane of data void CopyPlane(const uint8* src_y, int src_stride_y, uint8* dst_y, int dst_stride_y, int width, int height) { void (*CopyRow)(const uint8* src, uint8* dst, int width) = CopyRow_C; #if defined(HAS_COPYROW_NEON) if (TestCpuFlag(kCpuHasNEON) && IS_ALIGNED(width, 64)) { CopyRow = CopyRow_NEON; } #endif #if defined(HAS_COPYROW_X86) if (TestCpuFlag(kCpuHasX86) && IS_ALIGNED(width, 4)) { CopyRow = CopyRow_X86; } #endif #if defined(HAS_COPYROW_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(width, 32) && IS_ALIGNED(src_y, 16) && IS_ALIGNED(src_stride_y, 16) && IS_ALIGNED(dst_y, 16) && IS_ALIGNED(dst_stride_y, 16)) { CopyRow = CopyRow_SSE2; } #endif // Copy plane for (int y = 0; y < height; ++y) { CopyRow(src_y, dst_y, width); src_y += src_stride_y; dst_y += dst_stride_y; } } // Convert I420 to I400. (calls CopyPlane ignoring u/v) int I420ToI400(const uint8* src_y, int src_stride_y, uint8* dst_y, int dst_stride_y, uint8*, int, uint8*, int, int width, int height) { if (!src_y || !dst_y || width <= 0 || height == 0) { return -1; } // Negative height means invert the image. if (height < 0) { height = -height; src_y = src_y + (height - 1) * src_stride_y; src_stride_y = -src_stride_y; } CopyPlane(src_y, src_stride_y, dst_y, dst_stride_y, width, height); return 0; } // Mirror a plane of data void MirrorPlane(const uint8* src_y, int src_stride_y, uint8* dst_y, int dst_stride_y, int width, int height) { void (*MirrorRow)(const uint8* src, uint8* dst, int width) = MirrorRow_C; #if defined(HAS_MIRRORROW_NEON) if (TestCpuFlag(kCpuHasNEON) && IS_ALIGNED(width, 16)) { MirrorRow = MirrorRow_NEON; } #endif #if defined(HAS_MIRRORROW_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(width, 16)) { MirrorRow = MirrorRow_SSE2; #if defined(HAS_MIRRORROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(src_y, 16) && IS_ALIGNED(src_stride_y, 16)) { MirrorRow = MirrorRow_SSSE3; } #endif } #endif // Mirror plane for (int y = 0; y < height; ++y) { MirrorRow(src_y, dst_y, width); src_y += src_stride_y; dst_y += dst_stride_y; } } // Mirror I420 with optional flipping int I420Mirror(const uint8* src_y, int src_stride_y, const uint8* src_u, int src_stride_u, const uint8* src_v, int src_stride_v, uint8* dst_y, int dst_stride_y, uint8* dst_u, int dst_stride_u, uint8* dst_v, int dst_stride_v, int width, int height) { if (!src_y || !src_u || !src_v || !dst_y || !dst_u || !dst_v || width <= 0 || height == 0) { return -1; } // Negative height means invert the image. if (height < 0) { height = -height; int halfheight = (height + 1) >> 1; src_y = src_y + (height - 1) * src_stride_y; src_u = src_u + (halfheight - 1) * src_stride_u; src_v = src_v + (halfheight - 1) * src_stride_v; src_stride_y = -src_stride_y; src_stride_u = -src_stride_u; src_stride_v = -src_stride_v; } int halfwidth = (width + 1) >> 1; int halfheight = (height + 1) >> 1; if (dst_y) { MirrorPlane(src_y, src_stride_y, dst_y, dst_stride_y, width, height); } MirrorPlane(src_u, src_stride_u, dst_u, dst_stride_u, halfwidth, halfheight); MirrorPlane(src_v, src_stride_v, dst_v, dst_stride_v, halfwidth, halfheight); return 0; } // ARGB mirror. int ARGBMirror(const uint8* src_argb, int src_stride_argb, uint8* dst_argb, int dst_stride_argb, int width, int height) { if (!src_argb || !dst_argb || width <= 0 || height == 0) { return -1; } // Negative height means invert the image. if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBMirrorRow)(const uint8* src, uint8* dst, int width) = ARGBMirrorRow_C; #if defined(HAS_ARGBMIRRORROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(width, 4) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ARGBMirrorRow = ARGBMirrorRow_SSSE3; } #endif // Mirror plane for (int y = 0; y < height; ++y) { ARGBMirrorRow(src_argb, dst_argb, width); src_argb += src_stride_argb; dst_argb += dst_stride_argb; } return 0; } // Get a blender that optimized for the CPU, alignment and pixel count. // As there are 6 blenders to choose from, the caller should try to use // the same blend function for all pixels if possible. ARGBBlendRow GetARGBBlend() { void (*ARGBBlendRow)(const uint8* src_argb, const uint8* src_argb1, uint8* dst_argb, int width) = ARGBBlendRow_C; #if defined(HAS_ARGBBLENDROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3)) { ARGBBlendRow = ARGBBlendRow_SSSE3; return ARGBBlendRow; } #endif #if defined(HAS_ARGBBLENDROW_SSE2) if (TestCpuFlag(kCpuHasSSE2)) { ARGBBlendRow = ARGBBlendRow_SSE2; } #endif return ARGBBlendRow; } // Alpha Blend 2 ARGB images and store to destination. int ARGBBlend(const uint8* src_argb0, int src_stride_argb0, const uint8* src_argb1, int src_stride_argb1, uint8* dst_argb, int dst_stride_argb, int width, int height) { if (!src_argb0 || !src_argb1 || !dst_argb || width <= 0 || height == 0) { return -1; } // Negative height means invert the image. if (height < 0) { height = -height; dst_argb = dst_argb + (height - 1) * dst_stride_argb; dst_stride_argb = -dst_stride_argb; } void (*ARGBBlendRow)(const uint8* src_argb, const uint8* src_argb1, uint8* dst_argb, int width) = GetARGBBlend(); for (int y = 0; y < height; ++y) { ARGBBlendRow(src_argb0, src_argb1, dst_argb, width); src_argb0 += src_stride_argb0; src_argb1 += src_stride_argb1; dst_argb += dst_stride_argb; } return 0; } // Convert ARGB to I400. int ARGBToI400(const uint8* src_argb, int src_stride_argb, uint8* dst_y, int dst_stride_y, int width, int height) { if (!src_argb || !dst_y || width <= 0 || height == 0) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBToYRow)(const uint8* src_argb, uint8* dst_y, int pix) = ARGBToYRow_C; #if defined(HAS_ARGBTOYROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(width, 4) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16) && IS_ALIGNED(dst_y, 16) && IS_ALIGNED(dst_stride_y, 16)) { ARGBToYRow = ARGBToYRow_SSSE3; } #endif for (int y = 0; y < height; ++y) { ARGBToYRow(src_argb, dst_y, width); src_argb += src_stride_argb; dst_y += dst_stride_y; } return 0; } // ARGB little endian (bgra in memory) to I422 // same as I420 except UV plane is full height int ARGBToI422(const uint8* src_argb, int src_stride_argb, uint8* dst_y, int dst_stride_y, uint8* dst_u, int dst_stride_u, uint8* dst_v, int dst_stride_v, int width, int height) { if (!src_argb || !dst_y || !dst_u || !dst_v || width <= 0 || height == 0) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBToYRow)(const uint8* src_argb, uint8* dst_y, int pix) = ARGBToYRow_C; void (*ARGBToUVRow)(const uint8* src_argb0, int src_stride_argb, uint8* dst_u, uint8* dst_v, int width) = ARGBToUVRow_C; #if defined(HAS_ARGBTOYROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3)) { if (width > 16) { ARGBToUVRow = ARGBToUVRow_Any_SSSE3; ARGBToYRow = ARGBToYRow_Any_SSSE3; } if (IS_ALIGNED(width, 16)) { ARGBToUVRow = ARGBToUVRow_Unaligned_SSSE3; ARGBToYRow = ARGBToYRow_Unaligned_SSSE3; if (IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16)) { ARGBToUVRow = ARGBToUVRow_SSSE3; if (IS_ALIGNED(dst_y, 16) && IS_ALIGNED(dst_stride_y, 16)) { ARGBToYRow = ARGBToYRow_SSSE3; } } } } #endif for (int y = 0; y < height; ++y) { ARGBToUVRow(src_argb, 0, dst_u, dst_v, width); ARGBToYRow(src_argb, dst_y, width); src_argb += src_stride_argb; dst_y += dst_stride_y; dst_u += dst_stride_u; dst_v += dst_stride_v; } return 0; } // Convert ARGB To RGB24. int ARGBToRGB24(const uint8* src_argb, int src_stride_argb, uint8* dst_rgb24, int dst_stride_rgb24, int width, int height) { if (!src_argb || !dst_rgb24 || width <= 0 || height == 0) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBToRGB24Row)(const uint8* src_argb, uint8* dst_rgb, int pix) = ARGBToRGB24Row_C; #if defined(HAS_ARGBTORGB24ROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16)) { if (width * 3 <= kMaxStride) { ARGBToRGB24Row = ARGBToRGB24Row_Any_SSSE3; } if (IS_ALIGNED(width, 16) && IS_ALIGNED(dst_rgb24, 16) && IS_ALIGNED(dst_stride_rgb24, 16)) { ARGBToRGB24Row = ARGBToRGB24Row_SSSE3; } } #endif for (int y = 0; y < height; ++y) { ARGBToRGB24Row(src_argb, dst_rgb24, width); src_argb += src_stride_argb; dst_rgb24 += dst_stride_rgb24; } return 0; } // Convert ARGB To RAW. int ARGBToRAW(const uint8* src_argb, int src_stride_argb, uint8* dst_raw, int dst_stride_raw, int width, int height) { if (!src_argb || !dst_raw || width <= 0 || height == 0) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBToRAWRow)(const uint8* src_argb, uint8* dst_rgb, int pix) = ARGBToRAWRow_C; #if defined(HAS_ARGBTORAWROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16)) { if (width * 3 <= kMaxStride) { ARGBToRAWRow = ARGBToRAWRow_Any_SSSE3; } if (IS_ALIGNED(width, 16) && IS_ALIGNED(dst_raw, 16) && IS_ALIGNED(dst_stride_raw, 16)) { ARGBToRAWRow = ARGBToRAWRow_SSSE3; } } #endif for (int y = 0; y < height; ++y) { ARGBToRAWRow(src_argb, dst_raw, width); src_argb += src_stride_argb; dst_raw += dst_stride_raw; } return 0; } // Convert ARGB To RGB565. int ARGBToRGB565(const uint8* src_argb, int src_stride_argb, uint8* dst_rgb565, int dst_stride_rgb565, int width, int height) { if (!src_argb || !dst_rgb565 || width <= 0 || height == 0) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBToRGB565Row)(const uint8* src_argb, uint8* dst_rgb, int pix) = ARGBToRGB565Row_C; #if defined(HAS_ARGBTORGB565ROW_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16)) { if (width * 2 <= kMaxStride) { ARGBToRGB565Row = ARGBToRGB565Row_Any_SSE2; } if (IS_ALIGNED(width, 4)) { ARGBToRGB565Row = ARGBToRGB565Row_SSE2; } } #endif for (int y = 0; y < height; ++y) { ARGBToRGB565Row(src_argb, dst_rgb565, width); src_argb += src_stride_argb; dst_rgb565 += dst_stride_rgb565; } return 0; } // Convert ARGB To ARGB1555. int ARGBToARGB1555(const uint8* src_argb, int src_stride_argb, uint8* dst_argb1555, int dst_stride_argb1555, int width, int height) { if (!src_argb || !dst_argb1555 || width <= 0 || height == 0) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBToARGB1555Row)(const uint8* src_argb, uint8* dst_rgb, int pix) = ARGBToARGB1555Row_C; #if defined(HAS_ARGBTOARGB1555ROW_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16)) { if (width * 2 <= kMaxStride) { ARGBToARGB1555Row = ARGBToARGB1555Row_Any_SSE2; } if (IS_ALIGNED(width, 4)) { ARGBToARGB1555Row = ARGBToARGB1555Row_SSE2; } } #endif for (int y = 0; y < height; ++y) { ARGBToARGB1555Row(src_argb, dst_argb1555, width); src_argb += src_stride_argb; dst_argb1555 += dst_stride_argb1555; } return 0; } // Convert ARGB To ARGB4444. int ARGBToARGB4444(const uint8* src_argb, int src_stride_argb, uint8* dst_argb4444, int dst_stride_argb4444, int width, int height) { if (!src_argb || !dst_argb4444 || width <= 0 || height == 0) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBToARGB4444Row)(const uint8* src_argb, uint8* dst_rgb, int pix) = ARGBToARGB4444Row_C; #if defined(HAS_ARGBTOARGB4444ROW_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16)) { if (width * 2 <= kMaxStride) { ARGBToARGB4444Row = ARGBToARGB4444Row_Any_SSE2; } if (IS_ALIGNED(width, 4)) { ARGBToARGB4444Row = ARGBToARGB4444Row_SSE2; } } #endif for (int y = 0; y < height; ++y) { ARGBToARGB4444Row(src_argb, dst_argb4444, width); src_argb += src_stride_argb; dst_argb4444 += dst_stride_argb4444; } return 0; } // Convert NV12 to RGB565. // TODO(fbarchard): (Re) Optimize for Neon. int NV12ToRGB565(const uint8* src_y, int src_stride_y, const uint8* src_uv, int src_stride_uv, uint8* dst_rgb565, int dst_stride_rgb565, int width, int height) { if (!src_y || !src_uv || !dst_rgb565 || width <= 0 || height == 0) { return -1; } // Negative height means invert the image. if (height < 0) { height = -height; dst_rgb565 = dst_rgb565 + (height - 1) * dst_stride_rgb565; dst_stride_rgb565 = -dst_stride_rgb565; } void (*NV12ToARGBRow)(const uint8* y_buf, const uint8* uv_buf, uint8* rgb_buf, int width) = NV12ToARGBRow_C; #if defined(HAS_NV12TOARGBROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && width * 4 <= kMaxStride) { NV12ToARGBRow = NV12ToARGBRow_SSSE3; } #endif SIMD_ALIGNED(uint8 row[kMaxStride]); void (*ARGBToRGB565Row)(const uint8* src_argb, uint8* dst_rgb, int pix) = ARGBToRGB565Row_C; #if defined(HAS_ARGBTORGB565ROW_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(width, 4)) { ARGBToRGB565Row = ARGBToRGB565Row_SSE2; } #endif for (int y = 0; y < height; ++y) { NV12ToARGBRow(src_y, src_uv, row, width); ARGBToRGB565Row(row, dst_rgb565, width); dst_rgb565 += dst_stride_rgb565; src_y += src_stride_y; if (y & 1) { src_uv += src_stride_uv; } } return 0; } // Convert NV21 to RGB565. int NV21ToRGB565(const uint8* src_y, int src_stride_y, const uint8* src_vu, int src_stride_vu, uint8* dst_rgb565, int dst_stride_rgb565, int width, int height) { if (!src_y || !src_vu || !dst_rgb565 || width <= 0 || height == 0) { return -1; } // Negative height means invert the image. if (height < 0) { height = -height; dst_rgb565 = dst_rgb565 + (height - 1) * dst_stride_rgb565; dst_stride_rgb565 = -dst_stride_rgb565; } void (*NV21ToARGBRow)(const uint8* y_buf, const uint8* uv_buf, uint8* rgb_buf, int width) = NV21ToARGBRow_C; #if defined(HAS_NV21TOARGBROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && width * 4 <= kMaxStride) { NV21ToARGBRow = NV21ToARGBRow_SSSE3; } #endif SIMD_ALIGNED(uint8 row[kMaxStride]); void (*ARGBToRGB565Row)(const uint8* src_argb, uint8* dst_rgb, int pix) = ARGBToRGB565Row_C; #if defined(HAS_ARGBTORGB565ROW_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(width, 4)) { ARGBToRGB565Row = ARGBToRGB565Row_SSE2; } #endif for (int y = 0; y < height; ++y) { NV21ToARGBRow(src_y, src_vu, row, width); ARGBToRGB565Row(row, dst_rgb565, width); dst_rgb565 += dst_stride_rgb565; src_y += src_stride_y; if (y & 1) { src_vu += src_stride_vu; } } return 0; } // SetRow8 writes 'count' bytes using a 32 bit value repeated // SetRow32 writes 'count' words using a 32 bit value repeated #if !defined(YUV_DISABLE_ASM) && defined(__ARM_NEON__) #define HAS_SETROW_NEON static void SetRow8_NEON(uint8* dst, uint32 v32, int count) { asm volatile ( "vdup.u32 q0, %2 \n" // duplicate 4 ints "1: \n" "subs %1, %1, #16 \n" // 16 bytes per loop "vst1.u32 {q0}, [%0]! \n" // store "bgt 1b \n" : "+r"(dst), // %0 "+r"(count) // %1 : "r"(v32) // %2 : "q0", "memory", "cc"); } // TODO(fbarchard): Make fully assembler static void SetRows32_NEON(uint8* dst, uint32 v32, int width, int dst_stride, int height) { for (int y = 0; y < height; ++y) { SetRow8_NEON(dst, v32, width << 2); dst += dst_stride; } } #elif !defined(YUV_DISABLE_ASM) && defined(_M_IX86) #define HAS_SETROW_X86 __declspec(naked) __declspec(align(16)) static void SetRow8_X86(uint8* dst, uint32 v32, int count) { __asm { mov edx, edi mov edi, [esp + 4] // dst mov eax, [esp + 8] // v32 mov ecx, [esp + 12] // count shr ecx, 2 rep stosd mov edi, edx ret } } __declspec(naked) __declspec(align(16)) static void SetRows32_X86(uint8* dst, uint32 v32, int width, int dst_stride, int height) { __asm { push esi push edi push ebp mov edi, [esp + 12 + 4] // dst mov eax, [esp + 12 + 8] // v32 mov ebp, [esp + 12 + 12] // width mov edx, [esp + 12 + 16] // dst_stride mov esi, [esp + 12 + 20] // height lea ecx, [ebp * 4] sub edx, ecx // stride - width * 4 align 16 convertloop: mov ecx, ebp rep stosd add edi, edx sub esi, 1 jg convertloop pop ebp pop edi pop esi ret } } #elif !defined(YUV_DISABLE_ASM) && (defined(__x86_64__) || defined(__i386__)) #define HAS_SETROW_X86 static void SetRow8_X86(uint8* dst, uint32 v32, int width) { size_t width_tmp = static_cast<size_t>(width); asm volatile ( "shr $0x2,%1 \n" "rep stosl \n" : "+D"(dst), // %0 "+c"(width_tmp) // %1 : "a"(v32) // %2 : "memory", "cc"); } static void SetRows32_X86(uint8* dst, uint32 v32, int width, int dst_stride, int height) { for (int y = 0; y < height; ++y) { size_t width_tmp = static_cast<size_t>(width); uint32* d = reinterpret_cast<uint32*>(dst); asm volatile ( "rep stosl \n" : "+D"(d), // %0 "+c"(width_tmp) // %1 : "a"(v32) // %2 : "memory", "cc"); dst += dst_stride; } } #endif static void SetRow8_C(uint8* dst, uint32 v8, int count) { #ifdef _MSC_VER for (int x = 0; x < count; ++x) { dst[x] = v8; } #else memset(dst, v8, count); #endif } static void SetRows32_C(uint8* dst, uint32 v32, int width, int dst_stride, int height) { for (int y = 0; y < height; ++y) { uint32* d = reinterpret_cast<uint32*>(dst); for (int x = 0; x < width; ++x) { d[x] = v32; } dst += dst_stride; } } void SetPlane(uint8* dst_y, int dst_stride_y, int width, int height, uint32 value) { void (*SetRow)(uint8* dst, uint32 value, int pix) = SetRow8_C; #if defined(HAS_SETROW_NEON) if (TestCpuFlag(kCpuHasNEON) && IS_ALIGNED(width, 16) && IS_ALIGNED(dst_y, 16) && IS_ALIGNED(dst_stride_y, 16)) { SetRow = SetRow8_NEON; } #endif #if defined(HAS_SETROW_X86) if (TestCpuFlag(kCpuHasX86) && IS_ALIGNED(width, 4)) { SetRow = SetRow8_X86; } #endif #if defined(HAS_SETROW_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(width, 16) && IS_ALIGNED(dst_y, 16) && IS_ALIGNED(dst_stride_y, 16)) { SetRow = SetRow8_SSE2; } #endif uint32 v32 = value | (value << 8) | (value << 16) | (value << 24); // Set plane for (int y = 0; y < height; ++y) { SetRow(dst_y, v32, width); dst_y += dst_stride_y; } } // Draw a rectangle into I420 int I420Rect(uint8* dst_y, int dst_stride_y, uint8* dst_u, int dst_stride_u, uint8* dst_v, int dst_stride_v, int x, int y, int width, int height, int value_y, int value_u, int value_v) { if (!dst_y || !dst_u || !dst_v || width <= 0 || height <= 0 || x < 0 || y < 0 || value_y < 0 || value_y > 255 || value_u < 0 || value_u > 255 || value_v < 0 || value_v > 255) { return -1; } int halfwidth = (width + 1) >> 1; int halfheight = (height + 1) >> 1; uint8* start_y = dst_y + y * dst_stride_y + x; uint8* start_u = dst_u + (y / 2) * dst_stride_u + (x / 2); uint8* start_v = dst_v + (y / 2) * dst_stride_v + (x / 2); SetPlane(start_y, dst_stride_y, width, height, value_y); SetPlane(start_u, dst_stride_u, halfwidth, halfheight, value_u); SetPlane(start_v, dst_stride_v, halfwidth, halfheight, value_v); return 0; } // Draw a rectangle into ARGB int ARGBRect(uint8* dst_argb, int dst_stride_argb, int dst_x, int dst_y, int width, int height, uint32 value) { if (!dst_argb || width <= 0 || height <= 0 || dst_x < 0 || dst_y < 0) { return -1; } uint8* dst = dst_argb + dst_y * dst_stride_argb + dst_x * 4; #if defined(HAS_SETROW_NEON) if (TestCpuFlag(kCpuHasNEON) && IS_ALIGNED(width, 16) && IS_ALIGNED(dst, 16) && IS_ALIGNED(dst_stride_argb, 16)) { SetRows32_NEON(dst, value, width, dst_stride_argb, height); return 0; } #endif #if defined(HAS_SETROW_X86) if (TestCpuFlag(kCpuHasX86)) { SetRows32_X86(dst, value, width, dst_stride_argb, height); return 0; } #endif SetRows32_C(dst, value, width, dst_stride_argb, height); return 0; } // Convert unattentuated ARGB to preattenuated ARGB. // An unattenutated ARGB alpha blend uses the formula // p = a * f + (1 - a) * b // where // p is output pixel // f is foreground pixel // b is background pixel // a is alpha value from foreground pixel // An preattenutated ARGB alpha blend uses the formula // p = f + (1 - a) * b // where // f is foreground pixel premultiplied by alpha int ARGBAttenuate(const uint8* src_argb, int src_stride_argb, uint8* dst_argb, int dst_stride_argb, int width, int height) { if (!src_argb || !dst_argb || width <= 0 || height == 0) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBAttenuateRow)(const uint8* src_argb, uint8* dst_argb, int width) = ARGBAttenuateRow_C; #if defined(HAS_ARGBATTENUATE_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(width, 4) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ARGBAttenuateRow = ARGBAttenuateRow_SSE2; } #endif #if defined(HAS_ARGBATTENUATEROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(width, 4) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ARGBAttenuateRow = ARGBAttenuateRow_SSSE3; } #endif for (int y = 0; y < height; ++y) { ARGBAttenuateRow(src_argb, dst_argb, width); src_argb += src_stride_argb; dst_argb += dst_stride_argb; } return 0; } // Convert preattentuated ARGB to unattenuated ARGB. int ARGBUnattenuate(const uint8* src_argb, int src_stride_argb, uint8* dst_argb, int dst_stride_argb, int width, int height) { if (!src_argb || !dst_argb || width <= 0 || height == 0) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBUnattenuateRow)(const uint8* src_argb, uint8* dst_argb, int width) = ARGBUnattenuateRow_C; #if defined(HAS_ARGBUNATTENUATEROW_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(width, 4) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ARGBUnattenuateRow = ARGBUnattenuateRow_SSE2; } #endif for (int y = 0; y < height; ++y) { ARGBUnattenuateRow(src_argb, dst_argb, width); src_argb += src_stride_argb; dst_argb += dst_stride_argb; } return 0; } // Convert ARGB to Grayed ARGB. int ARGBGrayTo(const uint8* src_argb, int src_stride_argb, uint8* dst_argb, int dst_stride_argb, int width, int height) { if (!src_argb || !dst_argb || width <= 0 || height == 0) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBGrayRow)(const uint8* src_argb, uint8* dst_argb, int width) = ARGBGrayRow_C; #if defined(HAS_ARGBGRAYROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(width, 8) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ARGBGrayRow = ARGBGrayRow_SSSE3; } #endif for (int y = 0; y < height; ++y) { ARGBGrayRow(src_argb, dst_argb, width); src_argb += src_stride_argb; dst_argb += dst_stride_argb; } return 0; } // Make a rectangle of ARGB gray scale. int ARGBGray(uint8* dst_argb, int dst_stride_argb, int dst_x, int dst_y, int width, int height) { if (!dst_argb || width <= 0 || height <= 0 || dst_x < 0 || dst_y < 0) { return -1; } void (*ARGBGrayRow)(const uint8* src_argb, uint8* dst_argb, int width) = ARGBGrayRow_C; #if defined(HAS_ARGBGRAYROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(width, 8) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ARGBGrayRow = ARGBGrayRow_SSSE3; } #endif uint8* dst = dst_argb + dst_y * dst_stride_argb + dst_x * 4; for (int y = 0; y < height; ++y) { ARGBGrayRow(dst, dst, width); dst += dst_stride_argb; } return 0; } // Make a rectangle of ARGB Sepia tone. int ARGBSepia(uint8* dst_argb, int dst_stride_argb, int dst_x, int dst_y, int width, int height) { if (!dst_argb || width <= 0 || height <= 0 || dst_x < 0 || dst_y < 0) { return -1; } void (*ARGBSepiaRow)(uint8* dst_argb, int width) = ARGBSepiaRow_C; #if defined(HAS_ARGBSEPIAROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(width, 8) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ARGBSepiaRow = ARGBSepiaRow_SSSE3; } #endif uint8* dst = dst_argb + dst_y * dst_stride_argb + dst_x * 4; for (int y = 0; y < height; ++y) { ARGBSepiaRow(dst, width); dst += dst_stride_argb; } return 0; } // Apply a 4x3 matrix rotation to each ARGB pixel. int ARGBColorMatrix(uint8* dst_argb, int dst_stride_argb, const int8* matrix_argb, int dst_x, int dst_y, int width, int height) { if (!dst_argb || !matrix_argb || width <= 0 || height <= 0 || dst_x < 0 || dst_y < 0) { return -1; } void (*ARGBColorMatrixRow)(uint8* dst_argb, const int8* matrix_argb, int width) = ARGBColorMatrixRow_C; #if defined(HAS_ARGBCOLORMATRIXROW_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(width, 8) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ARGBColorMatrixRow = ARGBColorMatrixRow_SSSE3; } #endif uint8* dst = dst_argb + dst_y * dst_stride_argb + dst_x * 4; for (int y = 0; y < height; ++y) { ARGBColorMatrixRow(dst, matrix_argb, width); dst += dst_stride_argb; } return 0; } // Apply a color table each ARGB pixel. // Table contains 256 ARGB values. int ARGBColorTable(uint8* dst_argb, int dst_stride_argb, const uint8* table_argb, int dst_x, int dst_y, int width, int height) { if (!dst_argb || !table_argb || width <= 0 || height <= 0 || dst_x < 0 || dst_y < 0) { return -1; } void (*ARGBColorTableRow)(uint8* dst_argb, const uint8* table_argb, int width) = ARGBColorTableRow_C; #if defined(HAS_ARGBCOLORTABLEROW_X86) if (TestCpuFlag(kCpuHasX86)) { ARGBColorTableRow = ARGBColorTableRow_X86; } #endif uint8* dst = dst_argb + dst_y * dst_stride_argb + dst_x * 4; for (int y = 0; y < height; ++y) { ARGBColorTableRow(dst, table_argb, width); dst += dst_stride_argb; } return 0; } // ARGBQuantize is used to posterize art. // e.g. rgb / qvalue * qvalue + qvalue / 2 // But the low levels implement efficiently with 3 parameters, and could be // used for other high level operations. // The divide is replaces with a multiply by reciprocal fixed point multiply. // Caveat - although SSE2 saturates, the C function does not and should be used // with care if doing anything but quantization. int ARGBQuantize(uint8* dst_argb, int dst_stride_argb, int scale, int interval_size, int interval_offset, int dst_x, int dst_y, int width, int height) { if (!dst_argb || width <= 0 || height <= 0 || dst_x < 0 || dst_y < 0 || interval_size < 1 || interval_size > 255) { return -1; } void (*ARGBQuantizeRow)(uint8* dst_argb, int scale, int interval_size, int interval_offset, int width) = ARGBQuantizeRow_C; #if defined(HAS_ARGBQUANTIZEROW_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(width, 4) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ARGBQuantizeRow = ARGBQuantizeRow_SSE2; } #endif uint8* dst = dst_argb + dst_y * dst_stride_argb + dst_x * 4; for (int y = 0; y < height; ++y) { ARGBQuantizeRow(dst, scale, interval_size, interval_offset, width); dst += dst_stride_argb; } return 0; } // Computes table of cumulative sum for image where the value is the sum // of all values above and to the left of the entry. Used by ARGBBlur. int ARGBComputeCumulativeSum(const uint8* src_argb, int src_stride_argb, int32* dst_cumsum, int dst_stride32_cumsum, int width, int height) { if (!dst_cumsum || !src_argb || width <= 0 || height <= 0) { return -1; } void (*ComputeCumulativeSumRow)(const uint8* row, int32* cumsum, const int32* previous_cumsum, int width) = ComputeCumulativeSumRow_C; #if defined(HAS_CUMULATIVESUMTOAVERAGE_SSE2) if (TestCpuFlag(kCpuHasSSE2)) { ComputeCumulativeSumRow = ComputeCumulativeSumRow_SSE2; } #endif memset(dst_cumsum, 0, width * sizeof(dst_cumsum[0]) * 4); // 4 int per pixel. int32* previous_cumsum = dst_cumsum; for (int y = 0; y < height; ++y) { ComputeCumulativeSumRow(src_argb, dst_cumsum, previous_cumsum, width); previous_cumsum = dst_cumsum; dst_cumsum += dst_stride32_cumsum; src_argb += src_stride_argb; } return 0; } // Blur ARGB image. // Caller should allocate CumulativeSum table of width * height * 16 bytes // aligned to 16 byte boundary. height can be radius * 2 + 2 to save memory // as the buffer is treated as circular. int ARGBBlur(const uint8* src_argb, int src_stride_argb, uint8* dst_argb, int dst_stride_argb, int32* dst_cumsum, int dst_stride32_cumsum, int width, int height, int radius) { if (!src_argb || !dst_argb || width <= 0 || height == 0) { return -1; } void (*ComputeCumulativeSumRow)(const uint8* row, int32* cumsum, const int32* previous_cumsum, int width) = ComputeCumulativeSumRow_C; void (*CumulativeSumToAverage)(const int32* topleft, const int32* botleft, int width, int area, uint8* dst, int count) = CumulativeSumToAverage_C; #if defined(HAS_CUMULATIVESUMTOAVERAGE_SSE2) if (TestCpuFlag(kCpuHasSSE2)) { ComputeCumulativeSumRow = ComputeCumulativeSumRow_SSE2; CumulativeSumToAverage = CumulativeSumToAverage_SSE2; } #endif // Compute enough CumulativeSum for first row to be blurred. After this // one row of CumulativeSum is updated at a time. ARGBComputeCumulativeSum(src_argb, src_stride_argb, dst_cumsum, dst_stride32_cumsum, width, radius); src_argb = src_argb + radius * src_stride_argb; int32* cumsum_bot_row = &dst_cumsum[(radius - 1) * dst_stride32_cumsum]; const int32* max_cumsum_bot_row = &dst_cumsum[(radius * 2 + 2) * dst_stride32_cumsum]; const int32* cumsum_top_row = &dst_cumsum[0]; for (int y = 0; y < height; ++y) { int top_y = ((y - radius - 1) >= 0) ? (y - radius - 1) : 0; int bot_y = ((y + radius) < height) ? (y + radius) : (height - 1); int area = radius * (bot_y - top_y); // Increment cumsum_top_row pointer with circular buffer wrap around. if (top_y) { cumsum_top_row += dst_stride32_cumsum; if (cumsum_top_row >= max_cumsum_bot_row) { cumsum_top_row = dst_cumsum; } } // Increment cumsum_bot_row pointer with circular buffer wrap around and // then fill in a row of CumulativeSum. if ((y + radius) < height) { const int32* prev_cumsum_bot_row = cumsum_bot_row; cumsum_bot_row += dst_stride32_cumsum; if (cumsum_bot_row >= max_cumsum_bot_row) { cumsum_bot_row = dst_cumsum; } ComputeCumulativeSumRow(src_argb, cumsum_bot_row, prev_cumsum_bot_row, width); src_argb += src_stride_argb; } // Left clipped. int boxwidth = radius * 4; int x; for (x = 0; x < radius + 1; ++x) { CumulativeSumToAverage(cumsum_top_row, cumsum_bot_row, boxwidth, area, &dst_argb[x * 4], 1); area += (bot_y - top_y); boxwidth += 4; } // Middle unclipped. int n = (width - 1) - radius - x + 1; CumulativeSumToAverage(cumsum_top_row, cumsum_bot_row, boxwidth, area, &dst_argb[x * 4], n); // Right clipped. for (x += n; x <= width - 1; ++x) { area -= (bot_y - top_y); boxwidth -= 4; CumulativeSumToAverage(cumsum_top_row + (x - radius - 1) * 4, cumsum_bot_row + (x - radius - 1) * 4, boxwidth, area, &dst_argb[x * 4], 1); } dst_argb += dst_stride_argb; } return 0; } // Multiply ARGB image by a specified ARGB value. int ARGBShade(const uint8* src_argb, int src_stride_argb, uint8* dst_argb, int dst_stride_argb, int width, int height, uint32 value) { if (!src_argb || !dst_argb || width <= 0 || height == 0 || value == 0u) { return -1; } if (height < 0) { height = -height; src_argb = src_argb + (height - 1) * src_stride_argb; src_stride_argb = -src_stride_argb; } void (*ARGBShadeRow)(const uint8* src_argb, uint8* dst_argb, int width, uint32 value) = ARGBShadeRow_C; #if defined(HAS_ARGBSHADE_SSE2) if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(width, 4) && IS_ALIGNED(src_argb, 16) && IS_ALIGNED(src_stride_argb, 16) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ARGBShadeRow = ARGBShadeRow_SSE2; } #endif for (int y = 0; y < height; ++y) { ARGBShadeRow(src_argb, dst_argb, width, value); src_argb += src_stride_argb; dst_argb += dst_stride_argb; } return 0; } #if !defined(YUV_DISABLE_ASM) && (defined(_M_IX86) || \ (defined(__x86_64__) || defined(__i386__))) #define HAS_SCALEARGBFILTERROWS_SSSE3 #endif void ScaleARGBFilterRows_C(uint8* dst_ptr, const uint8* src_ptr, ptrdiff_t src_stride, int dst_width, int source_y_fraction); void ScaleARGBFilterRows_SSSE3(uint8* dst_ptr, const uint8* src_ptr, ptrdiff_t src_stride, int dst_width, int source_y_fraction); // Interpolate 2 ARGB images by specified amount (0 to 255). int ARGBInterpolate(const uint8* src_argb0, int src_stride_argb0, const uint8* src_argb1, int src_stride_argb1, uint8* dst_argb, int dst_stride_argb, int width, int height, int interpolation) { if (!src_argb0 || !src_argb1 || !dst_argb || width <= 0 || height == 0) { return -1; } // Negative height means invert the image. if (height < 0) { height = -height; dst_argb = dst_argb + (height - 1) * dst_stride_argb; dst_stride_argb = -dst_stride_argb; } void (*ScaleARGBFilterRows)(uint8* dst_ptr, const uint8* src_ptr, ptrdiff_t src_stride, int dst_width, int source_y_fraction) = ScaleARGBFilterRows_C; #if defined(HAS_SCALEARGBFILTERROWS_SSSE3) if (TestCpuFlag(kCpuHasSSSE3) && IS_ALIGNED(src_argb0, 16) && IS_ALIGNED(src_stride_argb0, 16) && IS_ALIGNED(src_argb1, 16) && IS_ALIGNED(src_stride_argb1, 16) && IS_ALIGNED(dst_argb, 16) && IS_ALIGNED(dst_stride_argb, 16)) { ScaleARGBFilterRows = ScaleARGBFilterRows_SSSE3; } #endif uint8 last16[16]; for (int y = 0; y < height; ++y) { // Filter extrudes edge for its scaling purpose. memcpy(last16, dst_argb + width * 4, 16); // Save last 16 beyond end. ScaleARGBFilterRows(dst_argb, src_argb0, src_argb1 - src_argb0, width, interpolation); memcpy(dst_argb + width * 4, last16, 16); // Restore last 16 beyond end. src_argb0 += src_stride_argb0; src_argb1 += src_stride_argb1; dst_argb += dst_stride_argb; } return 0; } #ifdef __cplusplus } // extern "C" } // namespace libyuv #endif
/* * All or portions of this file Copyright(c) Amazon.com, Inc.or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution(the "License").All use of this software is governed by the License, *or, if provided, by the license below or the license accompanying this file.Do not * remove or modify any license notices.This file is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "CopyDependencyBuilderComponent.h" #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Serialization/EditContextConstants.inl> namespace CopyDependencyBuilder { void CopyDependencyBuilderComponent::Activate() { m_fontBuilderWorker.RegisterBuilderWorker(); m_audioControlBuilderWorker.RegisterBuilderWorker(); m_cfgBuilderWorker.RegisterBuilderWorker(); m_schemaBuilderWorker.RegisterBuilderWorker(); m_xmlBuilderWorker.RegisterBuilderWorker(); m_particlePreloadBuilderWorker.RegisterBuilderWorker(); } void CopyDependencyBuilderComponent::Deactivate() { m_particlePreloadBuilderWorker.UnregisterBuilderWorker(); m_xmlBuilderWorker.UnregisterBuilderWorker(); m_schemaBuilderWorker.UnregisterBuilderWorker(); m_cfgBuilderWorker.UnregisterBuilderWorker(); m_audioControlBuilderWorker.UnregisterBuilderWorker(); m_fontBuilderWorker.UnregisterBuilderWorker(); } void CopyDependencyBuilderComponent::Reflect(AZ::ReflectContext* context) { if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->Class<CopyDependencyBuilderComponent, AZ::Component>() ->Version(2); } } }
// Copyright 2020 The IREE Authors // // Licensed 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 #include "iree/hal/drivers/vulkan/native_descriptor_set.h" #include <cstddef> #include "iree/base/api.h" #include "iree/base/tracing.h" using namespace iree::hal::vulkan; typedef struct iree_hal_vulkan_native_descriptor_set_t { iree_hal_resource_t resource; VkDeviceHandle* logical_device; VkDescriptorSet handle; } iree_hal_vulkan_native_descriptor_set_t; namespace { extern const iree_hal_descriptor_set_vtable_t iree_hal_vulkan_native_descriptor_set_vtable; } // namespace static iree_hal_vulkan_native_descriptor_set_t* iree_hal_vulkan_native_descriptor_set_cast( iree_hal_descriptor_set_t* base_value) { IREE_HAL_ASSERT_TYPE(base_value, &iree_hal_vulkan_native_descriptor_set_vtable); return (iree_hal_vulkan_native_descriptor_set_t*)base_value; } iree_status_t iree_hal_vulkan_native_descriptor_set_create( iree::hal::vulkan::VkDeviceHandle* logical_device, VkDescriptorSet handle, iree_hal_descriptor_set_t** out_descriptor_set) { IREE_ASSERT_ARGUMENT(logical_device); IREE_ASSERT_ARGUMENT(handle); IREE_ASSERT_ARGUMENT(out_descriptor_set); *out_descriptor_set = NULL; IREE_TRACE_ZONE_BEGIN(z0); iree_hal_vulkan_native_descriptor_set_t* descriptor_set = NULL; iree_status_t status = iree_allocator_malloc(logical_device->host_allocator(), sizeof(*descriptor_set), (void**)&descriptor_set); if (iree_status_is_ok(status)) { iree_hal_resource_initialize(&iree_hal_vulkan_native_descriptor_set_vtable, &descriptor_set->resource); descriptor_set->logical_device = logical_device; descriptor_set->handle = handle; *out_descriptor_set = (iree_hal_descriptor_set_t*)descriptor_set; } IREE_TRACE_ZONE_END(z0); return status; } static void iree_hal_vulkan_native_descriptor_set_destroy( iree_hal_descriptor_set_t* base_descriptor_set) { iree_hal_vulkan_native_descriptor_set_t* descriptor_set = iree_hal_vulkan_native_descriptor_set_cast(base_descriptor_set); iree_allocator_t host_allocator = descriptor_set->logical_device->host_allocator(); IREE_TRACE_ZONE_BEGIN(z0); // TODO(benvanik): return to pool. For now we rely on the descriptor cache to // reset entire pools at once via via vkResetDescriptorPool so we don't need // to do anything here (the VkDescriptorSet handle will just be invalidated). // In the future if we want to have generational collection/defragmentation // of the descriptor cache we'll want to allow both pooled and unpooled // descriptors and clean them up here appropriately. iree_allocator_free(host_allocator, descriptor_set); IREE_TRACE_ZONE_END(z0); } VkDescriptorSet iree_hal_vulkan_native_descriptor_set_handle( iree_hal_descriptor_set_t* base_descriptor_set) { iree_hal_vulkan_native_descriptor_set_t* descriptor_set = iree_hal_vulkan_native_descriptor_set_cast(base_descriptor_set); return descriptor_set->handle; } namespace { const iree_hal_descriptor_set_vtable_t iree_hal_vulkan_native_descriptor_set_vtable = { /*.destroy=*/iree_hal_vulkan_native_descriptor_set_destroy, }; } // namespace
/* * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org> * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/Demangle.h> #include <AK/HashMap.h> #include <AK/HashTable.h> #include <AK/ScopeGuard.h> #include <AK/StringBuilder.h> #include <AK/TemporaryChange.h> #include <LibCrypto/BigInt/SignedBigInteger.h> #include <LibJS/AST.h> #include <LibJS/Interpreter.h> #include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/Accessor.h> #include <LibJS/Runtime/Array.h> #include <LibJS/Runtime/BigInt.h> #include <LibJS/Runtime/Error.h> #include <LibJS/Runtime/FunctionEnvironment.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/IteratorOperations.h> #include <LibJS/Runtime/MarkedValueList.h> #include <LibJS/Runtime/NativeFunction.h> #include <LibJS/Runtime/ObjectEnvironment.h> #include <LibJS/Runtime/OrdinaryFunctionObject.h> #include <LibJS/Runtime/PrimitiveString.h> #include <LibJS/Runtime/Reference.h> #include <LibJS/Runtime/RegExpObject.h> #include <LibJS/Runtime/Shape.h> #include <typeinfo> namespace JS { class InterpreterNodeScope { AK_MAKE_NONCOPYABLE(InterpreterNodeScope); AK_MAKE_NONMOVABLE(InterpreterNodeScope); public: InterpreterNodeScope(Interpreter& interpreter, ASTNode const& node) : m_interpreter(interpreter) , m_chain_node { nullptr, node } { m_interpreter.vm().running_execution_context().current_node = &node; m_interpreter.push_ast_node(m_chain_node); } ~InterpreterNodeScope() { m_interpreter.pop_ast_node(); } private: Interpreter& m_interpreter; ExecutingASTNodeChain m_chain_node; }; String ASTNode::class_name() const { // NOTE: We strip the "JS::" prefix. return demangle(typeid(*this).name()).substring(4); } static void update_function_name(Value value, FlyString const& name) { if (!value.is_function()) return; auto& function = value.as_function(); if (is<OrdinaryFunctionObject>(function) && function.name().is_empty()) static_cast<OrdinaryFunctionObject&>(function).set_name(name); } static String get_function_name(GlobalObject& global_object, Value value) { if (value.is_symbol()) return String::formatted("[{}]", value.as_symbol().description()); if (value.is_string()) return value.as_string().string(); return value.to_string(global_object); } Value ScopeNode::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; return interpreter.execute_statement(global_object, *this); } Value Program::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; return interpreter.execute_statement(global_object, *this, ScopeType::Block); } Value FunctionDeclaration::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; return {}; } Value FunctionExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; return OrdinaryFunctionObject::create(global_object, name(), body(), parameters(), function_length(), interpreter.lexical_environment(), kind(), is_strict_mode() || interpreter.vm().in_strict_mode(), is_arrow_function()); } Value ExpressionStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; return m_expression->execute(interpreter, global_object); } CallExpression::ThisAndCallee CallExpression::compute_this_and_callee(Interpreter& interpreter, GlobalObject& global_object) const { auto& vm = interpreter.vm(); if (is<MemberExpression>(*m_callee)) { auto& member_expression = static_cast<MemberExpression const&>(*m_callee); Value callee; Value this_value; if (is<SuperExpression>(member_expression.object())) { auto super_base = interpreter.current_function_environment()->get_super_base(); if (super_base.is_nullish()) { vm.throw_exception<TypeError>(global_object, ErrorType::ObjectPrototypeNullOrUndefinedOnSuperPropertyAccess, super_base.to_string_without_side_effects()); return {}; } auto property_name = member_expression.computed_property_name(interpreter, global_object); if (!property_name.is_valid()) return {}; auto reference = Reference { super_base, property_name, super_base }; callee = reference.get_value(global_object); if (vm.exception()) return {}; this_value = &vm.this_value(global_object).as_object(); } else { auto reference = member_expression.to_reference(interpreter, global_object); if (vm.exception()) return {}; callee = reference.get_value(global_object); if (vm.exception()) return {}; this_value = reference.get_this_value(); } return { this_value, callee }; } if (interpreter.vm().in_strict_mode()) { // If we are in strict mode, |this| should never be bound to global object by default. return { js_undefined(), m_callee->execute(interpreter, global_object) }; } return { &global_object, m_callee->execute(interpreter, global_object) }; } // 13.3.8.1 Runtime Semantics: ArgumentListEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation static void argument_list_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<CallExpression::Argument> const& arguments, MarkedValueList& list) { auto& vm = global_object.vm(); list.ensure_capacity(arguments.size()); for (auto& argument : arguments) { auto value = argument.value->execute(interpreter, global_object); if (vm.exception()) return; if (argument.is_spread) { get_iterator_values(global_object, value, [&](Value iterator_value) { if (vm.exception()) return IterationDecision::Break; list.append(iterator_value); return IterationDecision::Continue; }); if (vm.exception()) return; } else { list.append(value); } } } Value NewExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto& vm = interpreter.vm(); auto callee_value = m_callee->execute(interpreter, global_object); if (vm.exception()) return {}; if (!callee_value.is_function() || (is<NativeFunction>(callee_value.as_object()) && !static_cast<NativeFunction&>(callee_value.as_object()).has_constructor())) { throw_type_error_for_callee(interpreter, global_object, callee_value, "constructor"sv); return {}; } MarkedValueList arg_list(vm.heap()); argument_list_evaluation(interpreter, global_object, m_arguments, arg_list); if (interpreter.exception()) return {}; auto& function = callee_value.as_function(); return vm.construct(function, function, move(arg_list)); } void CallExpression::throw_type_error_for_callee(Interpreter& interpreter, GlobalObject& global_object, Value callee_value, StringView call_type) const { auto& vm = interpreter.vm(); if (is<Identifier>(*m_callee) || is<MemberExpression>(*m_callee)) { String expression_string; if (is<Identifier>(*m_callee)) { expression_string = static_cast<Identifier const&>(*m_callee).string(); } else { expression_string = static_cast<MemberExpression const&>(*m_callee).to_string_approximation(); } vm.throw_exception<TypeError>(global_object, ErrorType::IsNotAEvaluatedFrom, callee_value.to_string_without_side_effects(), call_type, expression_string); } else { vm.throw_exception<TypeError>(global_object, ErrorType::IsNotA, callee_value.to_string_without_side_effects(), call_type); } } Value CallExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto& vm = interpreter.vm(); auto [this_value, callee] = compute_this_and_callee(interpreter, global_object); if (vm.exception()) return {}; VERIFY(!callee.is_empty()); if (!callee.is_function()) { throw_type_error_for_callee(interpreter, global_object, callee, "function"sv); return {}; } MarkedValueList arg_list(vm.heap()); argument_list_evaluation(interpreter, global_object, m_arguments, arg_list); if (interpreter.exception()) return {}; auto& function = callee.as_function(); if (is<Identifier>(*m_callee) && static_cast<Identifier const&>(*m_callee).string() == vm.names.eval.as_string() && &function == global_object.eval_function()) { auto script_value = arg_list.size() == 0 ? js_undefined() : arg_list[0]; return perform_eval(script_value, global_object, vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct); } return vm.call(function, this_value, move(arg_list)); } // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation // SuperCall : super Arguments Value SuperCall::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto& vm = interpreter.vm(); // 1. Let newTarget be GetNewTarget(). auto new_target = vm.get_new_target(); if (vm.exception()) return {}; // 2. Assert: Type(newTarget) is Object. VERIFY(new_target.is_function()); // 3. Let func be ! GetSuperConstructor(). auto* func = get_super_constructor(interpreter.vm()); VERIFY(!vm.exception()); // 4. Let argList be ? ArgumentListEvaluation of Arguments. MarkedValueList arg_list(vm.heap()); argument_list_evaluation(interpreter, global_object, m_arguments, arg_list); if (interpreter.exception()) return {}; // 5. If IsConstructor(func) is false, throw a TypeError exception. // FIXME: This check is non-conforming. if (!func || !func->is_function()) { vm.throw_exception<TypeError>(global_object, ErrorType::NotAConstructor, "Super constructor"); return {}; } // 6. Let result be ? Construct(func, argList, newTarget). auto& function = new_target.as_function(); auto result = vm.construct(static_cast<FunctionObject&>(*func), function, move(arg_list)); if (vm.exception()) return {}; // 7. Let thisER be GetThisEnvironment(). auto& this_er = verify_cast<FunctionEnvironment>(get_this_environment(interpreter.vm())); // 8. Perform ? thisER.BindThisValue(result). this_er.bind_this_value(global_object, result); if (vm.exception()) return {}; // 9. Let F be thisER.[[FunctionObject]]. // 10. Assert: F is an ECMAScript function object. (NOTE: This is implied by the strong C++ type.) [[maybe_unused]] auto& f = this_er.function_object(); // 11. Perform ? InitializeInstanceElements(result, F). // FIXME: This is missing here. // 12. Return result. return result; } Value YieldExpression::execute(Interpreter&, GlobalObject&) const { // This should be transformed to a return. VERIFY_NOT_REACHED(); } Value ReturnStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto value = argument() ? argument()->execute(interpreter, global_object) : js_undefined(); if (interpreter.exception()) return {}; interpreter.vm().unwind(ScopeType::Function); return value; } Value IfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto predicate_result = m_predicate->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (predicate_result.to_boolean()) return interpreter.execute_statement(global_object, *m_consequent); if (m_alternate) return interpreter.execute_statement(global_object, *m_alternate); return js_undefined(); } // 14.11.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-with-statement-runtime-semantics-evaluation // WithStatement : with ( Expression ) Statement Value WithStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; // 1. Let value be the result of evaluating Expression. auto value = m_object->execute(interpreter, global_object); if (interpreter.exception()) return {}; // 2. Let obj be ? ToObject(? GetValue(value)). auto* object = value.to_object(global_object); if (interpreter.exception()) return {}; // 3. Let oldEnv be the running execution context's LexicalEnvironment. auto* old_environment = interpreter.vm().running_execution_context().lexical_environment; // 4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv). auto* new_environment = new_object_environment(*object, true, old_environment); if (interpreter.exception()) return {}; // 5. Set the running execution context's LexicalEnvironment to newEnv. interpreter.vm().running_execution_context().lexical_environment = new_environment; // 6. Let C be the result of evaluating Statement. auto result = interpreter.execute_statement(global_object, m_body).value_or(js_undefined()); if (interpreter.exception()) return {}; // 7. Set the running execution context's LexicalEnvironment to oldEnv. interpreter.vm().running_execution_context().lexical_environment = old_environment; // 8. Return Completion(UpdateEmpty(C, undefined)). return result; } Value WhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto last_value = js_undefined(); for (;;) { auto test_result = m_test->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (!test_result.to_boolean()) break; last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value); if (interpreter.exception()) return {}; if (interpreter.vm().should_unwind()) { if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) { interpreter.vm().stop_unwind(); } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) { interpreter.vm().stop_unwind(); break; } else { return last_value; } } } return last_value; } Value DoWhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto last_value = js_undefined(); for (;;) { if (interpreter.exception()) return {}; last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value); if (interpreter.exception()) return {}; if (interpreter.vm().should_unwind()) { if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) { interpreter.vm().stop_unwind(); } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) { interpreter.vm().stop_unwind(); break; } else { return last_value; } } auto test_result = m_test->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (!test_result.to_boolean()) break; } return last_value; } Value ForStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; RefPtr<BlockStatement> wrapper; if (m_init && is<VariableDeclaration>(*m_init) && static_cast<VariableDeclaration const&>(*m_init).declaration_kind() != DeclarationKind::Var) { wrapper = create_ast_node<BlockStatement>(source_range()); NonnullRefPtrVector<VariableDeclaration> decls; decls.append(*static_cast<VariableDeclaration const*>(m_init.ptr())); wrapper->add_variables(decls); interpreter.enter_scope(*wrapper, ScopeType::Block, global_object); } auto wrapper_cleanup = ScopeGuard([&] { if (wrapper) interpreter.exit_scope(*wrapper); }); auto last_value = js_undefined(); if (m_init) { m_init->execute(interpreter, global_object); if (interpreter.exception()) return {}; } if (m_test) { while (true) { auto test_result = m_test->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (!test_result.to_boolean()) break; last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value); if (interpreter.exception()) return {}; if (interpreter.vm().should_unwind()) { if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) { interpreter.vm().stop_unwind(); } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) { interpreter.vm().stop_unwind(); break; } else { return last_value; } } if (m_update) { m_update->execute(interpreter, global_object); if (interpreter.exception()) return {}; } } } else { while (true) { last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value); if (interpreter.exception()) return {}; if (interpreter.vm().should_unwind()) { if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) { interpreter.vm().stop_unwind(); } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) { interpreter.vm().stop_unwind(); break; } else { return last_value; } } if (m_update) { m_update->execute(interpreter, global_object); if (interpreter.exception()) return {}; } } } return last_value; } static Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>> variable_from_for_declaration(Interpreter& interpreter, GlobalObject& global_object, ASTNode const& node, RefPtr<BlockStatement> wrapper) { if (is<VariableDeclaration>(node)) { auto& variable_declaration = static_cast<VariableDeclaration const&>(node); VERIFY(!variable_declaration.declarations().is_empty()); if (variable_declaration.declaration_kind() != DeclarationKind::Var) { wrapper = create_ast_node<BlockStatement>(node.source_range()); interpreter.enter_scope(*wrapper, ScopeType::Block, global_object); } variable_declaration.execute(interpreter, global_object); return variable_declaration.declarations().first().target(); } if (is<Identifier>(node)) { return NonnullRefPtr(static_cast<Identifier const&>(node)); } VERIFY_NOT_REACHED(); } Value ForInStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; bool has_declaration = is<VariableDeclaration>(*m_lhs); if (!has_declaration && !is<Identifier>(*m_lhs)) { // FIXME: Implement "for (foo.bar in baz)", "for (foo[0] in bar)" VERIFY_NOT_REACHED(); } RefPtr<BlockStatement> wrapper; auto target = variable_from_for_declaration(interpreter, global_object, m_lhs, wrapper); auto wrapper_cleanup = ScopeGuard([&] { if (wrapper) interpreter.exit_scope(*wrapper); }); auto last_value = js_undefined(); auto rhs_result = m_rhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (rhs_result.is_nullish()) return {}; auto* object = rhs_result.to_object(global_object); while (object) { auto property_names = object->get_enumerable_own_property_names(Object::PropertyKind::Key); for (auto& value : property_names) { interpreter.vm().assign(target, value, global_object, has_declaration); if (interpreter.exception()) return {}; last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value); if (interpreter.exception()) return {}; if (interpreter.vm().should_unwind()) { if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) { interpreter.vm().stop_unwind(); } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) { interpreter.vm().stop_unwind(); break; } else { return last_value; } } } object = object->prototype(); if (interpreter.exception()) return {}; } return last_value; } Value ForOfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; bool has_declaration = is<VariableDeclaration>(*m_lhs); if (!has_declaration && !is<Identifier>(*m_lhs)) { // FIXME: Implement "for (foo.bar of baz)", "for (foo[0] of bar)" VERIFY_NOT_REACHED(); } RefPtr<BlockStatement> wrapper; auto target = variable_from_for_declaration(interpreter, global_object, m_lhs, wrapper); auto wrapper_cleanup = ScopeGuard([&] { if (wrapper) interpreter.exit_scope(*wrapper); }); auto last_value = js_undefined(); auto rhs_result = m_rhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; get_iterator_values(global_object, rhs_result, [&](Value value) { interpreter.vm().assign(target, value, global_object, has_declaration); last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value); if (interpreter.exception()) return IterationDecision::Break; if (interpreter.vm().should_unwind()) { if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) { interpreter.vm().stop_unwind(); } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) { interpreter.vm().stop_unwind(); return IterationDecision::Break; } else { return IterationDecision::Break; } } return IterationDecision::Continue; }); if (interpreter.exception()) return {}; return last_value; } Value BinaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto lhs_result = m_lhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; auto rhs_result = m_rhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; switch (m_op) { case BinaryOp::Addition: return add(global_object, lhs_result, rhs_result); case BinaryOp::Subtraction: return sub(global_object, lhs_result, rhs_result); case BinaryOp::Multiplication: return mul(global_object, lhs_result, rhs_result); case BinaryOp::Division: return div(global_object, lhs_result, rhs_result); case BinaryOp::Modulo: return mod(global_object, lhs_result, rhs_result); case BinaryOp::Exponentiation: return exp(global_object, lhs_result, rhs_result); case BinaryOp::TypedEquals: return Value(strict_eq(lhs_result, rhs_result)); case BinaryOp::TypedInequals: return Value(!strict_eq(lhs_result, rhs_result)); case BinaryOp::AbstractEquals: return Value(abstract_eq(global_object, lhs_result, rhs_result)); case BinaryOp::AbstractInequals: return Value(!abstract_eq(global_object, lhs_result, rhs_result)); case BinaryOp::GreaterThan: return greater_than(global_object, lhs_result, rhs_result); case BinaryOp::GreaterThanEquals: return greater_than_equals(global_object, lhs_result, rhs_result); case BinaryOp::LessThan: return less_than(global_object, lhs_result, rhs_result); case BinaryOp::LessThanEquals: return less_than_equals(global_object, lhs_result, rhs_result); case BinaryOp::BitwiseAnd: return bitwise_and(global_object, lhs_result, rhs_result); case BinaryOp::BitwiseOr: return bitwise_or(global_object, lhs_result, rhs_result); case BinaryOp::BitwiseXor: return bitwise_xor(global_object, lhs_result, rhs_result); case BinaryOp::LeftShift: return left_shift(global_object, lhs_result, rhs_result); case BinaryOp::RightShift: return right_shift(global_object, lhs_result, rhs_result); case BinaryOp::UnsignedRightShift: return unsigned_right_shift(global_object, lhs_result, rhs_result); case BinaryOp::In: return in(global_object, lhs_result, rhs_result); case BinaryOp::InstanceOf: return instance_of(global_object, lhs_result, rhs_result); } VERIFY_NOT_REACHED(); } Value LogicalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto lhs_result = m_lhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; switch (m_op) { case LogicalOp::And: if (lhs_result.to_boolean()) { auto rhs_result = m_rhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; return rhs_result; } return lhs_result; case LogicalOp::Or: { if (lhs_result.to_boolean()) return lhs_result; auto rhs_result = m_rhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; return rhs_result; } case LogicalOp::NullishCoalescing: if (lhs_result.is_nullish()) { auto rhs_result = m_rhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; return rhs_result; } return lhs_result; } VERIFY_NOT_REACHED(); } Reference Expression::to_reference(Interpreter&, GlobalObject&) const { return {}; } Reference Identifier::to_reference(Interpreter& interpreter, GlobalObject&) const { return interpreter.vm().resolve_binding(string()); } Reference MemberExpression::to_reference(Interpreter& interpreter, GlobalObject& global_object) const { // 13.3.7.1 Runtime Semantics: Evaluation // SuperProperty : super [ Expression ] // SuperProperty : super . IdentifierName // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation if (is<SuperExpression>(object())) { // 1. Let env be GetThisEnvironment(). auto& environment = get_this_environment(interpreter.vm()); // 2. Let actualThis be ? env.GetThisBinding(). auto actual_this = environment.get_this_binding(global_object); StringOrSymbol property_key; if (is_computed()) { // SuperProperty : super [ Expression ] // 3. Let propertyNameReference be the result of evaluating Expression. // 4. Let propertyNameValue be ? GetValue(propertyNameReference). auto property_name_value = m_property->execute(interpreter, global_object); if (interpreter.exception()) return {}; // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue). property_key = property_name_value.to_property_key(global_object); } else { // SuperProperty : super . IdentifierName // 3. Let propertyKey be StringValue of IdentifierName. VERIFY(is<Identifier>(property())); property_key = static_cast<Identifier const&>(property()).string(); } // 6. If the code matched by this SuperProperty is strict mode code, let strict be true; else let strict be false. bool strict = interpreter.vm().in_strict_mode(); // 7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict). return make_super_property_reference(global_object, actual_this, property_key, strict); } auto object_value = m_object->execute(interpreter, global_object); if (interpreter.exception()) return {}; object_value = require_object_coercible(global_object, object_value); if (interpreter.exception()) return {}; auto property_name = computed_property_name(interpreter, global_object); if (!property_name.is_valid()) return Reference {}; return Reference { object_value, property_name, {} }; } Value UnaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto& vm = interpreter.vm(); if (m_op == UnaryOp::Delete) { auto reference = m_lhs->to_reference(interpreter, global_object); if (interpreter.exception()) return {}; return Value(reference.delete_(global_object)); } Value lhs_result; if (m_op == UnaryOp::Typeof && is<Identifier>(*m_lhs)) { auto reference = m_lhs->to_reference(interpreter, global_object); if (interpreter.exception()) { return {}; } if (reference.is_unresolvable()) { lhs_result = js_undefined(); } else { lhs_result = reference.get_value(global_object, false); } } else { lhs_result = m_lhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; } switch (m_op) { case UnaryOp::BitwiseNot: return bitwise_not(global_object, lhs_result); case UnaryOp::Not: return Value(!lhs_result.to_boolean()); case UnaryOp::Plus: return unary_plus(global_object, lhs_result); case UnaryOp::Minus: return unary_minus(global_object, lhs_result); case UnaryOp::Typeof: return js_string(vm, lhs_result.typeof()); case UnaryOp::Void: return js_undefined(); case UnaryOp::Delete: VERIFY_NOT_REACHED(); } VERIFY_NOT_REACHED(); } Value SuperExpression::execute(Interpreter&, GlobalObject&) const { // The semantics for SuperExpression are handled in CallExpression and SuperCall. VERIFY_NOT_REACHED(); } Value ClassMethod::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; return m_function->execute(interpreter, global_object); } Value ClassExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto& vm = interpreter.vm(); Value class_constructor_value = m_constructor->execute(interpreter, global_object); if (interpreter.exception()) return {}; update_function_name(class_constructor_value, m_name); VERIFY(class_constructor_value.is_function() && is<OrdinaryFunctionObject>(class_constructor_value.as_function())); auto* class_constructor = static_cast<OrdinaryFunctionObject*>(&class_constructor_value.as_function()); class_constructor->set_is_class_constructor(); Value super_constructor = js_undefined(); if (!m_super_class.is_null()) { super_constructor = m_super_class->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (!super_constructor.is_function() && !super_constructor.is_null()) { interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::ClassExtendsValueNotAConstructorOrNull, super_constructor.to_string_without_side_effects()); return {}; } class_constructor->set_constructor_kind(FunctionObject::ConstructorKind::Derived); Object* super_constructor_prototype = nullptr; if (!super_constructor.is_null()) { auto super_constructor_prototype_value = super_constructor.as_object().get(vm.names.prototype).value_or(js_undefined()); if (interpreter.exception()) return {}; if (!super_constructor_prototype_value.is_object() && !super_constructor_prototype_value.is_null()) { interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::ClassExtendsValueInvalidPrototype, super_constructor_prototype_value.to_string_without_side_effects()); return {}; } if (super_constructor_prototype_value.is_object()) super_constructor_prototype = &super_constructor_prototype_value.as_object(); } auto* prototype = Object::create(global_object, super_constructor_prototype); prototype->define_property(vm.names.constructor, class_constructor, 0); if (interpreter.exception()) return {}; class_constructor->define_property(vm.names.prototype, prototype, Attribute::Writable); if (interpreter.exception()) return {}; class_constructor->set_prototype(super_constructor.is_null() ? global_object.function_prototype() : &super_constructor.as_object()); } auto class_prototype = class_constructor->get(vm.names.prototype); if (interpreter.exception()) return {}; if (!class_prototype.is_object()) { interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::NotAnObject, "Class prototype"); return {}; } for (const auto& method : m_methods) { auto method_value = method.execute(interpreter, global_object); if (interpreter.exception()) return {}; auto& method_function = method_value.as_function(); auto key = method.key().execute(interpreter, global_object); if (interpreter.exception()) return {}; auto property_key = key.to_property_key(global_object); if (interpreter.exception()) return {}; auto& target = method.is_static() ? *class_constructor : class_prototype.as_object(); method_function.set_home_object(&target); switch (method.kind()) { case ClassMethod::Kind::Method: target.define_property(property_key, method_value); break; case ClassMethod::Kind::Getter: update_function_name(method_value, String::formatted("get {}", get_function_name(global_object, key))); target.define_accessor(property_key, &method_function, nullptr, Attribute::Configurable | Attribute::Enumerable); break; case ClassMethod::Kind::Setter: update_function_name(method_value, String::formatted("set {}", get_function_name(global_object, key))); target.define_accessor(property_key, nullptr, &method_function, Attribute::Configurable | Attribute::Enumerable); break; default: VERIFY_NOT_REACHED(); } if (interpreter.exception()) return {}; } return class_constructor; } Value ClassDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; Value class_constructor = m_class_expression->execute(interpreter, global_object); if (interpreter.exception()) return {}; interpreter.lexical_environment()->put_into_environment(m_class_expression->name(), { class_constructor, DeclarationKind::Let }); return {}; } static void print_indent(int indent) { out("{}", String::repeated(' ', indent * 2)); } void ASTNode::dump(int indent) const { print_indent(indent); outln("{}", class_name()); } void ScopeNode::dump(int indent) const { ASTNode::dump(indent); if (!m_variables.is_empty()) { print_indent(indent + 1); outln("(Variables)"); for (auto& variable : m_variables) variable.dump(indent + 2); } if (!m_children.is_empty()) { print_indent(indent + 1); outln("(Children)"); for (auto& child : children()) child.dump(indent + 2); } } void BinaryExpression::dump(int indent) const { const char* op_string = nullptr; switch (m_op) { case BinaryOp::Addition: op_string = "+"; break; case BinaryOp::Subtraction: op_string = "-"; break; case BinaryOp::Multiplication: op_string = "*"; break; case BinaryOp::Division: op_string = "/"; break; case BinaryOp::Modulo: op_string = "%"; break; case BinaryOp::Exponentiation: op_string = "**"; break; case BinaryOp::TypedEquals: op_string = "==="; break; case BinaryOp::TypedInequals: op_string = "!=="; break; case BinaryOp::AbstractEquals: op_string = "=="; break; case BinaryOp::AbstractInequals: op_string = "!="; break; case BinaryOp::GreaterThan: op_string = ">"; break; case BinaryOp::GreaterThanEquals: op_string = ">="; break; case BinaryOp::LessThan: op_string = "<"; break; case BinaryOp::LessThanEquals: op_string = "<="; break; case BinaryOp::BitwiseAnd: op_string = "&"; break; case BinaryOp::BitwiseOr: op_string = "|"; break; case BinaryOp::BitwiseXor: op_string = "^"; break; case BinaryOp::LeftShift: op_string = "<<"; break; case BinaryOp::RightShift: op_string = ">>"; break; case BinaryOp::UnsignedRightShift: op_string = ">>>"; break; case BinaryOp::In: op_string = "in"; break; case BinaryOp::InstanceOf: op_string = "instanceof"; break; } print_indent(indent); outln("{}", class_name()); m_lhs->dump(indent + 1); print_indent(indent + 1); outln("{}", op_string); m_rhs->dump(indent + 1); } void LogicalExpression::dump(int indent) const { const char* op_string = nullptr; switch (m_op) { case LogicalOp::And: op_string = "&&"; break; case LogicalOp::Or: op_string = "||"; break; case LogicalOp::NullishCoalescing: op_string = "??"; break; } print_indent(indent); outln("{}", class_name()); m_lhs->dump(indent + 1); print_indent(indent + 1); outln("{}", op_string); m_rhs->dump(indent + 1); } void UnaryExpression::dump(int indent) const { const char* op_string = nullptr; switch (m_op) { case UnaryOp::BitwiseNot: op_string = "~"; break; case UnaryOp::Not: op_string = "!"; break; case UnaryOp::Plus: op_string = "+"; break; case UnaryOp::Minus: op_string = "-"; break; case UnaryOp::Typeof: op_string = "typeof "; break; case UnaryOp::Void: op_string = "void "; break; case UnaryOp::Delete: op_string = "delete "; break; } print_indent(indent); outln("{}", class_name()); print_indent(indent + 1); outln("{}", op_string); m_lhs->dump(indent + 1); } void CallExpression::dump(int indent) const { print_indent(indent); if (is<NewExpression>(*this)) outln("CallExpression [new]"); else outln("CallExpression"); m_callee->dump(indent + 1); for (auto& argument : m_arguments) argument.value->dump(indent + 1); } void SuperCall::dump(int indent) const { print_indent(indent); outln("SuperCall"); for (auto& argument : m_arguments) argument.value->dump(indent + 1); } void ClassDeclaration::dump(int indent) const { ASTNode::dump(indent); m_class_expression->dump(indent + 1); } void ClassExpression::dump(int indent) const { print_indent(indent); outln("ClassExpression: \"{}\"", m_name); print_indent(indent); outln("(Constructor)"); m_constructor->dump(indent + 1); if (!m_super_class.is_null()) { print_indent(indent); outln("(Super Class)"); m_super_class->dump(indent + 1); } print_indent(indent); outln("(Methods)"); for (auto& method : m_methods) method.dump(indent + 1); } void ClassMethod::dump(int indent) const { ASTNode::dump(indent); print_indent(indent); outln("(Key)"); m_key->dump(indent + 1); const char* kind_string = nullptr; switch (m_kind) { case Kind::Method: kind_string = "Method"; break; case Kind::Getter: kind_string = "Getter"; break; case Kind::Setter: kind_string = "Setter"; break; } print_indent(indent); outln("Kind: {}", kind_string); print_indent(indent); outln("Static: {}", m_is_static); print_indent(indent); outln("(Function)"); m_function->dump(indent + 1); } void StringLiteral::dump(int indent) const { print_indent(indent); outln("StringLiteral \"{}\"", m_value); } void SuperExpression::dump(int indent) const { print_indent(indent); outln("super"); } void NumericLiteral::dump(int indent) const { print_indent(indent); outln("NumericLiteral {}", m_value); } void BigIntLiteral::dump(int indent) const { print_indent(indent); outln("BigIntLiteral {}", m_value); } void BooleanLiteral::dump(int indent) const { print_indent(indent); outln("BooleanLiteral {}", m_value); } void NullLiteral::dump(int indent) const { print_indent(indent); outln("null"); } void BindingPattern::dump(int indent) const { print_indent(indent); outln("BindingPattern {}", kind == Kind::Array ? "Array" : "Object"); for (auto& entry : entries) { print_indent(indent + 1); outln("(Property)"); if (kind == Kind::Object) { print_indent(indent + 2); outln("(Identifier)"); if (entry.name.has<NonnullRefPtr<Identifier>>()) { entry.name.get<NonnullRefPtr<Identifier>>()->dump(indent + 3); } else { entry.name.get<NonnullRefPtr<Expression>>()->dump(indent + 3); } } else if (entry.is_elision()) { print_indent(indent + 2); outln("(Elision)"); continue; } print_indent(indent + 2); outln("(Pattern{})", entry.is_rest ? " rest=true" : ""); if (entry.alias.has<NonnullRefPtr<Identifier>>()) { entry.alias.get<NonnullRefPtr<Identifier>>()->dump(indent + 3); } else if (entry.alias.has<NonnullRefPtr<BindingPattern>>()) { entry.alias.get<NonnullRefPtr<BindingPattern>>()->dump(indent + 3); } else { print_indent(indent + 3); outln("<empty>"); } if (entry.initializer) { print_indent(indent + 2); outln("(Initializer)"); entry.initializer->dump(indent + 3); } } } void FunctionNode::dump(int indent, String const& class_name) const { print_indent(indent); outln("{}{} '{}'", class_name, m_kind == FunctionKind::Generator ? "*" : "", name()); if (!m_parameters.is_empty()) { print_indent(indent + 1); outln("(Parameters)"); for (auto& parameter : m_parameters) { print_indent(indent + 2); if (parameter.is_rest) out("..."); parameter.binding.visit( [&](FlyString const& name) { outln("{}", name); }, [&](BindingPattern const& pattern) { pattern.dump(indent + 2); }); if (parameter.default_value) parameter.default_value->dump(indent + 3); } } if (!m_variables.is_empty()) { print_indent(indent + 1); outln("(Variables)"); for (auto& variable : m_variables) variable.dump(indent + 2); } print_indent(indent + 1); outln("(Body)"); body().dump(indent + 2); } void FunctionDeclaration::dump(int indent) const { FunctionNode::dump(indent, class_name()); } void FunctionExpression::dump(int indent) const { FunctionNode::dump(indent, class_name()); } void YieldExpression::dump(int indent) const { ASTNode::dump(indent); if (argument()) argument()->dump(indent + 1); } void ReturnStatement::dump(int indent) const { ASTNode::dump(indent); if (argument()) argument()->dump(indent + 1); } void IfStatement::dump(int indent) const { ASTNode::dump(indent); print_indent(indent); outln("If"); predicate().dump(indent + 1); consequent().dump(indent + 1); if (alternate()) { print_indent(indent); outln("Else"); alternate()->dump(indent + 1); } } void WhileStatement::dump(int indent) const { ASTNode::dump(indent); print_indent(indent); outln("While"); test().dump(indent + 1); body().dump(indent + 1); } void WithStatement::dump(int indent) const { ASTNode::dump(indent); print_indent(indent + 1); outln("Object"); object().dump(indent + 2); print_indent(indent + 1); outln("Body"); body().dump(indent + 2); } void DoWhileStatement::dump(int indent) const { ASTNode::dump(indent); print_indent(indent); outln("DoWhile"); test().dump(indent + 1); body().dump(indent + 1); } void ForStatement::dump(int indent) const { ASTNode::dump(indent); print_indent(indent); outln("For"); if (init()) init()->dump(indent + 1); if (test()) test()->dump(indent + 1); if (update()) update()->dump(indent + 1); body().dump(indent + 1); } void ForInStatement::dump(int indent) const { ASTNode::dump(indent); print_indent(indent); outln("ForIn"); lhs().dump(indent + 1); rhs().dump(indent + 1); body().dump(indent + 1); } void ForOfStatement::dump(int indent) const { ASTNode::dump(indent); print_indent(indent); outln("ForOf"); lhs().dump(indent + 1); rhs().dump(indent + 1); body().dump(indent + 1); } Value Identifier::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto value = interpreter.vm().get_variable(string(), global_object); if (value.is_empty()) { if (!interpreter.exception()) interpreter.vm().throw_exception<ReferenceError>(global_object, ErrorType::UnknownIdentifier, string()); return {}; } return value; } void Identifier::dump(int indent) const { print_indent(indent); outln("Identifier \"{}\"", m_string); } void SpreadExpression::dump(int indent) const { ASTNode::dump(indent); m_target->dump(indent + 1); } Value SpreadExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; return m_target->execute(interpreter, global_object); } Value ThisExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; return interpreter.vm().resolve_this_binding(global_object); } void ThisExpression::dump(int indent) const { ASTNode::dump(indent); } Value AssignmentExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; #define EXECUTE_LHS_AND_RHS() \ do { \ lhs_result = m_lhs->execute(interpreter, global_object); \ if (interpreter.exception()) \ return {}; \ rhs_result = m_rhs->execute(interpreter, global_object); \ if (interpreter.exception()) \ return {}; \ } while (0) Value lhs_result; Value rhs_result; switch (m_op) { case AssignmentOp::Assignment: break; case AssignmentOp::AdditionAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = add(global_object, lhs_result, rhs_result); break; case AssignmentOp::SubtractionAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = sub(global_object, lhs_result, rhs_result); break; case AssignmentOp::MultiplicationAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = mul(global_object, lhs_result, rhs_result); break; case AssignmentOp::DivisionAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = div(global_object, lhs_result, rhs_result); break; case AssignmentOp::ModuloAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = mod(global_object, lhs_result, rhs_result); break; case AssignmentOp::ExponentiationAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = exp(global_object, lhs_result, rhs_result); break; case AssignmentOp::BitwiseAndAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = bitwise_and(global_object, lhs_result, rhs_result); break; case AssignmentOp::BitwiseOrAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = bitwise_or(global_object, lhs_result, rhs_result); break; case AssignmentOp::BitwiseXorAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = bitwise_xor(global_object, lhs_result, rhs_result); break; case AssignmentOp::LeftShiftAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = left_shift(global_object, lhs_result, rhs_result); break; case AssignmentOp::RightShiftAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = right_shift(global_object, lhs_result, rhs_result); break; case AssignmentOp::UnsignedRightShiftAssignment: EXECUTE_LHS_AND_RHS(); rhs_result = unsigned_right_shift(global_object, lhs_result, rhs_result); break; case AssignmentOp::AndAssignment: lhs_result = m_lhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (!lhs_result.to_boolean()) return lhs_result; rhs_result = m_rhs->execute(interpreter, global_object); break; case AssignmentOp::OrAssignment: lhs_result = m_lhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (lhs_result.to_boolean()) return lhs_result; rhs_result = m_rhs->execute(interpreter, global_object); break; case AssignmentOp::NullishAssignment: lhs_result = m_lhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (!lhs_result.is_nullish()) return lhs_result; rhs_result = m_rhs->execute(interpreter, global_object); break; } if (interpreter.exception()) return {}; auto reference = m_lhs->to_reference(interpreter, global_object); if (interpreter.exception()) return {}; if (m_op == AssignmentOp::Assignment) { rhs_result = m_rhs->execute(interpreter, global_object); if (interpreter.exception()) return {}; } if (reference.is_unresolvable()) { interpreter.vm().throw_exception<ReferenceError>(global_object, ErrorType::InvalidLeftHandAssignment); return {}; } reference.put_value(global_object, rhs_result); if (interpreter.exception()) return {}; return rhs_result; } Value UpdateExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto reference = m_argument->to_reference(interpreter, global_object); if (interpreter.exception()) return {}; auto old_value = reference.get_value(global_object); if (interpreter.exception()) return {}; old_value = old_value.to_numeric(global_object); if (interpreter.exception()) return {}; Value new_value; switch (m_op) { case UpdateOp::Increment: if (old_value.is_number()) new_value = Value(old_value.as_double() + 1); else new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 })); break; case UpdateOp::Decrement: if (old_value.is_number()) new_value = Value(old_value.as_double() - 1); else new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 })); break; default: VERIFY_NOT_REACHED(); } reference.put_value(global_object, new_value); if (interpreter.exception()) return {}; return m_prefixed ? new_value : old_value; } void AssignmentExpression::dump(int indent) const { const char* op_string = nullptr; switch (m_op) { case AssignmentOp::Assignment: op_string = "="; break; case AssignmentOp::AdditionAssignment: op_string = "+="; break; case AssignmentOp::SubtractionAssignment: op_string = "-="; break; case AssignmentOp::MultiplicationAssignment: op_string = "*="; break; case AssignmentOp::DivisionAssignment: op_string = "/="; break; case AssignmentOp::ModuloAssignment: op_string = "%="; break; case AssignmentOp::ExponentiationAssignment: op_string = "**="; break; case AssignmentOp::BitwiseAndAssignment: op_string = "&="; break; case AssignmentOp::BitwiseOrAssignment: op_string = "|="; break; case AssignmentOp::BitwiseXorAssignment: op_string = "^="; break; case AssignmentOp::LeftShiftAssignment: op_string = "<<="; break; case AssignmentOp::RightShiftAssignment: op_string = ">>="; break; case AssignmentOp::UnsignedRightShiftAssignment: op_string = ">>>="; break; case AssignmentOp::AndAssignment: op_string = "&&="; break; case AssignmentOp::OrAssignment: op_string = "||="; break; case AssignmentOp::NullishAssignment: op_string = "\?\?="; break; } ASTNode::dump(indent); print_indent(indent + 1); outln("{}", op_string); m_lhs->dump(indent + 1); m_rhs->dump(indent + 1); } void UpdateExpression::dump(int indent) const { const char* op_string = nullptr; switch (m_op) { case UpdateOp::Increment: op_string = "++"; break; case UpdateOp::Decrement: op_string = "--"; break; } ASTNode::dump(indent); if (m_prefixed) { print_indent(indent + 1); outln("{}", op_string); } m_argument->dump(indent + 1); if (!m_prefixed) { print_indent(indent + 1); outln("{}", op_string); } } Value VariableDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; for (auto& declarator : m_declarations) { if (auto* init = declarator.init()) { auto initializer_result = init->execute(interpreter, global_object); if (interpreter.exception()) return {}; declarator.target().visit( [&](NonnullRefPtr<Identifier> const& id) { auto variable_name = id->string(); if (is<ClassExpression>(*init)) update_function_name(initializer_result, variable_name); interpreter.vm().set_variable(variable_name, initializer_result, global_object, true); }, [&](NonnullRefPtr<BindingPattern> const& pattern) { interpreter.vm().assign(pattern, initializer_result, global_object, true); }); } } return {}; } Value VariableDeclarator::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; // NOTE: VariableDeclarator execution is handled by VariableDeclaration. VERIFY_NOT_REACHED(); } void VariableDeclaration::dump(int indent) const { const char* declaration_kind_string = nullptr; switch (m_declaration_kind) { case DeclarationKind::Let: declaration_kind_string = "Let"; break; case DeclarationKind::Var: declaration_kind_string = "Var"; break; case DeclarationKind::Const: declaration_kind_string = "Const"; break; } ASTNode::dump(indent); print_indent(indent + 1); outln("{}", declaration_kind_string); for (auto& declarator : m_declarations) declarator.dump(indent + 1); } void VariableDeclarator::dump(int indent) const { ASTNode::dump(indent); m_target.visit([indent](const auto& value) { value->dump(indent + 1); }); if (m_init) m_init->dump(indent + 1); } void ObjectProperty::dump(int indent) const { ASTNode::dump(indent); m_key->dump(indent + 1); m_value->dump(indent + 1); } void ObjectExpression::dump(int indent) const { ASTNode::dump(indent); for (auto& property : m_properties) { property.dump(indent + 1); } } void ExpressionStatement::dump(int indent) const { ASTNode::dump(indent); m_expression->dump(indent + 1); } Value ObjectProperty::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; // NOTE: ObjectProperty execution is handled by ObjectExpression. VERIFY_NOT_REACHED(); } Value ObjectExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto* object = Object::create(global_object, global_object.object_prototype()); for (auto& property : m_properties) { auto key = property.key().execute(interpreter, global_object); if (interpreter.exception()) return {}; if (property.type() == ObjectProperty::Type::Spread) { if (key.is_object() && key.as_object().is_array()) { auto& array_to_spread = static_cast<Array&>(key.as_object()); for (auto& entry : array_to_spread.indexed_properties()) { object->indexed_properties().put(object, entry.index(), entry.value_and_attributes(&array_to_spread).value); if (interpreter.exception()) return {}; } } else if (key.is_object()) { auto& obj_to_spread = key.as_object(); for (auto& it : obj_to_spread.shape().property_table_ordered()) { if (it.value.attributes.is_enumerable()) { object->define_property(it.key, obj_to_spread.get(it.key)); if (interpreter.exception()) return {}; } } } else if (key.is_string()) { auto& str_to_spread = key.as_string().string(); for (size_t i = 0; i < str_to_spread.length(); i++) { object->define_property(i, js_string(interpreter.heap(), str_to_spread.substring(i, 1))); if (interpreter.exception()) return {}; } } continue; } auto value = property.value().execute(interpreter, global_object); if (interpreter.exception()) return {}; if (value.is_function() && property.is_method()) value.as_function().set_home_object(object); String name = get_function_name(global_object, key); if (property.type() == ObjectProperty::Type::Getter) { name = String::formatted("get {}", name); } else if (property.type() == ObjectProperty::Type::Setter) { name = String::formatted("set {}", name); } update_function_name(value, name); switch (property.type()) { case ObjectProperty::Type::Getter: VERIFY(value.is_function()); object->define_accessor(PropertyName::from_value(global_object, key), &value.as_function(), nullptr, Attribute::Configurable | Attribute::Enumerable); break; case ObjectProperty::Type::Setter: VERIFY(value.is_function()); object->define_accessor(PropertyName::from_value(global_object, key), nullptr, &value.as_function(), Attribute::Configurable | Attribute::Enumerable); break; case ObjectProperty::Type::KeyValue: object->define_property(PropertyName::from_value(global_object, key), value); break; case ObjectProperty::Type::Spread: default: VERIFY_NOT_REACHED(); } if (interpreter.exception()) return {}; } return object; } void MemberExpression::dump(int indent) const { print_indent(indent); outln("{}(computed={})", class_name(), is_computed()); m_object->dump(indent + 1); m_property->dump(indent + 1); } PropertyName MemberExpression::computed_property_name(Interpreter& interpreter, GlobalObject& global_object) const { if (!is_computed()) return verify_cast<Identifier>(*m_property).string(); auto value = m_property->execute(interpreter, global_object); if (interpreter.exception()) return {}; VERIFY(!value.is_empty()); return PropertyName::from_value(global_object, value); } String MemberExpression::to_string_approximation() const { String object_string = "<object>"; if (is<Identifier>(*m_object)) object_string = static_cast<Identifier const&>(*m_object).string(); if (is_computed()) return String::formatted("{}[<computed>]", object_string); return String::formatted("{}.{}", object_string, verify_cast<Identifier>(*m_property).string()); } Value MemberExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto reference = to_reference(interpreter, global_object); if (interpreter.exception()) return {}; return reference.get_value(global_object); } void MetaProperty::dump(int indent) const { String name; if (m_type == MetaProperty::Type::NewTarget) name = "new.target"; else if (m_type == MetaProperty::Type::ImportMeta) name = "import.meta"; else VERIFY_NOT_REACHED(); print_indent(indent); outln("{} {}", class_name(), name); } Value MetaProperty::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; if (m_type == MetaProperty::Type::NewTarget) return interpreter.vm().get_new_target().value_or(js_undefined()); if (m_type == MetaProperty::Type::ImportMeta) TODO(); VERIFY_NOT_REACHED(); } Value StringLiteral::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; return js_string(interpreter.heap(), m_value); } Value NumericLiteral::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; return Value(m_value); } Value BigIntLiteral::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; Crypto::SignedBigInteger integer; if (m_value[0] == '0' && m_value.length() >= 3) { if (m_value[1] == 'x' || m_value[1] == 'X') { return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3))); } else if (m_value[1] == 'o' || m_value[1] == 'O') { return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3))); } else if (m_value[1] == 'b' || m_value[1] == 'B') { return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3))); } } return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1))); } Value BooleanLiteral::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; return Value(m_value); } Value NullLiteral::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; return js_null(); } void RegExpLiteral::dump(int indent) const { print_indent(indent); outln("{} (/{}/{})", class_name(), pattern(), flags()); } Value RegExpLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; return RegExpObject::create(global_object, pattern(), flags()); } void ArrayExpression::dump(int indent) const { ASTNode::dump(indent); for (auto& element : m_elements) { if (element) { element->dump(indent + 1); } else { print_indent(indent + 1); outln("<empty>"); } } } Value ArrayExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto* array = Array::create(global_object, 0); for (auto& element : m_elements) { auto value = Value(); if (element) { value = element->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (is<SpreadExpression>(*element)) { get_iterator_values(global_object, value, [&](Value iterator_value) { array->indexed_properties().append(iterator_value); return IterationDecision::Continue; }); if (interpreter.exception()) return {}; continue; } } array->indexed_properties().append(value); } return array; } void TemplateLiteral::dump(int indent) const { ASTNode::dump(indent); for (auto& expression : m_expressions) expression.dump(indent + 1); } Value TemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; StringBuilder string_builder; for (auto& expression : m_expressions) { auto expr = expression.execute(interpreter, global_object); if (interpreter.exception()) return {}; auto string = expr.to_string(global_object); if (interpreter.exception()) return {}; string_builder.append(string); } return js_string(interpreter.heap(), string_builder.build()); } void TaggedTemplateLiteral::dump(int indent) const { ASTNode::dump(indent); print_indent(indent + 1); outln("(Tag)"); m_tag->dump(indent + 2); print_indent(indent + 1); outln("(Template Literal)"); m_template_literal->dump(indent + 2); } Value TaggedTemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto& vm = interpreter.vm(); auto tag = m_tag->execute(interpreter, global_object); if (vm.exception()) return {}; if (!tag.is_function()) { vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, tag.to_string_without_side_effects()); return {}; } auto& tag_function = tag.as_function(); auto& expressions = m_template_literal->expressions(); auto* strings = Array::create(global_object, 0); MarkedValueList arguments(vm.heap()); arguments.append(strings); for (size_t i = 0; i < expressions.size(); ++i) { auto value = expressions[i].execute(interpreter, global_object); if (vm.exception()) return {}; // tag`${foo}` -> "", foo, "" -> tag(["", ""], foo) // tag`foo${bar}baz${qux}` -> "foo", bar, "baz", qux, "" -> tag(["foo", "baz", ""], bar, qux) if (i % 2 == 0) { strings->indexed_properties().append(value); } else { arguments.append(value); } } auto* raw_strings = Array::create(global_object, 0); for (auto& raw_string : m_template_literal->raw_strings()) { auto value = raw_string.execute(interpreter, global_object); if (vm.exception()) return {}; raw_strings->indexed_properties().append(value); } strings->define_property(vm.names.raw, raw_strings, 0); return vm.call(tag_function, js_undefined(), move(arguments)); } void TryStatement::dump(int indent) const { ASTNode::dump(indent); print_indent(indent); outln("(Block)"); block().dump(indent + 1); if (handler()) { print_indent(indent); outln("(Handler)"); handler()->dump(indent + 1); } if (finalizer()) { print_indent(indent); outln("(Finalizer)"); finalizer()->dump(indent + 1); } } void CatchClause::dump(int indent) const { print_indent(indent); if (m_parameter.is_null()) outln("CatchClause"); else outln("CatchClause ({})", m_parameter); body().dump(indent + 1); } void ThrowStatement::dump(int indent) const { ASTNode::dump(indent); argument().dump(indent + 1); } Value TryStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto result = interpreter.execute_statement(global_object, m_block, ScopeType::Try); if (auto* exception = interpreter.exception()) { if (m_handler) { interpreter.vm().clear_exception(); HashMap<FlyString, Variable> parameters; parameters.set(m_handler->parameter(), Variable { exception->value(), DeclarationKind::Var }); auto* catch_scope = interpreter.heap().allocate<DeclarativeEnvironment>(global_object, move(parameters), interpreter.vm().running_execution_context().lexical_environment); TemporaryChange<Environment*> scope_change(interpreter.vm().running_execution_context().lexical_environment, catch_scope); result = interpreter.execute_statement(global_object, m_handler->body()); } } if (m_finalizer) { // Keep, if any, and then clear the current exception so we can // execute() the finalizer without an exception in our way. auto* previous_exception = interpreter.exception(); interpreter.vm().clear_exception(); // Remember what scope type we were unwinding to, and temporarily // clear it as well (e.g. return from handler). auto unwind_until = interpreter.vm().unwind_until(); interpreter.vm().stop_unwind(); auto finalizer_result = m_finalizer->execute(interpreter, global_object); if (interpreter.vm().should_unwind()) { // This was NOT a 'normal' completion (e.g. return from finalizer). result = finalizer_result; } else { // Continue unwinding to whatever we found ourselves unwinding // to when the finalizer was entered (e.g. return from handler, // which is unaffected by normal completion from finalizer). interpreter.vm().unwind(unwind_until); // If we previously had an exception and the finalizer didn't // throw a new one, restore the old one. if (previous_exception && !interpreter.exception()) interpreter.vm().set_exception(*previous_exception); } } return result.value_or(js_undefined()); } Value CatchClause::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; // NOTE: CatchClause execution is handled by TryStatement. VERIFY_NOT_REACHED(); return {}; } Value ThrowStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto value = m_argument->execute(interpreter, global_object); if (interpreter.vm().exception()) return {}; interpreter.vm().throw_exception(global_object, value); return {}; } Value SwitchStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto discriminant_result = m_discriminant->execute(interpreter, global_object); if (interpreter.exception()) return {}; bool falling_through = false; auto last_value = js_undefined(); for (auto& switch_case : m_cases) { if (!falling_through && switch_case.test()) { auto test_result = switch_case.test()->execute(interpreter, global_object); if (interpreter.exception()) return {}; if (!strict_eq(discriminant_result, test_result)) continue; } falling_through = true; for (auto& statement : switch_case.consequent()) { auto value = statement.execute(interpreter, global_object); if (!value.is_empty()) last_value = value; if (interpreter.exception()) return {}; if (interpreter.vm().should_unwind()) { if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) { // No stop_unwind(), the outer loop will handle that - we just need to break out of the switch/case. return last_value; } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) { interpreter.vm().stop_unwind(); return last_value; } else { return last_value; } } } } return last_value; } Value SwitchCase::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; // NOTE: SwitchCase execution is handled by SwitchStatement. VERIFY_NOT_REACHED(); return {}; } Value BreakStatement::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; interpreter.vm().unwind(ScopeType::Breakable, m_target_label); return {}; } Value ContinueStatement::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; interpreter.vm().unwind(ScopeType::Continuable, m_target_label); return {}; } void SwitchStatement::dump(int indent) const { ASTNode::dump(indent); m_discriminant->dump(indent + 1); for (auto& switch_case : m_cases) { switch_case.dump(indent + 1); } } void SwitchCase::dump(int indent) const { ASTNode::dump(indent); print_indent(indent + 1); if (m_test) { outln("(Test)"); m_test->dump(indent + 2); } else { outln("(Default)"); } print_indent(indent + 1); outln("(Consequent)"); for (auto& statement : m_consequent) statement.dump(indent + 2); } Value ConditionalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; auto test_result = m_test->execute(interpreter, global_object); if (interpreter.exception()) return {}; Value result; if (test_result.to_boolean()) { result = m_consequent->execute(interpreter, global_object); } else { result = m_alternate->execute(interpreter, global_object); } if (interpreter.exception()) return {}; return result; } void ConditionalExpression::dump(int indent) const { ASTNode::dump(indent); print_indent(indent + 1); outln("(Test)"); m_test->dump(indent + 2); print_indent(indent + 1); outln("(Consequent)"); m_consequent->dump(indent + 2); print_indent(indent + 1); outln("(Alternate)"); m_alternate->dump(indent + 2); } void SequenceExpression::dump(int indent) const { ASTNode::dump(indent); for (auto& expression : m_expressions) expression.dump(indent + 1); } Value SequenceExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const { InterpreterNodeScope node_scope { interpreter, *this }; Value last_value; for (auto& expression : m_expressions) { last_value = expression.execute(interpreter, global_object); if (interpreter.exception()) return {}; } return last_value; } Value DebuggerStatement::execute(Interpreter& interpreter, GlobalObject&) const { InterpreterNodeScope node_scope { interpreter, *this }; // Sorry, no JavaScript debugger available (yet)! return {}; } void ScopeNode::add_variables(NonnullRefPtrVector<VariableDeclaration> variables) { m_variables.extend(move(variables)); } void ScopeNode::add_functions(NonnullRefPtrVector<FunctionDeclaration> functions) { m_functions.extend(move(functions)); } }
// // memory_window.cpp: Memory view window. // // CEN64D: Cycle-Accurate Nintendo 64 Debugger // Copyright (C) 2015, Tyler J. Stachecki. // // This file is subject to the terms and conditions defined in // 'LICENSE', which is part of this source code package. // #include "memory_window.h" MemoryWindow::MemoryWindow(QAction *toggleAction, bool initiallyVisible) : ToggleWindow(tr("CEN64D: Memory"), toggleAction, initiallyVisible), memoryView(8) { addressLabel.setText("Address: "); layout.addWidget(&memoryView, 0, 1, 1, 2); layout.addWidget(&addressLabel, 1, 1); layout.addWidget(&addressLine, 1, 2); setLayout(&layout); } MemoryWindow::~MemoryWindow() { }
/*************************************************************************/ /* editor_file_system.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "editor_file_system.h" #include "core/io/resource_importer.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/os/file_access.h" #include "core/os/os.h" #include "core/project_settings.h" #include "core/variant_parser.h" #include "editor_node.h" #include "editor_resource_preview.h" #include "editor_settings.h" EditorFileSystem *EditorFileSystem::singleton = NULL; //the name is the version, to keep compatibility with different versions of Godot #define CACHE_FILE_NAME "filesystem_cache6" void EditorFileSystemDirectory::sort_files() { files.sort_custom<FileInfoSort>(); } int EditorFileSystemDirectory::find_file_index(const String &p_file) const { for (int i = 0; i < files.size(); i++) { if (files[i]->file == p_file) return i; } return -1; } int EditorFileSystemDirectory::find_dir_index(const String &p_dir) const { for (int i = 0; i < subdirs.size(); i++) { if (subdirs[i]->name == p_dir) return i; } return -1; } int EditorFileSystemDirectory::get_subdir_count() const { return subdirs.size(); } EditorFileSystemDirectory *EditorFileSystemDirectory::get_subdir(int p_idx) { ERR_FAIL_INDEX_V(p_idx, subdirs.size(), NULL); return subdirs[p_idx]; } int EditorFileSystemDirectory::get_file_count() const { return files.size(); } String EditorFileSystemDirectory::get_file(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, files.size(), ""); return files[p_idx]->file; } String EditorFileSystemDirectory::get_path() const { String p; const EditorFileSystemDirectory *d = this; while (d->parent) { p = d->name.plus_file(p); d = d->parent; } return "res://" + p; } String EditorFileSystemDirectory::get_file_path(int p_idx) const { String file = get_file(p_idx); const EditorFileSystemDirectory *d = this; while (d->parent) { file = d->name.plus_file(file); d = d->parent; } return "res://" + file; } Vector<String> EditorFileSystemDirectory::get_file_deps(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, files.size(), Vector<String>()); return files[p_idx]->deps; } bool EditorFileSystemDirectory::get_file_import_is_valid(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, files.size(), false); return files[p_idx]->import_valid; } String EditorFileSystemDirectory::get_file_script_class_name(int p_idx) const { return files[p_idx]->script_class_name; } String EditorFileSystemDirectory::get_file_script_class_extends(int p_idx) const { return files[p_idx]->script_class_extends; } String EditorFileSystemDirectory::get_file_script_class_icon_path(int p_idx) const { return files[p_idx]->script_class_icon_path; } StringName EditorFileSystemDirectory::get_file_type(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, files.size(), ""); return files[p_idx]->type; } String EditorFileSystemDirectory::get_name() { return name; } EditorFileSystemDirectory *EditorFileSystemDirectory::get_parent() { return parent; } void EditorFileSystemDirectory::_bind_methods() { ClassDB::bind_method(D_METHOD("get_subdir_count"), &EditorFileSystemDirectory::get_subdir_count); ClassDB::bind_method(D_METHOD("get_subdir", "idx"), &EditorFileSystemDirectory::get_subdir); ClassDB::bind_method(D_METHOD("get_file_count"), &EditorFileSystemDirectory::get_file_count); ClassDB::bind_method(D_METHOD("get_file", "idx"), &EditorFileSystemDirectory::get_file); ClassDB::bind_method(D_METHOD("get_file_path", "idx"), &EditorFileSystemDirectory::get_file_path); ClassDB::bind_method(D_METHOD("get_file_type", "idx"), &EditorFileSystemDirectory::get_file_type); ClassDB::bind_method(D_METHOD("get_file_script_class_name", "idx"), &EditorFileSystemDirectory::get_file_script_class_name); ClassDB::bind_method(D_METHOD("get_file_script_class_extends", "idx"), &EditorFileSystemDirectory::get_file_script_class_extends); ClassDB::bind_method(D_METHOD("get_file_import_is_valid", "idx"), &EditorFileSystemDirectory::get_file_import_is_valid); ClassDB::bind_method(D_METHOD("get_name"), &EditorFileSystemDirectory::get_name); ClassDB::bind_method(D_METHOD("get_path"), &EditorFileSystemDirectory::get_path); ClassDB::bind_method(D_METHOD("get_parent"), &EditorFileSystemDirectory::get_parent); ClassDB::bind_method(D_METHOD("find_file_index", "name"), &EditorFileSystemDirectory::find_file_index); ClassDB::bind_method(D_METHOD("find_dir_index", "name"), &EditorFileSystemDirectory::find_dir_index); } EditorFileSystemDirectory::EditorFileSystemDirectory() { modified_time = 0; parent = NULL; verified = false; } EditorFileSystemDirectory::~EditorFileSystemDirectory() { for (int i = 0; i < files.size(); i++) { memdelete(files[i]); } for (int i = 0; i < subdirs.size(); i++) { memdelete(subdirs[i]); } } void EditorFileSystem::_scan_filesystem() { ERR_FAIL_COND(!scanning || new_filesystem); //read .fscache String cpath; sources_changed.clear(); file_cache.clear(); String project = ProjectSettings::get_singleton()->get_resource_path(); String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(CACHE_FILE_NAME); FileAccess *f = FileAccess::open(fscache, FileAccess::READ); bool first = true; if (f) { //read the disk cache while (!f->eof_reached()) { String l = f->get_line().strip_edges(); if (first) { if (first_scan) { // only use this on first scan, afterwards it gets ignored // this is so on first reimport we synchronize versions, then // we don't care until editor restart. This is for usability mainly so // your workflow is not killed after changing a setting by forceful reimporting // everything there is. filesystem_settings_version_for_import = l.strip_edges(); if (filesystem_settings_version_for_import != ResourceFormatImporter::get_singleton()->get_import_settings_hash()) { revalidate_import_files = true; } } first = false; continue; } if (l == String()) continue; if (l.begins_with("::")) { Vector<String> split = l.split("::"); ERR_CONTINUE(split.size() != 3); String name = split[1]; cpath = name; } else { Vector<String> split = l.split("::"); ERR_CONTINUE(split.size() != 8); String name = split[0]; String file; file = name; name = cpath.plus_file(name); FileCache fc; fc.type = split[1]; fc.modification_time = split[2].to_int64(); fc.import_modification_time = split[3].to_int64(); fc.import_valid = split[4].to_int64() != 0; fc.import_group_file = split[5].strip_edges(); fc.script_class_name = split[6].get_slice("<>", 0); fc.script_class_extends = split[6].get_slice("<>", 1); fc.script_class_icon_path = split[6].get_slice("<>", 2); String deps = split[7].strip_edges(); if (deps.length()) { Vector<String> dp = deps.split("<>"); for (int i = 0; i < dp.size(); i++) { String path = dp[i]; fc.deps.push_back(path); } } file_cache[name] = fc; } } f->close(); memdelete(f); } String update_cache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update4"); if (FileAccess::exists(update_cache)) { { FileAccessRef f2 = FileAccess::open(update_cache, FileAccess::READ); String l = f2->get_line().strip_edges(); while (l != String()) { file_cache.erase(l); //erase cache for this, so it gets updated l = f2->get_line().strip_edges(); } } DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); d->remove(update_cache); //bye bye update cache } EditorProgressBG scan_progress("efs", "ScanFS", 1000); ScanProgress sp; sp.low = 0; sp.hi = 1; sp.progress = &scan_progress; new_filesystem = memnew(EditorFileSystemDirectory); new_filesystem->parent = NULL; DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES); d->change_dir("res://"); _scan_new_dir(new_filesystem, d, sp); file_cache.clear(); //clear caches, no longer needed memdelete(d); if (!first_scan) { //on the first scan this is done from the main thread after re-importing _save_filesystem_cache(); } scanning = false; } void EditorFileSystem::_save_filesystem_cache() { group_file_cache.clear(); String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(CACHE_FILE_NAME); FileAccess *f = FileAccess::open(fscache, FileAccess::WRITE); ERR_FAIL_COND_MSG(!f, "Cannot create file '" + fscache + "'. Check user write permissions."); f->store_line(filesystem_settings_version_for_import); _save_filesystem_cache(filesystem, f); f->close(); memdelete(f); } void EditorFileSystem::_thread_func(void *_userdata) { EditorFileSystem *sd = (EditorFileSystem *)_userdata; sd->_scan_filesystem(); } bool EditorFileSystem::_test_for_reimport(const String &p_path, bool p_only_imported_files) { if (!reimport_on_missing_imported_files && p_only_imported_files) return false; if (!FileAccess::exists(p_path + ".import")) { return true; } if (!ResourceFormatImporter::get_singleton()->are_import_settings_valid(p_path)) { //reimport settings are not valid, reimport return true; } Error err; FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err); if (!f) { //no import file, do reimport return true; } VariantParser::StreamFile stream; stream.f = f; String assign; Variant value; VariantParser::Tag next_tag; int lines = 0; String error_text; List<String> to_check; String importer_name; String source_file = ""; String source_md5 = ""; Vector<String> dest_files; String dest_md5 = ""; while (true) { assign = Variant(); next_tag.fields.clear(); next_tag.name = String(); err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true); if (err == ERR_FILE_EOF) { break; } else if (err != OK) { ERR_PRINTS("ResourceFormatImporter::load - '" + p_path + ".import:" + itos(lines) + "' error '" + error_text + "'."); memdelete(f); return false; //parse error, try reimport manually (Avoid reimport loop on broken file) } if (assign != String()) { if (assign.begins_with("path")) { to_check.push_back(value); } else if (assign == "files") { Array fa = value; for (int i = 0; i < fa.size(); i++) { to_check.push_back(fa[i]); } } else if (assign == "importer") { importer_name = value; } else if (!p_only_imported_files) { if (assign == "source_file") { source_file = value; } else if (assign == "dest_files") { dest_files = value; } } } else if (next_tag.name != "remap" && next_tag.name != "deps") { break; } } memdelete(f); if (importer_name == "keep") { return false; //keep mode, do not reimport } // Read the md5's from a separate file (so the import parameters aren't dependent on the file version String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_path); FileAccess *md5s = FileAccess::open(base_path + ".md5", FileAccess::READ, &err); if (!md5s) { // No md5's stored for this resource return true; } VariantParser::StreamFile md5_stream; md5_stream.f = md5s; while (true) { assign = Variant(); next_tag.fields.clear(); next_tag.name = String(); err = VariantParser::parse_tag_assign_eof(&md5_stream, lines, error_text, next_tag, assign, value, NULL, true); if (err == ERR_FILE_EOF) { break; } else if (err != OK) { ERR_PRINTS("ResourceFormatImporter::load - '" + p_path + ".import.md5:" + itos(lines) + "' error '" + error_text + "'."); memdelete(md5s); return false; // parse error } if (assign != String()) { if (!p_only_imported_files) { if (assign == "source_md5") { source_md5 = value; } else if (assign == "dest_md5") { dest_md5 = value; } } } } memdelete(md5s); //imported files are gone, reimport for (List<String>::Element *E = to_check.front(); E; E = E->next()) { if (!FileAccess::exists(E->get())) { return true; } } //check source md5 matching if (!p_only_imported_files) { if (source_file != String() && source_file != p_path) { return true; //file was moved, reimport } if (source_md5 == String()) { return true; //lacks md5, so just reimport } String md5 = FileAccess::get_md5(p_path); if (md5 != source_md5) { return true; } if (dest_files.size() && dest_md5 != String()) { md5 = FileAccess::get_multiple_md5(dest_files); if (md5 != dest_md5) { return true; } } } return false; //nothing changed } bool EditorFileSystem::_update_scan_actions() { sources_changed.clear(); bool fs_changed = false; Vector<String> reimports; Vector<String> reloads; for (List<ItemAction>::Element *E = scan_actions.front(); E; E = E->next()) { ItemAction &ia = E->get(); switch (ia.action) { case ItemAction::ACTION_NONE: { } break; case ItemAction::ACTION_DIR_ADD: { int idx = 0; for (int i = 0; i < ia.dir->subdirs.size(); i++) { if (ia.new_dir->name < ia.dir->subdirs[i]->name) break; idx++; } if (idx == ia.dir->subdirs.size()) { ia.dir->subdirs.push_back(ia.new_dir); } else { ia.dir->subdirs.insert(idx, ia.new_dir); } fs_changed = true; } break; case ItemAction::ACTION_DIR_REMOVE: { ERR_CONTINUE(!ia.dir->parent); ia.dir->parent->subdirs.erase(ia.dir); memdelete(ia.dir); fs_changed = true; } break; case ItemAction::ACTION_FILE_ADD: { int idx = 0; for (int i = 0; i < ia.dir->files.size(); i++) { if (ia.new_file->file < ia.dir->files[i]->file) break; idx++; } if (idx == ia.dir->files.size()) { ia.dir->files.push_back(ia.new_file); } else { ia.dir->files.insert(idx, ia.new_file); } fs_changed = true; } break; case ItemAction::ACTION_FILE_REMOVE: { int idx = ia.dir->find_file_index(ia.file); ERR_CONTINUE(idx == -1); _delete_internal_files(ia.dir->files[idx]->file); memdelete(ia.dir->files[idx]); ia.dir->files.remove(idx); fs_changed = true; } break; case ItemAction::ACTION_FILE_TEST_REIMPORT: { int idx = ia.dir->find_file_index(ia.file); ERR_CONTINUE(idx == -1); String full_path = ia.dir->get_file_path(idx); if (_test_for_reimport(full_path, false)) { //must reimport reimports.push_back(full_path); reimports.append_array(_get_dependencies(full_path)); } else { //must not reimport, all was good //update modified times, to avoid reimport ia.dir->files[idx]->modified_time = FileAccess::get_modified_time(full_path); ia.dir->files[idx]->import_modified_time = FileAccess::get_modified_time(full_path + ".import"); } fs_changed = true; } break; case ItemAction::ACTION_FILE_RELOAD: { int idx = ia.dir->find_file_index(ia.file); ERR_CONTINUE(idx == -1); String full_path = ia.dir->get_file_path(idx); reloads.push_back(full_path); } break; } } if (reimports.size()) { reimport_files(reimports); } if (first_scan) { //only on first scan this is valid and updated, then settings changed. revalidate_import_files = false; filesystem_settings_version_for_import = ResourceFormatImporter::get_singleton()->get_import_settings_hash(); _save_filesystem_cache(); } if (reloads.size()) { emit_signal("resources_reload", reloads); } scan_actions.clear(); return fs_changed; } void EditorFileSystem::scan() { if (false /*&& bool(Globals::get_singleton()->get("debug/disable_scan"))*/) return; if (scanning || scanning_changes || thread.is_started()) return; _update_extensions(); abort_scan = false; if (!use_threads) { scanning = true; scan_total = 0; _scan_filesystem(); if (filesystem) memdelete(filesystem); //file_type_cache.clear(); filesystem = new_filesystem; new_filesystem = NULL; _update_scan_actions(); scanning = false; emit_signal("filesystem_changed"); emit_signal("sources_changed", sources_changed.size() > 0); _queue_update_script_classes(); first_scan = false; } else { ERR_FAIL_COND(thread.is_started()); set_process(true); Thread::Settings s; scanning = true; scan_total = 0; s.priority = Thread::PRIORITY_LOW; thread.start(_thread_func, this, s); //tree->hide(); //progress->show(); } } void EditorFileSystem::ScanProgress::update(int p_current, int p_total) const { float ratio = low + ((hi - low) / p_total) * p_current; progress->step(ratio * 1000); EditorFileSystem::singleton->scan_total = ratio; } EditorFileSystem::ScanProgress EditorFileSystem::ScanProgress::get_sub(int p_current, int p_total) const { ScanProgress sp = *this; float slice = (sp.hi - sp.low) / p_total; sp.low += slice * p_current; sp.hi = slice; return sp; } void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess *da, const ScanProgress &p_progress) { List<String> dirs; List<String> files; String cd = da->get_current_dir(); p_dir->modified_time = FileAccess::get_modified_time(cd); da->list_dir_begin(); while (true) { String f = da->get_next(); if (f == "") break; if (da->current_is_hidden()) continue; if (da->current_is_dir()) { if (f.begins_with(".")) // Ignore special and . / .. continue; if (_should_skip_directory(cd.plus_file(f))) continue; dirs.push_back(f); } else { files.push_back(f); } } da->list_dir_end(); dirs.sort_custom<NaturalNoCaseComparator>(); files.sort_custom<NaturalNoCaseComparator>(); int total = dirs.size() + files.size(); int idx = 0; for (List<String>::Element *E = dirs.front(); E; E = E->next(), idx++) { if (da->change_dir(E->get()) == OK) { String d = da->get_current_dir(); if (d == cd || !d.begins_with(cd)) { da->change_dir(cd); //avoid recursion } else { EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory); efd->parent = p_dir; efd->name = E->get(); _scan_new_dir(efd, da, p_progress.get_sub(idx, total)); int idx2 = 0; for (int i = 0; i < p_dir->subdirs.size(); i++) { if (efd->name < p_dir->subdirs[i]->name) break; idx2++; } if (idx2 == p_dir->subdirs.size()) { p_dir->subdirs.push_back(efd); } else { p_dir->subdirs.insert(idx2, efd); } da->change_dir(".."); } } else { ERR_PRINTS("Cannot go into subdir '" + E->get() + "'."); } p_progress.update(idx, total); } for (List<String>::Element *E = files.front(); E; E = E->next(), idx++) { String ext = E->get().get_extension().to_lower(); if (!valid_extensions.has(ext)) { continue; //invalid } EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo); fi->file = E->get(); String path = cd.plus_file(fi->file); FileCache *fc = file_cache.getptr(path); uint64_t mt = FileAccess::get_modified_time(path); if (import_extensions.has(ext)) { //is imported uint64_t import_mt = 0; if (FileAccess::exists(path + ".import")) { import_mt = FileAccess::get_modified_time(path + ".import"); } if (fc && fc->modification_time == mt && fc->import_modification_time == import_mt && !_test_for_reimport(path, true)) { fi->type = fc->type; fi->deps = fc->deps; fi->modified_time = fc->modification_time; fi->import_modified_time = fc->import_modification_time; fi->import_valid = fc->import_valid; fi->script_class_name = fc->script_class_name; fi->import_group_file = fc->import_group_file; fi->script_class_extends = fc->script_class_extends; fi->script_class_icon_path = fc->script_class_icon_path; if (revalidate_import_files && !ResourceFormatImporter::get_singleton()->are_import_settings_valid(path)) { ItemAction ia; ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT; ia.dir = p_dir; ia.file = E->get(); scan_actions.push_back(ia); } if (fc->type == String()) { fi->type = ResourceLoader::get_resource_type(path); fi->import_group_file = ResourceLoader::get_import_group_file(path); //there is also the chance that file type changed due to reimport, must probably check this somehow here (or kind of note it for next time in another file?) //note: I think this should not happen any longer.. } } else { fi->type = ResourceFormatImporter::get_singleton()->get_resource_type(path); fi->import_group_file = ResourceFormatImporter::get_singleton()->get_import_group_file(path); fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path); fi->modified_time = 0; fi->import_modified_time = 0; fi->import_valid = ResourceLoader::is_import_valid(path); ItemAction ia; ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT; ia.dir = p_dir; ia.file = E->get(); scan_actions.push_back(ia); } } else { if (fc && fc->modification_time == mt) { //not imported, so just update type if changed fi->type = fc->type; fi->modified_time = fc->modification_time; fi->deps = fc->deps; fi->import_modified_time = 0; fi->import_valid = true; fi->script_class_name = fc->script_class_name; fi->script_class_extends = fc->script_class_extends; fi->script_class_icon_path = fc->script_class_icon_path; } else { //new or modified time fi->type = ResourceLoader::get_resource_type(path); fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path); fi->deps = _get_dependencies(path); fi->modified_time = mt; fi->import_modified_time = 0; fi->import_valid = true; } } p_dir->files.push_back(fi); p_progress.update(idx, total); } } void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir, const ScanProgress &p_progress) { uint64_t current_mtime = FileAccess::get_modified_time(p_dir->get_path()); bool updated_dir = false; String cd = p_dir->get_path(); if (current_mtime != p_dir->modified_time || using_fat32_or_exfat) { updated_dir = true; p_dir->modified_time = current_mtime; //ooooops, dir changed, see what's going on //first mark everything as veryfied for (int i = 0; i < p_dir->files.size(); i++) { p_dir->files[i]->verified = false; } for (int i = 0; i < p_dir->subdirs.size(); i++) { p_dir->get_subdir(i)->verified = false; } //then scan files and directories and check what's different DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->change_dir(cd); da->list_dir_begin(); while (true) { String f = da->get_next(); if (f == "") break; if (da->current_is_hidden()) continue; if (da->current_is_dir()) { if (f.begins_with(".")) // Ignore special and . / .. continue; int idx = p_dir->find_dir_index(f); if (idx == -1) { if (_should_skip_directory(cd.plus_file(f))) continue; EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory); efd->parent = p_dir; efd->name = f; DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES); d->change_dir(cd.plus_file(f)); _scan_new_dir(efd, d, p_progress.get_sub(1, 1)); memdelete(d); ItemAction ia; ia.action = ItemAction::ACTION_DIR_ADD; ia.dir = p_dir; ia.file = f; ia.new_dir = efd; scan_actions.push_back(ia); } else { p_dir->subdirs[idx]->verified = true; } } else { String ext = f.get_extension().to_lower(); if (!valid_extensions.has(ext)) continue; //invalid int idx = p_dir->find_file_index(f); if (idx == -1) { //never seen this file, add actition to add it EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo); fi->file = f; String path = cd.plus_file(fi->file); fi->modified_time = FileAccess::get_modified_time(path); fi->import_modified_time = 0; fi->type = ResourceLoader::get_resource_type(path); fi->script_class_name = _get_global_script_class(fi->type, path, &fi->script_class_extends, &fi->script_class_icon_path); fi->import_valid = ResourceLoader::is_import_valid(path); fi->import_group_file = ResourceLoader::get_import_group_file(path); { ItemAction ia; ia.action = ItemAction::ACTION_FILE_ADD; ia.dir = p_dir; ia.file = f; ia.new_file = fi; scan_actions.push_back(ia); } if (import_extensions.has(ext)) { //if it can be imported, and it was added, it needs to be reimported ItemAction ia; ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT; ia.dir = p_dir; ia.file = f; scan_actions.push_back(ia); } } else { p_dir->files[idx]->verified = true; } } } da->list_dir_end(); memdelete(da); } for (int i = 0; i < p_dir->files.size(); i++) { if (updated_dir && !p_dir->files[i]->verified) { //this file was removed, add action to remove it ItemAction ia; ia.action = ItemAction::ACTION_FILE_REMOVE; ia.dir = p_dir; ia.file = p_dir->files[i]->file; scan_actions.push_back(ia); continue; } String path = cd.plus_file(p_dir->files[i]->file); if (import_extensions.has(p_dir->files[i]->file.get_extension().to_lower())) { //check here if file must be imported or not uint64_t mt = FileAccess::get_modified_time(path); bool reimport = false; if (mt != p_dir->files[i]->modified_time) { reimport = true; //it was modified, must be reimported. } else if (!FileAccess::exists(path + ".import")) { reimport = true; //no .import file, obviously reimport } else { uint64_t import_mt = FileAccess::get_modified_time(path + ".import"); if (import_mt != p_dir->files[i]->import_modified_time) { reimport = true; } else if (_test_for_reimport(path, true)) { reimport = true; } } if (reimport) { ItemAction ia; ia.action = ItemAction::ACTION_FILE_TEST_REIMPORT; ia.dir = p_dir; ia.file = p_dir->files[i]->file; scan_actions.push_back(ia); } } else if (ResourceCache::has(path)) { //test for potential reload uint64_t mt = FileAccess::get_modified_time(path); if (mt != p_dir->files[i]->modified_time) { p_dir->files[i]->modified_time = mt; //save new time, but test for reload ItemAction ia; ia.action = ItemAction::ACTION_FILE_RELOAD; ia.dir = p_dir; ia.file = p_dir->files[i]->file; scan_actions.push_back(ia); } } } for (int i = 0; i < p_dir->subdirs.size(); i++) { if (updated_dir && !p_dir->subdirs[i]->verified) { //this directory was removed, add action to remove it ItemAction ia; ia.action = ItemAction::ACTION_DIR_REMOVE; ia.dir = p_dir->subdirs[i]; scan_actions.push_back(ia); continue; } _scan_fs_changes(p_dir->get_subdir(i), p_progress); } } void EditorFileSystem::_delete_internal_files(String p_file) { if (FileAccess::exists(p_file + ".import")) { List<String> paths; ResourceFormatImporter::get_singleton()->get_internal_resource_path_list(p_file, &paths); DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); for (List<String>::Element *E = paths.front(); E; E = E->next()) { da->remove(E->get()); } da->remove(p_file + ".import"); memdelete(da); } } void EditorFileSystem::_thread_func_sources(void *_userdata) { EditorFileSystem *efs = (EditorFileSystem *)_userdata; if (efs->filesystem) { EditorProgressBG pr("sources", TTR("ScanSources"), 1000); ScanProgress sp; sp.progress = &pr; sp.hi = 1; sp.low = 0; efs->_scan_fs_changes(efs->filesystem, sp); } efs->scanning_changes_done = true; } void EditorFileSystem::get_changed_sources(List<String> *r_changed) { *r_changed = sources_changed; } void EditorFileSystem::scan_changes() { if (first_scan || // Prevent a premature changes scan from inhibiting the first full scan scanning || scanning_changes || thread.is_started()) { scan_changes_pending = true; set_process(true); return; } _update_extensions(); sources_changed.clear(); scanning_changes = true; scanning_changes_done = false; abort_scan = false; if (!use_threads) { if (filesystem) { EditorProgressBG pr("sources", TTR("ScanSources"), 1000); ScanProgress sp; sp.progress = &pr; sp.hi = 1; sp.low = 0; scan_total = 0; _scan_fs_changes(filesystem, sp); if (_update_scan_actions()) emit_signal("filesystem_changed"); } scanning_changes = false; scanning_changes_done = true; emit_signal("sources_changed", sources_changed.size() > 0); } else { ERR_FAIL_COND(thread_sources.is_started()); set_process(true); scan_total = 0; Thread::Settings s; s.priority = Thread::PRIORITY_LOW; thread_sources.start(_thread_func_sources, this, s); } } void EditorFileSystem::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { call_deferred("scan"); //this should happen after every editor node entered the tree } break; case NOTIFICATION_EXIT_TREE: { Thread &active_thread = thread.is_started() ? thread : thread_sources; if (use_threads && active_thread.is_started()) { //abort thread if in progress abort_scan = true; while (scanning) { OS::get_singleton()->delay_usec(1000); } active_thread.wait_to_finish(); WARN_PRINT("Scan thread aborted..."); set_process(false); } if (filesystem) memdelete(filesystem); if (new_filesystem) memdelete(new_filesystem); filesystem = NULL; new_filesystem = NULL; } break; case NOTIFICATION_PROCESS: { if (use_threads) { if (scanning_changes) { if (scanning_changes_done) { scanning_changes = false; set_process(false); thread_sources.wait_to_finish(); if (_update_scan_actions()) emit_signal("filesystem_changed"); emit_signal("sources_changed", sources_changed.size() > 0); _queue_update_script_classes(); first_scan = false; } } else if (!scanning) { set_process(false); if (filesystem) memdelete(filesystem); filesystem = new_filesystem; new_filesystem = NULL; thread.wait_to_finish(); _update_scan_actions(); emit_signal("filesystem_changed"); emit_signal("sources_changed", sources_changed.size() > 0); _queue_update_script_classes(); first_scan = false; } if (!is_processing() && scan_changes_pending) { scan_changes_pending = false; scan_changes(); } } } break; } } bool EditorFileSystem::is_scanning() const { return scanning || scanning_changes; } float EditorFileSystem::get_scanning_progress() const { return scan_total; } EditorFileSystemDirectory *EditorFileSystem::get_filesystem() { return filesystem; } void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory *p_dir, FileAccess *p_file) { if (!p_dir) return; //none p_file->store_line("::" + p_dir->get_path() + "::" + String::num(p_dir->modified_time)); for (int i = 0; i < p_dir->files.size(); i++) { if (p_dir->files[i]->import_group_file != String()) { group_file_cache.insert(p_dir->files[i]->import_group_file); } String s = p_dir->files[i]->file + "::" + p_dir->files[i]->type + "::" + itos(p_dir->files[i]->modified_time) + "::" + itos(p_dir->files[i]->import_modified_time) + "::" + itos(p_dir->files[i]->import_valid) + "::" + p_dir->files[i]->import_group_file + "::" + p_dir->files[i]->script_class_name + "<>" + p_dir->files[i]->script_class_extends + "<>" + p_dir->files[i]->script_class_icon_path; s += "::"; for (int j = 0; j < p_dir->files[i]->deps.size(); j++) { if (j > 0) s += "<>"; s += p_dir->files[i]->deps[j]; } p_file->store_line(s); } for (int i = 0; i < p_dir->subdirs.size(); i++) { _save_filesystem_cache(p_dir->subdirs[i], p_file); } } bool EditorFileSystem::_find_file(const String &p_file, EditorFileSystemDirectory **r_d, int &r_file_pos) const { //todo make faster if (!filesystem || scanning) return false; String f = ProjectSettings::get_singleton()->localize_path(p_file); if (!f.begins_with("res://")) return false; f = f.substr(6, f.length()); f = f.replace("\\", "/"); Vector<String> path = f.split("/"); if (path.size() == 0) return false; String file = path[path.size() - 1]; path.resize(path.size() - 1); EditorFileSystemDirectory *fs = filesystem; for (int i = 0; i < path.size(); i++) { if (path[i].begins_with(".")) return false; int idx = -1; for (int j = 0; j < fs->get_subdir_count(); j++) { if (fs->get_subdir(j)->get_name() == path[i]) { idx = j; break; } } if (idx == -1) { //does not exist, create i guess? EditorFileSystemDirectory *efsd = memnew(EditorFileSystemDirectory); efsd->name = path[i]; efsd->parent = fs; int idx2 = 0; for (int j = 0; j < fs->get_subdir_count(); j++) { if (efsd->name < fs->get_subdir(j)->get_name()) break; idx2++; } if (idx2 == fs->get_subdir_count()) fs->subdirs.push_back(efsd); else fs->subdirs.insert(idx2, efsd); fs = efsd; } else { fs = fs->get_subdir(idx); } } int cpos = -1; for (int i = 0; i < fs->files.size(); i++) { if (fs->files[i]->file == file) { cpos = i; break; } } r_file_pos = cpos; *r_d = fs; return cpos != -1; } String EditorFileSystem::get_file_type(const String &p_file) const { EditorFileSystemDirectory *fs = NULL; int cpos = -1; if (!_find_file(p_file, &fs, cpos)) { return ""; } return fs->files[cpos]->type; } EditorFileSystemDirectory *EditorFileSystem::find_file(const String &p_file, int *r_index) const { if (!filesystem || scanning) return NULL; EditorFileSystemDirectory *fs = NULL; int cpos = -1; if (!_find_file(p_file, &fs, cpos)) { return NULL; } if (r_index) *r_index = cpos; return fs; } EditorFileSystemDirectory *EditorFileSystem::get_filesystem_path(const String &p_path) { if (!filesystem || scanning) return NULL; String f = ProjectSettings::get_singleton()->localize_path(p_path); if (!f.begins_with("res://")) return NULL; f = f.substr(6, f.length()); f = f.replace("\\", "/"); if (f == String()) return filesystem; if (f.ends_with("/")) f = f.substr(0, f.length() - 1); Vector<String> path = f.split("/"); if (path.size() == 0) return NULL; EditorFileSystemDirectory *fs = filesystem; for (int i = 0; i < path.size(); i++) { int idx = -1; for (int j = 0; j < fs->get_subdir_count(); j++) { if (fs->get_subdir(j)->get_name() == path[i]) { idx = j; break; } } if (idx == -1) { return NULL; } else { fs = fs->get_subdir(idx); } } return fs; } void EditorFileSystem::_save_late_updated_files() { //files that already existed, and were modified, need re-scanning for dependencies upon project restart. This is done via saving this special file String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update4"); FileAccessRef f = FileAccess::open(fscache, FileAccess::WRITE); ERR_FAIL_COND_MSG(!f, "Cannot create file '" + fscache + "'. Check user write permissions."); for (Set<String>::Element *E = late_update_files.front(); E; E = E->next()) { f->store_line(E->get()); } } Vector<String> EditorFileSystem::_get_dependencies(const String &p_path) { List<String> deps; ResourceLoader::get_dependencies(p_path, &deps); Vector<String> ret; for (List<String>::Element *E = deps.front(); E; E = E->next()) { ret.push_back(E->get()); } return ret; } String EditorFileSystem::_get_global_script_class(const String &p_type, const String &p_path, String *r_extends, String *r_icon_path) const { for (int i = 0; i < ScriptServer::get_language_count(); i++) { if (ScriptServer::get_language(i)->handles_global_class_type(p_type)) { String global_name; String extends; String icon_path; global_name = ScriptServer::get_language(i)->get_global_class_name(p_path, &extends, &icon_path); *r_extends = extends; *r_icon_path = icon_path; return global_name; } } *r_extends = String(); *r_icon_path = String(); return String(); } void EditorFileSystem::_scan_script_classes(EditorFileSystemDirectory *p_dir) { int filecount = p_dir->files.size(); const EditorFileSystemDirectory::FileInfo *const *files = p_dir->files.ptr(); for (int i = 0; i < filecount; i++) { if (files[i]->script_class_name == String()) { continue; } String lang; for (int j = 0; j < ScriptServer::get_language_count(); j++) { if (ScriptServer::get_language(j)->handles_global_class_type(files[i]->type)) { lang = ScriptServer::get_language(j)->get_name(); } } ScriptServer::add_global_class(files[i]->script_class_name, files[i]->script_class_extends, lang, p_dir->get_file_path(i)); EditorNode::get_editor_data().script_class_set_icon_path(files[i]->script_class_name, files[i]->script_class_icon_path); EditorNode::get_editor_data().script_class_set_name(files[i]->file, files[i]->script_class_name); } for (int i = 0; i < p_dir->get_subdir_count(); i++) { _scan_script_classes(p_dir->get_subdir(i)); } } void EditorFileSystem::update_script_classes() { if (!update_script_classes_queued.is_set()) return; update_script_classes_queued.clear(); ScriptServer::global_classes_clear(); if (get_filesystem()) { _scan_script_classes(get_filesystem()); } ScriptServer::save_global_classes(); EditorNode::get_editor_data().script_class_save_icon_paths(); // Rescan custom loaders and savers. // Doing the following here because the `filesystem_changed` signal fires multiple times and isn't always followed by script classes update. // So I thought it's better to do this when script classes really get updated ResourceLoader::remove_custom_loaders(); ResourceLoader::add_custom_loaders(); ResourceSaver::remove_custom_savers(); ResourceSaver::add_custom_savers(); } void EditorFileSystem::_queue_update_script_classes() { if (update_script_classes_queued.is_set()) { return; } update_script_classes_queued.set(); call_deferred("update_script_classes"); } void EditorFileSystem::update_file(const String &p_file) { EditorFileSystemDirectory *fs = NULL; int cpos = -1; if (!_find_file(p_file, &fs, cpos)) { if (!fs) return; } if (!FileAccess::exists(p_file)) { //was removed _delete_internal_files(p_file); if (cpos != -1) { // Might've never been part of the editor file system (*.* files deleted in Open dialog). memdelete(fs->files[cpos]); fs->files.remove(cpos); } call_deferred("emit_signal", "filesystem_changed"); //update later _queue_update_script_classes(); return; } String type = ResourceLoader::get_resource_type(p_file); if (cpos == -1) { // The file did not exist, it was added. late_added_files.insert(p_file); // Remember that it was added. This mean it will be scanned and imported on editor restart. int idx = 0; String file_name = p_file.get_file(); for (int i = 0; i < fs->files.size(); i++) { if (file_name < fs->files[i]->file) { break; } idx++; } EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo); fi->file = file_name; fi->import_modified_time = 0; fi->import_valid = ResourceLoader::is_import_valid(p_file); if (idx == fs->files.size()) { fs->files.push_back(fi); } else { fs->files.insert(idx, fi); } cpos = idx; } else { //the file exists and it was updated, and was not added in this step. //this means we must force upon next restart to scan it again, to get proper type and dependencies late_update_files.insert(p_file); _save_late_updated_files(); //files need to be updated in the re-scan } fs->files[cpos]->type = type; fs->files[cpos]->script_class_name = _get_global_script_class(type, p_file, &fs->files[cpos]->script_class_extends, &fs->files[cpos]->script_class_icon_path); fs->files[cpos]->import_group_file = ResourceLoader::get_import_group_file(p_file); fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file); fs->files[cpos]->deps = _get_dependencies(p_file); fs->files[cpos]->import_valid = ResourceLoader::is_import_valid(p_file); // Update preview EditorResourcePreview::get_singleton()->check_for_invalidation(p_file); call_deferred("emit_signal", "filesystem_changed"); //update later _queue_update_script_classes(); } Error EditorFileSystem::_reimport_group(const String &p_group_file, const Vector<String> &p_files) { String importer_name; Map<String, Map<StringName, Variant> > source_file_options; Map<String, String> base_paths; for (int i = 0; i < p_files.size(); i++) { Ref<ConfigFile> config; config.instance(); Error err = config->load(p_files[i] + ".import"); ERR_CONTINUE(err != OK); ERR_CONTINUE(!config->has_section_key("remap", "importer")); String file_importer_name = config->get_value("remap", "importer"); ERR_CONTINUE(file_importer_name == String()); if (importer_name != String() && importer_name != file_importer_name) { print_line("one importer '" + importer_name + "' the other '" + file_importer_name + "'."); EditorNode::get_singleton()->show_warning(vformat(TTR("There are multiple importers for different types pointing to file %s, import aborted"), p_group_file)); ERR_FAIL_V(ERR_FILE_CORRUPT); } source_file_options[p_files[i]] = Map<StringName, Variant>(); importer_name = file_importer_name; if (importer_name == "keep") { continue; //do nothing } Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name); ERR_FAIL_COND_V(!importer.is_valid(), ERR_FILE_CORRUPT); List<ResourceImporter::ImportOption> options; importer->get_import_options(&options); //set default values for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) { source_file_options[p_files[i]][E->get().option.name] = E->get().default_value; } if (config->has_section("params")) { List<String> sk; config->get_section_keys("params", &sk); for (List<String>::Element *E = sk.front(); E; E = E->next()) { String param = E->get(); Variant value = config->get_value("params", param); //override with whathever is in file source_file_options[p_files[i]][param] = value; } } base_paths[p_files[i]] = ResourceFormatImporter::get_singleton()->get_import_base_path(p_files[i]); } if (importer_name == "keep") { return OK; // (do nothing) } ERR_FAIL_COND_V(importer_name == String(), ERR_UNCONFIGURED); Ref<ResourceImporter> importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name); Error err = importer->import_group_file(p_group_file, source_file_options, base_paths); //all went well, overwrite config files with proper remaps and md5s for (Map<String, Map<StringName, Variant> >::Element *E = source_file_options.front(); E; E = E->next()) { const String &file = E->key(); String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(file); FileAccessRef f = FileAccess::open(file + ".import", FileAccess::WRITE); ERR_FAIL_COND_V_MSG(!f, ERR_FILE_CANT_OPEN, "Cannot open import file '" + file + ".import'."); //write manually, as order matters ([remap] has to go first for performance). f->store_line("[remap]"); f->store_line(""); f->store_line("importer=\"" + importer->get_importer_name() + "\""); if (importer->get_resource_type() != "") { f->store_line("type=\"" + importer->get_resource_type() + "\""); } Vector<String> dest_paths; if (err == OK) { String path = base_path + "." + importer->get_save_extension(); f->store_line("path=\"" + path + "\""); dest_paths.push_back(path); } f->store_line("group_file=" + Variant(p_group_file).get_construct_string()); if (err == OK) { f->store_line("valid=true"); } else { f->store_line("valid=false"); } f->store_line("[deps]\n"); f->store_line(""); f->store_line("source_file=" + Variant(file).get_construct_string()); if (dest_paths.size()) { Array dp; for (int i = 0; i < dest_paths.size(); i++) { dp.push_back(dest_paths[i]); } f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n"); } f->store_line("[params]"); f->store_line(""); //store options in provided order, to avoid file changing. Order is also important because first match is accepted first. List<ResourceImporter::ImportOption> options; importer->get_import_options(&options); //set default values for (List<ResourceImporter::ImportOption>::Element *F = options.front(); F; F = F->next()) { String base = F->get().option.name; Variant v = F->get().default_value; if (source_file_options[file].has(base)) { v = source_file_options[file][base]; } String value; VariantWriter::write_to_string(v, value); f->store_line(base + "=" + value); } f->close(); // Store the md5's of the various files. These are stored separately so that the .import files can be version controlled. FileAccessRef md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE); ERR_FAIL_COND_V_MSG(!md5s, ERR_FILE_CANT_OPEN, "Cannot open MD5 file '" + base_path + ".md5'."); md5s->store_line("source_md5=\"" + FileAccess::get_md5(file) + "\""); if (dest_paths.size()) { md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n"); } md5s->close(); EditorFileSystemDirectory *fs = NULL; int cpos = -1; bool found = _find_file(file, &fs, cpos); ERR_FAIL_COND_V_MSG(!found, ERR_UNCONFIGURED, "Can't find file '" + file + "'."); //update modified times, to avoid reimport fs->files[cpos]->modified_time = FileAccess::get_modified_time(file); fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(file + ".import"); fs->files[cpos]->deps = _get_dependencies(file); fs->files[cpos]->type = importer->get_resource_type(); fs->files[cpos]->import_valid = err == OK; //if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it //to reload properly if (ResourceCache::has(file)) { Resource *r = ResourceCache::get(file); if (r->get_import_path() != String()) { String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(file); r->set_import_path(dst_path); r->set_import_last_modified_time(0); } } EditorResourcePreview::get_singleton()->check_for_invalidation(file); } return err; } void EditorFileSystem::_reimport_file(const String &p_file) { EditorFileSystemDirectory *fs = NULL; int cpos = -1; bool found = _find_file(p_file, &fs, cpos); ERR_FAIL_COND_MSG(!found, "Can't find file '" + p_file + "'."); //try to obtain existing params Map<StringName, Variant> params; String importer_name; if (FileAccess::exists(p_file + ".import")) { //use existing Ref<ConfigFile> cf; cf.instance(); Error err = cf->load(p_file + ".import"); if (err == OK) { if (cf->has_section("params")) { List<String> sk; cf->get_section_keys("params", &sk); for (List<String>::Element *E = sk.front(); E; E = E->next()) { params[E->get()] = cf->get_value("params", E->get()); } } if (cf->has_section("remap")) { importer_name = cf->get_value("remap", "importer"); } } } else { late_added_files.insert(p_file); //imported files do not call update_file(), but just in case.. } if (importer_name == "keep") { //keep files, do nothing. fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file); fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(p_file + ".import"); fs->files[cpos]->deps.clear(); fs->files[cpos]->type = ""; fs->files[cpos]->import_valid = false; EditorResourcePreview::get_singleton()->check_for_invalidation(p_file); return; } Ref<ResourceImporter> importer; bool load_default = false; //find the importer if (importer_name != "") { importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name); } if (importer.is_null()) { //not found by name, find by extension importer = ResourceFormatImporter::get_singleton()->get_importer_by_extension(p_file.get_extension()); load_default = true; if (importer.is_null()) { ERR_PRINT("BUG: File queued for import, but can't be imported!"); ERR_FAIL(); } } //mix with default params, in case a parameter is missing List<ResourceImporter::ImportOption> opts; importer->get_import_options(&opts); for (List<ResourceImporter::ImportOption>::Element *E = opts.front(); E; E = E->next()) { if (!params.has(E->get().option.name)) { //this one is not present params[E->get().option.name] = E->get().default_value; } } if (load_default && ProjectSettings::get_singleton()->has_setting("importer_defaults/" + importer->get_importer_name())) { //use defaults if exist Dictionary d = ProjectSettings::get_singleton()->get("importer_defaults/" + importer->get_importer_name()); List<Variant> v; d.get_key_list(&v); for (List<Variant>::Element *E = v.front(); E; E = E->next()) { params[E->get()] = d[E->get()]; } } //finally, perform import!! String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_file); List<String> import_variants; List<String> gen_files; Variant metadata; Error err = importer->import(p_file, base_path, params, &import_variants, &gen_files, &metadata); if (err != OK) { ERR_PRINTS("Error importing '" + p_file + "'."); } //as import is complete, save the .import file FileAccess *f = FileAccess::open(p_file + ".import", FileAccess::WRITE); ERR_FAIL_COND_MSG(!f, "Cannot open file from path '" + p_file + ".import'."); //write manually, as order matters ([remap] has to go first for performance). f->store_line("[remap]"); f->store_line(""); f->store_line("importer=\"" + importer->get_importer_name() + "\""); if (importer->get_resource_type() != "") { f->store_line("type=\"" + importer->get_resource_type() + "\""); } Vector<String> dest_paths; if (err == OK) { if (importer->get_save_extension() == "") { //no path } else if (import_variants.size()) { //import with variants for (List<String>::Element *E = import_variants.front(); E; E = E->next()) { String path = base_path.c_escape() + "." + E->get() + "." + importer->get_save_extension(); f->store_line("path." + E->get() + "=\"" + path + "\""); dest_paths.push_back(path); } } else { String path = base_path + "." + importer->get_save_extension(); f->store_line("path=\"" + path + "\""); dest_paths.push_back(path); } } else { f->store_line("valid=false"); } if (metadata != Variant()) { f->store_line("metadata=" + metadata.get_construct_string()); } f->store_line(""); f->store_line("[deps]\n"); if (gen_files.size()) { Array genf; for (List<String>::Element *E = gen_files.front(); E; E = E->next()) { genf.push_back(E->get()); dest_paths.push_back(E->get()); } String value; VariantWriter::write_to_string(genf, value); f->store_line("files=" + value); f->store_line(""); } f->store_line("source_file=" + Variant(p_file).get_construct_string()); if (dest_paths.size()) { Array dp; for (int i = 0; i < dest_paths.size(); i++) { dp.push_back(dest_paths[i]); } f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n"); } f->store_line("[params]"); f->store_line(""); //store options in provided order, to avoid file changing. Order is also important because first match is accepted first. for (List<ResourceImporter::ImportOption>::Element *E = opts.front(); E; E = E->next()) { String base = E->get().option.name; String value; VariantWriter::write_to_string(params[base], value); f->store_line(base + "=" + value); } f->close(); memdelete(f); // Store the md5's of the various files. These are stored separately so that the .import files can be version controlled. FileAccess *md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE); ERR_FAIL_COND_MSG(!md5s, "Cannot open MD5 file '" + base_path + ".md5'."); md5s->store_line("source_md5=\"" + FileAccess::get_md5(p_file) + "\""); if (dest_paths.size()) { md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n"); } md5s->close(); memdelete(md5s); //update modified times, to avoid reimport fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file); fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(p_file + ".import"); fs->files[cpos]->deps = _get_dependencies(p_file); fs->files[cpos]->type = importer->get_resource_type(); fs->files[cpos]->import_valid = ResourceLoader::is_import_valid(p_file); //if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it //to reload properly if (ResourceCache::has(p_file)) { Resource *r = ResourceCache::get(p_file); if (r->get_import_path() != String()) { String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_file); r->set_import_path(dst_path); r->set_import_last_modified_time(0); } } EditorResourcePreview::get_singleton()->check_for_invalidation(p_file); } void EditorFileSystem::_find_group_files(EditorFileSystemDirectory *efd, Map<String, Vector<String> > &group_files, Set<String> &groups_to_reimport) { int fc = efd->files.size(); const EditorFileSystemDirectory::FileInfo *const *files = efd->files.ptr(); for (int i = 0; i < fc; i++) { if (groups_to_reimport.has(files[i]->import_group_file)) { if (!group_files.has(files[i]->import_group_file)) { group_files[files[i]->import_group_file] = Vector<String>(); } group_files[files[i]->import_group_file].push_back(efd->get_file_path(i)); } } for (int i = 0; i < efd->get_subdir_count(); i++) { _find_group_files(efd->get_subdir(i), group_files, groups_to_reimport); } } void EditorFileSystem::reimport_files(const Vector<String> &p_files) { { //check that .import folder exists DirAccess *da = DirAccess::open("res://"); if (da->change_dir(".import") != OK) { Error err = da->make_dir(".import"); if (err) { memdelete(da); ERR_FAIL_MSG("Failed to create 'res://.import' folder."); } } memdelete(da); } importing = true; EditorProgress pr("reimport", TTR("(Re)Importing Assets"), p_files.size()); Vector<ImportFile> files; Set<String> groups_to_reimport; for (int i = 0; i < p_files.size(); i++) { String group_file = ResourceFormatImporter::get_singleton()->get_import_group_file(p_files[i]); if (group_file_cache.has(p_files[i])) { //maybe the file itself is a group! groups_to_reimport.insert(p_files[i]); //groups do not belong to grups group_file = String(); } else if (group_file != String()) { //it's a group file, add group to import and skip this file groups_to_reimport.insert(group_file); } else { //it's a regular file ImportFile ifile; ifile.path = p_files[i]; ifile.order = ResourceFormatImporter::get_singleton()->get_import_order(p_files[i]); files.push_back(ifile); } //group may have changed, so also update group reference EditorFileSystemDirectory *fs = NULL; int cpos = -1; if (_find_file(p_files[i], &fs, cpos)) { fs->files.write[cpos]->import_group_file = group_file; } } files.sort(); for (int i = 0; i < files.size(); i++) { pr.step(files[i].path.get_file(), i); _reimport_file(files[i].path); } //reimport groups if (groups_to_reimport.size()) { Map<String, Vector<String> > group_files; _find_group_files(filesystem, group_files, groups_to_reimport); for (Map<String, Vector<String> >::Element *E = group_files.front(); E; E = E->next()) { Error err = _reimport_group(E->key(), E->get()); if (err == OK) { _reimport_file(E->key()); } } } _save_filesystem_cache(); importing = false; if (!is_scanning()) { emit_signal("filesystem_changed"); } emit_signal("resources_reimported", p_files); } Error EditorFileSystem::_resource_import(const String &p_path) { Vector<String> files; files.push_back(p_path); singleton->update_file(p_path); singleton->reimport_files(files); return OK; } bool EditorFileSystem::_should_skip_directory(const String &p_path) { if (FileAccess::exists(p_path.plus_file("project.godot"))) // skip if another project inside this return true; if (FileAccess::exists(p_path.plus_file(".gdignore"))) // skip if a `.gdignore` file is inside this return true; return false; } bool EditorFileSystem::is_group_file(const String &p_path) const { return group_file_cache.has(p_path); } void EditorFileSystem::_move_group_files(EditorFileSystemDirectory *efd, const String &p_group_file, const String &p_new_location) { int fc = efd->files.size(); EditorFileSystemDirectory::FileInfo *const *files = efd->files.ptrw(); for (int i = 0; i < fc; i++) { if (files[i]->import_group_file == p_group_file) { files[i]->import_group_file = p_new_location; Ref<ConfigFile> config; config.instance(); String path = efd->get_file_path(i) + ".import"; Error err = config->load(path); if (err != OK) { continue; } if (config->has_section_key("remap", "group_file")) { config->set_value("remap", "group_file", p_new_location); } List<String> sk; config->get_section_keys("params", &sk); for (List<String>::Element *E = sk.front(); E; E = E->next()) { //not very clean, but should work String param = E->get(); String value = config->get_value("params", param); if (value == p_group_file) { config->set_value("params", param, p_new_location); } } config->save(path); } } for (int i = 0; i < efd->get_subdir_count(); i++) { _move_group_files(efd->get_subdir(i), p_group_file, p_new_location); } } void EditorFileSystem::move_group_file(const String &p_path, const String &p_new_path) { if (get_filesystem()) { _move_group_files(get_filesystem(), p_path, p_new_path); if (group_file_cache.has(p_path)) { group_file_cache.erase(p_path); group_file_cache.insert(p_new_path); } } } void EditorFileSystem::_bind_methods() { ClassDB::bind_method(D_METHOD("get_filesystem"), &EditorFileSystem::get_filesystem); ClassDB::bind_method(D_METHOD("is_scanning"), &EditorFileSystem::is_scanning); ClassDB::bind_method(D_METHOD("get_scanning_progress"), &EditorFileSystem::get_scanning_progress); ClassDB::bind_method(D_METHOD("scan"), &EditorFileSystem::scan); ClassDB::bind_method(D_METHOD("scan_sources"), &EditorFileSystem::scan_changes); ClassDB::bind_method(D_METHOD("update_file", "path"), &EditorFileSystem::update_file); ClassDB::bind_method(D_METHOD("get_filesystem_path", "path"), &EditorFileSystem::get_filesystem_path); ClassDB::bind_method(D_METHOD("get_file_type", "path"), &EditorFileSystem::get_file_type); ClassDB::bind_method(D_METHOD("update_script_classes"), &EditorFileSystem::update_script_classes); ADD_SIGNAL(MethodInfo("filesystem_changed")); ADD_SIGNAL(MethodInfo("sources_changed", PropertyInfo(Variant::BOOL, "exist"))); ADD_SIGNAL(MethodInfo("resources_reimported", PropertyInfo(Variant::POOL_STRING_ARRAY, "resources"))); ADD_SIGNAL(MethodInfo("resources_reload", PropertyInfo(Variant::POOL_STRING_ARRAY, "resources"))); } void EditorFileSystem::_update_extensions() { valid_extensions.clear(); import_extensions.clear(); List<String> extensionsl; ResourceLoader::get_recognized_extensions_for_type("", &extensionsl); for (List<String>::Element *E = extensionsl.front(); E; E = E->next()) { valid_extensions.insert(E->get()); } extensionsl.clear(); ResourceFormatImporter::get_singleton()->get_recognized_extensions(&extensionsl); for (List<String>::Element *E = extensionsl.front(); E; E = E->next()) { import_extensions.insert(E->get()); } } EditorFileSystem::EditorFileSystem() { ResourceLoader::import = _resource_import; reimport_on_missing_imported_files = GLOBAL_DEF("editor/reimport_missing_imported_files", true); singleton = this; filesystem = memnew(EditorFileSystemDirectory); //like, empty filesystem->parent = NULL; scanning = false; importing = false; use_threads = true; new_filesystem = NULL; abort_scan = false; scanning_changes = false; scanning_changes_done = false; DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->change_dir("res://.import") != OK) { da->make_dir("res://.import"); } // This should probably also work on Unix and use the string it returns for FAT32 or exFAT using_fat32_or_exfat = (da->get_filesystem_type() == "FAT32" || da->get_filesystem_type() == "exFAT"); memdelete(da); scan_total = 0; update_script_classes_queued.clear(); first_scan = true; scan_changes_pending = false; revalidate_import_files = false; } EditorFileSystem::~EditorFileSystem() { }
; A277546: a(n) = n/8^m mod 8, where 8^m is the greatest power of 8 that divides n. ; 1,2,3,4,5,6,7,1,1,2,3,4,5,6,7,2,1,2,3,4,5,6,7,3,1,2,3,4,5,6,7,4,1,2,3,4,5,6,7,5,1,2,3,4,5,6,7,6,1,2,3,4,5,6,7,7,1,2,3,4,5,6,7,1,1,2,3,4,5,6,7,1,1,2,3,4,5,6,7,2,1,2,3,4,5,6,7,3,1,2,3,4,5,6,7,4,1,2,3,4 add $0,1 lpb $0 dif $0,8 lpe lpb $0 mod $0,8 lpe
; A143839: Ulam's spiral (SSE spoke). ; 1,24,79,166,285,436,619,834,1081,1360,1671,2014,2389,2796,3235,3706,4209,4744,5311,5910,6541,7204,7899,8626,9385,10176,10999,11854,12741,13660,14611,15594,16609,17656,18735,19846,20989,22164,23371,24610,25881,27184,28519,29886,31285,32716,34179,35674,37201,38760,40351,41974,43629,45316,47035,48786,50569,52384,54231,56110,58021,59964,61939,63946,65985,68056,70159,72294,74461,76660,78891,81154,83449,85776,88135,90526,92949,95404,97891,100410,102961,105544,108159,110806,113485,116196,118939,121714,124521,127360,130231,133134,136069,139036,142035,145066,148129,151224,154351,157510,160701,163924,167179,170466,173785,177136,180519,183934,187381,190860,194371,197914,201489,205096,208735,212406,216109,219844,223611,227410,231241,235104,238999,242926,246885,250876,254899,258954,263041,267160,271311,275494,279709,283956,288235,292546,296889,301264,305671,310110,314581,319084,323619,328186,332785,337416,342079,346774,351501,356260,361051,365874,370729,375616,380535,385486,390469,395484,400531,405610,410721,415864,421039,426246,431485,436756,442059,447394,452761,458160,463591,469054,474549,480076,485635,491226,496849,502504,508191,513910,519661,525444,531259,537106,542985,548896,554839,560814,566821,572860,578931,585034,591169,597336,603535,609766,616029,622324,628651,635010,641401,647824,654279,660766,667285,673836,680419,687034,693681,700360,707071,713814,720589,727396,734235,741106,748009,754944,761911,768910,775941,783004,790099,797226,804385,811576,818799,826054,833341,840660,848011,855394,862809,870256,877735,885246,892789,900364,907971,915610,923281,930984,938719,946486,954285,962116,969979,977874,985801,993760 mov $1,16 mul $1,$0 add $1,7 mul $1,$0 add $1,1
; sp1_InvUpdateStruct SECTION code_clib SECTION code_temp_sp1 PUBLIC _sp1_InvUpdateStruct_fastcall EXTERN asm_sp1_InvUpdateStruct defc _sp1_InvUpdateStruct_fastcall = asm_sp1_InvUpdateStruct
/* By: facug91 From: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=898 Name: Popes Date: 02/04/2015 */ #include <bits/stdc++.h> #define EPS 1e-9 #define DEBUG(x) cerr << "#" << (#x) << ": " << (x) << endl const double PI = 2.0*acos(0.0); #define INF 1000000000 //#define MOD 1000000 //#define MAXN 1000005 using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef vector<int> vi; typedef vector<ii> vii; int y, p, l[100005], first, last, cant; int main () { ios_base::sync_with_stdio(0); cin.tie(0); int i, j; while (cin>>y) { cin>>p; for (i=0; i<p; i++) cin>>l[i]; i=0; j=0; cant = 0; while (i < p) { while (j < p-1 && l[j+1]-l[i] < y) j++; if (cant < j-i+1) { cant = j-i+1; first = l[i]; last = l[j]; } i++; if (i > j) j = i; } cout<<cant<<" "<<first<<" "<<last<<"\n"; } return 0; }
// Copyright Vladimir Prus 2004. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_VALUE_SEMANTIC_HPP_VP_2004_02_24 #define BOOST_VALUE_SEMANTIC_HPP_VP_2004_02_24 #include <boost/program_options/config.hpp> #include <boost/program_options/errors.hpp> #include <boost/any.hpp> #include <boost/function/function1.hpp> #include <boost/lexical_cast.hpp> #include <string> #include <vector> #include <typeinfo> namespace boost { namespace program_options { /** Class which specifies how the option's value is to be parsed and converted into C++ types. */ class BOOST_PROGRAM_OPTIONS_DECL value_semantic { public: /** Returns the name of the option. The name is only meaningful for automatic help message. */ virtual std::string name() const = 0; /** The minimum number of tokens for this option that should be present on the command line. */ virtual unsigned min_tokens() const = 0; /** The maximum number of tokens for this option that should be present on the command line. */ virtual unsigned max_tokens() const = 0; /** Returns true if values from different sources should be composed. Otherwise, value from the first source is used and values from other sources are discarded. */ virtual bool is_composing() const = 0; /** Returns true if value must be given. Non-optional value */ virtual bool is_required() const = 0; /** Parses a group of tokens that specify a value of option. Stores the result in 'value_store', using whatever representation is desired. May be be called several times if value of the same option is specified more than once. */ virtual void parse(boost::any& value_store, const std::vector<std::string>& new_tokens, bool utf8) const = 0; /** Called to assign default value to 'value_store'. Returns true if default value is assigned, and false if no default value exists. */ virtual bool apply_default(boost::any& value_store) const = 0; /** Called when final value of an option is determined. */ virtual void notify(const boost::any& value_store) const = 0; virtual ~value_semantic() {} }; /** Helper class which perform necessary character conversions in the 'parse' method and forwards the data further. */ template<class charT> class value_semantic_codecvt_helper { // Nothing here. Specializations to follow. }; /** Helper conversion class for values that accept ascii strings as input. Overrides the 'parse' method and defines new 'xparse' method taking std::string. Depending on whether input to parse is ascii or UTF8, will pass it to xparse unmodified, or with UTF8->ascii conversion. */ template<> class BOOST_PROGRAM_OPTIONS_DECL value_semantic_codecvt_helper<char> : public value_semantic { private: // base overrides void parse(boost::any& value_store, const std::vector<std::string>& new_tokens, bool utf8) const; protected: // interface for derived classes. virtual void xparse(boost::any& value_store, const std::vector<std::string>& new_tokens) const = 0; }; /** Helper conversion class for values that accept ascii strings as input. Overrides the 'parse' method and defines new 'xparse' method taking std::wstring. Depending on whether input to parse is ascii or UTF8, will recode input to Unicode, or pass it unmodified. */ template<> class BOOST_PROGRAM_OPTIONS_DECL value_semantic_codecvt_helper<wchar_t> : public value_semantic { private: // base overrides void parse(boost::any& value_store, const std::vector<std::string>& new_tokens, bool utf8) const; protected: // interface for derived classes. #if !defined(BOOST_NO_STD_WSTRING) virtual void xparse(boost::any& value_store, const std::vector<std::wstring>& new_tokens) const = 0; #endif }; /** Class which specifies a simple handling of a value: the value will have string type and only one token is allowed. */ class BOOST_PROGRAM_OPTIONS_DECL untyped_value : public value_semantic_codecvt_helper<char> { public: untyped_value(bool zero_tokens = false) : m_zero_tokens(zero_tokens) {} std::string name() const; unsigned min_tokens() const; unsigned max_tokens() const; bool is_composing() const { return false; } bool is_required() const { return false; } /** If 'value_store' is already initialized, or new_tokens has more than one elements, throws. Otherwise, assigns the first string from 'new_tokens' to 'value_store', without any modifications. */ void xparse(boost::any& value_store, const std::vector<std::string>& new_tokens) const; /** Does nothing. */ bool apply_default(boost::any&) const { return false; } /** Does nothing. */ void notify(const boost::any&) const {} private: bool m_zero_tokens; }; /** Base class for all option that have a fixed type, and are willing to announce this type to the outside world. Any 'value_semantics' for which you want to find out the type can be dynamic_cast-ed to typed_value_base. If conversion succeeds, the 'type' method can be called. */ class typed_value_base { public: // Returns the type of the value described by this // object. virtual const std::type_info& value_type() const = 0; // Not really needed, since deletion from this // class is silly, but just in case. virtual ~typed_value_base() {} }; /** Class which handles value of a specific type. */ template<class T, class charT = char> class typed_value : public value_semantic_codecvt_helper<charT>, public typed_value_base { public: /** Ctor. The 'store_to' parameter tells where to store the value when it's known. The parameter can be NULL. */ typed_value(T* store_to) : m_store_to(store_to), m_composing(false), m_multitoken(false), m_zero_tokens(false), m_required(false) {} /** Specifies default value, which will be used if none is explicitly specified. The type 'T' should provide operator<< for ostream. */ typed_value* default_value(const T& v) { m_default_value = boost::any(v); m_default_value_as_text = boost::lexical_cast<std::string>(v); return this; } /** Specifies default value, which will be used if none is explicitly specified. Unlike the above overload, the type 'T' need not provide operator<< for ostream, but textual representation of default value must be provided by the user. */ typed_value* default_value(const T& v, const std::string& textual) { m_default_value = boost::any(v); m_default_value_as_text = textual; return this; } /** Specifies an implicit value, which will be used if the option is given, but without an adjacent value. Using this implies that an explicit value is optional, but if given, must be strictly adjacent to the option, i.e.: '-ovalue' or '--option=value'. Giving '-o' or '--option' will cause the implicit value to be applied. */ typed_value* implicit_value(const T &v) { m_implicit_value = boost::any(v); m_implicit_value_as_text = boost::lexical_cast<std::string>(v); return this; } /** Specifies the name used to to the value in help message. */ typed_value* value_name(const std::string& name) { m_value_name = name; return this; } /** Specifies an implicit value, which will be used if the option is given, but without an adjacent value. Using this implies that an explicit value is optional, but if given, must be strictly adjacent to the option, i.e.: '-ovalue' or '--option=value'. Giving '-o' or '--option' will cause the implicit value to be applied. Unlike the above overload, the type 'T' need not provide operator<< for ostream, but textual representation of default value must be provided by the user. */ typed_value* implicit_value(const T &v, const std::string& textual) { m_implicit_value = boost::any(v); m_implicit_value_as_text = textual; return this; } /** Specifies a function to be called when the final value is determined. */ typed_value* notifier(function1<void, const T&> f) { m_notifier = f; return this; } /** Specifies that the value is composing. See the 'is_composing' method for explanation. */ typed_value* composing() { m_composing = true; return this; } /** Specifies that the value can span multiple tokens. */ typed_value* multitoken() { m_multitoken = true; return this; } /** Specifies that no tokens may be provided as the value of this option, which means that only presense of the option is significant. For such option to be useful, either the 'validate' function should be specialized, or the 'implicit_value' method should be also used. In most cases, you can use the 'bool_switch' function instead of using this method. */ typed_value* zero_tokens() { m_zero_tokens = true; return this; } /** Specifies that the value must occur. */ typed_value* required() { m_required = true; return this; } public: // value semantic overrides std::string name() const; bool is_composing() const { return m_composing; } unsigned min_tokens() const { if (m_zero_tokens || !m_implicit_value.empty()) { return 0; } else { return 1; } } unsigned max_tokens() const { if (m_multitoken) { return 32000; } else if (m_zero_tokens) { return 0; } else { return 1; } } bool is_required() const { return m_required; } /** Creates an instance of the 'validator' class and calls its operator() to perform the actual conversion. */ void xparse(boost::any& value_store, const std::vector< std::basic_string<charT> >& new_tokens) const; /** If default value was specified via previous call to 'default_value', stores that value into 'value_store'. Returns true if default value was stored. */ virtual bool apply_default(boost::any& value_store) const { if (m_default_value.empty()) { return false; } else { value_store = m_default_value; return true; } } /** If an address of variable to store value was specified when creating *this, stores the value there. Otherwise, does nothing. */ void notify(const boost::any& value_store) const; public: // typed_value_base overrides const std::type_info& value_type() const { return typeid(T); } private: T* m_store_to; // Default value is stored as boost::any and not // as boost::optional to avoid unnecessary instantiations. std::string m_value_name; boost::any m_default_value; std::string m_default_value_as_text; boost::any m_implicit_value; std::string m_implicit_value_as_text; bool m_composing, m_implicit, m_multitoken, m_zero_tokens, m_required; boost::function1<void, const T&> m_notifier; }; /** Creates a typed_value<T> instance. This function is the primary method to create value_semantic instance for a specific type, which can later be passed to 'option_description' constructor. The second overload is used when it's additionally desired to store the value of option into program variable. */ template<class T> typed_value<T>* value(); /** @overload */ template<class T> typed_value<T>* value(T* v); /** Creates a typed_value<T> instance. This function is the primary method to create value_semantic instance for a specific type, which can later be passed to 'option_description' constructor. */ template<class T> typed_value<T, wchar_t>* wvalue(); /** @overload */ template<class T> typed_value<T, wchar_t>* wvalue(T* v); /** Works the same way as the 'value<bool>' function, but the created value_semantic won't accept any explicit value. So, if the option is present on the command line, the value will be 'true'. */ BOOST_PROGRAM_OPTIONS_DECL typed_value<bool>* bool_switch(); /** @overload */ BOOST_PROGRAM_OPTIONS_DECL typed_value<bool>* bool_switch(bool* v); }} #include "boost/program_options/detail/value_semantic.hpp" #endif
//--------------------------------------------------------------------------- // Copyright (c) 2017 Michael G. Brehm // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //--------------------------------------------------------------------------- #include "stdafx.h" #include <chrono> #include <memory> #include <string> #include <sstream> #include <vector> #include <xbmc_addon_dll.h> #include <xbmc_pvr_dll.h> #include <version.h> #include <libXBMC_addon.h> #include <libXBMC_pvr.h> #include "database.h" #include "scheduler.h" #include "scalar_condition.h" #include "string_exception.h" #pragma warning(push, 4) // Enable maximum compiler warnings //--------------------------------------------------------------------------- // FUNCTION PROTOTYPES //--------------------------------------------------------------------------- // Exception helpers // static void handle_generalexception(char const* function); template<typename _result> static _result handle_generalexception(char const* function, _result result); static void handle_stdexception(char const* function, std::exception const& ex); template<typename _result> static _result handle_stdexception(char const* function, std::exception const& ex, _result result); // Log helpers // template<typename... _args> static void log_debug(_args&&... args); template<typename... _args> static void log_error(_args&&... args); template<typename... _args> static void log_info(_args&&... args); template<typename... _args> static void log_message(ADDON::addon_log_t level, _args&&... args); template<typename... _args> static void log_notice(_args&&... args); // Scheduled Tasks // static void discover_recordings_task(const scalar_condition<bool>& cancel); //--------------------------------------------------------------------------- // TYPE DECLARATIONS //--------------------------------------------------------------------------- // addon_settings // // Defines all of the configurable addon settings struct addon_settings { // Path to the Media Center RecordedTV folder // std::string recordedtv_folder; }; //--------------------------------------------------------------------------- // GLOBAL VARIABLES //--------------------------------------------------------------------------- // g_addon // // Kodi add-on callbacks static std::unique_ptr<ADDON::CHelper_libXBMC_addon> g_addon; // g_capabilities (const) // // PVR implementation capability flags static const PVR_ADDON_CAPABILITIES g_capabilities = { false, // bSupportsEPG false, // bSupportsEPGEdl false, // bSupportsTV false, // bSupportsRadio true, // bSupportsRecordings false, // bSupportsRecordingsUndelete false, // bSupportsTimers false, // bSupportsChannelGroups false, // bSupportsChannelScan false, // bSupportsChannelSettings false, // bHandlesInputStream false, // bHandlesDemuxing false, // bSupportsRecordingPlayCount false, // bSupportsLastPlayedPosition false, // bSupportsRecordingEdl false, // bSupportsRecordingsRename false, // bSupportsRecordingsLifetimeChange false, // bSupportsDescrambleInfo 0, // iRecordingsLifetimesSize { { 0, "" } }, // recordingsLifetimeValues false, // bSupportsAsyncEPGTransfer }; // g_connpool // // Global SQLite database connection pool instance static std::shared_ptr<connectionpool> g_connpool; // g_pvr // // Kodi PVR add-on callbacks static std::unique_ptr<CHelper_libXBMC_pvr> g_pvr; // g_scheduler // // Task scheduler static scheduler g_scheduler([](std::exception const& ex) -> void { handle_stdexception("scheduled task", ex); }); // g_settings // // Global addon settings instance static addon_settings g_settings; // g_settings_lock // // Synchronization object to serialize access to addon settings std::mutex g_settings_lock; //--------------------------------------------------------------------------- // HELPER FUNCTIONS //--------------------------------------------------------------------------- // discover_recordings_task // // Scheduled task implementation to discover the recordings static void discover_recordings_task(const scalar_condition<bool>& cancel) { bool changed = false; // Flag if the discovery data changed assert(g_addon && g_pvr); log_notice(__func__, ": initiated windows media center recording discovery"); // Grab copies of the required setting(s) up front std::unique_lock<std::mutex> settings_lock(g_settings_lock); std::string recordedtv_folder = g_settings.recordedtv_folder; settings_lock.unlock(); try { // Pull a database connection out from the connection pool connectionpool::handle dbhandle(g_connpool); // Discover the recordings available in the recordedtv_folder discover_recordings(dbhandle, g_addon, recordedtv_folder.c_str(), cancel, changed); if(changed) { // Changes in the recording data affects just the PVR recordings log_notice(__func__, ": recording discovery data changed -- trigger recording update"); g_pvr->TriggerRecordingUpdate(); } log_notice(__func__, ": windows media center recording discovery task completed"); } catch(std::exception& ex) { handle_stdexception(__func__, ex); } catch(...) { handle_generalexception(__func__); } } // handle_generalexception // // Handler for thrown generic exceptions static void handle_generalexception(char const* function) { log_error(function, " failed due to an unhandled exception"); } // handle_generalexception // // Handler for thrown generic exceptions template<typename _result> static _result handle_generalexception(char const* function, _result result) { handle_generalexception(function); return result; } // handle_stdexception // // Handler for thrown std::exceptions static void handle_stdexception(char const* function, std::exception const& ex) { log_error(function, " failed due to an unhandled exception: ", ex.what()); } // handle_stdexception // // Handler for thrown std::exceptions template<typename _result> static _result handle_stdexception(char const* function, std::exception const& ex, _result result) { handle_stdexception(function, ex); return result; } // log_debug // // Variadic method of writing a LOG_DEBUG entry into the Kodi application log template<typename... _args> static void log_debug(_args&&... args) { log_message(ADDON::addon_log_t::LOG_DEBUG, std::forward<_args>(args)...); } // log_error // // Variadic method of writing a LOG_ERROR entry into the Kodi application log template<typename... _args> static void log_error(_args&&... args) { log_message(ADDON::addon_log_t::LOG_ERROR, std::forward<_args>(args)...); } // log_info // // Variadic method of writing a LOG_INFO entry into the Kodi application log template<typename... _args> static void log_info(_args&&... args) { log_message(ADDON::addon_log_t::LOG_INFO, std::forward<_args>(args)...); } // log_message // // Variadic method of writing an entry into the Kodi application log template<typename... _args> static void log_message(ADDON::addon_log_t level, _args&&... args) { std::ostringstream stream; int unpack[] = {0, ( static_cast<void>(stream << args), 0 ) ... }; (void)unpack; if(g_addon) g_addon->Log(level, stream.str().c_str()); // Write LOG_ERROR level messages to an appropriate secondary log mechanism if(level == ADDON::addon_log_t::LOG_ERROR) { std::string message = "ERROR: " + stream.str() + "\r\n"; OutputDebugStringA(message.c_str()); } } // log_notice // // Variadic method of writing a LOG_NOTICE entry into the Kodi application log template<typename... _args> static void log_notice(_args&&... args) { log_message(ADDON::addon_log_t::LOG_NOTICE, std::forward<_args>(args)...); } //--------------------------------------------------------------------------- // KODI ADDON ENTRY POINTS //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // ADDON_Create // // Creates and initializes the Kodi addon instance // // Arguments: // // handle - Kodi add-on handle // props - Add-on specific properties structure (PVR_PROPERTIES) ADDON_STATUS ADDON_Create(void* handle, void* props) { char strvalue[1024] = { '\0' }; // Setting value if((handle == nullptr) || (props == nullptr)) return ADDON_STATUS::ADDON_STATUS_PERMANENT_FAILURE; // Pull out a pointer to the PVR_PROPERTIES PVR_PROPERTIES* pvrprops = reinterpret_cast<PVR_PROPERTIES*>(props); try { // Create the global addon callbacks instance g_addon.reset(new ADDON::CHelper_libXBMC_addon()); if(!g_addon->RegisterMe(handle)) throw string_exception("Failed to register addon handle (CHelper_libXBMC_addon::RegisterMe)"); // Throw a banner out to the Kodi log indicating that the add-on is being loaded log_notice(VERSION_PRODUCTNAME_ANSI, " v", VERSION_VERSION3_ANSI, " loading"); try { // The user data path doesn't always exist when an addon has been installed if(!g_addon->DirectoryExists(pvrprops->strUserPath)) { log_notice(__func__, ": user data directory ", pvrprops->strUserPath, " does not exist"); if(!g_addon->CreateDirectory(pvrprops->strUserPath)) throw string_exception("unable to create addon user data directory"); log_notice(__func__, ": user data directory ", pvrprops->strUserPath, " created"); } // Load the general settings if(g_addon->GetSetting("recordedtv_folder", strvalue)) g_settings.recordedtv_folder = strvalue; // Create the global pvrcallbacks instance g_pvr.reset(new CHelper_libXBMC_pvr()); if(!g_pvr->RegisterMe(handle)) throw string_exception("Failed to register pvr addon handle (CHelper_libXBMC_pvr::RegisterMe)"); try { // Create the global database connection pool instance, the file name is based on the versionb std::string databasefile = "file:///" + std::string(pvrprops->strUserPath) + "/mcerecordings-v" + VERSION_VERSION2_ANSI + ".db"; g_connpool = std::make_shared<connectionpool>(databasefile.c_str(), SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI); try { // Schedule the initial discovery run to execute as soon as possible std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); g_scheduler.add(now + std::chrono::seconds(1), discover_recordings_task); g_scheduler.start(); // <--- Start the task scheduler } // Clean up the database connection pool on exception catch(...) { g_connpool.reset(); throw; } } // Clean up the pvrcallbacks instance on exception catch(...) { g_pvr.reset(nullptr); throw; } } // Clean up the addoncallbacks on exception; but log the error first -- once the callbacks // are destroyed so is the ability to write to the Kodi log file catch(std::exception& ex) { handle_stdexception(__func__, ex); g_addon.reset(nullptr); throw; } catch(...) { handle_generalexception(__func__); g_addon.reset(nullptr); throw; } } // Anything that escapes above can't be logged at this point, just return ADDON_STATUS_PERMANENT_FAILURE catch(...) { return ADDON_STATUS::ADDON_STATUS_PERMANENT_FAILURE; } // Throw a simple banner out to the Kodi log indicating that the add-on has been loaded log_notice(VERSION_PRODUCTNAME_ANSI, " v", VERSION_VERSION3_ANSI, " loaded"); return ADDON_STATUS::ADDON_STATUS_OK; } //--------------------------------------------------------------------------- // ADDON_Destroy // // Destroys the Kodi addon instance // // Arguments: // // NONE void ADDON_Destroy(void) { // Throw a message out to the Kodi log indicating that the add-on is being unloaded log_notice(VERSION_PRODUCTNAME_ANSI, " v", VERSION_VERSION3_ANSI, " unloading"); // Stop the task scheduler g_scheduler.stop(); // Destroy all the dynamically created objects g_connpool.reset(); g_pvr.reset(nullptr); // Send a notice out to the Kodi log as late as possible and destroy the addon callbacks log_notice(__func__, ": ", VERSION_PRODUCTNAME_ANSI, " v", VERSION_VERSION3_ANSI, " unloaded"); g_addon.reset(); } //--------------------------------------------------------------------------- // ADDON_GetStatus // // Gets the current status of the Kodi addon // // Arguments: // // NONE ADDON_STATUS ADDON_GetStatus(void) { return ADDON_STATUS::ADDON_STATUS_OK; } //--------------------------------------------------------------------------- // ADDON_SetSetting // // Changes the value of a named Kodi addon setting // // Arguments: // // name - Name of the setting to change // value - New value of the setting to apply ADDON_STATUS ADDON_SetSetting(char const* name, void const* value) { std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); std::unique_lock<std::mutex> settings_lock(g_settings_lock); // recordedtv_folder // if(strcmp(name, "recordedtv_folder") == 0) { if(strcmp(g_settings.recordedtv_folder.c_str(), reinterpret_cast<char const*>(value)) != 0) { g_settings.recordedtv_folder = reinterpret_cast<char const*>(value); log_notice(__func__, ": setting recordedtv_folder changed to ", g_settings.recordedtv_folder.c_str()); // Reschedule the discovery task to run as soon as possible g_scheduler.remove(discover_recordings_task); g_scheduler.add(now + std::chrono::seconds(1), discover_recordings_task); log_notice(__func__, ": recorded tv folder changed -- scheduling discovery task to initiate in 1 second"); } } return ADDON_STATUS_OK; } //--------------------------------------------------------------------------- // KODI PVR ADDON ENTRY POINTS //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // GetAddonCapabilities // // Get the list of features that this add-on provides // // Arguments: // // capabilities - Capabilities structure to fill out PVR_ERROR GetAddonCapabilities(PVR_ADDON_CAPABILITIES *capabilities) { if(capabilities == nullptr) return PVR_ERROR::PVR_ERROR_INVALID_PARAMETERS; *capabilities = g_capabilities; return PVR_ERROR::PVR_ERROR_NO_ERROR; } //--------------------------------------------------------------------------- // GetBackendName // // Get the name reported by the backend that will be displayed in the UI // // Arguments: // // NONE char const* GetBackendName(void) { return VERSION_PRODUCTNAME_ANSI; } //--------------------------------------------------------------------------- // GetBackendVersion // // Get the version string reported by the backend that will be displayed in the UI // // Arguments: // // NONE char const* GetBackendVersion(void) { return VERSION_VERSION3_ANSI; } //--------------------------------------------------------------------------- // GetConnectionString // // Get the connection string reported by the backend that will be displayed in the UI // // Arguments: // // NONE char const* GetConnectionString(void) { return "conected"; } //--------------------------------------------------------------------------- // GetDriveSpace // // Get the disk space reported by the backend (if supported) // // Arguments: // // total - The total disk space in bytes // used - The used disk space in bytes PVR_ERROR GetDriveSpace(long long* /*total*/, long long* /*used*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // CallMenuHook // // Call one of the menu hooks (if supported) // // Arguments: // // menuhook - The hook to call // item - The selected item for which the hook is called PVR_ERROR CallMenuHook(PVR_MENUHOOK const& /*menuhook*/, PVR_MENUHOOK_DATA const& /*item*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetEPGForChannel // // Request the EPG for a channel from the backend // // Arguments: // // handle - Handle to pass to the callback method // channel - The channel to get the EPG table for // start - Get events after this time (UTC) // end - Get events before this time (UTC) PVR_ERROR GetEPGForChannel(ADDON_HANDLE /*handle*/, PVR_CHANNEL const& /*channel*/, time_t /*start*/, time_t /*end*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // IsEPGTagRecordable // // Check if the given EPG tag can be recorded // // Arguments: // // tag - EPG tag to be checked // recordable - Flag indicating if the EPG tag can be recorded PVR_ERROR IsEPGTagRecordable(EPG_TAG const* /*tag*/, bool* /*recordable*/) { return PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // IsEPGTagPlayable // // Check if the given EPG tag can be played // // Arguments: // // tag - EPG tag to be checked // playable - Flag indicating if the EPG tag can be played PVR_ERROR IsEPGTagPlayable(EPG_TAG const* /*tag*/, bool* /*playable*/) { return PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetEPGTagEdl // // Retrieve the edit decision list (EDL) of an EPG tag on the backend // // Arguments: // // tag - EPG tag // edl - The function has to write the EDL list into this array // count - The maximum size of the EDL, out: the actual size of the EDL PVR_ERROR GetEPGTagEdl(EPG_TAG const* /*tag*/, PVR_EDL_ENTRY /*edl*/[], int* /*count*/) { return PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetEPGTagStreamProperties // // Get the stream properties for an epg tag from the backend // // Arguments: // // tag - EPG tag for which to retrieve the properties // props - Array in which to set the stream properties // numprops - Number of properties returned by this function PVR_ERROR GetEPGTagStreamProperties(EPG_TAG const* /*tag*/, PVR_NAMED_VALUE* /*props*/, unsigned int* /*numprops*/) { return PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetChannelGroupsAmount // // Get the total amount of channel groups on the backend if it supports channel groups // // Arguments: // // NONE int GetChannelGroupsAmount(void) { return -1; } //--------------------------------------------------------------------------- // GetChannelGroups // // Request the list of all channel groups from the backend if it supports channel groups // // Arguments: // // handle - Handle to pass to the callack method // radio - True to get radio groups, false to get TV channel groups PVR_ERROR GetChannelGroups(ADDON_HANDLE /*handle*/, bool /*radio*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetChannelGroupMembers // // Request the list of all channel groups from the backend if it supports channel groups // // Arguments: // // handle - Handle to pass to the callack method // group - The group to get the members for PVR_ERROR GetChannelGroupMembers(ADDON_HANDLE /*handle*/, PVR_CHANNEL_GROUP const& /*group*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // OpenDialogChannelScan // // Show the channel scan dialog if this backend supports it // // Arguments: // // NONE PVR_ERROR OpenDialogChannelScan(void) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetChannelsAmount // // The total amount of channels on the backend, or -1 on error // // Arguments: // // NONE int GetChannelsAmount(void) { return -1; } //--------------------------------------------------------------------------- // GetChannels // // Request the list of all channels from the backend // // Arguments: // // handle - Handle to pass to the callback method // radio - True to get radio channels, false to get TV channels PVR_ERROR GetChannels(ADDON_HANDLE /*handle*/, bool /*radio*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // DeleteChannel // // Delete a channel from the backend // // Arguments: // // channel - The channel to delete PVR_ERROR DeleteChannel(PVR_CHANNEL const& /*channel*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // RenameChannel // // Rename a channel on the backend // // Arguments: // // channel - The channel to rename, containing the new channel name PVR_ERROR RenameChannel(PVR_CHANNEL const& /*channel*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // OpenDialogChannelSettings // // Show the channel settings dialog, if supported by the backend // // Arguments: // // channel - The channel to show the dialog for PVR_ERROR OpenDialogChannelSettings(PVR_CHANNEL const& /*channel*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // OpenDialogChannelAdd // // Show the dialog to add a channel on the backend, if supported by the backend // // Arguments: // // channel - The channel to add PVR_ERROR OpenDialogChannelAdd(PVR_CHANNEL const& /*channel*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetRecordingsAmount // // The total amount of recordings on the backend or -1 on error // // Arguments: // // deleted - if set return deleted recording int GetRecordingsAmount(bool deleted) { if(deleted) return 0; // Deleted recordings aren't supported try { return get_recording_count(connectionpool::handle(g_connpool)); } catch(std::exception& ex) { return handle_stdexception(__func__, ex, -1); } catch(...) { return handle_generalexception(__func__, -1); } } //--------------------------------------------------------------------------- // GetRecordings // // Request the list of all recordings from the backend, if supported // // Arguments: // // handle - Handle to pass to the callback method // deleted - If set return deleted recording PVR_ERROR GetRecordings(ADDON_HANDLE handle, bool deleted) { assert(g_pvr); if(handle == nullptr) return PVR_ERROR::PVR_ERROR_INVALID_PARAMETERS; // The PVR doesn't support tracking deleted recordings if(deleted) return PVR_ERROR::PVR_ERROR_NO_ERROR; try { // Pull a database connection out from the connection pool connectionpool::handle dbhandle(g_connpool); // Enumerate all of the recordings in the database enumerate_recordings(dbhandle, [&](struct recording const& item) -> void { PVR_RECORDING recording; // PVR_RECORDING to be transferred to Kodi memset(&recording, 0, sizeof(PVR_RECORDING)); // Initialize the structure // strRecordingId (required) if(item.recordingid == nullptr) return; snprintf(recording.strRecordingId, std::extent<decltype(recording.strRecordingId)>::value, "%s", item.recordingid); // strTitle (required) if(item.title == nullptr) return; snprintf(recording.strTitle, std::extent<decltype(recording.strTitle)>::value, "%s", item.title); // strEpisodeName if(item.episodename != nullptr) snprintf(recording.strEpisodeName, std::extent<decltype(recording.strEpisodeName)>::value, "%s", item.episodename); // iSeriesNumber recording.iSeriesNumber = item.seriesnumber; // iEpisodeNumber recording.iEpisodeNumber = item.episodenumber; // iYear recording.iYear = item.year; // strDirectory if(item.title != nullptr) snprintf(recording.strDirectory, std::extent<decltype(recording.strDirectory)>::value, "%s", item.directory); // strPlot if(item.plot != nullptr) snprintf(recording.strPlot, std::extent<decltype(recording.strPlot)>::value, "%s", item.plot); // strChannelName if(item.channelname != nullptr) snprintf(recording.strChannelName, std::extent<decltype(recording.strChannelName)>::value, "%s", item.channelname); // recordingTime recording.recordingTime = item.recordingtime; // iDuration recording.iDuration = item.duration; // iChannelUid recording.iChannelUid = PVR_CHANNEL_INVALID_UID; // channelType recording.channelType = PVR_RECORDING_CHANNEL_TYPE_TV; g_pvr->TransferRecordingEntry(handle, &recording); }); } catch(std::exception& ex) { return handle_stdexception(__func__, ex, PVR_ERROR::PVR_ERROR_FAILED); } catch(...) { return handle_generalexception(__func__, PVR_ERROR::PVR_ERROR_FAILED); } return PVR_ERROR::PVR_ERROR_NO_ERROR; } //--------------------------------------------------------------------------- // DeleteRecording // // Delete a recording on the backend // // Arguments: // // recording - The recording to delete PVR_ERROR DeleteRecording(PVR_RECORDING const& recording) { assert(g_addon); try { delete_recording(connectionpool::handle(g_connpool), g_addon, recording.strRecordingId); } catch(std::exception& ex) { return handle_stdexception(__func__, ex, PVR_ERROR::PVR_ERROR_FAILED); } catch(...) { return handle_generalexception(__func__, PVR_ERROR::PVR_ERROR_FAILED); } return PVR_ERROR::PVR_ERROR_NO_ERROR; } //--------------------------------------------------------------------------- // UndeleteRecording // // Undelete a recording on the backend // // Arguments: // // recording - The recording to undelete PVR_ERROR UndeleteRecording(PVR_RECORDING const& /*recording*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // DeleteAllRecordingsFromTrash // // Delete all recordings permanent which in the deleted folder on the backend // // Arguments: // // NONE PVR_ERROR DeleteAllRecordingsFromTrash() { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // RenameRecording // // Rename a recording on the backend // // Arguments: // // recording - The recording to rename, containing the new name PVR_ERROR RenameRecording(PVR_RECORDING const& /*recording*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // SetRecordingLifetime // // Set the lifetime of a recording on the backend // // Arguments: // // recording - The recording to change the lifetime for PVR_ERROR SetRecordingLifetime(PVR_RECORDING const* /*recording*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // SetRecordingPlayCount // // Set the play count of a recording on the backend // // Arguments: // // recording - The recording to change the play count // playcount - Play count PVR_ERROR SetRecordingPlayCount(PVR_RECORDING const& /*recording*/, int /*playcount*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // SetRecordingLastPlayedPosition // // Set the last watched position of a recording on the backend // // Arguments: // // recording - The recording // lastplayedposition - The last watched position in seconds PVR_ERROR SetRecordingLastPlayedPosition(PVR_RECORDING const& /*recording*/, int /*lastplayedposition*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetRecordingLastPlayedPosition // // Retrieve the last watched position of a recording (in seconds) on the backend // // Arguments: // // recording - The recording int GetRecordingLastPlayedPosition(PVR_RECORDING const& /*recording*/) { return -1; } //--------------------------------------------------------------------------- // GetRecordingEdl // // Retrieve the edit decision list (EDL) of a recording on the backend // // Arguments: // // recording - The recording // edl - The function has to write the EDL list into this array // count - in: The maximum size of the EDL, out: the actual size of the EDL PVR_ERROR GetRecordingEdl(PVR_RECORDING const& /*recording*/, PVR_EDL_ENTRY edl[], int* count) { if(count == nullptr) return PVR_ERROR::PVR_ERROR_INVALID_PARAMETERS; if((*count) && (edl == nullptr)) return PVR_ERROR::PVR_ERROR_INVALID_PARAMETERS; *count = 0; return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetTimerTypes // // Retrieve the timer types supported by the backend // // Arguments: // // types - The function has to write the definition of the supported timer types into this array // count - in: The maximum size of the list; out: the actual size of the list PVR_ERROR GetTimerTypes(PVR_TIMER_TYPE[] /*types*/, int* /*count*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetTimersAmount // // Gets the total amount of timers on the backend or -1 on error // // Arguments: // // NONE int GetTimersAmount(void) { return -1; } //--------------------------------------------------------------------------- // GetTimers // // Request the list of all timers from the backend if supported // // Arguments: // // handle - Handle to pass to the callback method PVR_ERROR GetTimers(ADDON_HANDLE /*handle*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // AddTimer // // Add a timer on the backend // // Arguments: // // timer - The timer to add PVR_ERROR AddTimer(PVR_TIMER const& /*timer*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // DeleteTimer // // Delete a timer on the backend // // Arguments: // // timer - The timer to delete // force - Set to true to delete a timer that is currently recording a program PVR_ERROR DeleteTimer(PVR_TIMER const& /*timer*/, bool /*force*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // UpdateTimer // // Update the timer information on the backend // // Arguments: // // timer - The timer to update PVR_ERROR UpdateTimer(PVR_TIMER const& /*timer*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // OpenLiveStream // // Open a live stream on the backend // // Arguments: // // channel - The channel to stream bool OpenLiveStream(PVR_CHANNEL const& /*channel*/) { return false; } //--------------------------------------------------------------------------- // CloseLiveStream // // Closes the live stream // // Arguments: // // NONE void CloseLiveStream(void) { } //--------------------------------------------------------------------------- // ReadLiveStream // // Read from an open live stream // // Arguments: // // buffer - The buffer to store the data in // size - The number of bytes to read into the buffer int ReadLiveStream(unsigned char* /*buffer*/, unsigned int /*size*/) { return -1; } //--------------------------------------------------------------------------- // SeekLiveStream // // Seek in a live stream on a backend that supports timeshifting // // Arguments: // // position - Delta within the stream to seek, relative to whence // whence - Starting position from which to apply the delta long long SeekLiveStream(long long /*position*/, int /*whence*/) { return -1; } //--------------------------------------------------------------------------- // PositionLiveStream // // Gets the position in the stream that's currently being read // // Arguments: // // NONE long long PositionLiveStream(void) { return -1; } //--------------------------------------------------------------------------- // LengthLiveStream // // The total length of the stream that's currently being read // // Arguments: // // NONE long long LengthLiveStream(void) { return -1; } //--------------------------------------------------------------------------- // SignalStatus // // Get the signal status of the stream that's currently open // // Arguments: // // status - The signal status PVR_ERROR SignalStatus(PVR_SIGNAL_STATUS& /*status*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetDescrambleInfo // // Get the descramble information of the stream that's currently open // // Arguments: // // descrambleinfo - Descramble information PVR_ERROR GetDescrambleInfo(PVR_DESCRAMBLE_INFO* /*descrambleinfo*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetChannelStreamProperties // // Gets the properties for channel streams when the input stream is not handled // // Arguments: // // channel - Channel to get the stream properties for // props - Array of properties to be set for the stream // numprops - Number of properties returned by this function PVR_ERROR GetChannelStreamProperties(PVR_CHANNEL const* /*channel*/, PVR_NAMED_VALUE* /*props*/, unsigned int* /*numprops*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetRecordingStreamProperties // // Gets the properties for recording streams when the input stream is not handled // // Arguments: // // recording - Recording to get the stream properties for // props - Array of properties to be set for the stream // numprops - Number of properties returned by this function PVR_ERROR GetRecordingStreamProperties(PVR_RECORDING const* recording, PVR_NAMED_VALUE* props, unsigned int* numprops) { try { // PVR_STREAM_PROPERTY_STREAMURL snprintf(props[0].strName, std::extent<decltype(props[0].strName)>::value, PVR_STREAM_PROPERTY_STREAMURL); snprintf(props[0].strValue, std::extent<decltype(props[0].strName)>::value, get_recording_stream_url(connectionpool::handle(g_connpool), recording->strRecordingId).c_str()); // PVR_STREAM_PROPERTY_MIMETYPE snprintf(props[1].strName, std::extent<decltype(props[1].strName)>::value, PVR_STREAM_PROPERTY_MIMETYPE); snprintf(props[1].strValue, std::extent<decltype(props[1].strName)>::value, "video/x-ms-wtv"); // PVR_STREAM_PROPERTY_ISREALTIMESTREAM snprintf(props[2].strName, std::extent<decltype(props[2].strName)>::value, PVR_STREAM_PROPERTY_ISREALTIMESTREAM); snprintf(props[2].strValue, std::extent<decltype(props[2].strName)>::value, "false"); *numprops = 3; } catch(std::exception& ex) { return handle_stdexception(__func__, ex, PVR_ERROR::PVR_ERROR_FAILED); } catch(...) { return handle_generalexception(__func__, PVR_ERROR::PVR_ERROR_FAILED); } return PVR_ERROR::PVR_ERROR_NO_ERROR; } //--------------------------------------------------------------------------- // GetStreamProperties // // Get the stream properties of the stream that's currently being read // // Arguments: // // properties - The properties of the currently playing stream PVR_ERROR GetStreamProperties(PVR_STREAM_PROPERTIES* properties) { if(properties == nullptr) return PVR_ERROR::PVR_ERROR_INVALID_PARAMETERS; return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // GetStreamReadChunkSize // // Obtain the chunk size to use when reading streams // // Arguments: // // properties - The properties of the currently playing stream PVR_ERROR GetStreamReadChunkSize(int* /*chunksize*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // OpenRecordedStream // // Open a stream to a recording on the backend // // Arguments: // // recording - The recording to open bool OpenRecordedStream(PVR_RECORDING const& /*recording*/) { return false; } //--------------------------------------------------------------------------- // CloseRecordedStream // // Close an open stream from a recording // // Arguments: // // NONE void CloseRecordedStream(void) { } //--------------------------------------------------------------------------- // ReadRecordedStream // // Read from a recording // // Arguments: // // buffer - The buffer to store the data in // size - The number of bytes to read into the buffer int ReadRecordedStream(unsigned char* /*buffer*/, unsigned int /*size*/) { return -1; } //--------------------------------------------------------------------------- // SeekRecordedStream // // Seek in a recorded stream // // Arguments: // // position - Delta within the stream to seek, relative to whence // whence - Starting position from which to apply the delta long long SeekRecordedStream(long long /*position*/, int /*whence*/) { return -1; } //--------------------------------------------------------------------------- // LengthRecordedStream // // Gets the total length of the stream that's currently being read // // Arguments: // // NONE long long LengthRecordedStream(void) { return -1; } //--------------------------------------------------------------------------- // DemuxReset // // Reset the demultiplexer in the add-on // // Arguments: // // NONE void DemuxReset(void) { } //--------------------------------------------------------------------------- // DemuxAbort // // Abort the demultiplexer thread in the add-on // // Arguments: // // NONE void DemuxAbort(void) { } //--------------------------------------------------------------------------- // DemuxFlush // // Flush all data that's currently in the demultiplexer buffer in the add-on // // Arguments: // // NONE void DemuxFlush(void) { } //--------------------------------------------------------------------------- // DemuxRead // // Read the next packet from the demultiplexer, if there is one // // Arguments: // // NONE DemuxPacket* DemuxRead(void) { return nullptr; } //--------------------------------------------------------------------------- // CanPauseStream // // Check if the backend support pausing the currently playing stream // // Arguments: // // NONE bool CanPauseStream(void) { return false; } //--------------------------------------------------------------------------- // CanSeekStream // // Check if the backend supports seeking for the currently playing stream // // Arguments: // // NONE bool CanSeekStream(void) { return false; } //--------------------------------------------------------------------------- // PauseStream // // Notify the pvr addon that XBMC (un)paused the currently playing stream // // Arguments: // // paused - Paused/unpaused flag void PauseStream(bool /*paused*/) { } //--------------------------------------------------------------------------- // SeekTime // // Notify the pvr addon/demuxer that XBMC wishes to seek the stream by time // // Arguments: // // time - The absolute time since stream start // backwards - True to seek to keyframe BEFORE time, else AFTER // startpts - Can be updated to point to where display should start bool SeekTime(double /*time*/, bool /*backwards*/, double* startpts) { if(startpts == nullptr) return false; return false; } //--------------------------------------------------------------------------- // SetSpeed // // Notify the pvr addon/demuxer that XBMC wishes to change playback speed // // Arguments: // // speed - The requested playback speed void SetSpeed(int /*speed*/) { } //--------------------------------------------------------------------------- // GetBackendHostname // // Get the hostname of the pvr backend server // // Arguments: // // NONE char const* GetBackendHostname(void) { return ""; } //--------------------------------------------------------------------------- // IsTimeshifting // // Check if timeshift is active // // Arguments: // // NONE bool IsTimeshifting(void) { return false; } //--------------------------------------------------------------------------- // IsRealTimeStream // // Check for real-time streaming // // Arguments: // // NONE bool IsRealTimeStream(void) { return false; } //--------------------------------------------------------------------------- // SetEPGTimeFrame // // Tell the client the time frame to use when notifying epg events back to Kodi // // Arguments: // // days - number of days from "now". EPG_TIMEFRAME_UNLIMITED means that Kodi is interested in all epg events PVR_ERROR SetEPGTimeFrame(int /*days*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- // OnSystemSleep // // Notification of system sleep power event // // Arguments: // // NONE void OnSystemSleep() { try { g_scheduler.stop(); // Stop the scheduler g_scheduler.clear(); // Clear out any pending tasks } catch(std::exception& ex) { return handle_stdexception(__func__, ex); } catch(...) { return handle_generalexception(__func__); } } //--------------------------------------------------------------------------- // OnSystemWake // // Notification of system wake power event // // Arguments: // // NONE void OnSystemWake() { try { // Reschedule the discovery to update everything std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); g_scheduler.add(now + std::chrono::seconds(1), discover_recordings_task); // Restart the scheduler g_scheduler.start(); } catch(std::exception& ex) { return handle_stdexception(__func__, ex); } catch(...) { return handle_generalexception(__func__); } } //--------------------------------------------------------------------------- // OnPowerSavingActivated // // Notification of system power saving activation event // // Arguments: // // NONE void OnPowerSavingActivated() { } //--------------------------------------------------------------------------- // OnPowerSavingDeactivated // // Notification of system power saving deactivation event // // Arguments: // // NONE void OnPowerSavingDeactivated() { } //--------------------------------------------------------------------------- // GetStreamTimes // // Temporary function to be removed in later PVR API version PVR_ERROR GetStreamTimes(PVR_STREAM_TIMES* /*times*/) { return PVR_ERROR::PVR_ERROR_NOT_IMPLEMENTED; } //--------------------------------------------------------------------------- #pragma warning(pop)
; SMSQ general KBD polling routine v1.01  1988 / 1993 / 2000 Tony Tebby ; 2003 Marcel Kilgus ; 2000-06-24 1.01 Handles left and right shift key separately. ; 2006-09-28 1.02 Allows normal code for CAPS + SFHT/CTRL/ALT ; uses LED routine qmp_updt_led (BC) ; This takes a stream of keyboard codes from the internal keyboard queue. ; These codes have bit 7 set for key up and special escape codes. ; It also handles 'button 3' keyboard stuffing for combined mouse kbd drivers. section kbd xdef kbd_poll xref kbd_krtab xref kbd_atab xref cv_upcas xref ioq_test xref ioq_gbyt xref ioq_pbyt xref pt_button3 xref qmp_updt_led xref smsq_sreset xref smsq_hreset include 'dev8_keys_sys' include 'dev8_keys_chn' include 'dev8_keys_con' include 'dev8_keys_k' include 'dev8_keys_qu' include 'dev8_smsq_kbd_keys' include 'dev8_mac_assert' kbd_poll assert kb_err,kb_b3 tst.b kb_err(a3) ; errors? (signalled by interrupt server) beq.s kbp_kq ; ... no blt.s kbp_b3 ; ... not really - it is a button 3 subq.b #1,kb_err(a3) ; wait a little bit bra.s kbp_rts kbp_b3 jsr pt_button3 ; do a button 3 sf kb_b3(a3) ; ... and clear it kbp_kq move.l sys_ckyq(a6),d6 ; any keyboard queue? beq.s kbp_rts move.l kb_queue(a3),a2 jsr ioq_gbyt beq.s kbp_do ; code in queue move.w kb_lcod(a3),d5 ; key still down? beq.s kbp_nextk ; ... no subq.w #1,sys_rcnt(a6) ; count down bgt.s kbp_nextk move.l d6,a2 ; anything in queue? jsr ioq_test beq.s kbp_nextk ; ... something there move.w sys_rtim(a6),sys_rcnt(a6); auto repeat time move.w sys_lchr(a6),d1 ; old char st kb_arep(a3) ; auto repeat!! bra.l kbp_send ; ... do it kbp_rts rts kbp_nrep move.w #$7fff,sys_rcnt(a6) ; do not auto repeat (very often!) kbp_nextk kbp_again move.l kb_queue(a3),a2 jsr ioq_gbyt bne.s kbp_rts ; no key available kbp_do and.w #$ff,d1 move.w d1,d2 ; d1 = key code and key state and.w #$7f,d2 ; d2 = key code only lea kbd_krtab,a1 ; get base of keyrow table move.b (a1,d2.w),d0 ; get bit/row move.w d0,d3 and.w #$f,d0 ; row only lsr.b #4,d3 btst #kb..up,d1 ; key up? bne.s kbp_keyu bset d3,kb_krwem(a3,d0.w) ; ... no, key down bra.s kbp_action kbp_keyu bclr d3,kb_krwem(a3,d0.w) ; key up kbp_action lea kbd_atab,a1 moveq #0,d0 move.b (a1,d2.w),d0 ; action add.w kbp_act(pc,d0.w),d0 jmp kbp_act(pc,d0.w) kbp_act dc.w kbp_norm-* dc.w kbp_shiftl-* dc.w kbp_shiftr-* dc.w kbp_ctrll-* dc.w kbp_ctrlr-* dc.w kbp_alt-* dc.w kbp_altgr-* dc.w kbp_caps-* dc.w kbp_slock-* dc.w kbp_nrep-* dc.w kbp_sys-* dc.w kbp_undo-* dc.w kbp_break-* dc.w kbp_tab-* ;--------------------------------------------------------------------- ; shift keys kbp_shiftl moveq #kb..shfl,d2 ; left shift key bra.s kbp_shift kbp_shiftr moveq #kb..shfr,d2 ; right shift key kbp_shift moveq #kb..shft,d3 ; combined status moveq #kb.shftb,d0 clr.b sys_dfrz(a6) ; unfreeze display jsr qmp_updt_led bra.s kbp_twokeys kbp_ctrll moveq #kb..ctll,d2 ; left ctrl key bra.s kbp_ctrl kbp_ctrlr moveq #kb..ctlr,d2 ; right ctrl key kbp_ctrl moveq #kb..ctrl,d3 ; combined status moveq #kb.ctrlb,d0 kbp_twokeys ; handler for SHIFT and CTRL assert kb..up,7 tst.b d1 ; key up? bmi.s kbp_twokeyup ; ... yes bset d2,kb_stat(a3) bra.s kbp_sspec ; key pressed -> set combined status kbp_twokeyup bclr d2,kb_stat(a3) and.b kb_stat(a3),d0 ; both keys up? beq.s kbp_cspec ; ... yes, clear combined status bra kbp_again kbp_alt moveq #kb..alt,d3 ; alt key bra.s kbp_spec kbp_altgr moveq #kb..agr,d3 ; alt gr key kbp_spec assert kb..up,7 tst.b d1 ; key up? bmi.s kbp_cspec ; ... yes kbp_sspec bset d3,kb_stat(a3) bra.s kbp_stab kbp_cspec bclr d3,kb_stat(a3) kbp_stab move.w #kb.gcs,d3 ; table is alt gr control and shift dep and.b kb_stat(a3),d3 bmi.s kbp_agtab lsl.w #kb..tabs,d3 ; set table pointer move.w d3,kb_tab(a3) bra kbp_again kbp_agtab move.w #4<<kb..tabs,kb_tab(a3) bra kbp_again ; capslock kbp_caps assert kb..up,7 ; Added 1.02 tst.w kb_stat(a3) ; If any of SHIFT, CONTROL, ALT . . bne kbp_norm ; . . set a normal code ; End of addition tst.b d1 ; key up? bmi kbp_again ; ... yes not.b sys_caps(a6) jsr qmp_updt_led move.l sys_capr(a6),d0 ; keyboard intercept routine? ble.s kbp_capsold ; ... no, try old style move.l d0,a1 jsr (a1) ; ... yes, do it bra kbp_nrep kbp_capsold tst.l sys_csub(a6) ; capslock routine? beq kbp_nrep ; ... no jsr sys_csub(a6) ; ... yes, do it bra kbp_nrep ;----------------------------------------------------------- ; special action keys ; freeze screen kbp_slock bsr.l kbp_keystroke ; check for keystroke kbp_freezz btst #sys..ssf,sys_klock(a6) ; suppressed? bne kbp_nrep not.b sys_dfrz(a6) ; ... toggle screen frozen flag jsr qmp_updt_led bra kbp_nrep ; system request kbp_sys bsr.l kbp_keystroke ; check for keystroke bra kbp_nrep ; sys req ignored ; undo / break hard reset kbp_undo kbp_break bsr.l kbp_keystroke ; check for keystroke moveq #kb.acs,d0 and.b kb_stat(a3),d0 cmp.b #kb.acs,d0 ; CTRL ALT SHIFT? beq.s kbp_hreset ; ... yes, do hard reset btst #kb..ctrl,kb_stat(a3) ; CTRL? beq.l kbp_dokey ; ... no, do normal key kbp_dobreak btst #sys..sbk,sys_klock(a6) ; suppressed? bne kbp_nrep tas sys_brk(a6) ; clean break bra kbp_nrep kbp_hreset btst #sys..shr,sys_klock(a6) ; hard reset suppressed? bne kbp_nrep jsr smsq_hreset bra kbp_nrep ; tab / soft reset kbp_tab bsr.s kbp_keystroke ; check for keystroke moveq #kb.acs,d0 and.b kb_stat(a3),d0 cmp.b #kb.acs,d0 ; CTRL ALT SHIFT? bne.l kbp_dokey ; ... no, normal key kbp_sreset btst #sys..ssr,sys_klock(a6) ; soft reset suppressed? bne kbp_nrep jsr smsq_sreset bra kbp_nrep ; switch keyboard queue - a bit odd because it needs to be QDOS compatible kbp_swt btst #sys..ssq,sys_klock(a6) ; suppressed? bne kbp_nrep move.l (a2),d2 ; keep next queue move.l d2,a2 bra.s kbp_ckq kbp_nxq move.l (a2),a2 ; next queue cmp.l a2,d2 ; same as saved queue? beq.s kbp_setq kbp_ckq tst.b sd_curf-sd_keyq(a2) ; cursor enabled? bne.s kbp_setq ; ... yes, go to it tst.b chn_stat-sd_keyq(a2) ; waiting? beq.s kbp_nxq ; ... no cmp.b #4,chn_actn-sd_keyq(a2) ; input? bgt.s kbp_nxq ; ... no kbp_setq move.l a2,sys_ckyq(a6) ; reset keyboard queue move.l a2,d6 move.w #$7fff,sys_rcnt(a6) ; do not auto repeat (very often!) rts ; do not try again straight away ;------------------------------------------------------ ; Suppress silly keyboard repeat for normal and special keystrokes kbp_keystroke bclr #kb..up,d1 ; key up? beq.s kbp_kdown ; ... no, down cmp.w kb_lcod(a3),d1 ; same code as last down? bne.s kbp_kjunk clr.w kb_lcod(a3) tst.b kb_arep(a3) ; autorepeated character? beq.s kbp_kjunk ; ... no move.l d6,a2 move.l qu_nexti(a2),qu_nexto(a2); ... yes, clear queue kbp_kjunk addq.l #4,sp ; skip return bra kbp_again ; and do next key kbp_kdown cmp.w kb_lcod(a3),d1 ; same key? beq.s kbp_kjunk ; ... yes, ignore it move.w d1,kb_lcod(a3) ; key down clr.b kb_arep(a3) ; not auto-repeated move.w sys_rdel(a6),sys_rcnt(a6); auto repeat delay rts ;------------------------------------------------------ ; process normal keystrokes kbp_norm ; normal keystroke bsr kbp_keystroke ; check for keystroke kbp_dokey move.l kb_ktab(a3),a1 ; key translate table add.w kb_tab(a3),a1 ; the right one move.l d6,a2 ; keyboard queue move.b (a1,d1.w),d1 ; get QL key code move.l kb_nstab(a3),a1 ; is it a non-spacing ident? moveq #0,d0 move.b (a1,d1.w),d0 beq.s kbp_cknsid ; ... no, check if it was already? move.w d0,kb_nsid(a3) ; ... yes, save it bra.l kbp_nrep ; ... and throw away kbp_cknsid move.w kb_nsid(a3),d0 ; have we a non-spacing ident? beq.s kbp_ckesc ; ... no clr.w kb_nsid(a3) ; ... not now add.w #$100,a1 ; chars to modify kbp_nsloop move.b (a1)+,d2 beq.s kbp_ckesc ; end of list cmp.b d2,d1 ; this one? bne.s kbp_nsloop ; ... no move.b -1(a1,d0.w),d1 ; ... yes, real character bra.s kbp_ckalt kbp_ckesc cmp.b #k.esc,d1 ; do not auto repeat ESC key bne.s kbp_ckalt move.w #$7fff,sys_rcnt(a6) ; do not auto repeat (very often!) kbp_ckalt btst #kb..alt,kb_stat(a3) ; alt beq.s kbp_case ; no, check special cases clr.b sys_dfrz(a6) ; unfreeze screen jsr qmp_updt_led cmp.b #k.alt1l,d1 ; below min altkey+1? blo.s kbp_alt2 ; ... yes cmp.b #k.alt1h,d1 ; above same? bhi.s kbp_alt2 ; ... yes addq.b #1,d1 ; ... no, add one bra.s kbp_send ; done kbp_alt2 ; send two bytes or.w #$ff00,d1 ; $ff/char cmp.b #'S',sys_idnt(a6) ; SMSQ/E type? beq.s kbp_send bra.s kbp_docaps kbp_case btst #kb..ctrl,kb_stat(a3) ; control? beq.s kbp_docaps ; ... no do capslock if set cmp.b #k.freez,d1 ; is it freez? beq kbp_freezz cmp.w sys_swtc(a6),d1 ; is it switch? beq kbp_swt cmp.b #k.break,d1 ; is it break? beq kbp_dobreak ; ... yes, do it kbp_docaps clr.b sys_dfrz(a6) ; unfreeze screen jsr qmp_updt_led tst.w sys_caps(a6) ; check capslock beq.s kbp_send ; ... not caps move.w d1,d2 ; save altkey flag jsr cv_upcas ; upper case it clr.b d2 or.w d2,d1 ; and restore altkey flag kbp_send move.w d1,sys_lchr(a6) ; save last char(s) beq kbp_again ; no character at all bpl.s kbp_pbyt ; just one move.w d1,d5 ; $ff/char, save character jsr ioq_test ; check room cmp.w #2,d2 ; at least 2? blt kbp_again ; ... no moveq #-1,d1 ; ... yes, send $ff jsr ioq_pbyt move.w d5,d1 ; and carry on kbp_pbyt jsr ioq_pbyt ; put character in bra kbp_again end
// (C) Copyright John Maddock 2000. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include "check_integral_constant.hpp" #ifdef TEST_STD # include <type_traits> #else # include <boost/type_traits/has_trivial_destructor.hpp> #endif #ifndef BOOST_NO_CXX11_DELETED_FUNCTIONS struct deleted_destruct { deleted_destruct(); ~deleted_destruct() = delete; }; #endif struct private_destruct { private_destruct(); private: ~private_destruct(); }; TT_TEST_BEGIN(has_trivial_destructor) BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<bool>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<bool const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<bool volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<bool const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<signed char>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<signed char const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<signed char volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<signed char const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned char>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<char>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned char const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<char const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned char volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<char volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned char const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<char const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned short>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<short>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned short const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<short const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned short volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<short volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned short const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<short const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned int>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<int>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned int const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<int const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned int volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<int volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned int const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<int const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned long>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<long>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned long const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<long const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned long volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<long volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned long const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<long const volatile>::value, true); #ifdef BOOST_HAS_LONG_LONG BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor< ::boost::ulong_long_type>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor< ::boost::long_long_type>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor< ::boost::ulong_long_type const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor< ::boost::long_long_type const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor< ::boost::ulong_long_type volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor< ::boost::long_long_type volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor< ::boost::ulong_long_type const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor< ::boost::long_long_type const volatile>::value, true); #endif #ifdef BOOST_HAS_MS_INT64 BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int8>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int8>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int8 const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int8 const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int8 volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int8 volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int8 const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int8 const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int16>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int16>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int16 const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int16 const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int16 volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int16 volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int16 const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int16 const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int32>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int32>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int32 const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int32 const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int32 volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int32 volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int32 const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int32 const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int64>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int64>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int64 const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int64 const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int64 volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int64 volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<unsigned __int64 const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<__int64 const volatile>::value, true); #endif BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<float>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<float const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<float volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<float const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<double>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<double const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<double volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<double const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<long double>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<long double const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<long double volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<long double const volatile>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<int>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<void*>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<int*const>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<f1>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<f2>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<f3>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<mf1>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<mf2>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<mf3>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<mp>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<cmf>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<enum_UDT>::value, true); // // These are commented out for now because it's not clear what the semantics should be: // on the one hand references always have trivial destructors (in the sense that there is // nothing to destruct), on the other hand the thing referenced may not have a trivial // destructor, it really depends upon the users code as to what should happen here: // //BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<int&>::value, false); //BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<const int&>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<int[2]>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<int[3][2]>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<int[2][4][5][6][3]>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<UDT>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<empty_UDT>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<void>::value, false); // cases we would like to succeed but can't implement in the language: BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<empty_POD_UDT>::value, true, false); BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<POD_UDT>::value, true, false); BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<POD_union_UDT>::value, true, false); BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<empty_POD_union_UDT>::value, true, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<trivial_except_destroy>::value, false); BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<trivial_except_copy>::value, true, false); BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<trivial_except_construct>::value, true, false); BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<trivial_except_assign>::value, true, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<wrap<trivial_except_destroy> >::value, false); BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<wrap<trivial_except_copy> >::value, true, false); BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<wrap<trivial_except_construct> >::value, true, false); BOOST_CHECK_SOFT_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<wrap<trivial_except_assign> >::value, true, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<private_destruct>::value, false); #ifndef BOOST_NO_CXX11_DELETED_FUNCTIONS BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<deleted_destruct>::value, false); #endif TT_TEST_END
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # 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. ############################################################################### .section .note.GNU-stack,"",%progbits .text sm2_data: _prime_sm2: .long 0xFFFFFFFF, 0xFFFFFFFF, 0x0, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE .p2align 4, 0x90 .type _add_256, @function _add_256: movl (%esi), %eax addl (%ebx), %eax movl %eax, (%edi) movl (4)(%esi), %eax adcl (4)(%ebx), %eax movl %eax, (4)(%edi) movl (8)(%esi), %eax adcl (8)(%ebx), %eax movl %eax, (8)(%edi) movl (12)(%esi), %eax adcl (12)(%ebx), %eax movl %eax, (12)(%edi) movl (16)(%esi), %eax adcl (16)(%ebx), %eax movl %eax, (16)(%edi) movl (20)(%esi), %eax adcl (20)(%ebx), %eax movl %eax, (20)(%edi) movl (24)(%esi), %eax adcl (24)(%ebx), %eax movl %eax, (24)(%edi) movl (28)(%esi), %eax adcl (28)(%ebx), %eax movl %eax, (28)(%edi) mov $(0), %eax adc $(0), %eax ret .Lfe1: .size _add_256, .Lfe1-(_add_256) .p2align 4, 0x90 .type _sub_256, @function _sub_256: movl (%esi), %eax subl (%ebx), %eax movl %eax, (%edi) movl (4)(%esi), %eax sbbl (4)(%ebx), %eax movl %eax, (4)(%edi) movl (8)(%esi), %eax sbbl (8)(%ebx), %eax movl %eax, (8)(%edi) movl (12)(%esi), %eax sbbl (12)(%ebx), %eax movl %eax, (12)(%edi) movl (16)(%esi), %eax sbbl (16)(%ebx), %eax movl %eax, (16)(%edi) movl (20)(%esi), %eax sbbl (20)(%ebx), %eax movl %eax, (20)(%edi) movl (24)(%esi), %eax sbbl (24)(%ebx), %eax movl %eax, (24)(%edi) movl (28)(%esi), %eax sbbl (28)(%ebx), %eax movl %eax, (28)(%edi) mov $(0), %eax adc $(0), %eax ret .Lfe2: .size _sub_256, .Lfe2-(_sub_256) .p2align 4, 0x90 .type _shl_256, @function _shl_256: movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movl (28)(%esi), %eax movdqa %xmm0, %xmm2 psllq $(1), %xmm0 psrlq $(63), %xmm2 movdqa %xmm1, %xmm3 psllq $(1), %xmm1 psrlq $(63), %xmm3 palignr $(8), %xmm2, %xmm3 pslldq $(8), %xmm2 por %xmm3, %xmm1 por %xmm2, %xmm0 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) shr $(31), %eax ret .Lfe3: .size _shl_256, .Lfe3-(_shl_256) .p2align 4, 0x90 .type _shr_256, @function _shr_256: movd %eax, %xmm4 movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 psllq $(63), %xmm4 movdqa %xmm0, %xmm2 psrlq $(1), %xmm0 psllq $(63), %xmm2 movdqa %xmm1, %xmm3 psrlq $(1), %xmm1 psllq $(63), %xmm3 palignr $(8), %xmm3, %xmm4 palignr $(8), %xmm2, %xmm3 por %xmm4, %xmm1 por %xmm3, %xmm0 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) ret .Lfe4: .size _shr_256, .Lfe4-(_shr_256) .p2align 4, 0x90 .globl sm2_add .type sm2_add, @function sm2_add: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(36), %esp and $(-16), %esp movl %eax, (32)(%esp) movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (16)(%ebp), %ebx call _add_256 mov %eax, %edx lea (%esp), %edi movl (8)(%ebp), %esi lea sm2_data, %ebx lea ((_prime_sm2-sm2_data))(%ebx), %ebx call _sub_256 lea (%esp), %esi movl (8)(%ebp), %edi sub %eax, %edx cmovne %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (32)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .Lfe5: .size sm2_add, .Lfe5-(sm2_add) .p2align 4, 0x90 .globl sm2_sub .type sm2_sub, @function sm2_sub: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(36), %esp and $(-16), %esp movl %eax, (32)(%esp) movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (16)(%ebp), %ebx call _sub_256 mov %eax, %edx lea (%esp), %edi movl (8)(%ebp), %esi lea sm2_data, %ebx lea ((_prime_sm2-sm2_data))(%ebx), %ebx call _add_256 lea (%esp), %esi movl (8)(%ebp), %edi test %edx, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (32)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .Lfe6: .size sm2_sub, .Lfe6-(sm2_sub) .p2align 4, 0x90 .globl sm2_neg .type sm2_neg, @function sm2_neg: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(36), %esp and $(-16), %esp movl %eax, (32)(%esp) movl (8)(%ebp), %edi movl (12)(%ebp), %esi mov $(0), %eax subl (%esi), %eax movl %eax, (%edi) mov $(0), %eax sbbl (4)(%esi), %eax movl %eax, (4)(%edi) mov $(0), %eax sbbl (8)(%esi), %eax movl %eax, (8)(%edi) mov $(0), %eax sbbl (12)(%esi), %eax movl %eax, (12)(%edi) mov $(0), %eax sbbl (16)(%esi), %eax movl %eax, (16)(%edi) mov $(0), %eax sbbl (20)(%esi), %eax movl %eax, (20)(%edi) mov $(0), %eax sbbl (24)(%esi), %eax movl %eax, (24)(%edi) mov $(0), %eax sbbl (28)(%esi), %eax movl %eax, (28)(%edi) sbb %edx, %edx lea (%esp), %edi movl (8)(%ebp), %esi lea sm2_data, %ebx lea ((_prime_sm2-sm2_data))(%ebx), %ebx call _add_256 lea (%esp), %esi movl (8)(%ebp), %edi test %edx, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (32)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .Lfe7: .size sm2_neg, .Lfe7-(sm2_neg) .p2align 4, 0x90 .globl sm2_mul_by_2 .type sm2_mul_by_2, @function sm2_mul_by_2: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(36), %esp and $(-16), %esp movl %eax, (32)(%esp) lea (%esp), %edi movl (12)(%ebp), %esi call _shl_256 mov %eax, %edx mov %edi, %esi movl (8)(%ebp), %edi lea sm2_data, %ebx lea ((_prime_sm2-sm2_data))(%ebx), %ebx call _sub_256 sub %eax, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (32)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .Lfe8: .size sm2_mul_by_2, .Lfe8-(sm2_mul_by_2) .p2align 4, 0x90 .globl sm2_mul_by_3 .type sm2_mul_by_3, @function sm2_mul_by_3: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(72), %esp and $(-16), %esp movl %eax, (68)(%esp) lea sm2_data, %eax lea ((_prime_sm2-sm2_data))(%eax), %eax movl %eax, (64)(%esp) lea (%esp), %edi movl (12)(%ebp), %esi call _shl_256 mov %eax, %edx mov %edi, %esi lea (32)(%esp), %edi mov (64)(%esp), %ebx call _sub_256 sub %eax, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov %edi, %esi movl (12)(%ebp), %ebx call _add_256 mov %eax, %edx movl (8)(%ebp), %edi mov (64)(%esp), %ebx call _sub_256 sub %eax, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (68)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .Lfe9: .size sm2_mul_by_3, .Lfe9-(sm2_mul_by_3) .p2align 4, 0x90 .globl sm2_div_by_2 .type sm2_div_by_2, @function sm2_div_by_2: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(36), %esp and $(-16), %esp movl %eax, (32)(%esp) lea (%esp), %edi movl (12)(%ebp), %esi lea sm2_data, %ebx lea ((_prime_sm2-sm2_data))(%ebx), %ebx call _add_256 mov $(0), %edx movl (%esi), %ecx and $(1), %ecx cmovne %edi, %esi cmove %edx, %eax movl (8)(%ebp), %edi call _shr_256 mov (32)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .Lfe10: .size sm2_div_by_2, .Lfe10-(sm2_div_by_2) .p2align 4, 0x90 .globl sm2_mul_mont_slm .type sm2_mul_mont_slm, @function sm2_mul_mont_slm: push %ebp mov %esp, %ebp push %ebx push %esi push %edi push %ebp mov %esp, %eax sub $(52), %esp and $(-16), %esp movl %eax, (48)(%esp) pxor %mm0, %mm0 movq %mm0, (%esp) movq %mm0, (8)(%esp) movq %mm0, (16)(%esp) movq %mm0, (24)(%esp) movd %mm0, (32)(%esp) movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (16)(%ebp), %ebp movl %edi, (36)(%esp) movl %esi, (40)(%esp) movl %ebp, (44)(%esp) mov $(8), %edi movd (4)(%esi), %mm1 movd (8)(%esi), %mm2 movd (12)(%esi), %mm3 movd (16)(%esi), %mm4 .p2align 4, 0x90 .Lmmul_loopgas_11: movd %edi, %mm7 movl (%ebp), %edx movl (%esi), %eax movd %edx, %mm0 add $(4), %ebp movl %ebp, (44)(%esp) pmuludq %mm0, %mm1 pmuludq %mm0, %mm2 mul %edx addl (%esp), %eax adc $(0), %edx pmuludq %mm0, %mm3 pmuludq %mm0, %mm4 movd %mm1, %ecx psrlq $(32), %mm1 add %edx, %ecx movd %mm1, %edx adc $(0), %edx addl (4)(%esp), %ecx movd (20)(%esi), %mm1 adc $(0), %edx movd %mm2, %ebx psrlq $(32), %mm2 add %edx, %ebx movd %mm2, %edx adc $(0), %edx addl (8)(%esp), %ebx movd (24)(%esi), %mm2 adc $(0), %edx pmuludq %mm0, %mm1 pmuludq %mm0, %mm2 movd %mm3, %ebp psrlq $(32), %mm3 add %edx, %ebp movd %mm3, %edx adc $(0), %edx addl (12)(%esp), %ebp movd (28)(%esi), %mm3 adc $(0), %edx movd %mm4, %edi psrlq $(32), %mm4 add %edx, %edi movd %mm4, %edx adc $(0), %edx addl (16)(%esp), %edi adc $(0), %edx pmuludq %mm0, %mm3 movl %ecx, (%esp) add %eax, %ebx movl %ebx, (4)(%esp) mov %eax, %ecx sbb $(0), %eax sub %eax, %ebp movl %ebp, (8)(%esp) sbb $(0), %edi movl %edi, (12)(%esp) mov $(0), %edi adc $(0), %edi mov %ecx, %eax movd %mm1, %ecx psrlq $(32), %mm1 add %edx, %ecx movd %mm1, %edx adc $(0), %edx addl (20)(%esp), %ecx adc $(0), %edx movd %mm2, %ebx psrlq $(32), %mm2 add %edx, %ebx movd %mm2, %edx adc $(0), %edx addl (24)(%esp), %ebx adc $(0), %edx movd %mm3, %ebp psrlq $(32), %mm3 add %edx, %ebp movd %mm3, %edx adc $(0), %edx addl (28)(%esp), %ebp adc $(0), %edx sub %edi, %ecx movl %ecx, (16)(%esp) sbb $(0), %ebx movl %ebx, (20)(%esp) sbb %eax, %ebp movl %ebp, (24)(%esp) movd %mm7, %edi sbb $(0), %eax mov $(0), %ebx addl (32)(%esp), %edx adc $(0), %ebx add %eax, %edx movl %edx, (28)(%esp) adc $(0), %ebx movl %ebx, (32)(%esp) sub $(1), %edi movd (4)(%esi), %mm1 movd (8)(%esi), %mm2 movd (12)(%esi), %mm3 movd (16)(%esi), %mm4 jz .Lexit_mmul_loopgas_11 movl (44)(%esp), %ebp jmp .Lmmul_loopgas_11 .Lexit_mmul_loopgas_11: emms mov (36)(%esp), %edi lea (%esp), %esi lea sm2_data, %ebx lea ((_prime_sm2-sm2_data))(%ebx), %ebx call _sub_256 movl (32)(%esp), %edx sub %eax, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (48)(%esp), %esp pop %ebp pop %edi pop %esi pop %ebx pop %ebp ret .Lfe11: .size sm2_mul_mont_slm, .Lfe11-(sm2_mul_mont_slm) .p2align 4, 0x90 .globl sm2_sqr_mont_slm .type sm2_sqr_mont_slm, @function sm2_sqr_mont_slm: push %ebp mov %esp, %ebp push %esi push %edi movl (12)(%ebp), %esi movl (8)(%ebp), %edi push %esi push %esi push %edi call sm2_mul_mont_slm add $(12), %esp pop %edi pop %esi pop %ebp ret .Lfe12: .size sm2_sqr_mont_slm, .Lfe12-(sm2_sqr_mont_slm) .p2align 4, 0x90 .globl sm2_mred .type sm2_mred, @function sm2_mred: push %ebp mov %esp, %ebp push %ebx push %esi push %edi movl (12)(%ebp), %esi mov $(8), %ecx xor %edx, %edx .p2align 4, 0x90 .Lmred_loopgas_13: movl (%esi), %eax mov $(0), %ebx movl %ebx, (%esi) movl (8)(%esi), %ebx add %eax, %ebx movl %ebx, (8)(%esi) movl (12)(%esi), %ebx push %eax sbb $(0), %eax sub %eax, %ebx movl %ebx, (12)(%esi) pop %eax movl (16)(%esi), %ebx sbb $(0), %ebx movl %ebx, (16)(%esi) movl (20)(%esi), %ebx sbb $(0), %ebx movl %ebx, (20)(%esi) movl (24)(%esi), %ebx sbb $(0), %ebx movl %ebx, (24)(%esi) movl (28)(%esi), %ebx sbb %eax, %ebx movl %ebx, (28)(%esi) movl (32)(%esi), %ebx sbb $(0), %eax add %edx, %eax mov $(0), %edx adc $(0), %edx add %eax, %ebx movl %ebx, (32)(%esi) adc $(0), %edx lea (4)(%esi), %esi sub $(1), %ecx jnz .Lmred_loopgas_13 movl (8)(%ebp), %edi lea sm2_data, %ebx lea ((_prime_sm2-sm2_data))(%ebx), %ebx call _sub_256 sub %eax, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) pop %edi pop %esi pop %ebx pop %ebp ret .Lfe13: .size sm2_mred, .Lfe13-(sm2_mred) .p2align 4, 0x90 .globl sm2_select_pp_w5 .type sm2_select_pp_w5, @function sm2_select_pp_w5: push %ebp mov %esp, %ebp push %esi push %edi pxor %xmm0, %xmm0 movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (16)(%ebp), %eax movd %eax, %xmm7 pshufd $(0), %xmm7, %xmm7 mov $(1), %edx movd %edx, %xmm6 pshufd $(0), %xmm6, %xmm6 movdqa %xmm0, (%edi) movdqa %xmm0, (16)(%edi) movdqa %xmm0, (32)(%edi) movdqa %xmm0, (48)(%edi) movdqa %xmm0, (64)(%edi) movdqa %xmm0, (80)(%edi) movdqa %xmm6, %xmm5 mov $(16), %ecx .p2align 4, 0x90 .Lselect_loopgas_14: movdqa %xmm5, %xmm4 pcmpeqd %xmm7, %xmm4 movdqa (%esi), %xmm0 pand %xmm4, %xmm0 por (%edi), %xmm0 movdqa %xmm0, (%edi) movdqa (16)(%esi), %xmm1 pand %xmm4, %xmm1 por (16)(%edi), %xmm1 movdqa %xmm1, (16)(%edi) movdqa (32)(%esi), %xmm0 pand %xmm4, %xmm0 por (32)(%edi), %xmm0 movdqa %xmm0, (32)(%edi) movdqa (48)(%esi), %xmm1 pand %xmm4, %xmm1 por (48)(%edi), %xmm1 movdqa %xmm1, (48)(%edi) movdqa (64)(%esi), %xmm0 pand %xmm4, %xmm0 por (64)(%edi), %xmm0 movdqa %xmm0, (64)(%edi) movdqa (80)(%esi), %xmm1 pand %xmm4, %xmm1 por (80)(%edi), %xmm1 movdqa %xmm1, (80)(%edi) paddd %xmm6, %xmm5 add $(96), %esi sub $(1), %ecx jnz .Lselect_loopgas_14 pop %edi pop %esi pop %ebp ret .Lfe14: .size sm2_select_pp_w5, .Lfe14-(sm2_select_pp_w5) .p2align 4, 0x90 .globl sm2_select_ap_w7 .type sm2_select_ap_w7, @function sm2_select_ap_w7: push %ebp mov %esp, %ebp push %esi push %edi pxor %xmm0, %xmm0 movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (16)(%ebp), %eax movd %eax, %xmm7 pshufd $(0), %xmm7, %xmm7 mov $(1), %edx movd %edx, %xmm6 pshufd $(0), %xmm6, %xmm6 movdqa %xmm0, (%edi) movdqa %xmm0, (16)(%edi) movdqa %xmm0, (32)(%edi) pxor %xmm3, %xmm3 movdqa %xmm6, %xmm5 mov $(64), %ecx .p2align 4, 0x90 .Lselect_loopgas_15: movdqa %xmm5, %xmm4 pcmpeqd %xmm7, %xmm4 movdqa (%esi), %xmm0 movdqa (16)(%esi), %xmm1 pand %xmm4, %xmm0 pand %xmm4, %xmm1 por (%edi), %xmm0 por (16)(%edi), %xmm1 movdqa %xmm0, (%edi) movdqa %xmm1, (16)(%edi) movdqa (32)(%esi), %xmm0 movdqa (48)(%esi), %xmm1 pand %xmm4, %xmm0 pand %xmm4, %xmm1 por (32)(%edi), %xmm0 por %xmm1, %xmm3 movdqa %xmm0, (32)(%edi) paddd %xmm6, %xmm5 add $(64), %esi sub $(1), %ecx jnz .Lselect_loopgas_15 movdqa %xmm3, (48)(%edi) pop %edi pop %esi pop %ebp ret .Lfe15: .size sm2_select_ap_w7, .Lfe15-(sm2_select_ap_w7)
; A123509: Rohrbach's problem: a(n) is the largest integer such that there exists a set of n integers that is a basis of order 2 for (0, 1, ..., a(n)-1). ; 1,3,5,9,13,17,21,27,33,41,47,55 add $0,3 mul $0,7 pow $0,2 div $0,336 sub $0,1 mul $0,2 add $0,1
;--------------------------------------------------------- ; ; LZ4 block 68k small depacker ; Written by Arnaud Carré ( @leonard_coder ) ; https://github.com/arnaud-carre/lz4-68k ; ; LZ4 technology by Yann Collet ( https://lz4.github.io/lz4/ ) ; ;--------------------------------------------------------- ; Smallest version: depacker is only 72 bytes ; ; input: a0.l : packed buffer ; a1.l : output buffer ; d0.l : LZ4 packed block size (in bytes) ; ; output: none ; lz4_depack: lea 0(a0,d0.l),a4 ; packed buffer end moveq #0,d0 moveq #0,d2 moveq #15,d4 .tokenLoop: move.b (a0)+,d0 move.l d0,d1 lsr.b #4,d1 beq.s .lenOffset bsr.s .readLen .litcopy: move.b (a0)+,(a1)+ subq.l #1,d1 ; block could be > 64KiB bne.s .litcopy ; end test is always done just after literals cmpa.l a0,a4 beq.s .readEnd .lenOffset: move.b (a0)+,d2 ; read 16bits offset, little endian, unaligned move.b (a0)+,-(a7) move.w (a7)+,d1 move.b d2,d1 movea.l a1,a3 sub.l d1,a3 ; d1 bits 31..16 are always 0 here moveq #$f,d1 and.w d0,d1 bsr.s .readLen addq.l #4,d1 .copy: move.b (a3)+,(a1)+ subq.l #1,d1 bne.s .copy bra.s .tokenLoop .readLen: cmp.b d1,d4 bne.s .readEnd .readLoop: move.b (a0)+,d2 add.l d2,d1 ; final len could be > 64KiB not.b d2 beq.s .readLoop .readEnd: rts
; ; Include code from halx86 ; This is a cpp style symbolic link include ..\..\halx86\i386\xxioacc.asm
; A209648: Number of n X 6 0..1 arrays avoiding 0 0 1 and 1 0 0 horizontally and 0 0 1 and 1 0 1 vertically. ; 22,484,2354,7128,16830,34012,61754,103664,163878,247060,358402,503624,688974,921228,1207690,1556192,1975094,2473284,3060178,3745720,4540382,5455164,6501594,7691728,9038150,10553972,12252834,14148904,16256878,18591980,21169962,24007104,27120214,30526628,34244210,38291352,42686974,47450524,52601978,58161840,64151142,70591444,77504834,84913928,92841870,101312332,110349514,119978144,130223478,141111300,152667922,164920184,177895454,191621628,206127130,221440912,237592454,254611764,272529378,291376360,311184302,331985324,353812074,376697728,400675990,425781092,452047794,479511384,508207678,538173020,569444282,602058864,636054694,671470228,708344450,746716872,786627534,828117004,871226378,915997280,962471862,1010692804,1060703314,1112547128,1166268510,1221912252,1279523674,1339148624,1400833478,1464625140,1530571042,1598719144,1669117934,1741816428,1816864170,1894311232,1974208214,2056606244,2141556978,2229112600 mov $3,$0 mov $7,$0 add $0,1 lpb $0 sub $0,1 add $2,$3 mov $3,6 add $3,$0 mov $4,6 trn $6,3 add $6,4 add $4,$6 add $6,$2 add $6,$2 lpe mov $1,$4 mul $1,2 add $1,2 mov $5,136 mov $8,$7 lpb $5 add $1,$8 sub $5,1 lpe mov $10,$7 lpb $10 add $9,$8 sub $10,1 lpe mov $5,182 mov $8,$9 lpb $5 add $1,$8 sub $5,1 lpe mov $9,0 mov $10,$7 lpb $10 add $9,$8 sub $10,1 lpe mov $5,116 mov $8,$9 lpb $5 add $1,$8 sub $5,1 lpe mov $9,0 mov $10,$7 lpb $10 add $9,$8 sub $10,1 lpe mov $5,22 mov $8,$9 lpb $5 add $1,$8 sub $5,1 lpe mov $0,$1
; *********************************************************************************** ; ; Blink two LEDs (PB1 and PB2) on an ATmega328p at 1 Hz on opposite duty cycles ; ; The MIT License (MIT) ; ; Copyright (c) 2020 Igor Mikolic-Torreira ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in all ; copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ; SOFTWARE. ; ; *********************************************************************************** .device "ATmega328p" ; *************************************** ; R E G I S T E R P O L I C Y ; *************************************** ; .def rSreg = r15 ; Save/Restore status port .def rTmp = r16 ; Define multipurpose register ; ********************************** ; M A C R O S ; ********************************** .macro initializeStack ; Takes 1 argument, @0 = register to use .ifdef SPH ; if SPH is defined ldi @0, High( RAMEND ) out SPH, @0 ; Upper byte of stack pointer (always load high-byte first) .endif ldi @0, Low( RAMEND ) out SPL, @0 ; Lower byte of stack pointer .endm ; ********************************** ; C O D E S E G M E N T ; ********************************** .cseg .org 000000 ; ************************************ ; I N T E R R U P T V E C T O R S ; ************************************ rjmp main ; Reset vector reti ; (other) reti ; INT0 reti ; (other) reti ; INT1 reti ; (other) reti ; PCI0 reti ; (other) reti ; PCI1 reti ; (other) reti ; PCI2 reti ; (other) reti ; WDT reti ; (other) reti ; OC2A reti ; (other) reti ; OC2B reti ; (other) reti ; OVF2 reti ; (other) reti ; ICP1 reti ; (other) rjmp Timer1CmpAInterrupt ; OC1A reti ; (other) reti ; OC1B reti ; (other) reti ; OVF1 reti ; (other) reti ; OC0A reti ; (other) reti ; OC0B reti ; (other) reti ; OVF0 reti ; (other) reti ; SPI reti ; (other) reti ; URXC reti ; (other) reti ; UDRE reti ; (other) reti ; UTXC reti ; (other) reti ; ADCC reti ; (other) reti ; ERDY reti ; (other) reti ; ACI reti ; (other) reti ; TWI reti ; (other) reti ; SPMR ; *************************************** ; I N T E R R U P T H A N D L E R S ; *************************************** Timer1CmpAInterrupt: ; Nothing in this interrupt affects SREG, so no need to save it ; Toggle pins. Note that PORTx bits can be toggled by writing a 1 to the corresponding PINx bit. sbi PINB, PINB1 ; Toggle green LED sbi PINB, PINB2 ; Toggle red LED reti ; ********************************** ; M A I N P R O G R A M ; ********************************** main: .def rArg = r24 ; Register for argument passing .equ kPauseTime = 20 ; Seconds .equ kTimer1Top = 62449 ; "Top" counter value for 1Hz output with prescalar of 256 using Timer1 initializeStack rTmp ; Set up the stack sbi DDRB, DDB1 ; Set pin connected to Green LED to output mode sbi DDRB, DDB2 ; Set pin connected to Red LED to output mode sbi PORTB, PORTB1 ; Green LED high sbi PORTB, PORTB2 ; Red LED high ldi rArg, kPauseTime rcall delayTenthsOfSeconds ; Pause (see both LEDs working) cbi PORTB, PORTB1 ; Green LED low cbi PORTB, PORTB2 ; Red LED low ldi rArg, kPauseTime rcall delayTenthsOfSeconds ; Pause before we start blinking them sbi PORTB, PORTB1 ; Green LED high ; Set up Timer1 (CTC mode, prescalar=256, CompA interrupt on) ; Timer1 located beyond the 0xFF I/O address range so must access via sts instruction ldi rTmp, ( 1 << WGM12 ) | ( 1 << CS12 ) ; Select CTC mode with prescalar = 256 sts TCCR1B, rTmp; ; Load the CompA "top" counter value, 16-bit value must be loaded high-byte first ldi rTmp, High( kTimer1Top ) ; Always load high byte first sts OCR1AH, rTmp; ldi rTmp, Low( kTimer1Top ) ; And load low byte second sts OCR1AL, rTmp; ; Enable the CompA interrupt for Timer1 ldi rTmp, ( 1 << OCIE1A ) ; Enable CompA interrupt sts TIMSK1, rTmp; sei ; Enable interrupts loopMain: rjmp loopMain ; infinite loop ; ********************************** ; S U B R O U T I N E ; ********************************** delayTenthsOfSeconds: ; Register r24 (tenthOfSecCounter) is passed as parameter ; r24 = number of tenths-of-seconds to count (comes in as argument) ; = number of times to execute the outer+inner loops combined ; r25 = outer loop counter byte ; r26 = low byte of inner loop counter word ; r27 = high byte of inner loop counter word .def r10ths = r24 ; r24 = number of tenths-of-seconds to count (comes in as argument) ; = number of times to execute the outer+inner loops combined .def rOuter = r25 ; r25 = outer loop counter byte .def rInnerL = r26 ; r26 = low byte of inner loop counter word .def rInnerH = r27 ; r27 = high byte of inner loop counter word ; Executing the following combination of inner and outer loop cycles takes almost precisely 0.1 seconds at 16 Mhz .equ kOuterCount = 7 .equ kInnerCount = 57142 ; Top of loop for number of tenths-of-seconds Loop1: ; Initialize outer loop (uses a byte counter and counts down) ldi rOuter, kOuterCount ; Top of outer loop Loop2: ; Initialze inner loop (uses a word counter and counts down) ldi rInnerL, Low( kInnerCount ) ldi rInnerH, High( kInnerCount ) ; Top of inner loop Loop3: ; Decrement and test inner loop sbiw rInnerL, 1 brne Loop3 ; Done with inner loop ; Decrement and test outer loop dec rOuter brne Loop2 ; Done with outer loop ; Decrement and test tenth-of-second loop dec r10ths brne Loop1 ; Done with the requested number of tenths-of-seconds ret
; A169346: Number of reduced words of length n in Coxeter group on 45 generators S_i with relations (S_i)^2 = (S_i S_j)^30 = I. ; 1,45,1980,87120,3833280,168664320,7421230080,326534123520,14367501434880,632170063134720,27815482777927680,1223881242228817920,53850774658067988480,2369434084954991493120,104255099738019625697280 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 div $3,$2 mul $2,44 lpe mov $0,$2 div $0,44
; Small C+ Math Library - Support routine ; Negate a floating point number XLIB minusfa XREF fa .MINUSFA LD HL,FA+4 LD A,(HL) XOR $80 LD (HL),A RET
#include <atomic> #include <bitset> #include <chrono> #include <iostream> #include <unordered_map> #include <unordered_set> #include <vector> #include "atomic_types.hpp" #include "container_growth.hpp" #include "experiment_runner.hpp" #include "memory.hpp" #include "shared_ptr.hpp" #include "sorting.hpp" #include "special_member_function_monitor.hpp" #include "sso.hpp" #include "struct_reordering.hpp" #include "types.hpp" #include "underlying_enum_types.hpp" namespace Experiments { void testVectorAssignment() { std::array<std::size_t, 3> sizes = {10, 100, 1000}; for (const auto lhsSize : sizes) { for (const auto rhsSize : sizes) { std::vector<U8> lhs(lhsSize); std::vector<U8> rhs(rhsSize); std::cout << "Testing assigning vector of size " << rhsSize << " to a vector of size " << lhsSize << ". "; AllocationTrackerGuard allocationTrackerGuard(true, false); lhs = rhs; } } } void testVectorAllocationsAndFreesWithBlocks() { AllocationTrackerGuard allocationTrackerGuard(true, true); const std::size_t vectorSize = 4; std::cout << "Creating two vectors of size " << vectorSize << " in the same block.\n"; { std::vector<std::byte> vectorA(vectorSize); std::vector<std::byte> vectorB(vectorSize); } std::cout << "Creating two vectors of size " << vectorSize << " in two consecutive blocks.\n"; { { std::vector<std::byte> vector(vectorSize); } { std::vector<std::byte> vector(vectorSize); } } } void testInsertWithConflictingKeyInUnorderedMap() { std::unordered_map<int, int> map; map.insert(std::pair<int, int>{1, 2}); map.insert(std::pair<int, int>{2, 3}); map.insert(std::pair<int, int>{1, 3}); for (const auto [key, value] : map) { std::cout << key << ": " << value << '\n'; } } void testPushBackAndEmplaceBackAllocations() { const auto printSpecialMemberFunctionCallCount = [](const std::string &situation) { std::cout << "When using " << situation << ", "; SpecialMemberFunctionMonitor::print(); std::cout << "\n"; SpecialMemberFunctionMonitor::reset(); }; { std::vector<SpecialMemberFunctionMonitor> vector; SpecialMemberFunctionMonitor monitor; vector.push_back(monitor); } printSpecialMemberFunctionCallCount("push_back() with lvalue"); { std::vector<SpecialMemberFunctionMonitor> vector; vector.push_back({}); } printSpecialMemberFunctionCallCount("push_back() with rvalue"); { std::vector<SpecialMemberFunctionMonitor> vector; SpecialMemberFunctionMonitor monitor; vector.emplace_back(monitor); } printSpecialMemberFunctionCallCount("emplace_back() with lvalue"); { std::vector<SpecialMemberFunctionMonitor> vector; vector.emplace_back(); } printSpecialMemberFunctionCallCount("emplace_back() constructor arguments"); } static constexpr auto CPlusPlus98 = 199711L; static constexpr auto CPlusPlus11 = 201103L; static constexpr auto CPlusPlus14 = 201402L; static constexpr auto CPlusPlus17 = 201703L; void printStandard() noexcept { std::cout << "The C++ standard used "; if (__cplusplus < CPlusPlus98) { std::cout << "predates C++98"; } else if (__cplusplus == CPlusPlus98) { std::cout << "is C++98"; } else if (__cplusplus < CPlusPlus11) { std::cout << "predates C++11"; } else if (__cplusplus == CPlusPlus11) { std::cout << "is C++11"; } else if (__cplusplus < CPlusPlus14) { std::cout << "predates C++14"; } else if (__cplusplus == CPlusPlus14) { std::cout << "is C++14"; } else if (__cplusplus < CPlusPlus17) { std::cout << "predates C++17"; } else if (__cplusplus == CPlusPlus17) { std::cout << "is C++17"; } else { std::cout << "succeeds C++17"; } std::cout << ".\n"; } [[nodiscard]] int main() { printStandard(); ExperimentRunner(testVectorAssignment).run(); ExperimentRunner(testVectorAllocationsAndFreesWithBlocks).run(); ExperimentRunner(testVectorGrowth).run(); ExperimentRunner(testVectorReserveGrowth).run(); ExperimentRunner(testUnorderedSetGrowth).run(); ExperimentRunner(testInsertWithConflictingKeyInUnorderedMap).run(); ExperimentRunner(testUnderlyingEnumTypes).run(); ExperimentRunner(testSmallStringOptimizationSize).run(); ExperimentRunner(testPushBackAndEmplaceBackAllocations).run(); ExperimentRunner(testSharedPointerMemoryAllocations).run(); ExperimentRunner(testSortAllocations).run(); ExperimentRunner(testStableSortAllocations).run(); ExperimentRunner(testSizesOfAtomicTypes).run(); ExperimentRunner(testStructReordering).run(); return EXIT_SUCCESS; } } // namespace Experiments int main() { return Experiments::main(); }
// // detail/impl/kqueue_reactor.ipp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2005 Stefan Arentz (stefan at soze dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_IMPL_KQUEUE_REACTOR_IPP #define BOOST_ASIO_DETAIL_IMPL_KQUEUE_REACTOR_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_KQUEUE) #include <boost/asio/detail/kqueue_reactor.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> #if defined(__NetBSD__) # define BOOST_ASIO_KQUEUE_EV_SET(ev, ident, filt, flags, fflags, data, udata) \ EV_SET(ev, ident, filt, flags, fflags, \ data, reinterpret_cast<intptr_t>(udata)) #else # define BOOST_ASIO_KQUEUE_EV_SET(ev, ident, filt, flags, fflags, data, udata) \ EV_SET(ev, ident, filt, flags, fflags, data, udata) #endif namespace boost { namespace asio { namespace detail { kqueue_reactor::kqueue_reactor(boost::asio::io_service& io_service) : boost::asio::detail::service_base<kqueue_reactor>(io_service), io_service_(use_service<io_service_impl>(io_service)), mutex_(), kqueue_fd_(do_kqueue_create()), interrupter_(), shutdown_(false) { // The interrupter is put into a permanently readable state. Whenever we // want to interrupt the blocked kevent call we register a one-shot read // operation against the descriptor. interrupter_.interrupt(); } kqueue_reactor::~kqueue_reactor() { close(kqueue_fd_); } void kqueue_reactor::shutdown_service() { mutex::scoped_lock lock(mutex_); shutdown_ = true; lock.unlock(); op_queue<operation> ops; while (descriptor_state* state = registered_descriptors_.first()) { for (int i = 0; i < max_ops; ++i) ops.push(state->op_queue_[i]); state->shutdown_ = true; registered_descriptors_.free(state); } timer_queues_.get_all_timers(ops); } void kqueue_reactor::init_task() { io_service_.init_task(); } int kqueue_reactor::register_descriptor(socket_type, kqueue_reactor::per_descriptor_data& descriptor_data) { mutex::scoped_lock lock(registered_descriptors_mutex_); descriptor_data = registered_descriptors_.alloc(); descriptor_data->shutdown_ = false; return 0; } void kqueue_reactor::start_op(int op_type, socket_type descriptor, kqueue_reactor::per_descriptor_data& descriptor_data, reactor_op* op, bool allow_speculative) { if (!descriptor_data) { op->ec_ = boost::asio::error::bad_descriptor; post_immediate_completion(op); return; } mutex::scoped_lock descriptor_lock(descriptor_data->mutex_); if (descriptor_data->shutdown_) { post_immediate_completion(op); return; } bool first = descriptor_data->op_queue_[op_type].empty(); if (first) { if (allow_speculative) { if (op_type != read_op || descriptor_data->op_queue_[except_op].empty()) { if (op->perform()) { descriptor_lock.unlock(); io_service_.post_immediate_completion(op); return; } } } } descriptor_data->op_queue_[op_type].push(op); io_service_.work_started(); if (first) { struct kevent event; switch (op_type) { case read_op: BOOST_ASIO_KQUEUE_EV_SET(&event, descriptor, EVFILT_READ, EV_ADD | EV_ONESHOT, 0, 0, descriptor_data); break; case write_op: BOOST_ASIO_KQUEUE_EV_SET(&event, descriptor, EVFILT_WRITE, EV_ADD | EV_ONESHOT, 0, 0, descriptor_data); break; case except_op: if (!descriptor_data->op_queue_[read_op].empty()) return; // Already registered for read events. BOOST_ASIO_KQUEUE_EV_SET(&event, descriptor, EVFILT_READ, EV_ADD | EV_ONESHOT, EV_OOBAND, 0, descriptor_data); break; } if (::kevent(kqueue_fd_, &event, 1, 0, 0, 0) == -1) { op->ec_ = boost::system::error_code(errno, boost::asio::error::get_system_category()); descriptor_data->op_queue_[op_type].pop(); io_service_.post_deferred_completion(op); } } } void kqueue_reactor::cancel_ops(socket_type, kqueue_reactor::per_descriptor_data& descriptor_data) { if (!descriptor_data) return; mutex::scoped_lock descriptor_lock(descriptor_data->mutex_); op_queue<operation> ops; for (int i = 0; i < max_ops; ++i) { while (reactor_op* op = descriptor_data->op_queue_[i].front()) { op->ec_ = boost::asio::error::operation_aborted; descriptor_data->op_queue_[i].pop(); ops.push(op); } } descriptor_lock.unlock(); io_service_.post_deferred_completions(ops); } void kqueue_reactor::close_descriptor(socket_type, kqueue_reactor::per_descriptor_data& descriptor_data) { if (!descriptor_data) return; mutex::scoped_lock descriptor_lock(descriptor_data->mutex_); mutex::scoped_lock descriptors_lock(registered_descriptors_mutex_); if (!descriptor_data->shutdown_) { // Remove the descriptor from the set of known descriptors. The descriptor // will be automatically removed from the kqueue set when it is closed. op_queue<operation> ops; for (int i = 0; i < max_ops; ++i) { while (reactor_op* op = descriptor_data->op_queue_[i].front()) { op->ec_ = boost::asio::error::operation_aborted; descriptor_data->op_queue_[i].pop(); ops.push(op); } } descriptor_data->shutdown_ = true; descriptor_lock.unlock(); registered_descriptors_.free(descriptor_data); descriptor_data = 0; descriptors_lock.unlock(); io_service_.post_deferred_completions(ops); } } void kqueue_reactor::run(bool block, op_queue<operation>& ops) { mutex::scoped_lock lock(mutex_); // Determine how long to block while waiting for events. timespec timeout_buf = { 0, 0 }; timespec* timeout = block ? get_timeout(timeout_buf) : &timeout_buf; lock.unlock(); // Block on the kqueue descriptor. struct kevent events[128]; int num_events = kevent(kqueue_fd_, 0, 0, events, 128, timeout); // Dispatch the waiting events. for (int i = 0; i < num_events; ++i) { int descriptor = events[i].ident; void* ptr = reinterpret_cast<void*>(events[i].udata); if (ptr == &interrupter_) { // No need to reset the interrupter since we're leaving the descriptor // in a ready-to-read state and relying on one-shot notifications. } else { descriptor_state* descriptor_data = static_cast<descriptor_state*>(ptr); mutex::scoped_lock descriptor_lock(descriptor_data->mutex_); // Exception operations must be processed first to ensure that any // out-of-band data is read before normal data. #if defined(__NetBSD__) static const unsigned int filter[max_ops] = #else static const int filter[max_ops] = #endif { EVFILT_READ, EVFILT_WRITE, EVFILT_READ }; for (int j = max_ops - 1; j >= 0; --j) { if (events[i].filter == filter[j]) { if (j != except_op || events[i].flags & EV_OOBAND) { while (reactor_op* op = descriptor_data->op_queue_[j].front()) { if (events[i].flags & EV_ERROR) { op->ec_ = boost::system::error_code(events[i].data, boost::asio::error::get_system_category()); descriptor_data->op_queue_[j].pop(); ops.push(op); } if (op->perform()) { descriptor_data->op_queue_[j].pop(); ops.push(op); } else break; } } } } // Renew registration for event notifications. struct kevent event; switch (events[i].filter) { case EVFILT_READ: if (!descriptor_data->op_queue_[read_op].empty()) BOOST_ASIO_KQUEUE_EV_SET(&event, descriptor, EVFILT_READ, EV_ADD | EV_ONESHOT, 0, 0, descriptor_data); else if (!descriptor_data->op_queue_[except_op].empty()) BOOST_ASIO_KQUEUE_EV_SET(&event, descriptor, EVFILT_READ, EV_ADD | EV_ONESHOT, EV_OOBAND, 0, descriptor_data); else continue; case EVFILT_WRITE: if (!descriptor_data->op_queue_[write_op].empty()) BOOST_ASIO_KQUEUE_EV_SET(&event, descriptor, EVFILT_WRITE, EV_ADD | EV_ONESHOT, 0, 0, descriptor_data); else continue; default: break; } if (::kevent(kqueue_fd_, &event, 1, 0, 0, 0) == -1) { boost::system::error_code error(errno, boost::asio::error::get_system_category()); for (int j = 0; j < max_ops; ++j) { while (reactor_op* op = descriptor_data->op_queue_[j].front()) { op->ec_ = error; descriptor_data->op_queue_[j].pop(); ops.push(op); } } } } } lock.lock(); timer_queues_.get_ready_timers(ops); } void kqueue_reactor::interrupt() { struct kevent event; BOOST_ASIO_KQUEUE_EV_SET(&event, interrupter_.read_descriptor(), EVFILT_READ, EV_ADD | EV_ONESHOT, 0, 0, &interrupter_); ::kevent(kqueue_fd_, &event, 1, 0, 0, 0); } int kqueue_reactor::do_kqueue_create() { int fd = ::kqueue(); if (fd == -1) { boost::system::error_code ec(errno, boost::asio::error::get_system_category()); boost::asio::detail::throw_error(ec, "kqueue"); } return fd; } void kqueue_reactor::do_add_timer_queue(timer_queue_base& queue) { mutex::scoped_lock lock(mutex_); timer_queues_.insert(&queue); } void kqueue_reactor::do_remove_timer_queue(timer_queue_base& queue) { mutex::scoped_lock lock(mutex_); timer_queues_.erase(&queue); } timespec* kqueue_reactor::get_timeout(timespec& ts) { // By default we will wait no longer than 5 minutes. This will ensure that // any changes to the system clock are detected after no longer than this. long usec = timer_queues_.wait_duration_usec(5 * 60 * 1000 * 1000); ts.tv_sec = usec / 1000000; ts.tv_nsec = (usec % 1000000) * 1000; return &ts; } } // namespace detail } // namespace asio } // namespace boost #undef BOOST_ASIO_KQUEUE_EV_SET #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_KQUEUE) #endif // BOOST_ASIO_DETAIL_IMPL_KQUEUE_REACTOR_IPP
;------------------------------------------------------------------------------ ; ; Copyright (c) 2018, Advanced Micro Device, Inc. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; VmgExit.Asm ; ; Abstract: ; ; AsmVmgExit function ; ; Notes: ; ;------------------------------------------------------------------------------ DEFAULT REL SECTION .text ;------------------------------------------------------------------------------ ; VOID ; EFIAPI ; AsmVmgExit ( ; VOID ; ); ;------------------------------------------------------------------------------ global ASM_PFX(AsmVmgExit) ASM_PFX(AsmVmgExit): rep; vmmcall ret
############################################################################### # Copyright 2018 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # 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. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 4, 0x90 LOne: .long 1,1,1,1,1,1,1,1 LTwo: .long 2,2,2,2,2,2,2,2 LThree: .long 3,3,3,3,3,3,3,3 Lpoly: .quad 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff .quad 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff .quad 0xffffffffffffffff, 0xffffffffffffffff, 0x1ff .p2align 4, 0x90 .globl p521r1_mul_by_2 .type p521r1_mul_by_2, @function p521r1_mul_by_2: push %r12 push %r13 push %r14 push %r15 xor %rcx, %rcx movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 movq (32)(%rsi), %r12 movq (40)(%rsi), %r13 movq (48)(%rsi), %r14 movq (56)(%rsi), %r15 movq (64)(%rsi), %rax shld $(1), %rax, %rcx shld $(1), %r15, %rax shld $(1), %r14, %r15 shld $(1), %r13, %r14 shld $(1), %r12, %r13 shld $(1), %r11, %r12 shld $(1), %r10, %r11 shld $(1), %r9, %r10 shld $(1), %r8, %r9 shl $(1), %r8 movq %rax, (64)(%rdi) movq %r15, (56)(%rdi) movq %r14, (48)(%rdi) movq %r13, (40)(%rdi) movq %r12, (32)(%rdi) movq %r11, (24)(%rdi) movq %r10, (16)(%rdi) movq %r9, (8)(%rdi) movq %r8, (%rdi) subq Lpoly+0(%rip), %r8 sbbq Lpoly+8(%rip), %r9 sbbq Lpoly+16(%rip), %r10 sbbq Lpoly+24(%rip), %r11 sbbq Lpoly+32(%rip), %r12 sbbq Lpoly+40(%rip), %r13 sbbq Lpoly+48(%rip), %r14 sbbq Lpoly+56(%rip), %r15 sbbq Lpoly+64(%rip), %rax sbb $(0), %rcx movq (%rdi), %rdx cmovne %rdx, %r8 movq (8)(%rdi), %rdx cmovne %rdx, %r9 movq (16)(%rdi), %rdx cmovne %rdx, %r10 movq (24)(%rdi), %rdx cmovne %rdx, %r11 movq (32)(%rdi), %rdx cmovne %rdx, %r12 movq (40)(%rdi), %rdx cmovne %rdx, %r13 movq (48)(%rdi), %rdx cmovne %rdx, %r14 movq (56)(%rdi), %rdx cmovne %rdx, %r15 movq (64)(%rdi), %rdx cmovne %rdx, %rax movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %r12, (32)(%rdi) movq %r13, (40)(%rdi) movq %r14, (48)(%rdi) movq %r15, (56)(%rdi) movq %rax, (64)(%rdi) pop %r15 pop %r14 pop %r13 pop %r12 ret .Lfe1: .size p521r1_mul_by_2, .Lfe1-(p521r1_mul_by_2) .p2align 4, 0x90 .globl p521r1_div_by_2 .type p521r1_div_by_2, @function p521r1_div_by_2: push %r12 push %r13 push %r14 push %r15 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 movq (32)(%rsi), %r12 movq (40)(%rsi), %r13 movq (48)(%rsi), %r14 movq (56)(%rsi), %r15 movq (64)(%rsi), %rax xor %rdx, %rdx xor %rcx, %rcx addq Lpoly+0(%rip), %r8 adcq Lpoly+8(%rip), %r9 adcq Lpoly+16(%rip), %r10 adcq Lpoly+24(%rip), %r11 adcq Lpoly+32(%rip), %r12 adcq Lpoly+40(%rip), %r13 adcq Lpoly+48(%rip), %r14 adcq Lpoly+56(%rip), %r15 adcq Lpoly+64(%rip), %rax adc $(0), %rcx test $(1), %r8 cmovne %rdx, %rcx movq (%rsi), %rdx cmovne %rdx, %r8 movq (8)(%rsi), %rdx cmovne %rdx, %r9 movq (16)(%rsi), %rdx cmovne %rdx, %r10 movq (24)(%rsi), %rdx cmovne %rdx, %r11 movq (32)(%rsi), %rdx cmovne %rdx, %r12 movq (40)(%rsi), %rdx cmovne %rdx, %r13 movq (48)(%rsi), %rdx cmovne %rdx, %r14 movq (56)(%rsi), %rdx cmovne %rdx, %r15 movq (64)(%rsi), %rdx cmovne %rdx, %rax shrd $(1), %r9, %r8 shrd $(1), %r10, %r9 shrd $(1), %r11, %r10 shrd $(1), %r12, %r11 shrd $(1), %r13, %r12 shrd $(1), %r14, %r13 shrd $(1), %r15, %r14 shrd $(1), %rax, %r15 shrd $(1), %rcx, %rax movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %r12, (32)(%rdi) movq %r13, (40)(%rdi) movq %r14, (48)(%rdi) movq %r15, (56)(%rdi) movq %rax, (64)(%rdi) pop %r15 pop %r14 pop %r13 pop %r12 ret .Lfe2: .size p521r1_div_by_2, .Lfe2-(p521r1_div_by_2) .p2align 4, 0x90 .globl p521r1_mul_by_3 .type p521r1_mul_by_3, @function p521r1_mul_by_3: push %r12 push %r13 push %r14 push %r15 sub $(88), %rsp movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 movq (32)(%rsi), %r12 movq (40)(%rsi), %r13 movq (48)(%rsi), %r14 movq (56)(%rsi), %r15 movq (64)(%rsi), %rax xor %rcx, %rcx shld $(1), %rax, %rcx shld $(1), %r15, %rax shld $(1), %r14, %r15 shld $(1), %r13, %r14 shld $(1), %r12, %r13 shld $(1), %r11, %r12 shld $(1), %r10, %r11 shld $(1), %r9, %r10 shld $(1), %r8, %r9 shl $(1), %r8 movq %rax, (64)(%rsp) movq %r15, (56)(%rsp) movq %r14, (48)(%rsp) movq %r13, (40)(%rsp) movq %r12, (32)(%rsp) movq %r11, (24)(%rsp) movq %r10, (16)(%rsp) movq %r9, (8)(%rsp) movq %r8, (%rsp) subq Lpoly+0(%rip), %r8 sbbq Lpoly+8(%rip), %r9 sbbq Lpoly+16(%rip), %r10 sbbq Lpoly+24(%rip), %r11 sbbq Lpoly+32(%rip), %r12 sbbq Lpoly+40(%rip), %r13 sbbq Lpoly+48(%rip), %r14 sbbq Lpoly+56(%rip), %r15 sbbq Lpoly+64(%rip), %rax sbb $(0), %rcx movq (%rsp), %rdx cmovb %rdx, %r8 movq (8)(%rsp), %rdx cmovb %rdx, %r9 movq (16)(%rsp), %rdx cmovb %rdx, %r10 movq (24)(%rsp), %rdx cmovb %rdx, %r11 movq (32)(%rsp), %rdx cmovb %rdx, %r12 movq (40)(%rsp), %rdx cmovb %rdx, %r13 movq (48)(%rsp), %rdx cmovb %rdx, %r14 movq (56)(%rsp), %rdx cmovb %rdx, %r15 movq (64)(%rsp), %rdx cmovb %rdx, %rax xor %rcx, %rcx addq (%rsi), %r8 adcq (8)(%rsi), %r9 adcq (16)(%rsi), %r10 adcq (24)(%rsi), %r11 adcq (32)(%rsi), %r12 adcq (40)(%rsi), %r13 adcq (48)(%rsi), %r14 adcq (56)(%rsi), %r15 adcq (64)(%rsi), %rax adc $(0), %rcx movq %r8, (%rsp) movq %r9, (8)(%rsp) movq %r10, (16)(%rsp) movq %r11, (24)(%rsp) movq %r12, (32)(%rsp) movq %r13, (40)(%rsp) movq %r14, (48)(%rsp) movq %r15, (56)(%rsp) movq %rax, (64)(%rsp) subq Lpoly+0(%rip), %r8 sbbq Lpoly+8(%rip), %r9 sbbq Lpoly+16(%rip), %r10 sbbq Lpoly+24(%rip), %r11 sbbq Lpoly+32(%rip), %r12 sbbq Lpoly+40(%rip), %r13 sbbq Lpoly+48(%rip), %r14 sbbq Lpoly+56(%rip), %r15 sbbq Lpoly+64(%rip), %rax sbb $(0), %rcx movq (%rsp), %rdx cmovb %rdx, %r8 movq (8)(%rsp), %rdx cmovb %rdx, %r9 movq (16)(%rsp), %rdx cmovb %rdx, %r10 movq (24)(%rsp), %rdx cmovb %rdx, %r11 movq (32)(%rsp), %rdx cmovb %rdx, %r12 movq (40)(%rsp), %rdx cmovb %rdx, %r13 movq (48)(%rsp), %rdx cmovb %rdx, %r14 movq (56)(%rsp), %rdx cmovb %rdx, %r15 movq (64)(%rsp), %rdx cmovb %rdx, %rax movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %r12, (32)(%rdi) movq %r13, (40)(%rdi) movq %r14, (48)(%rdi) movq %r15, (56)(%rdi) movq %rax, (64)(%rdi) add $(88), %rsp pop %r15 pop %r14 pop %r13 pop %r12 ret .Lfe3: .size p521r1_mul_by_3, .Lfe3-(p521r1_mul_by_3) .p2align 4, 0x90 .globl p521r1_add .type p521r1_add, @function p521r1_add: push %rbx push %r12 push %r13 push %r14 push %r15 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 movq (32)(%rsi), %r12 movq (40)(%rsi), %r13 movq (48)(%rsi), %r14 movq (56)(%rsi), %r15 movq (64)(%rsi), %rax xor %rcx, %rcx addq (%rdx), %r8 adcq (8)(%rdx), %r9 adcq (16)(%rdx), %r10 adcq (24)(%rdx), %r11 adcq (32)(%rdx), %r12 adcq (40)(%rdx), %r13 adcq (48)(%rdx), %r14 adcq (56)(%rdx), %r15 adcq (64)(%rdx), %rax adc $(0), %rcx movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %r12, (32)(%rdi) movq %r13, (40)(%rdi) movq %r14, (48)(%rdi) movq %r15, (56)(%rdi) movq %rax, (64)(%rdi) subq Lpoly+0(%rip), %r8 sbbq Lpoly+8(%rip), %r9 sbbq Lpoly+16(%rip), %r10 sbbq Lpoly+24(%rip), %r11 sbbq Lpoly+32(%rip), %r12 sbbq Lpoly+40(%rip), %r13 sbbq Lpoly+48(%rip), %r14 sbbq Lpoly+56(%rip), %r15 sbbq Lpoly+64(%rip), %rax sbb $(0), %rcx movq (%rdi), %rdx cmovb %rdx, %r8 movq (8)(%rdi), %rdx cmovb %rdx, %r9 movq (16)(%rdi), %rdx cmovb %rdx, %r10 movq (24)(%rdi), %rdx cmovb %rdx, %r11 movq (32)(%rdi), %rdx cmovb %rdx, %r12 movq (40)(%rdi), %rdx cmovb %rdx, %r13 movq (48)(%rdi), %rdx cmovb %rdx, %r14 movq (56)(%rdi), %rdx cmovb %rdx, %r15 movq (64)(%rdi), %rdx cmovb %rdx, %rax movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %r12, (32)(%rdi) movq %r13, (40)(%rdi) movq %r14, (48)(%rdi) movq %r15, (56)(%rdi) movq %rax, (64)(%rdi) pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx ret .Lfe4: .size p521r1_add, .Lfe4-(p521r1_add) .p2align 4, 0x90 .globl p521r1_sub .type p521r1_sub, @function p521r1_sub: push %rbx push %r12 push %r13 push %r14 push %r15 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 movq (32)(%rsi), %r12 movq (40)(%rsi), %r13 movq (48)(%rsi), %r14 movq (56)(%rsi), %r15 movq (64)(%rsi), %rax xor %rcx, %rcx subq (%rdx), %r8 sbbq (8)(%rdx), %r9 sbbq (16)(%rdx), %r10 sbbq (24)(%rdx), %r11 sbbq (32)(%rdx), %r12 sbbq (40)(%rdx), %r13 sbbq (48)(%rdx), %r14 sbbq (56)(%rdx), %r15 sbbq (64)(%rdx), %rax sbb $(0), %rcx movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %r12, (32)(%rdi) movq %r13, (40)(%rdi) movq %r14, (48)(%rdi) movq %r15, (56)(%rdi) movq %rax, (64)(%rdi) addq Lpoly+0(%rip), %r8 adcq Lpoly+8(%rip), %r9 adcq Lpoly+16(%rip), %r10 adcq Lpoly+24(%rip), %r11 adcq Lpoly+32(%rip), %r12 adcq Lpoly+40(%rip), %r13 adcq Lpoly+48(%rip), %r14 adcq Lpoly+56(%rip), %r15 adcq Lpoly+64(%rip), %rax test %rcx, %rcx movq (%rdi), %rdx cmove %rdx, %r8 movq (8)(%rdi), %rdx cmove %rdx, %r9 movq (16)(%rdi), %rdx cmove %rdx, %r10 movq (24)(%rdi), %rdx cmove %rdx, %r11 movq (32)(%rdi), %rdx cmove %rdx, %r12 movq (40)(%rdi), %rdx cmove %rdx, %r13 movq (48)(%rdi), %rdx cmove %rdx, %r14 movq (56)(%rdi), %rdx cmove %rdx, %r15 movq (64)(%rdi), %rdx cmove %rdx, %rax movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %r12, (32)(%rdi) movq %r13, (40)(%rdi) movq %r14, (48)(%rdi) movq %r15, (56)(%rdi) movq %rax, (64)(%rdi) pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx ret .Lfe5: .size p521r1_sub, .Lfe5-(p521r1_sub) .p2align 4, 0x90 .globl p521r1_neg .type p521r1_neg, @function p521r1_neg: push %r12 push %r13 push %r14 push %r15 xor %r8, %r8 xor %r9, %r9 xor %r10, %r10 xor %r11, %r11 xor %r12, %r12 xor %r13, %r13 xor %r14, %r14 xor %r15, %r15 xor %rax, %rax xor %rcx, %rcx subq (%rsi), %r8 sbbq (8)(%rsi), %r9 sbbq (16)(%rsi), %r10 sbbq (24)(%rsi), %r11 sbbq (32)(%rsi), %r12 sbbq (40)(%rsi), %r13 sbbq (48)(%rsi), %r14 sbbq (56)(%rsi), %r15 sbbq (64)(%rsi), %rax sbb $(0), %rcx movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %r12, (32)(%rdi) movq %r13, (40)(%rdi) movq %r14, (48)(%rdi) movq %r15, (56)(%rdi) movq %rax, (64)(%rdi) addq Lpoly+0(%rip), %r8 adcq Lpoly+8(%rip), %r9 adcq Lpoly+16(%rip), %r10 adcq Lpoly+24(%rip), %r11 adcq Lpoly+32(%rip), %r12 adcq Lpoly+40(%rip), %r13 adcq Lpoly+48(%rip), %r14 adcq Lpoly+56(%rip), %r15 adcq Lpoly+64(%rip), %rax test %rcx, %rcx movq (%rdi), %rdx cmove %rdx, %r8 movq (8)(%rdi), %rdx cmove %rdx, %r9 movq (16)(%rdi), %rdx cmove %rdx, %r10 movq (24)(%rdi), %rdx cmove %rdx, %r11 movq (32)(%rdi), %rdx cmove %rdx, %r12 movq (40)(%rdi), %rdx cmove %rdx, %r13 movq (48)(%rdi), %rdx cmove %rdx, %r14 movq (56)(%rdi), %rdx cmove %rdx, %r15 movq (64)(%rdi), %rdx cmove %rdx, %rax movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %r12, (32)(%rdi) movq %r13, (40)(%rdi) movq %r14, (48)(%rdi) movq %r15, (56)(%rdi) movq %rax, (64)(%rdi) pop %r15 pop %r14 pop %r13 pop %r12 ret .Lfe6: .size p521r1_neg, .Lfe6-(p521r1_neg) .p2align 4, 0x90 .globl p521r1_mred .type p521r1_mred, @function p521r1_mred: push %rbx push %r12 push %r13 push %r14 push %r15 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 movq (32)(%rsi), %r12 movq (40)(%rsi), %r13 movq (48)(%rsi), %r14 movq (56)(%rsi), %r15 movq (64)(%rsi), %rax movq (72)(%rsi), %rcx xor %rdx, %rdx mov %r8, %rbx shr $(55), %rbx shl $(9), %r8 add %rdx, %rbx add %r8, %rax adc %rbx, %rcx mov $(0), %rdx adc $(0), %rdx movq (80)(%rsi), %r8 mov %r9, %rbx shr $(55), %rbx shl $(9), %r9 add %rdx, %rbx add %r9, %rcx adc %rbx, %r8 mov $(0), %rdx adc $(0), %rdx movq (88)(%rsi), %r9 mov %r10, %rbx shr $(55), %rbx shl $(9), %r10 add %rdx, %rbx add %r10, %r8 adc %rbx, %r9 mov $(0), %rdx adc $(0), %rdx movq (96)(%rsi), %r10 mov %r11, %rbx shr $(55), %rbx shl $(9), %r11 add %rdx, %rbx add %r11, %r9 adc %rbx, %r10 mov $(0), %rdx adc $(0), %rdx movq (104)(%rsi), %r11 mov %r12, %rbx shr $(55), %rbx shl $(9), %r12 add %rdx, %rbx add %r12, %r10 adc %rbx, %r11 mov $(0), %rdx adc $(0), %rdx movq (112)(%rsi), %r12 mov %r13, %rbx shr $(55), %rbx shl $(9), %r13 add %rdx, %rbx add %r13, %r11 adc %rbx, %r12 mov $(0), %rdx adc $(0), %rdx movq (120)(%rsi), %r13 mov %r14, %rbx shr $(55), %rbx shl $(9), %r14 add %rdx, %rbx add %r14, %r12 adc %rbx, %r13 mov $(0), %rdx adc $(0), %rdx movq (128)(%rsi), %r14 mov %r15, %rbx shr $(55), %rbx shl $(9), %r15 add %rdx, %rbx add %r15, %r13 adc %rbx, %r14 mov $(0), %rdx adc $(0), %rdx movq (136)(%rsi), %r15 mov %rax, %rbx shr $(55), %rbx shl $(9), %rax add %rdx, %rbx add %rax, %r14 adc %rbx, %r15 mov $(0), %rdx adc $(0), %rdx movq %rcx, (%rdi) movq %r8, (8)(%rdi) movq %r9, (16)(%rdi) movq %r10, (24)(%rdi) movq %r11, (32)(%rdi) movq %r12, (40)(%rdi) movq %r13, (48)(%rdi) movq %r14, (56)(%rdi) movq %r15, (64)(%rdi) subq Lpoly+0(%rip), %rcx sbbq Lpoly+8(%rip), %r8 sbbq Lpoly+16(%rip), %r9 sbbq Lpoly+24(%rip), %r10 sbbq Lpoly+32(%rip), %r11 sbbq Lpoly+40(%rip), %r12 sbbq Lpoly+48(%rip), %r13 sbbq Lpoly+56(%rip), %r14 sbbq Lpoly+64(%rip), %r15 movq (%rdi), %rbx cmovb %rbx, %rcx movq (8)(%rdi), %rbx cmovb %rbx, %r8 movq (16)(%rdi), %rbx cmovb %rbx, %r9 movq (24)(%rdi), %rbx cmovb %rbx, %r10 movq (32)(%rdi), %rbx cmovb %rbx, %r11 movq (40)(%rdi), %rbx cmovb %rbx, %r12 movq (48)(%rdi), %rbx cmovb %rbx, %r13 movq (56)(%rdi), %rbx cmovb %rbx, %r14 movq (64)(%rdi), %rbx cmovb %rbx, %r15 movq %rcx, (%rdi) movq %r8, (8)(%rdi) movq %r9, (16)(%rdi) movq %r10, (24)(%rdi) movq %r11, (32)(%rdi) movq %r12, (40)(%rdi) movq %r13, (48)(%rdi) movq %r14, (56)(%rdi) movq %r15, (64)(%rdi) pop %r15 pop %r14 pop %r13 pop %r12 pop %rbx ret .Lfe7: .size p521r1_mred, .Lfe7-(p521r1_mred) .p2align 4, 0x90 .globl p521r1_select_pp_w5 .type p521r1_select_pp_w5, @function p521r1_select_pp_w5: push %r12 push %r13 sub $(40), %rsp movd %edx, %xmm15 pshufd $(0), %xmm15, %xmm15 movdqa %xmm15, (%rsp) movdqa LOne(%rip), %xmm14 movdqa %xmm14, (16)(%rsp) pxor %xmm0, %xmm0 pxor %xmm1, %xmm1 pxor %xmm2, %xmm2 pxor %xmm3, %xmm3 pxor %xmm4, %xmm4 pxor %xmm5, %xmm5 pxor %xmm6, %xmm6 pxor %xmm7, %xmm7 pxor %xmm8, %xmm8 pxor %xmm9, %xmm9 pxor %xmm10, %xmm10 pxor %xmm11, %xmm11 pxor %xmm12, %xmm12 pxor %xmm13, %xmm13 mov $(16), %rcx .Lselect_loopgas_8: movdqa (16)(%rsp), %xmm15 movdqa %xmm15, %xmm14 pcmpeqd (%rsp), %xmm15 paddd LOne(%rip), %xmm14 movdqa %xmm14, (16)(%rsp) movdqu (%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm0 movdqu (16)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm1 movdqu (32)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm2 movdqu (48)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm3 movdqu (64)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm4 movdqu (80)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm5 movdqu (96)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm6 movdqu (112)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm7 movdqu (128)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm8 movdqu (144)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm9 movdqu (160)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm10 movdqu (176)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm11 movdqu (192)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm12 movd (208)(%rsi), %xmm14 pand %xmm15, %xmm14 por %xmm14, %xmm13 add $(216), %rsi dec %rcx jnz .Lselect_loopgas_8 movdqu %xmm0, (%rdi) movdqu %xmm1, (16)(%rdi) movdqu %xmm2, (32)(%rdi) movdqu %xmm3, (48)(%rdi) movdqu %xmm4, (64)(%rdi) movdqu %xmm5, (80)(%rdi) movdqu %xmm6, (96)(%rdi) movdqu %xmm7, (112)(%rdi) movdqu %xmm8, (128)(%rdi) movdqu %xmm9, (144)(%rdi) movdqu %xmm10, (160)(%rdi) movdqu %xmm11, (176)(%rdi) movdqu %xmm12, (192)(%rdi) movq %xmm13, (208)(%rdi) add $(40), %rsp pop %r13 pop %r12 ret .Lfe8: .size p521r1_select_pp_w5, .Lfe8-(p521r1_select_pp_w5) .p2align 4, 0x90 .globl p521r1_select_ap_w5 .type p521r1_select_ap_w5, @function p521r1_select_ap_w5: push %r12 push %r13 movdqa LOne(%rip), %xmm10 movd %edx, %xmm9 pshufd $(0), %xmm9, %xmm9 pxor %xmm0, %xmm0 pxor %xmm1, %xmm1 pxor %xmm2, %xmm2 pxor %xmm3, %xmm3 pxor %xmm4, %xmm4 pxor %xmm5, %xmm5 pxor %xmm6, %xmm6 pxor %xmm7, %xmm7 pxor %xmm8, %xmm8 mov $(16), %rcx .Lselect_loopgas_9: movdqa %xmm10, %xmm11 pcmpeqd %xmm9, %xmm11 paddd LOne(%rip), %xmm10 movdqa (%rsi), %xmm12 pand %xmm11, %xmm12 por %xmm12, %xmm0 movdqa (16)(%rsi), %xmm12 pand %xmm11, %xmm12 por %xmm12, %xmm1 movdqa (32)(%rsi), %xmm12 pand %xmm11, %xmm12 por %xmm12, %xmm2 movdqa (48)(%rsi), %xmm12 pand %xmm11, %xmm12 por %xmm12, %xmm3 movdqa (64)(%rsi), %xmm12 pand %xmm11, %xmm12 por %xmm12, %xmm4 movdqa (80)(%rsi), %xmm12 pand %xmm11, %xmm12 por %xmm12, %xmm5 movdqa (96)(%rsi), %xmm12 pand %xmm11, %xmm12 por %xmm12, %xmm6 movdqa (112)(%rsi), %xmm12 pand %xmm11, %xmm12 por %xmm12, %xmm7 movdqa (128)(%rsi), %xmm12 pand %xmm11, %xmm12 por %xmm12, %xmm8 add $(144), %rsi dec %rcx jnz .Lselect_loopgas_9 movdqu %xmm0, (%rdi) movdqu %xmm1, (16)(%rdi) movdqu %xmm2, (32)(%rdi) movdqu %xmm3, (48)(%rdi) movdqu %xmm4, (64)(%rdi) movdqu %xmm5, (80)(%rdi) movdqu %xmm6, (96)(%rdi) movdqu %xmm7, (112)(%rdi) movdqu %xmm8, (128)(%rdi) pop %r13 pop %r12 ret .Lfe9: .size p521r1_select_ap_w5, .Lfe9-(p521r1_select_ap_w5)
; ; jiss2fst-64.asm - fast integer IDCT (64-bit SSE2) ; ; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB ; Copyright 2009 D. R. Commander ; ; Based on ; x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/projecpt/showfiles.php?group_id=6208 ; ; This file contains a fast, not so accurate integer implementation of ; the inverse DCT (Discrete Cosine Transform). The following code is ; based directly on the IJG's original jidctfst.c; see the jidctfst.c ; for more details. ; ; [TAB8] %include "jsimdext.inc" %include "jdct.inc" ; -------------------------------------------------------------------------- %define CONST_BITS 8 ; 14 is also OK. %define PASS1_BITS 2 %if IFAST_SCALE_BITS != PASS1_BITS %error "'IFAST_SCALE_BITS' must be equal to 'PASS1_BITS'." %endif %if CONST_BITS == 8 F_1_082 equ 277 ; FIX(1.082392200) F_1_414 equ 362 ; FIX(1.414213562) F_1_847 equ 473 ; FIX(1.847759065) F_2_613 equ 669 ; FIX(2.613125930) F_1_613 equ (F_2_613 - 256) ; FIX(2.613125930) - FIX(1) %else ; NASM cannot do compile-time arithmetic on floating-point constants. %define DESCALE(x,n) (((x)+(1<<((n)-1)))>>(n)) F_1_082 equ DESCALE(1162209775,30-CONST_BITS) ; FIX(1.082392200) F_1_414 equ DESCALE(1518500249,30-CONST_BITS) ; FIX(1.414213562) F_1_847 equ DESCALE(1984016188,30-CONST_BITS) ; FIX(1.847759065) F_2_613 equ DESCALE(2805822602,30-CONST_BITS) ; FIX(2.613125930) F_1_613 equ (F_2_613 - (1 << CONST_BITS)) ; FIX(2.613125930) - FIX(1) %endif ; -------------------------------------------------------------------------- SECTION SEG_CONST ; PRE_MULTIPLY_SCALE_BITS <= 2 (to avoid overflow) ; CONST_BITS + CONST_SHIFT + PRE_MULTIPLY_SCALE_BITS == 16 (for pmulhw) %define PRE_MULTIPLY_SCALE_BITS 2 %define CONST_SHIFT (16 - PRE_MULTIPLY_SCALE_BITS - CONST_BITS) alignz 16 global EXTN(jconst_idct_ifast_sse2) EXTN(jconst_idct_ifast_sse2): PW_F1414 times 8 dw F_1_414 << CONST_SHIFT PW_F1847 times 8 dw F_1_847 << CONST_SHIFT PW_MF1613 times 8 dw -F_1_613 << CONST_SHIFT PW_F1082 times 8 dw F_1_082 << CONST_SHIFT PB_CENTERJSAMP times 16 db CENTERJSAMPLE alignz 16 ; -------------------------------------------------------------------------- SECTION SEG_TEXT BITS 64 ; ; Perform dequantization and inverse DCT on one block of coefficients. ; ; GLOBAL(void) ; jsimd_idct_ifast_sse2 (void * dct_table, JCOEFPTR coef_block, ; JSAMPARRAY output_buf, JDIMENSION output_col) ; ; r10 = jpeg_component_info * compptr ; r11 = JCOEFPTR coef_block ; r12 = JSAMPARRAY output_buf ; r13 = JDIMENSION output_col %define original_rbp rbp+0 %define wk(i) rbp-(WK_NUM-(i))*SIZEOF_XMMWORD ; xmmword wk[WK_NUM] %define WK_NUM 2 align 16 global EXTN(jsimd_idct_ifast_sse2) EXTN(jsimd_idct_ifast_sse2): push rbp mov rax,rsp ; rax = original rbp sub rsp, byte 4 and rsp, byte (-SIZEOF_XMMWORD) ; align to 128 bits mov [rsp],rax mov rbp,rsp ; rbp = aligned rbp lea rsp, [wk(0)] collect_args ; ---- Pass 1: process columns from input. mov rdx, r10 ; quantptr mov rsi, r11 ; inptr %ifndef NO_ZERO_COLUMN_TEST_IFAST_SSE2 mov eax, DWORD [DWBLOCK(1,0,rsi,SIZEOF_JCOEF)] or eax, DWORD [DWBLOCK(2,0,rsi,SIZEOF_JCOEF)] jnz near .columnDCT movdqa xmm0, XMMWORD [XMMBLOCK(1,0,rsi,SIZEOF_JCOEF)] movdqa xmm1, XMMWORD [XMMBLOCK(2,0,rsi,SIZEOF_JCOEF)] por xmm0, XMMWORD [XMMBLOCK(3,0,rsi,SIZEOF_JCOEF)] por xmm1, XMMWORD [XMMBLOCK(4,0,rsi,SIZEOF_JCOEF)] por xmm0, XMMWORD [XMMBLOCK(5,0,rsi,SIZEOF_JCOEF)] por xmm1, XMMWORD [XMMBLOCK(6,0,rsi,SIZEOF_JCOEF)] por xmm0, XMMWORD [XMMBLOCK(7,0,rsi,SIZEOF_JCOEF)] por xmm1,xmm0 packsswb xmm1,xmm1 packsswb xmm1,xmm1 movd eax,xmm1 test rax,rax jnz short .columnDCT ; -- AC terms all zero movdqa xmm0, XMMWORD [XMMBLOCK(0,0,rsi,SIZEOF_JCOEF)] pmullw xmm0, XMMWORD [XMMBLOCK(0,0,rdx,SIZEOF_ISLOW_MULT_TYPE)] movdqa xmm7,xmm0 ; xmm0=in0=(00 01 02 03 04 05 06 07) punpcklwd xmm0,xmm0 ; xmm0=(00 00 01 01 02 02 03 03) punpckhwd xmm7,xmm7 ; xmm7=(04 04 05 05 06 06 07 07) pshufd xmm6,xmm0,0x00 ; xmm6=col0=(00 00 00 00 00 00 00 00) pshufd xmm2,xmm0,0x55 ; xmm2=col1=(01 01 01 01 01 01 01 01) pshufd xmm5,xmm0,0xAA ; xmm5=col2=(02 02 02 02 02 02 02 02) pshufd xmm0,xmm0,0xFF ; xmm0=col3=(03 03 03 03 03 03 03 03) pshufd xmm1,xmm7,0x00 ; xmm1=col4=(04 04 04 04 04 04 04 04) pshufd xmm4,xmm7,0x55 ; xmm4=col5=(05 05 05 05 05 05 05 05) pshufd xmm3,xmm7,0xAA ; xmm3=col6=(06 06 06 06 06 06 06 06) pshufd xmm7,xmm7,0xFF ; xmm7=col7=(07 07 07 07 07 07 07 07) movdqa XMMWORD [wk(0)], xmm2 ; wk(0)=col1 movdqa XMMWORD [wk(1)], xmm0 ; wk(1)=col3 jmp near .column_end %endif .columnDCT: ; -- Even part movdqa xmm0, XMMWORD [XMMBLOCK(0,0,rsi,SIZEOF_JCOEF)] movdqa xmm1, XMMWORD [XMMBLOCK(2,0,rsi,SIZEOF_JCOEF)] pmullw xmm0, XMMWORD [XMMBLOCK(0,0,rdx,SIZEOF_IFAST_MULT_TYPE)] pmullw xmm1, XMMWORD [XMMBLOCK(2,0,rdx,SIZEOF_IFAST_MULT_TYPE)] movdqa xmm2, XMMWORD [XMMBLOCK(4,0,rsi,SIZEOF_JCOEF)] movdqa xmm3, XMMWORD [XMMBLOCK(6,0,rsi,SIZEOF_JCOEF)] pmullw xmm2, XMMWORD [XMMBLOCK(4,0,rdx,SIZEOF_IFAST_MULT_TYPE)] pmullw xmm3, XMMWORD [XMMBLOCK(6,0,rdx,SIZEOF_IFAST_MULT_TYPE)] movdqa xmm4,xmm0 movdqa xmm5,xmm1 psubw xmm0,xmm2 ; xmm0=tmp11 psubw xmm1,xmm3 paddw xmm4,xmm2 ; xmm4=tmp10 paddw xmm5,xmm3 ; xmm5=tmp13 psllw xmm1,PRE_MULTIPLY_SCALE_BITS pmulhw xmm1,[rel PW_F1414] psubw xmm1,xmm5 ; xmm1=tmp12 movdqa xmm6,xmm4 movdqa xmm7,xmm0 psubw xmm4,xmm5 ; xmm4=tmp3 psubw xmm0,xmm1 ; xmm0=tmp2 paddw xmm6,xmm5 ; xmm6=tmp0 paddw xmm7,xmm1 ; xmm7=tmp1 movdqa XMMWORD [wk(1)], xmm4 ; wk(1)=tmp3 movdqa XMMWORD [wk(0)], xmm0 ; wk(0)=tmp2 ; -- Odd part movdqa xmm2, XMMWORD [XMMBLOCK(1,0,rsi,SIZEOF_JCOEF)] movdqa xmm3, XMMWORD [XMMBLOCK(3,0,rsi,SIZEOF_JCOEF)] pmullw xmm2, XMMWORD [XMMBLOCK(1,0,rdx,SIZEOF_IFAST_MULT_TYPE)] pmullw xmm3, XMMWORD [XMMBLOCK(3,0,rdx,SIZEOF_IFAST_MULT_TYPE)] movdqa xmm5, XMMWORD [XMMBLOCK(5,0,rsi,SIZEOF_JCOEF)] movdqa xmm1, XMMWORD [XMMBLOCK(7,0,rsi,SIZEOF_JCOEF)] pmullw xmm5, XMMWORD [XMMBLOCK(5,0,rdx,SIZEOF_IFAST_MULT_TYPE)] pmullw xmm1, XMMWORD [XMMBLOCK(7,0,rdx,SIZEOF_IFAST_MULT_TYPE)] movdqa xmm4,xmm2 movdqa xmm0,xmm5 psubw xmm2,xmm1 ; xmm2=z12 psubw xmm5,xmm3 ; xmm5=z10 paddw xmm4,xmm1 ; xmm4=z11 paddw xmm0,xmm3 ; xmm0=z13 movdqa xmm1,xmm5 ; xmm1=z10(unscaled) psllw xmm2,PRE_MULTIPLY_SCALE_BITS psllw xmm5,PRE_MULTIPLY_SCALE_BITS movdqa xmm3,xmm4 psubw xmm4,xmm0 paddw xmm3,xmm0 ; xmm3=tmp7 psllw xmm4,PRE_MULTIPLY_SCALE_BITS pmulhw xmm4,[rel PW_F1414] ; xmm4=tmp11 ; To avoid overflow... ; ; (Original) ; tmp12 = -2.613125930 * z10 + z5; ; ; (This implementation) ; tmp12 = (-1.613125930 - 1) * z10 + z5; ; = -1.613125930 * z10 - z10 + z5; movdqa xmm0,xmm5 paddw xmm5,xmm2 pmulhw xmm5,[rel PW_F1847] ; xmm5=z5 pmulhw xmm0,[rel PW_MF1613] pmulhw xmm2,[rel PW_F1082] psubw xmm0,xmm1 psubw xmm2,xmm5 ; xmm2=tmp10 paddw xmm0,xmm5 ; xmm0=tmp12 ; -- Final output stage psubw xmm0,xmm3 ; xmm0=tmp6 movdqa xmm1,xmm6 movdqa xmm5,xmm7 paddw xmm6,xmm3 ; xmm6=data0=(00 01 02 03 04 05 06 07) paddw xmm7,xmm0 ; xmm7=data1=(10 11 12 13 14 15 16 17) psubw xmm1,xmm3 ; xmm1=data7=(70 71 72 73 74 75 76 77) psubw xmm5,xmm0 ; xmm5=data6=(60 61 62 63 64 65 66 67) psubw xmm4,xmm0 ; xmm4=tmp5 movdqa xmm3,xmm6 ; transpose coefficients(phase 1) punpcklwd xmm6,xmm7 ; xmm6=(00 10 01 11 02 12 03 13) punpckhwd xmm3,xmm7 ; xmm3=(04 14 05 15 06 16 07 17) movdqa xmm0,xmm5 ; transpose coefficients(phase 1) punpcklwd xmm5,xmm1 ; xmm5=(60 70 61 71 62 72 63 73) punpckhwd xmm0,xmm1 ; xmm0=(64 74 65 75 66 76 67 77) movdqa xmm7, XMMWORD [wk(0)] ; xmm7=tmp2 movdqa xmm1, XMMWORD [wk(1)] ; xmm1=tmp3 movdqa XMMWORD [wk(0)], xmm5 ; wk(0)=(60 70 61 71 62 72 63 73) movdqa XMMWORD [wk(1)], xmm0 ; wk(1)=(64 74 65 75 66 76 67 77) paddw xmm2,xmm4 ; xmm2=tmp4 movdqa xmm5,xmm7 movdqa xmm0,xmm1 paddw xmm7,xmm4 ; xmm7=data2=(20 21 22 23 24 25 26 27) paddw xmm1,xmm2 ; xmm1=data4=(40 41 42 43 44 45 46 47) psubw xmm5,xmm4 ; xmm5=data5=(50 51 52 53 54 55 56 57) psubw xmm0,xmm2 ; xmm0=data3=(30 31 32 33 34 35 36 37) movdqa xmm4,xmm7 ; transpose coefficients(phase 1) punpcklwd xmm7,xmm0 ; xmm7=(20 30 21 31 22 32 23 33) punpckhwd xmm4,xmm0 ; xmm4=(24 34 25 35 26 36 27 37) movdqa xmm2,xmm1 ; transpose coefficients(phase 1) punpcklwd xmm1,xmm5 ; xmm1=(40 50 41 51 42 52 43 53) punpckhwd xmm2,xmm5 ; xmm2=(44 54 45 55 46 56 47 57) movdqa xmm0,xmm3 ; transpose coefficients(phase 2) punpckldq xmm3,xmm4 ; xmm3=(04 14 24 34 05 15 25 35) punpckhdq xmm0,xmm4 ; xmm0=(06 16 26 36 07 17 27 37) movdqa xmm5,xmm6 ; transpose coefficients(phase 2) punpckldq xmm6,xmm7 ; xmm6=(00 10 20 30 01 11 21 31) punpckhdq xmm5,xmm7 ; xmm5=(02 12 22 32 03 13 23 33) movdqa xmm4, XMMWORD [wk(0)] ; xmm4=(60 70 61 71 62 72 63 73) movdqa xmm7, XMMWORD [wk(1)] ; xmm7=(64 74 65 75 66 76 67 77) movdqa XMMWORD [wk(0)], xmm3 ; wk(0)=(04 14 24 34 05 15 25 35) movdqa XMMWORD [wk(1)], xmm0 ; wk(1)=(06 16 26 36 07 17 27 37) movdqa xmm3,xmm1 ; transpose coefficients(phase 2) punpckldq xmm1,xmm4 ; xmm1=(40 50 60 70 41 51 61 71) punpckhdq xmm3,xmm4 ; xmm3=(42 52 62 72 43 53 63 73) movdqa xmm0,xmm2 ; transpose coefficients(phase 2) punpckldq xmm2,xmm7 ; xmm2=(44 54 64 74 45 55 65 75) punpckhdq xmm0,xmm7 ; xmm0=(46 56 66 76 47 57 67 77) movdqa xmm4,xmm6 ; transpose coefficients(phase 3) punpcklqdq xmm6,xmm1 ; xmm6=col0=(00 10 20 30 40 50 60 70) punpckhqdq xmm4,xmm1 ; xmm4=col1=(01 11 21 31 41 51 61 71) movdqa xmm7,xmm5 ; transpose coefficients(phase 3) punpcklqdq xmm5,xmm3 ; xmm5=col2=(02 12 22 32 42 52 62 72) punpckhqdq xmm7,xmm3 ; xmm7=col3=(03 13 23 33 43 53 63 73) movdqa xmm1, XMMWORD [wk(0)] ; xmm1=(04 14 24 34 05 15 25 35) movdqa xmm3, XMMWORD [wk(1)] ; xmm3=(06 16 26 36 07 17 27 37) movdqa XMMWORD [wk(0)], xmm4 ; wk(0)=col1 movdqa XMMWORD [wk(1)], xmm7 ; wk(1)=col3 movdqa xmm4,xmm1 ; transpose coefficients(phase 3) punpcklqdq xmm1,xmm2 ; xmm1=col4=(04 14 24 34 44 54 64 74) punpckhqdq xmm4,xmm2 ; xmm4=col5=(05 15 25 35 45 55 65 75) movdqa xmm7,xmm3 ; transpose coefficients(phase 3) punpcklqdq xmm3,xmm0 ; xmm3=col6=(06 16 26 36 46 56 66 76) punpckhqdq xmm7,xmm0 ; xmm7=col7=(07 17 27 37 47 57 67 77) .column_end: ; -- Prefetch the next coefficient block prefetchnta [rsi + DCTSIZE2*SIZEOF_JCOEF + 0*32] prefetchnta [rsi + DCTSIZE2*SIZEOF_JCOEF + 1*32] prefetchnta [rsi + DCTSIZE2*SIZEOF_JCOEF + 2*32] prefetchnta [rsi + DCTSIZE2*SIZEOF_JCOEF + 3*32] ; ---- Pass 2: process rows from work array, store into output array. mov rax, [original_rbp] mov rdi, r12 ; (JSAMPROW *) mov rax, r13 ; -- Even part ; xmm6=col0, xmm5=col2, xmm1=col4, xmm3=col6 movdqa xmm2,xmm6 movdqa xmm0,xmm5 psubw xmm6,xmm1 ; xmm6=tmp11 psubw xmm5,xmm3 paddw xmm2,xmm1 ; xmm2=tmp10 paddw xmm0,xmm3 ; xmm0=tmp13 psllw xmm5,PRE_MULTIPLY_SCALE_BITS pmulhw xmm5,[rel PW_F1414] psubw xmm5,xmm0 ; xmm5=tmp12 movdqa xmm1,xmm2 movdqa xmm3,xmm6 psubw xmm2,xmm0 ; xmm2=tmp3 psubw xmm6,xmm5 ; xmm6=tmp2 paddw xmm1,xmm0 ; xmm1=tmp0 paddw xmm3,xmm5 ; xmm3=tmp1 movdqa xmm0, XMMWORD [wk(0)] ; xmm0=col1 movdqa xmm5, XMMWORD [wk(1)] ; xmm5=col3 movdqa XMMWORD [wk(0)], xmm2 ; wk(0)=tmp3 movdqa XMMWORD [wk(1)], xmm6 ; wk(1)=tmp2 ; -- Odd part ; xmm0=col1, xmm5=col3, xmm4=col5, xmm7=col7 movdqa xmm2,xmm0 movdqa xmm6,xmm4 psubw xmm0,xmm7 ; xmm0=z12 psubw xmm4,xmm5 ; xmm4=z10 paddw xmm2,xmm7 ; xmm2=z11 paddw xmm6,xmm5 ; xmm6=z13 movdqa xmm7,xmm4 ; xmm7=z10(unscaled) psllw xmm0,PRE_MULTIPLY_SCALE_BITS psllw xmm4,PRE_MULTIPLY_SCALE_BITS movdqa xmm5,xmm2 psubw xmm2,xmm6 paddw xmm5,xmm6 ; xmm5=tmp7 psllw xmm2,PRE_MULTIPLY_SCALE_BITS pmulhw xmm2,[rel PW_F1414] ; xmm2=tmp11 ; To avoid overflow... ; ; (Original) ; tmp12 = -2.613125930 * z10 + z5; ; ; (This implementation) ; tmp12 = (-1.613125930 - 1) * z10 + z5; ; = -1.613125930 * z10 - z10 + z5; movdqa xmm6,xmm4 paddw xmm4,xmm0 pmulhw xmm4,[rel PW_F1847] ; xmm4=z5 pmulhw xmm6,[rel PW_MF1613] pmulhw xmm0,[rel PW_F1082] psubw xmm6,xmm7 psubw xmm0,xmm4 ; xmm0=tmp10 paddw xmm6,xmm4 ; xmm6=tmp12 ; -- Final output stage psubw xmm6,xmm5 ; xmm6=tmp6 movdqa xmm7,xmm1 movdqa xmm4,xmm3 paddw xmm1,xmm5 ; xmm1=data0=(00 10 20 30 40 50 60 70) paddw xmm3,xmm6 ; xmm3=data1=(01 11 21 31 41 51 61 71) psraw xmm1,(PASS1_BITS+3) ; descale psraw xmm3,(PASS1_BITS+3) ; descale psubw xmm7,xmm5 ; xmm7=data7=(07 17 27 37 47 57 67 77) psubw xmm4,xmm6 ; xmm4=data6=(06 16 26 36 46 56 66 76) psraw xmm7,(PASS1_BITS+3) ; descale psraw xmm4,(PASS1_BITS+3) ; descale psubw xmm2,xmm6 ; xmm2=tmp5 packsswb xmm1,xmm4 ; xmm1=(00 10 20 30 40 50 60 70 06 16 26 36 46 56 66 76) packsswb xmm3,xmm7 ; xmm3=(01 11 21 31 41 51 61 71 07 17 27 37 47 57 67 77) movdqa xmm5, XMMWORD [wk(1)] ; xmm5=tmp2 movdqa xmm6, XMMWORD [wk(0)] ; xmm6=tmp3 paddw xmm0,xmm2 ; xmm0=tmp4 movdqa xmm4,xmm5 movdqa xmm7,xmm6 paddw xmm5,xmm2 ; xmm5=data2=(02 12 22 32 42 52 62 72) paddw xmm6,xmm0 ; xmm6=data4=(04 14 24 34 44 54 64 74) psraw xmm5,(PASS1_BITS+3) ; descale psraw xmm6,(PASS1_BITS+3) ; descale psubw xmm4,xmm2 ; xmm4=data5=(05 15 25 35 45 55 65 75) psubw xmm7,xmm0 ; xmm7=data3=(03 13 23 33 43 53 63 73) psraw xmm4,(PASS1_BITS+3) ; descale psraw xmm7,(PASS1_BITS+3) ; descale movdqa xmm2,[rel PB_CENTERJSAMP] ; xmm2=[rel PB_CENTERJSAMP] packsswb xmm5,xmm6 ; xmm5=(02 12 22 32 42 52 62 72 04 14 24 34 44 54 64 74) packsswb xmm7,xmm4 ; xmm7=(03 13 23 33 43 53 63 73 05 15 25 35 45 55 65 75) paddb xmm1,xmm2 paddb xmm3,xmm2 paddb xmm5,xmm2 paddb xmm7,xmm2 movdqa xmm0,xmm1 ; transpose coefficients(phase 1) punpcklbw xmm1,xmm3 ; xmm1=(00 01 10 11 20 21 30 31 40 41 50 51 60 61 70 71) punpckhbw xmm0,xmm3 ; xmm0=(06 07 16 17 26 27 36 37 46 47 56 57 66 67 76 77) movdqa xmm6,xmm5 ; transpose coefficients(phase 1) punpcklbw xmm5,xmm7 ; xmm5=(02 03 12 13 22 23 32 33 42 43 52 53 62 63 72 73) punpckhbw xmm6,xmm7 ; xmm6=(04 05 14 15 24 25 34 35 44 45 54 55 64 65 74 75) movdqa xmm4,xmm1 ; transpose coefficients(phase 2) punpcklwd xmm1,xmm5 ; xmm1=(00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33) punpckhwd xmm4,xmm5 ; xmm4=(40 41 42 43 50 51 52 53 60 61 62 63 70 71 72 73) movdqa xmm2,xmm6 ; transpose coefficients(phase 2) punpcklwd xmm6,xmm0 ; xmm6=(04 05 06 07 14 15 16 17 24 25 26 27 34 35 36 37) punpckhwd xmm2,xmm0 ; xmm2=(44 45 46 47 54 55 56 57 64 65 66 67 74 75 76 77) movdqa xmm3,xmm1 ; transpose coefficients(phase 3) punpckldq xmm1,xmm6 ; xmm1=(00 01 02 03 04 05 06 07 10 11 12 13 14 15 16 17) punpckhdq xmm3,xmm6 ; xmm3=(20 21 22 23 24 25 26 27 30 31 32 33 34 35 36 37) movdqa xmm7,xmm4 ; transpose coefficients(phase 3) punpckldq xmm4,xmm2 ; xmm4=(40 41 42 43 44 45 46 47 50 51 52 53 54 55 56 57) punpckhdq xmm7,xmm2 ; xmm7=(60 61 62 63 64 65 66 67 70 71 72 73 74 75 76 77) pshufd xmm5,xmm1,0x4E ; xmm5=(10 11 12 13 14 15 16 17 00 01 02 03 04 05 06 07) pshufd xmm0,xmm3,0x4E ; xmm0=(30 31 32 33 34 35 36 37 20 21 22 23 24 25 26 27) pshufd xmm6,xmm4,0x4E ; xmm6=(50 51 52 53 54 55 56 57 40 41 42 43 44 45 46 47) pshufd xmm2,xmm7,0x4E ; xmm2=(70 71 72 73 74 75 76 77 60 61 62 63 64 65 66 67) mov rdx, JSAMPROW [rdi+0*SIZEOF_JSAMPROW] mov rsi, JSAMPROW [rdi+2*SIZEOF_JSAMPROW] movq XMM_MMWORD [rdx+rax*SIZEOF_JSAMPLE], xmm1 movq XMM_MMWORD [rsi+rax*SIZEOF_JSAMPLE], xmm3 mov rdx, JSAMPROW [rdi+4*SIZEOF_JSAMPROW] mov rsi, JSAMPROW [rdi+6*SIZEOF_JSAMPROW] movq XMM_MMWORD [rdx+rax*SIZEOF_JSAMPLE], xmm4 movq XMM_MMWORD [rsi+rax*SIZEOF_JSAMPLE], xmm7 mov rdx, JSAMPROW [rdi+1*SIZEOF_JSAMPROW] mov rsi, JSAMPROW [rdi+3*SIZEOF_JSAMPROW] movq XMM_MMWORD [rdx+rax*SIZEOF_JSAMPLE], xmm5 movq XMM_MMWORD [rsi+rax*SIZEOF_JSAMPLE], xmm0 mov rdx, JSAMPROW [rdi+5*SIZEOF_JSAMPROW] mov rsi, JSAMPROW [rdi+7*SIZEOF_JSAMPROW] movq XMM_MMWORD [rdx+rax*SIZEOF_JSAMPLE], xmm6 movq XMM_MMWORD [rsi+rax*SIZEOF_JSAMPLE], xmm2 uncollect_args mov rsp,rbp ; rsp <- aligned rbp pop rsp ; rsp <- original rbp pop rbp ret ret ; For some reason, the OS X linker does not honor the request to align the ; segment unless we do this. align 16
; A178142: Sum over the divisors d = 2 and/or 3 of n. ; 0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3,2,0,5,0,2,3 add $0,7 lpb $0 mul $1,2 div $1,3 add $1,6 gcd $0,$1 sub $0,1 sub $1,3 add $1,$0 lpe sub $1,3
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r14 push %r8 push %rbx push %rcx push %rdi push %rsi lea addresses_WT_ht+0x200f, %r8 nop nop nop nop nop sub %r14, %r14 mov $0x6162636465666768, %r10 movq %r10, %xmm3 movups %xmm3, (%r8) nop nop xor %rbx, %rbx lea addresses_A_ht+0x15b7d, %rsi lea addresses_D_ht+0x1a10, %rdi clflush (%rsi) nop nop nop nop nop dec %r13 mov $126, %rcx rep movsl nop nop nop nop nop add $42890, %r13 lea addresses_A_ht+0x1250f, %r8 nop nop nop sub %r13, %r13 mov $0x6162636465666768, %rcx movq %rcx, %xmm2 movups %xmm2, (%r8) nop nop nop nop sub $36151, %r10 lea addresses_normal_ht+0x1ba0f, %r8 nop nop cmp $30290, %r10 mov (%r8), %r14 nop nop nop nop nop dec %rcx lea addresses_UC_ht+0x1bd4f, %r8 nop nop nop nop add %r14, %r14 vmovups (%r8), %ymm4 vextracti128 $0, %ymm4, %xmm4 vpextrq $1, %xmm4, %rcx nop dec %rbx lea addresses_WC_ht+0xd10f, %rbx nop and $16131, %rsi mov $0x6162636465666768, %rdi movq %rdi, %xmm7 movups %xmm7, (%rbx) nop nop xor $51003, %rcx lea addresses_WT_ht+0x14b8f, %rdi nop nop nop nop nop add $38609, %rsi mov $0x6162636465666768, %rbx movq %rbx, %xmm3 vmovups %ymm3, (%rdi) nop nop nop sub %rbx, %rbx pop %rsi pop %rdi pop %rcx pop %rbx pop %r8 pop %r14 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %rax push %rbx push %rsi // Faulty Load lea addresses_normal+0xad0f, %rsi nop nop nop sub %r13, %r13 vmovups (%rsi), %ymm6 vextracti128 $1, %ymm6, %xmm6 vpextrq $0, %xmm6, %rax lea oracles, %rsi and $0xff, %rax shlq $12, %rax mov (%rsi,%rax,1), %rax pop %rsi pop %rbx pop %rax pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': True, 'type': 'addresses_normal'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 7, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'src': {'congruent': 0, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 10, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 6, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 8, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 7, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
// created by Kona @VSCode #include <algorithm> #include <iostream> #include <map> #include <string> #include <queue> #include <vector> #include <string.h> #define LOCAL_TEST typedef long long ll; using std::cin; using std::cout; using std::endl; using std::map; using std::queue; using std::string; using std::vector; class Solution { public: int myAtoi(string &s) { long long res = 0; long long high = (1ll << 31); int sign = 1; int ind = 0; int len = s.size(); if (len == 0) return 0; while (ind < len and s[ind++] == ' ') continue; --ind; if (s[ind] == '-' or s[ind] == '+') { sign = s[ind] == '-' ? -1 : 1; ++ind; } while (ind < len and std::isdigit(s[ind])) { res = res * 10 + s[ind++] - '0'; if (res > high) { // cout << "res == " << res << endl; res = high; break; } } return sign == -1 ? sign * res : (res == high ? --res : res); } }; int main() { std::ios_base::sync_with_stdio(false); #ifdef LOCAL_TEST freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif /* code */ return 0; }
LOD 15 STR 1000 LOD 3 STR 1001 LOD 8 LOD 1001 JMP 19
/* * Copyright (c) 2017, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ L0: mov (1|M0) r22.5<1>:ud 0x400040:ud mov (1|M0) f0.0<1>:uw r24.0<0;1,0>:ub (W&~f0.0)jmpi L448 L48: cmp (1|M0) (eq)f1.0 null.0<1>:w r24.2<0;1,0>:ub 0x1:uw (~f1.0) mov (1|M0) r26.2<1>:f r9.1<0;1,0>:f (f1.0) mov (1|M0) r26.2<1>:f r9.6<0;1,0>:f mov (8|M0) r17.0<1>:ud r26.0<8;8,1>:ud add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x44EB100:ud mov (1|M0) r16.2<1>:ud 0xD000:ud send (1|M0) r50:uw r16:ub 0x2 a0.0 add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x48EB301:ud or (1|M0) r17.7<1>:ud r17.7<0;1,0>:ud 0x8000000:ud mov (1|M0) r16.2<1>:ud 0xA000:ud send (1|M0) r54:uw r16:ub 0x2 a0.0 mov (16|M0) r46.0<1>:uw r56.0<16;16,1>:uw mov (16|M0) r47.0<1>:uw r57.0<16;16,1>:uw mov (16|M0) r56.0<1>:uw r58.0<16;16,1>:uw mov (16|M0) r57.0<1>:uw r59.0<16;16,1>:uw mov (16|M0) r48.0<1>:uw r60.0<16;16,1>:uw mov (16|M0) r49.0<1>:uw r61.0<16;16,1>:uw add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x44EB102:ud mov (1|M0) r16.2<1>:ud 0xD000:ud send (1|M0) r58:uw r16:ub 0x2 a0.0 mov (1|M0) a0.8<1>:uw 0x5C0:uw mov (1|M0) a0.9<1>:uw 0x640:uw mov (1|M0) a0.10<1>:uw 0x6C0:uw mov (1|M0) a0.11<1>:uw 0x740:uw add (4|M0) a0.12<1>:uw a0.8<4;4,1>:uw 0x40:uw L448: nop
; tabsize = 8 ; Plazma by .nebula (June, 2001) ; This is my first 256b intro, so it is rather simple. .model tiny .code .386 org 100h start: mov al,13h int 10h ;================================================================================================ ; Set the palette (black->red->yellow->white->black) ;================================================================================================ mov dx,3C8h xor ax,ax out dx,al ; initialize inc dx mov cx,300h mov al,62 ; EAX=<Green=0,Blue=0,Red=0,temp=62> set_pal: cmp al,62 jb okidoki inc ah mov al,62 okidoki: ; \/---------------/\ ror eax,8 ; first run Green->Blue->Red->temp test cl,1 bt cx,1 ja skip ; jump if CF!=0 && ZF!=0 out dx,al jmp short continue_loop skip: test al,al jnz continue_loop test ah,ah jz continue_loop sub eax,01010100h continue_loop: loop set_pal test ah,ah jz leave_set_pal mov eax,3d3d3d00h mov cx,100h jmp short set_pal leave_set_pal: ;================================================================================================ ; Make a cosines lookup table using cos(x[k])=2*cos(span/steps)*cos(x[k-1])-cos(x[k-2]) ; where span is the span of cosines to calculate ; steps is the number of steps this span is broken into ;================================================================================================ mov di,offset cos_table[4] mov ebx,16777137 mov eax,ebx stosd mov cx,2046 build_table_loop: imul ebx shrd eax,edx,23 sub eax,dword ptr [di-8] stosd loop build_table_loop ;================================================================================================ push 0A000h pop es main_loop: ;================================================================================================ ; Drawing plazma ;================================================================================================ ; x and y coordinates are stored on stack ; ; The pixel color is determined by this formula: ; color(x,y)=32*{cos(c_a*x+c_b*p_time+c_c)+ ; cos(c_d*x+c_e*p_time+c_f)+ ; cos(c_g*y+c_h*p_time+c_i)+ ; cos(c_j*y+c_k*p_time+c_l)+4} xor di,di xor ax,ax draw_plasma_loop: push ax ; x coordinate push cx ; y coordinate xor ecx,ecx xor eax,eax mov si,offset c_a mov bp,sp calculate: ; bp+2=x, bp+4=y xor bx,bx lodsw ; AX=c_a imul word ptr [bp+2] ; AX=x*c_a add bx,ax ; BX=BX+AX lodsw ; AX=c_b imul word ptr p_time ; AX=t*c_b add bx,ax ; BX=BX+AX lodsw ; AX=c_c add bx,ax ; BX=BX+AX and bx,2047 ; BX=BX mod 1111111111b shl bx,2 ; BX=BX > 2 add ecx,dword ptr cos_table[bx] ; ECX=cos(BX) cmp si,offset c_d ; if (si==c_d) //first interation jz calculate ; calculate cos(c_d*x+c_e*p_time+c_f) cmp si,offset c_j ; if (si==c_j) //second interation jz calculate ; calculate cos(c_j*y+c_k*p_time+c_l) cmp bp,sp ; if (haven't switched to ; cos(c_g*y+c_h*p_time+c_i)+ ; cos(c_j*y+c_k*p_time+c_l) ; caclulation) jb leave_calculate dec bp ; then DO dec bp ; switch to y jmp short calculate leave_calculate: shr ecx,18 mov al,cl stosb ; put pixel pop cx pop ax inc ax cmp ax,320 jl continue_draw_plasma_loop xor ax,ax inc cx cmp cx,200 jg exit continue_draw_plasma_loop: jmp short draw_plasma_loop exit: ;================================================================================================ inc word ptr p_time mov dx,5000 ; delay xor cx,cx mov ah,86h int 15h mov ah,11h int 16h jz main_loop mov ax,0003h int 10h ret ; Constants ; for X c_a dw 2 ; scale c_b dw -17 ; spped c_c dw 0 ; phase c_d dw 7 ; scale c_e dw 13 ; speed c_f dw 0 ; phase ; for Y c_g dw 3 ; scale c_h dw -3 ; speed c_i dw 0 ; phase c_j dw 5 ; scale c_k dw 23 ; speed c_l dw 0 ; phase p_time dw 0 ; time ; Data: Cosines lookup table cos_table dd 01000000h end start
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_62a.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129.label.xml Template File: sources-sinks-62a.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: rand Set data to result of rand(), which may be zero * GoodSource: Larger than zero but less than 10 * Sinks: * GoodSink: Ensure the array index is valid * BadSink : Improperly check the array index by not checking the upper bound * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_62 { #ifndef OMITBAD /* bad function declaration */ void badSource(int &data); void bad() { int data; /* Initialize data */ data = -1; badSource(data); { int i; int * buffer = new int[10]; /* initialize buffer */ for (i = 0; i < 10; i++) { buffer[i] = 0; } /* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound * This code does check to see if the array index is negative */ if (data >= 0) { buffer[data] = 1; /* Print the array values */ for(i = 0; i < 10; i++) { printIntLine(buffer[i]); } } else { printLine("ERROR: Array index is negative."); } delete[] buffer; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSource(int &data); static void goodG2B() { int data; /* Initialize data */ data = -1; goodG2BSource(data); { int i; int * buffer = new int[10]; /* initialize buffer */ for (i = 0; i < 10; i++) { buffer[i] = 0; } /* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound * This code does check to see if the array index is negative */ if (data >= 0) { buffer[data] = 1; /* Print the array values */ for(i = 0; i < 10; i++) { printIntLine(buffer[i]); } } else { printLine("ERROR: Array index is negative."); } delete[] buffer; } } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSource(int &data); static void goodB2G() { int data; /* Initialize data */ data = -1; goodB2GSource(data); { int i; int * buffer = new int[10]; /* initialize buffer */ for (i = 0; i < 10; i++) { buffer[i] = 0; } /* FIX: Properly validate the array index and prevent a buffer overflow */ if (data >= 0 && data < (10)) { buffer[data] = 1; /* Print the array values */ for(i = 0; i < 10; i++) { printIntLine(buffer[i]); } } else { printLine("ERROR: Array index is out-of-bounds"); } delete[] buffer; } } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_62; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
SECTION code_fp_am9511 PUBLIC cam32_sccz80_tanh EXTERN _am9511_tanh defc cam32_sccz80_tanh = _am9511_tanh
GiveDratini: ; if wScriptVar is 0 or 1, change the moveset of the last Dratini in the party. ; 0: give it a special moveset with Extremespeed. ; 1: give it the normal moveset of a level 15 Dratini. ld a, [wScriptVar] cp $2 ret nc ld bc, wPartyCount ld a, [bc] ld hl, MON_SPECIES call .GetNthPartyMon ld a, [bc] ld c, a push hl ld hl, DRATINI call GetPokemonIDFromIndex pop hl ld b, a ld de, PARTYMON_STRUCT_LENGTH .CheckForDratini: ; start at the end of the party and search backwards for a Dratini ld a, [hl] cp b jr z, .GiveMoveset ld a, l sub e ld l, a ld a, h sbc d ld h, a dec c jr nz, .CheckForDratini ret .GiveMoveset: push hl ld a, [wScriptVar] ld hl, .Movesets ld bc, .Moveset1 - .Moveset0 call AddNTimes ; get address of mon's first move pop de inc de inc de .GiveMoves: ld a, [hl] and a ; is the move 00? ret z ; if so, we're done here push hl push de ld [de], a ; give the Pokémon the new move ; get the PP of the new move dec a ld hl, Moves + MOVE_PP ld bc, MOVE_LENGTH call AddNTimes ld a, BANK(Moves) call GetFarByte ; get the address of the move's PP and update the PP ld hl, MON_PP - MON_MOVES add hl, de ld [hl], a pop de pop hl inc de inc hl jr .GiveMoves .Movesets: .Moveset0: ; Dratini does not normally learn Extremespeed. This is a special gift. db WRAP db THUNDER_WAVE db TWISTER db EXTREMESPEED db 0 .Moveset1: ; This is the normal moveset of a level 15 Dratini db WRAP db LEER db THUNDER_WAVE db TWISTER db 0 .GetNthPartyMon: ; inputs: ; hl must be set to 0 before calling this function. ; a must be set to the number of Pokémon in the party. ; outputs: ; returns the address of the last Pokémon in the party in hl. ; sets carry if a is 0. ld de, wPartyMon1 add hl, de and a jr z, .EmptyParty dec a ret z ld de, PARTYMON_STRUCT_LENGTH .loop add hl, de dec a jr nz, .loop ret .EmptyParty: scf ret
#pragma once #include "indexer/feature_data.hpp" #include "coding/file_reader.hpp" #include "coding/file_writer.hpp" #include "coding/read_write_utils.hpp" #include "base/geo_object_id.hpp" #include "base/stl_helpers.hpp" #include "base/thread_pool_delayed.hpp" #include <functional> #include <list> #include <mutex> #include <string> #include <thread> #include <vector> namespace serial { class GeometryCodingParams; } // namespace serial namespace feature { class FeatureBuilder { public: using PointSeq = std::vector<m2::PointD>; using Geometry = std::list<PointSeq>; using Buffer = std::vector<char>; using Offsets = std::vector<uint32_t>; struct SupportingData { Offsets m_ptsOffset; Offsets m_trgOffset; uint8_t m_ptsMask = 0; uint8_t m_trgMask = 0; uint32_t m_ptsSimpMask = 0; PointSeq m_innerPts; PointSeq m_innerTrg; Buffer m_buffer; }; FeatureBuilder(); // Checks for equality. The error of coordinates is allowed. bool operator==(FeatureBuilder const & fb) const; // Checks for equality. The error of coordinates isn't allowed. Binary equality check of // coordinates is used. bool IsExactEq(FeatureBuilder const & fb) const; // To work with geometry. void AddPoint(m2::PointD const & p); void SetHoles(Geometry const & holes); void AddPolygon(std::vector<m2::PointD> & poly); void ResetGeometry(); m2::RectD const & GetLimitRect() const { return m_limitRect; } Geometry const & GetGeometry() const { return m_polygons; } PointSeq const & GetOuterGeometry() const { return m_polygons.front(); } GeomType GetGeomType() const { return m_params.GetGeomType(); } bool IsGeometryClosed() const; m2::PointD GetGeometryCenter() const; m2::PointD GetKeyPoint() const; size_t GetPointsCount() const; size_t GetPolygonsCount() const { return m_polygons.size(); } size_t GetTypesCount() const { return m_params.m_types.size(); } template <class ToDo> void ForEachGeometryPointEx(ToDo && toDo) const { if (IsPoint()) { toDo(m_center); } else { for (PointSeq const & points : m_polygons) { for (auto const & pt : points) { if (!toDo(pt)) return; } toDo.EndRegion(); } } } template <class ToDo> void ForEachGeometryPoint(ToDo && toDo) const { ToDoWrapper<ToDo> wrapper(std::forward<ToDo>(toDo)); ForEachGeometryPointEx(std::move(wrapper)); } template <class ToDo> bool ForAnyGeometryPointEx(ToDo && toDo) const { if (IsPoint()) return toDo(m_center); for (PointSeq const & points : m_polygons) { for (auto const & pt : points) { if (toDo(pt)) return true; } toDo.EndRegion(); } return false; } template <class ToDo> bool ForAnyGeometryPoint(ToDo && toDo) const { ToDoWrapper<ToDo> wrapper(std::forward<ToDo>(toDo)); return ForAnyGeometryPointEx(std::move(wrapper)); } // To work with geometry type. void SetCenter(m2::PointD const & p); void SetLinear(bool reverseGeometry = false); void SetArea() { m_params.SetGeomType(GeomType::Area); } bool IsPoint() const { return GetGeomType() == GeomType::Point; } bool IsLine() const { return GetGeomType() == GeomType::Line; } bool IsArea() const { return GetGeomType() == GeomType::Area; } // To work with types. void SetType(uint32_t type) { m_params.SetType(type); } void AddType(uint32_t type) { m_params.AddType(type); } bool PopExactType(uint32_t type) { return m_params.PopExactType(type); } template <class Fn> bool RemoveTypesIf(Fn && fn) { base::EraseIf(m_params.m_types, std::forward<Fn>(fn)); return m_params.m_types.empty(); } bool HasType(uint32_t t) const { return m_params.IsTypeExist(t); } bool HasType(uint32_t t, uint8_t level) const { return m_params.IsTypeExist(t, level); } uint32_t FindType(uint32_t comp, uint8_t level) const { return m_params.FindType(comp, level); } FeatureParams::Types const & GetTypes() const { return m_params.m_types; } // To work with additional information. void SetRank(uint8_t rank); void AddHouseNumber(std::string const & houseNumber); void AddStreet(std::string const & streetName); void AddPostcode(std::string const & postcode); bool AddName(std::string const & lang, std::string const & name); void SetParams(FeatureParams const & params) { m_params.SetParams(params); } FeatureParams const & GetParams() const { return m_params; } FeatureParams & GetParams() { return m_params; } std::string GetName(int8_t lang = StringUtf8Multilang::kDefaultCode) const; StringUtf8Multilang const & GetMultilangName() const { return m_params.name; } uint8_t GetRank() const { return m_params.rank; } bool FormatFullAddress(std::string & res) const; AddressData const & GetAddressData() const { return m_params.GetAddressData(); } Metadata const & GetMetadata() const { return m_params.GetMetadata(); } Metadata & GetMetadata() { return m_params.GetMetadata(); } // To work with types and names based on drawing. // Check classificator types for their compatibility with feature geometry type. // Need to call when using any classificator types manipulating. // Return false If no any valid types. bool RemoveInvalidTypes(); // Clear name if it's not visible in scale range [minS, maxS]. void RemoveNameIfInvisible(int minS = 0, int maxS = 1000); void RemoveUselessNames(); int GetMinFeatureDrawScale() const; bool IsDrawableInRange(int lowScale, int highScale) const; // Serialization. bool PreSerialize(); void SerializeBase(Buffer & data, serial::GeometryCodingParams const & params, bool saveAddInfo) const; bool PreSerializeAndRemoveUselessNamesForIntermediate(); void SerializeForIntermediate(Buffer & data) const; void SerializeBorderForIntermediate(serial::GeometryCodingParams const & params, Buffer & data) const; void DeserializeFromIntermediate(Buffer & data); // These methods use geometry without loss of accuracy. void SerializeAccuratelyForIntermediate(Buffer & data) const; void DeserializeAccuratelyFromIntermediate(Buffer & data); bool PreSerializeAndRemoveUselessNamesForMwm(SupportingData const & data); void SerializeLocalityObject(serial::GeometryCodingParams const & params, SupportingData & data) const; void SerializeForMwm(SupportingData & data, serial::GeometryCodingParams const & params) const; // Get common parameters of feature. TypesHolder GetTypesHolder() const; // To work with osm ids. void AddOsmId(base::GeoObjectId id); void SetOsmId(base::GeoObjectId id); base::GeoObjectId GetFirstOsmId() const; base::GeoObjectId GetLastOsmId() const; // Returns an id of the most general element: node's one if there is no area or relation, // area's one if there is no relation, and relation id otherwise. base::GeoObjectId GetMostGenericOsmId() const; bool HasOsmId(base::GeoObjectId const & id) const; bool HasOsmIds() const { return !m_osmIds.empty(); } std::vector<base::GeoObjectId> const & GetOsmIds() const { return m_osmIds; } // To work with coasts. void SetCoastCell(int64_t iCell) { m_coastCell = iCell; } bool IsCoastCell() const { return (m_coastCell != -1); } protected: template <class ToDo> class ToDoWrapper { public: ToDoWrapper(ToDo && toDo) : m_toDo(std::forward<ToDo>(toDo)) {} bool operator()(m2::PointD const & p) { return m_toDo(p); } void EndRegion() {} private: ToDo && m_toDo; }; // Can be one of the following: // - point in point-feature // - origin point of text [future] in line-feature // - origin point of text or symbol in area-feature m2::PointD m_center; // Check HEADER_HAS_POINT // List of geometry polygons. Geometry m_polygons; // Check HEADER_IS_AREA m2::RectD m_limitRect; std::vector<base::GeoObjectId> m_osmIds; FeatureParams m_params; /// Not used in GEOM_POINTs int64_t m_coastCell; }; void Check(FeatureBuilder const fb); std::string DebugPrint(FeatureBuilder const & fb); // SerializationPolicy serialization and deserialization. namespace serialization_policy { enum class SerializationVersion : uint32_t { Undefined, MinSize, MaxAccuracy }; using TypeSerializationVersion = typename std::underlying_type<SerializationVersion>::type; struct MinSize { auto static const kSerializationVersion = static_cast<TypeSerializationVersion>(SerializationVersion::MinSize); static void Serialize(FeatureBuilder const & fb, FeatureBuilder::Buffer & data) { fb.SerializeForIntermediate(data); } static void Deserialize(FeatureBuilder & fb, FeatureBuilder::Buffer & data) { fb.DeserializeFromIntermediate(data); } }; struct MaxAccuracy { auto static const kSerializationVersion = static_cast<TypeSerializationVersion>(SerializationVersion::MinSize); static void Serialize(FeatureBuilder const & fb, FeatureBuilder::Buffer & data) { fb.SerializeAccuratelyForIntermediate(data); } static void Deserialize(FeatureBuilder & fb, FeatureBuilder::Buffer & data) { fb.DeserializeAccuratelyFromIntermediate(data); } }; } // namespace serialization_policy // TODO(maksimandrianov): I would like to support the verification of serialization versions, // but this requires reworking of FeatureCollector class and its derived classes. It is in future plans //template <class SerializationPolicy, class Source> //void TryReadAndCheckVersion(Source & src) //{ // if (src.Size() - src.Pos() >= sizeof(serialization_policy::TypeSerializationVersion)) // { // auto const type = ReadVarUint<serialization_policy::TypeSerializationVersion>(src); // CHECK_EQUAL(type, SerializationPolicy::kSerializationVersion, ()); // } // else // { // LOG(LWARNING, ("Unable to read file version.")) // } //} // Read feature from feature source. template <class SerializationPolicy = serialization_policy::MinSize, class Source> void ReadFromSourceRawFormat(Source & src, FeatureBuilder & fb) { uint32_t const sz = ReadVarUint<uint32_t>(src); typename FeatureBuilder::Buffer buffer(sz); src.Read(&buffer[0], sz); SerializationPolicy::Deserialize(fb, buffer); } // Process features in .dat file. template <class SerializationPolicy = serialization_policy::MinSize, class ToDo> void ForEachFromDatRawFormat(std::string const & filename, ToDo && toDo) { FileReader reader(filename); ReaderSource<FileReader> src(reader); // TryReadAndCheckVersion<SerializationPolicy>(src); auto const fileSize = reader.Size(); auto currPos = src.Pos(); // read features one by one while (currPos < fileSize) { FeatureBuilder fb; ReadFromSourceRawFormat<SerializationPolicy>(src, fb); toDo(fb, currPos); currPos = src.Pos(); } } /// Parallel process features in .dat file. template <class SerializationPolicy = serialization_policy::MinSize, class ToDo> void ForEachParallelFromDatRawFormat(size_t threadsCount, std::string const & filename, ToDo && toDo) { CHECK_GREATER_OR_EQUAL(threadsCount, 1, ()); if (threadsCount == 1) return ForEachFromDatRawFormat(filename, std::forward<ToDo>(toDo)); FileReader reader(filename); ReaderSource<FileReader> src(reader); // TryReadAndCheckVersion<SerializationPolicy>(src); auto const fileSize = reader.Size(); auto currPos = src.Pos(); std::mutex readMutex; auto concurrentProcessor = [&] { for (;;) { FeatureBuilder fb; uint64_t featurePos; { std::lock_guard<std::mutex> lock(readMutex); if (fileSize <= currPos) break; ReadFromSourceRawFormat<SerializationPolicy>(src, fb); featurePos = currPos; currPos = src.Pos(); } toDo(fb, featurePos); } }; std::vector<std::thread> workers; for (size_t i = 0; i < threadsCount; ++i) workers.emplace_back(concurrentProcessor); for (auto & thread : workers) thread.join(); } template <class SerializationPolicy = serialization_policy::MinSize> std::vector<FeatureBuilder> ReadAllDatRawFormat(std::string const & fileName) { std::vector<FeatureBuilder> fbs; ForEachFromDatRawFormat<SerializationPolicy>(fileName, [&](auto && fb, auto const &) { fbs.emplace_back(std::move(fb)); }); return fbs; } template <class SerializationPolicy = serialization_policy::MinSize, class Writer = FileWriter> class FeatureBuilderWriter { public: explicit FeatureBuilderWriter(std::string const & filename, FileWriter::Op op = FileWriter::Op::OP_WRITE_TRUNCATE) : m_writer(filename, op) { // TODO(maksimandrianov): I would like to support the verification of serialization versions, // but this requires reworking of FeatureCollector class and its derived classes. It is in future plans // WriteVarUint(m_writer, static_cast<serialization_policy::TypeSerializationVersion>(SerializationPolicy::kSerializationVersion)); } void Write(FeatureBuilder const & fb) { FeatureBuilder::Buffer buffer; SerializationPolicy::Serialize(fb, buffer); WriteVarUint(m_writer, static_cast<uint32_t>(buffer.size())); m_writer.Write(buffer.data(), buffer.size() * sizeof(FeatureBuilder::Buffer::value_type)); } private: Writer m_writer; }; } // namespace feature
; A005251: a(0) = 0, a(1) = a(2) = a(3) = 1; thereafter, a(n) = a(n-1) + a(n-2) + a(n-4). ; 0,1,1,1,2,4,7,12,21,37,65,114,200,351,616,1081,1897,3329,5842,10252,17991,31572,55405,97229,170625,299426,525456,922111,1618192,2839729,4983377,8745217,15346786,26931732,47261895,82938844,145547525,255418101,448227521,786584466,1380359512,2422362079,4250949112,7459895657,13091204281,22973462017,40315615410,70748973084,124155792775,217878227876,382349636061,670976837021,1177482265857,2066337330754,3626169232672,6363483400447,11167134898976,19596955630177,34390259761825,60350698792449,105908093453250,185855747875876,326154101090951,572360547759276,1004422742303477,1762639037938629,3093215881333057,5428215467030962,9525854090667496,16716708595637087,29335778567637640,51480702630305689,90342335288610825,158539746514553601,278217860370802066,488238309515661356,856798505175074247,1503576561205289204,2638592926751165517,4630407797472116077,8125799229398355841,14259783588075761122,25024175744225282480,43914367129773159679,77064342103396798000,135238492821245718801,237327010668867799281,416479870619886677761,730871223392151275042,1282589586833283671604,2250787820894302745927,3949857278347473095292,6931516322633927116261,12163963187814683883157,21346267331342913745345,37460087797505070723794,65737871451481911585400,115361922436801666192351,202446061219626491523096,355268071453933228439241 mov $3,6 lpb $0 sub $0,1 add $3,$1 mov $1,$5 trn $1,6 add $1,1 add $4,1 sub $5,$4 trn $5,1 add $5,$2 mov $2,$3 mov $4,4 lpe mov $0,$1
; A261585: Number of sexagesimal digits of Fibonacci numbers in base-60 representation. ; 1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,30 sub $0,2 mul $0,2 div $0,17 mov $1,$0 add $1,1
;RECEIVING AND SENDING RS232 DATA @57600 BITS/S ON A STANDARD MSX 3.58MHz CPU Z80 FNAME "RS232.BIN" VOICEAQ: EQU $F975 ;BUFFER TO OCCUPY IN SYSTEM AREA: DO NOT USE PLAY... ;MSX .BIN HEADER DB $FE DW START, END, START ORG VOICEAQ START: ;TRANSFER 'BC' BYTES FROM JOY2, 'UP', PIN1 TO (HL) ;MSX, Z80 3.58MHz 57600bps ;SETS CARRY BIT ON ERROR. A HOLDS ERROR CODE: ;A=1 RS232 LINE NOT HIGH,A=2 STARTBIT TIMEOUT RECBYTES: DI ;NO INTERRUPTS, TIME CRITICAL ROUTINE LD A,$0F ;PSG REGISTER 15, SELECT JOYSTICK PORT 2 OUT ($A0),A IN A,($A2) SET 6,A ;SELECT JOY2 OUT ($A1),A LD A,C ; FAST LOOP WITH BC (GRAUW, FAST LOOPS) DEC BC ; COMPENSATION FOR THE CASE C=0 INC B LD C,B ; SWAP B AND C FOR LOOP STRUCTURE LD B,A LD A,$0E ;SET PSG #14 OUT ($A0),A LD E,$01 ;FOR FASTER 'AND' OPERATION 'AND r'(5) VS. 'AND n'(8) IN A,($A2) AND E JR NZ,.FIRSTSTARTBIT ;RS232 LINE SHOULD BE HIGH, OTHERWISE STOP LD A,$01 ;ERROR, RS232 LINE NOT READY SCF EI RET ;THE NEXT PART IS TIME CRITICAL. EVERY CYCLE COUNTS .FIRSTSTARTBIT: ;WAIT FOR FIRST STARTBIT IN A,($A2) AND E JP NZ,.FIRSTSTARTBIT JP .READFIRSTBIT ;START READING BIT0, COMPENSATED FOR 12 CYCLES, 1 JP .STARTBIT: IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITS IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITS IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITS IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITS LD A,$02 ;ERROR, STARTBIT TIMEOUT SCF EI RET .READBITSNEXTBLOCK: INC HL DEC C JR NZ,.INITBITLOOP ;NEXT BLOCK UNLESS WE ARE DONE (C=0) JR .EXIT .READBITSNEXTBYTE: INC HL NOP ;DUMMY JR .INITBITLOOP .READBITS: IN A,($A2) ;DUMMY .READFIRSTBIT: ;ALT TIMING TO COMPENSATE FOR 1 JP ADD A,$00 ;DUMMY NOP ;DUMMY .INITBITLOOP: LD D,B LD B,$08 .BITLOOP: INC HL ;DUMMY DEC HL ;DUMMY IN A,($A2) RRCA ;SHIFT DATA BIT (0) -> CARRY RR (HL) ;SHIFT CARRY -> [HL] DJNZ .BITLOOP LD B,D DJNZ .STARTBITNEXTBYTE ;NEXT BYTE, SKIP STOPBIT AND WAIT FOR STARTBIT NOP ;DUMMY .STARTBITNEXTBLOCK: IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITSNEXTBLOCK IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITSNEXTBLOCK IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITSNEXTBLOCK IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITSNEXTBLOCK DEC C ;POSTPONED CHECK JR Z,.EXIT ;IF C=0, WE ARE DONE SO EXIT OTHERWISE ERROR LD A,$02; ERROR STARTBIT TIMEOUT SCF EI RET .STARTBITNEXTBYTE: IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITSNEXTBYTE IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITSNEXTBYTE IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITSNEXTBYTE IN A,($A2) ;WAIT FOR THE HIGH->LOW TRANSITION (STARTBIT) AND E JP Z,.READBITSNEXTBYTE LD A,$02 SCF EI RET .EXIT: OR A ;RESET CARRY EI RET ;SEND 'BC' BYTES FROM [HL] TO PIN6, JOY2 ;MSX, Z80 3.58MHz 57600bps SENDBYTES: DI ;NO INTERRUPTS LD A,$0F ;SELECT PSG REG #15 OUT ($A0),A IN A,($A2) ;SAVE VALUE PUSH AF SET 6,A ;JOY2 RES 2,A ;TRIG1 LOW LD E,A ;0V VALUE (0) IN E SET 2,A ;TRIG1 HIGH LD D,A ;5V VALUE (1) IN D .BYTELOOP: PUSH BC LD A,E .STARTBIT: OUT ($A1),A LD C,(HL) LD B,$08 .BITLOOP: RRC C ;ASSUME BIT=1 LD A,D JR C,.SETBIT ;NO, BIT=0 LD A,E .SETBIT: ADD A,$00 ;DUMMY OUT ($A1),A DJNZ .BITLOOP LD A,E POP BC DEC BC NOP ;DUMMY ADD A,$00 ;DUMMY .STOPBIT: LD A,D OUT ($A1),A INC HL LD A,B OR C NOP ;DUMMY JP NZ,.BYTELOOP .EXIT: NOP ;DUMMY POP AF OUT ($A1),A EI RET END:
; A304615: a(n) = 507*2^n - 273. ; 234,741,1755,3783,7839,15951,32175,64623,129519,259311,518895,1038063,2076399,4153071,8306415,16613103,33226479,66453231,132906735,265813743,531627759,1063255791,2126511855,4253023983,8506048239,17012096751,34024193775,68048387823,136096775919,272193552111,544387104495,1088774209263,2177548418799,4355096837871,8710193676015,17420387352303,34840774704879,69681549410031,139363098820335,278726197640943,557452395282159,1114904790564591,2229809581129455,4459619162259183,8919238324518639 mov $1,2 pow $1,$0 sub $1,1 mul $1,507 add $1,234 mov $0,$1
FuchsiaGymScript: call FuchsiaGymScript_75453 call EnableAutoTextBoxDrawing ld hl, FuchsiaGymTrainerHeaders ld de, FuchsiaGymScriptPointers ld a, [wFuchsiaGymCurScript] call ExecuteCurMapScriptInTable ld [wFuchsiaGymCurScript], a ret FuchsiaGymScript_75453: ld hl, wCurrentMapScriptFlags bit 6, [hl] res 6, [hl] ret z ld hl, Gym5CityName ld de, Gym5LeaderName call LoadGymLeaderAndCityName ret Gym5CityName: db "FUCHSIA CITY@" Gym5LeaderName: db "KOGA@" FuchsiaGymScript_75477: xor a ld [wJoyIgnore], a ld [wFuchsiaGymCurScript], a ld [wCurMapScript], a ret FuchsiaGymScriptPointers: dw CheckFightingMapTrainers dw DisplayEnemyTrainerTextAndStartBattle dw EndTrainerBattle dw FuchsiaGymScript3 FuchsiaGymScript3: ld a, [wIsInBattle] cp $ff jp z, FuchsiaGymScript_75477 ld a, $f0 ld [wJoyIgnore], a FuchsiaGymScript3_75497: ld a, $9 ld [hSpriteIndexOrTextID], a call DisplayTextID SetEvent EVENT_BEAT_KOGA lb bc, TM_06, 1 call GiveItem jr nc, .BagFull ld a, $a ld [hSpriteIndexOrTextID], a call DisplayTextID SetEvent EVENT_GOT_TM06 jr .asm_754c0 .BagFull ld a, $b ld [hSpriteIndexOrTextID], a call DisplayTextID .asm_754c0 ld hl, wObtainedBadges set 4, [hl] ld hl, wBeatGymFlags set 4, [hl] ; deactivate gym trainers SetEventRange EVENT_BEAT_FUCHSIA_GYM_TRAINER_0, EVENT_BEAT_FUCHSIA_GYM_TRAINER_6 jp FuchsiaGymScript_75477 FuchsiaGymTextPointers: dw FuchsiaGymText1 dw FuchsiaGymText2 dw FuchsiaGymText3 dw FuchsiaGymText4 dw FuchsiaGymText5 dw FuchsiaGymText6 dw FuchsiaGymText7 dw FuchsiaGymText8 dw FuchsiaGymText9 dw FuchsiaGymText10 dw FuchsiaGymText11 FuchsiaGymTrainerHeaders: FuchsiaGymTrainerHeader0: dbEventFlagBit EVENT_BEAT_FUCHSIA_GYM_TRAINER_0 db ($2 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_FUCHSIA_GYM_TRAINER_0 dw FuchsiaGymBattleText1 ; TextBeforeBattle dw FuchsiaGymAfterBattleText1 ; TextAfterBattle dw FuchsiaGymEndBattleText1 ; TextEndBattle dw FuchsiaGymEndBattleText1 ; TextEndBattle FuchsiaGymTrainerHeader2: dbEventFlagBit EVENT_BEAT_FUCHSIA_GYM_TRAINER_2 db ($2 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_FUCHSIA_GYM_TRAINER_2 dw FuchsiaGymBattleText2 ; TextBeforeBattle dw FuchsiaGymAfterBattleText2 ; TextAfterBattle dw FuchsiaGymEndBattleText2 ; TextEndBattle dw FuchsiaGymEndBattleText2 ; TextEndBattle FuchsiaGymTrainerHeader3: dbEventFlagBit EVENT_BEAT_FUCHSIA_GYM_TRAINER_3 db ($4 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_FUCHSIA_GYM_TRAINER_3 dw FuchsiaGymBattleText3 ; TextBeforeBattle dw FuchsiaGymAfterBattleText3 ; TextAfterBattle dw FuchsiaGymEndBattleText3 ; TextEndBattle dw FuchsiaGymEndBattleText3 ; TextEndBattle FuchsiaGymTrainerHeader4: dbEventFlagBit EVENT_BEAT_FUCHSIA_GYM_TRAINER_4 db ($2 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_FUCHSIA_GYM_TRAINER_4 dw FuchsiaGymBattleText4 ; TextBeforeBattle dw FuchsiaGymAfterBattleText4 ; TextAfterBattle dw FuchsiaGymEndBattleText4 ; TextEndBattle dw FuchsiaGymEndBattleText4 ; TextEndBattle FuchsiaGymTrainerHeader5: dbEventFlagBit EVENT_BEAT_FUCHSIA_GYM_TRAINER_5 db ($2 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_FUCHSIA_GYM_TRAINER_5 dw FuchsiaGymBattleText5 ; TextBeforeBattle dw FuchsiaGymAfterBattleText5 ; TextAfterBattle dw FuchsiaGymEndBattleText5 ; TextEndBattle dw FuchsiaGymEndBattleText5 ; TextEndBattle FuchsiaGymTrainerHeader6: dbEventFlagBit EVENT_BEAT_FUCHSIA_GYM_TRAINER_6 db ($2 << 4) ; trainer's view range dwEventFlagAddress EVENT_BEAT_FUCHSIA_GYM_TRAINER_6 dw FuchsiaGymBattleText6 ; TextBeforeBattle dw FuchsiaGymAfterBattleText6 ; TextAfterBattle dw FuchsiaGymEndBattleText6 ; TextEndBattle dw FuchsiaGymEndBattleText6 ; TextEndBattle db $ff FuchsiaGymText1: TX_ASM CheckEvent EVENT_BEAT_KOGA jr z, .asm_181b6 CheckEventReuseA EVENT_GOT_TM06 jr nz, .asm_adc3b call z, FuchsiaGymScript3_75497 call DisableWaitingAfterTextDisplay jr .asm_e84c6 .asm_adc3b ld hl, KogaExplainToxicText call PrintText jr .asm_e84c6 .asm_181b6 ld hl, KogaBeforeBattleText call PrintText ld hl, wd72d set 6, [hl] set 7, [hl] ld hl, KogaAfterBattleText ld de, KogaAfterBattleText call SaveEndBattleTextPointers ld a, [H_SPRITEINDEX] ld [wSpriteIndex], a call EngageMapTrainer call InitBattleEnemyParameters ld a, $5 ld [wGymLeaderNo], a xor a ld [hJoyHeld], a ld a, $3 ld [wFuchsiaGymCurScript], a .asm_e84c6 jp TextScriptEnd KogaBeforeBattleText: TX_FAR _KogaBeforeBattleText db "@" KogaAfterBattleText: TX_FAR _KogaAfterBattleText db "@" KogaExplainToxicText: TX_FAR _KogaExplainToxicText db "@" FuchsiaGymText9: TX_FAR _FuchsiaGymText9 db "@" FuchsiaGymText10: TX_FAR _ReceivedTM06Text db $11 TM06ExplanationText: TX_FAR _TM06ExplanationText db "@" FuchsiaGymText11: TX_FAR _TM06NoRoomText db "@" FuchsiaGymText2: TX_ASM ld hl, FuchsiaGymTrainerHeader0 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText1: TX_FAR _FuchsiaGymBattleText1 db "@" FuchsiaGymEndBattleText1: TX_FAR _FuchsiaGymEndBattleText1 db "@" FuchsiaGymAfterBattleText1: TX_FAR _FuchsiaGymAfterBattleText1 db "@" FuchsiaGymText3: TX_ASM ld hl, FuchsiaGymTrainerHeader2 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText2: TX_FAR _FuchsiaGymBattleText2 db "@" FuchsiaGymEndBattleText2: TX_FAR _FuchsiaGymEndBattleText2 db "@" FuchsiaGymAfterBattleText2: TX_FAR _FuchsiaGymAfterBattleText2 db "@" FuchsiaGymText4: TX_ASM ld hl, FuchsiaGymTrainerHeader3 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText3: TX_FAR _FuchsiaGymBattleText3 db "@" FuchsiaGymEndBattleText3: TX_FAR _FuchsiaGymEndBattleText3 db "@" FuchsiaGymAfterBattleText3: TX_FAR _FuchsiaGymAfterBattleText3 db "@" FuchsiaGymText5: TX_ASM ld hl, FuchsiaGymTrainerHeader4 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText4: TX_FAR _FuchsiaGymBattleText4 db "@" FuchsiaGymEndBattleText4: TX_FAR _FuchsiaGymEndBattleText4 db "@" FuchsiaGymAfterBattleText4: TX_FAR _FuchsiaGymAfterBattleText4 db "@" FuchsiaGymText6: TX_ASM ld hl, FuchsiaGymTrainerHeader5 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText5: TX_FAR _FuchsiaGymBattleText5 db "@" FuchsiaGymEndBattleText5: TX_FAR _FuchsiaGymEndBattleText5 db "@" FuchsiaGymAfterBattleText5: TX_FAR _FuchsiaGymAfterBattleText5 db "@" FuchsiaGymText7: TX_ASM ld hl, FuchsiaGymTrainerHeader6 call TalkToTrainer jp TextScriptEnd FuchsiaGymBattleText6: TX_FAR _FuchsiaGymBattleText6 db "@" FuchsiaGymEndBattleText6: TX_FAR _FuchsiaGymEndBattleText6 db "@" FuchsiaGymAfterBattleText6: TX_FAR _FuchsiaGymAfterBattleText6 db "@" FuchsiaGymText8: TX_ASM CheckEvent EVENT_BEAT_KOGA ld hl, FuchsiaGymText_7564e jr z, .asm_50671 ResetEvent EVENT_BEAT_KOGA ResetEventRange EVENT_BEAT_FUCHSIA_GYM_TRAINER_0, EVENT_BEAT_FUCHSIA_GYM_TRAINER_6 ld hl, FuchsiaGymText_75653 .asm_50671 call PrintText jp TextScriptEnd FuchsiaGymText_7564e: ;not beaten yet TX_FAR _FuchsiaGymText_7564e db "@" FuchsiaGymText_75653: TX_FAR _FuchsiaGymText_75653 db "@"
// Copyright (C) 2004 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #include <sstream> #include <string> #include <cstdlib> #include <ctime> #include <dlib/sequence.h> #include "tester.h" namespace { using namespace test; using namespace std; using namespace dlib; logger dlog("test.sequence"); template < typename seq > void sequence_sort_test ( ) /*! requires - seq is an implementation of sequence/sequence_sort_aseqract.h is instantiated with int ensures - runs tests on seq for compliance with the specs !*/ { srand(static_cast<unsigned int>(time(0))); print_spinner(); { // this test is to make sure that jumping around via // operator[] doesn't corrupt the object seq a; for (int i = 0; i < 100; ++i) { int x = i; a.add(a.size(),x); } int x = 0; for (int i = 0; i < (int)a.size(); ++i) { DLIB_TEST_MSG(a[i] >= i,"1"); // cout << a[i] << endl; } for (unsigned long i = 0; i < a.size(); ++i) { for (unsigned long j = i+1; j < a.size(); ++j) { if ((a[j]+a[i])%3 ==0) { a.remove(j,x); --j; } } } //cout << endl; for (int i = 0; i < (int)a.size(); ++i) { // cout << a[i] << endl; DLIB_TEST_MSG(a[i] >= i,"2"); } } seq test, test2; DLIB_TEST(test.size() == 0); DLIB_TEST(test.at_start() == true); DLIB_TEST(test.current_element_valid() == false); enumerable<int>& e = test; DLIB_TEST(e.at_start() == true); DLIB_TEST(e.current_element_valid() == false); for (int g = 0; g < 5; ++g) { test.clear(); test2.clear(); DLIB_TEST(test.size() == 0); DLIB_TEST(test.at_start() == true); DLIB_TEST(test.current_element_valid() == false); DLIB_TEST(e.at_start() == true); DLIB_TEST(e.current_element_valid() == false); DLIB_TEST(e.move_next() == false); DLIB_TEST(e.current_element_valid() == false); DLIB_TEST(e.at_start() == false); DLIB_TEST(test.at_start() == false); swap(test,test2); DLIB_TEST(test.at_start() == true); test.clear(); test2.clear(); int a; for (int i = 0; i < 100; ++i) { a = i; test.add(i,a); } DLIB_TEST(test.size() == 100); for (int i = 0; i < static_cast<int>(test.size()); ++i) { DLIB_TEST(test[i] == i); } swap(test,test2); a = 0; DLIB_TEST(test2.at_start() == true); while(test2.move_next()) { DLIB_TEST(test2.at_start() == false); DLIB_TEST(test2.current_element_valid() == true); DLIB_TEST(test2.element() == a); ++a; } DLIB_TEST(test2.at_start() == false); DLIB_TEST(test2.current_element_valid() == false); test2.reset(); DLIB_TEST(test2.at_start() == true); DLIB_TEST(test2.current_element_valid() == false); a = 0; while(test2.move_next()) { DLIB_TEST(test2.at_start() == false); DLIB_TEST(test2.current_element_valid() == true); DLIB_TEST(test2.element() == a); ++a; } for (int i = 0; i < 1000; ++i) { a = ::rand(); test.add(0,a); } DLIB_TEST(test.size() == 1000); test.sort(); for (unsigned long i = 0; i < test.size()-1; ++i) { DLIB_TEST(test[i] <= test[i+1]); } a = 0; while(test.move_next()) { DLIB_TEST(a <= test.element()); a = test.element(); } test.clear(); test2.clear(); DLIB_TEST(test.size() == 0); DLIB_TEST(test2.size() == 0); for (int i = 0; i < 100; ++i) { a = i; test.add(i,a); } for (int i = 100; i < 200; ++i) { a = i; test.add(i,a); } test.cat(test2); DLIB_TEST(test.size() == 200); DLIB_TEST(test2.size() == 0); // serialize the state of test, then clear test, then // load the state back into test. ostringstream sout; serialize(test,sout); DLIB_TEST(test.at_start() == true); istringstream sin(sout.str()); test.clear(); deserialize(test,sin); for (int i = 0; i < 200; ++i) { DLIB_TEST(test[i] == i); } a = 0; while (test.move_next()) { DLIB_TEST(test.element() == a); DLIB_TEST(test[0]==0); ++a; } DLIB_TEST(a == 200); DLIB_TEST(test[9] == 9); test.remove(9,a); DLIB_TEST(a == 9); DLIB_TEST(test[9] == 10); DLIB_TEST(test.size() == 199); test.remove(0,a); DLIB_TEST(test[0] == 1); DLIB_TEST(test.size() == 198); DLIB_TEST(a == 0); DLIB_TEST(test[9] == 11); DLIB_TEST(test[20] == 22); } { test.clear(); for (int i = 0; i < 100; ++i) { int a = 3; test.add(0,a); } DLIB_TEST(test.size() == 100); remover<int>& go = test; for (int i = 0; i < 100; ++i) { int a = 9; go.remove_any(a); DLIB_TEST(a == 3); } DLIB_TEST(go.size() == 0); } } class sequence_tester : public tester { public: sequence_tester ( ) : tester ("test_sequence", "Runs tests on the sequence component.") {} void perform_test ( ) { dlog << LINFO << "testing sort_1a"; sequence_sort_test<sequence<int>::sort_1a> (); dlog << LINFO << "testing sort_1a_c"; sequence_sort_test<sequence<int>::sort_1a_c>(); dlog << LINFO << "testing sort_2a"; sequence_sort_test<sequence<int>::sort_2a> (); dlog << LINFO << "testing sort_2a_c"; sequence_sort_test<sequence<int>::sort_2a_c>(); } } a; }
; A100587: Number of nonempty subsets of divisors of n. ; 1,3,3,7,3,15,3,15,7,15,3,63,3,15,15,31,3,63,3,63,15,15,3,255,7,15,15,63,3,255,3,63,15,15,15,511,3,15,15,255,3,255,3,63,63,15,3,1023,7,63,15,63,3,255,15,255,15,15,3,4095,3,15,63,127,15,255,3,63,15,255,3,4095,3,15,63,63,15,255,3,1023,31,15,3,4095,15,15,15,255,3,4095,15,63,15,15,15,4095,3,63,63,511,3,255,3,255,255,15,3,4095,3,255,15,1023,3,255,15,63,63,15,15,65535,7,15,15,63,15,4095,3,255,15,255,3,4095,15,15,255,255,3,255,3,4095,15,15,15,32767,15,15,63,63,3,4095,3,255,63,255,15,4095,3,15,15,4095,15,1023,3,63,255,15,3,65535,7,255,63,63,3,255,63,1023,15,15,3,262143,3,255,15,255,15,255,15,63,255,255,3,16383,3,15,255,511,3,4095,3,4095,15,15,15,4095,15,15,63,1023,15,65535,3,63,15,15,15,65535,15,15,15,4095,15,255,3,4095,511,15,3,4095,3,255,255,255,3,4095,15,63,15,255,3,1048575,3,63,63,63,63,255,15,255,15,255 cal $0,5 ; d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n. mov $1,$0 mov $0,2 pow $0,$1 mov $1,$0 sub $1,2 div $1,2 mul $1,2 add $1,1
include w2.inc include noxport.inc include consts.inc include structs.inc createSeg _LAYOUT2,layout2,byte,public,CODE ; DEBUGGING DECLARATIONS ifdef DEBUG midLayout2n equ 18 ; module ID, for native asserts endif ; EXTERNAL FUNCTIONS externFP <CpPlc> externFP <FInCa> externFP <IInPlcRef> externFP <GetPlc> externFP <FAbsPap> externFP <LinkDocToWw> externFP <AbortLayout> externFP <N_FormatLineDxa> externFP <PutPlcLastProc> externFP <N_FInsertInPlc> externFP <N_GetCpFirstCpLimDisplayPara> externFP <N_CachePara> externFP <CacheSectProc> externFP <N_PdodMother> externFP <FQueryAbortCheckProc> externFP <FMsgPresent> externFP <PutCpPlc> externFP <NMultDiv> externFP <CpRefFromCpSub> externFP <SetAbsLr> externFP <ConstrainToAbs> externFP <RcToDrc> externFP <CpFromCpCl> externFP <HpInPl> externFP <PInPl> externFP <FInsertInPl> externFP <FChngSizePhqlcb> externFP <FreeHpl> externFP <HplInit2> externFP <IInPlcCheck> externFP <IInPlc> externFP <FGetValidPhe> externFP <DeleteFromPl> externFP <CpMacDoc> externFP <SetFlm> externFP <PutIMacPlc> externFP <AssignAbsXl> externFP <DocMother> externFP <N_LbcFormatPara> externFP <FResetWwLayout> externFP <DocMotherLayout> externFP <N_FetchCpPccpVisible> ifdef DEBUG externFP <AssertProcForNative> externFP <ScribbleProc> externFP <ShowLbsProc> externFP <S_FAbortLayout> externFP <S_FormatLineDxa> externFP <S_CachePara> externFP <S_GetCpFirstCpLimDisplayPara> externFP <PutPlcLastDebugProc> externFP <S_PushLbs> externFP <S_PopLbs> externFP <S_ClFormatLines> externFP <S_CopyLbs> externFP <S_FAssignLr> externFP <S_ReplaceInPllr> externFP <S_LbcFormatPara> externFP <S_CopyLrs> externFP <S_FInsertInPlc> externFP <S_FetchCpPccpVisible> endif ;DEBUG sBegin data ; EXTERNALS externW vfls externW vfli externW caParaL externW caPara externW vfti externW caSect externW vfInFormatPage externW vlm externW vpapFetch externW mpdochdod externD vcpFetch externW vsepFetch externW vhplcFrl externW vhpllbs externW vhpllrSpare externW vrghdt externW vflm externW vpisPrompt externW mpwwhwwd ifdef DEBUG externD vcpFirstLayout externD vcpLimLayout externW mpsbps externW vdbs externW vfDypsInScreenUnits externW vpri endif ;DEBUG sEnd data ; CODE SEGMENT _LAYOUT2 sBegin layout2 assumes cs,layout2 assumes ds,dgroup assumes ss,dgroup ;------------------------------------------------------------------------- ; ClFormatLines(plbs, cpLim, dylFill, dylMax, clLim, dxl, fRefLine, fStopAtPageBreak) ;------------------------------------------------------------------------- ;/* C l F o r m a t L i n e s */ ;NATIVE int ClFormatLines(plbs, cpLim, dylFill, dylMax, clLim, dxl, fRefLine, fStopAtPageBreak) ;struct LBS *plbs; ;CP cpLim; ;int dylFill; /* space to fill */ ;int dylMax; /* lines can go past dylFill but not dylMax */ ;int clLim; /* 0 means cache is made to refer to plbs->cp */ ;int dxl; /* width in which to format */ ;int fRefLine; /* true means that line containing cpLim is required */ ;int fStopAtPageBreak; /* care about page breaks? */ ;{ ;/* returns the cl of the line after the lines that fully fit into dylFIll ; with [cpFirst,cpLim) but not more than clLim. ; Updates at least the relevant elements in plcyl and ; updates clMac if end of para is reached in the process. ; Does not modify/advance plbs. ;*/ ; int ilnh, ilnh2, ilnhMac; ; struct PLC **hplclnh; ; int dyl, dylFirst; ; int dxa; ; int fBreakLast; ; int dylFixed; ; struct LNH lnh, lnhPrev; ; BOOL fNotDylFillMax = (dylFill != ylLarge); ; BOOL fNotDylMax = (dylMax != ylLarge); ; YLL dyllFill = fNotDylFillMax ? (YLL)dylFill : yllLarge; ; YLL dyllMax = fNotDylMax ? (YLL)dylMax : yllLarge; ; CP cp; ; %%Function:N_ClFormatLines %%Owner:BRADV cProc N_ClFormatLines,<PUBLIC,FAR>,<si,di> ParmW <plbs> ParmD <cpLim> ParmW <dylFill> ParmW <dylMax> ParmW <clLim> ParmW <dxl> ParmW <fRefLine> ParmW <fStopAtPageBreak> LocalW ilnh LocalW dylFixed LocalW fBreakLast LocalW dxa LocalW ilnhMac LocalW wMaxFlags LocalD dyllFill LocalD dyllMax LocalV lnh,cbLnhMin LocalV lnhPrev,cbLnhMin ifdef DEBUG LocalW cCallsIInPlcRef endif ;DEBUG cBegin xor cx,cx mov ax,[dylFill] lea bx,[dyllFill] CFL003: cwd xchg ch,cl cmp ax,ylLarge jne CFL007 inc cx mov dx,HI_yllLarge mov ax,LO_yllLarge CFL007: mov [bx],ax mov [bx+2],dx xchg ax,bx lea bx,[dyllMax] cmp ax,bx mov ax,[dylMax] jne CFL003 ;fDylFillMax in ch, fDylMax in cl mov [wMaxFlags],cx mov si,[plbs] ; StartProfile(); ; Win(Assert(vflm == flmRepaginate || vflm == flmPrint || ; vfDypsInScreenUnits || (vlm == lmPagevw && vpri.hdc == NULL))); ifdef DEBUG push ax push bx push cx push dx cmp [vflm],flmRepaginate je CFL008 cmp [vflm],flmPrint je CFL008 cmp [vfDypsInScreenUnits],fFalse jne CFL008 mov ax,[vlm] sub ax,lmPagevw errnz <NULL> or ax,[vpri.hdcPri] je CFL008 mov ax,midLayout2n mov bx,1060 cCall AssertProcForNative,<ax,bx> CFL008: pop dx pop cx pop bx pop ax endif ;DEBUG ; hplclnh = vfls.hplclnh; ; CacheParaL(plbs->doc, plbs->cp, plbs->fOutline); ;LN_CacheParaLbs takes plbs in si ;and performs CacheParaL(plbs->doc, plbs->cp, plbs->fOutline). ;ax, bx, cx, dx are altered. call LN_CacheParaLbs ; if (!FInCa(plbs->doc, plbs->cp, &vfls.ca) || vfls.dxl != dxl || ; plbs->cp < CpPlc(hplclnh, 0)) ; { xor cx,cx ;LN_CpPlc performs CpPlc(vfls.hplclnh, cx) ;ax, bx, cx, dx are altered. call LN_CpPlc mov bx,[si.LO_cpLbs] mov cx,[si.HI_cpLbs] cmp bx,ax mov ax,cx sbb ax,dx jl CFL01 mov ax,[vfls.dxlFls] cmp ax,[dxl] jne CFL01 mov ax,dataoffset [vfls.caFls] cCall FInCa,<[si.docLbs], cx, bx, ax> or ax,ax jne CFL04 CFL01: ; /* reset fls; no knowledge of para's height or lines */ ;LResetFls: ; vfls.ca = caParaL; LResetFls: push ds pop es push si ;save plbs mov si,dataoffset [caParaL] mov di,dataoffset [vfls.caFls] mov cx,cbCaMin/2 rep movsw pop si ;restore plbs ; vfls.ww = plbs->ww; errnz <(wwFls) - (caFls) - cbCaMin> mov ax,[si.wwLbs] stosw ; SetWords(&vfls.phe, 0, cwPHE); errnz <(pheFls) - (wwFls) - 4> xor ax,ax inc di inc di errnz <cbPheMin - 6> stosw stosw stosw ; vfls.clMac = clNil; errnz <(clMacFls) - (pheFls) - cbPheMin> errnz <(clNil) - (-1)> dec ax stosw ; vfls.fVolatile = vfls.fPageBreak = vfls.fBreakLast = fFalse; inc ax errnz <(fVolatileFls) - (clMacFls) - 3> inc di stosb errnz <(fPageBreakFls) - (fVolatileFls) - 3> errnz <(fBreakLastFls) - (fPageBreakFls) - 1> inc di inc di stosw ; vfls.fOutline = plbs->fOutline; errnz <(fOutlineFls) - (fBreakLastFls) - 2> inc di mov al,[si.fOutlineLbs] stosb ; vfls.dxl = dxl; errnz <(dxlFls) - (fOutlineFls) - 1> mov ax,[dxl] stosw ; if (cpLim != cpMax) ; vfls.ca.cpLim = CpMax(cpLim, caParaL.cpLim); mov ax,[OFF_cpLim] mov dx,[SEG_cpLim] errnz <LO_cpMax - 0FFFFh> errnz <HI_cpMax - 07FFFh> mov cx,dx xor ch,080h and cx,ax inc cx je CFL03 cmp ax,[caParaL.LO_cpLimCa] mov cx,dx sbb cx,[caParaL.HI_cpLimCa] jge CFL02 mov ax,[caParaL.LO_cpLimCa] mov dx,[caParaL.HI_cpLimCa] CFL02: mov [vfls.caFls.LO_cpLimCa],ax mov [vfls.caFls.HI_cpLimCa],dx CFL03: ; PutIMacPlc(hplclnh, 0); xor ax,ax cCall PutIMacPlc,<[vfls.hplclnhFls],ax> ; PutCpPlc(hplclnh, 0, plbs->cp); ;LN_PutCpPlc performs PutCpPlc(vfls.hplclnh, cx, dx:ax) ;ax, bx, cx, dx are altered. xor cx,cx mov ax,[si.LO_cpLbs] mov dx,[si.HI_cpLbs] call LN_PutCpPlc ; } CFL04: ; if (clLim == 0) ; { ; StopProfile(); ; return 0; /* just wanted to establish cache */ ; } xor ax,ax cmp [clLim],ax jne Ltemp001 jmp CFL21 Ltemp001: ;/* find cpFirst */ ; vfls.fFirstColumn = plbs->fFirstColumn; mov al,[si.fFirstColumnLbs] mov [vfls.fFirstColumnFls],al ; CacheSectL(vfls.ca.doc, vfls.ca.cpFirst, plbs->fOutline); mov bx,[vfls.caFls.docCa] mov dx,[vfls.caFls.HI_cpFirstCa] mov ax,[vfls.caFls.LO_cpFirstCa] mov cl,[si.fOutlineLbs] xor ch,ch ;LN_CacheSectL takes doc in bx, cp in dx:ax, fOutline in cx ;ax, bx, cx, dx are altered. call LN_CacheSectL ; cpLim = CpMin(cpLim, vfls.ca.cpLim); mov dx,[vfls.caFls.HI_cpLimCa] mov ax,[vfls.caFls.LO_cpLimCa] cmp ax,[OFF_cpLim] mov cx,dx sbb cx,[SEG_cpLim] jge CFL05 mov [OFF_cpLim],ax mov [SEG_cpLim],dx CFL05: ; dxa = NMultDiv(dxl, dxaInch, vfli.dxuInch); ; LN_NMultDivL performs NMultDiv(ax, dx, bx) ; ax, bx, cx, dx are altered. mov ax,dxaInch mov dx,[dxl] mov bx,[vfli.dxuInchFli] call LN_NMultDivL mov [dxa],ax ; ilnh = IInPlcRef(hplclnh, plbs->cp); ; if (ilnh < 0) ; { ; FillLinesUntil(plbs, plbs->cp, yllLarge, clMax, dxa, fFalse, fFalse); ; ilnh = IInPlcRef(hplclnh, plbs->cp); ; Assert(ilnh >= 0); ; } ifdef DEBUG mov [cCallsIInPlcRef],0 endif ;DEBUG jmp short CFL057 Ltemp032: jmp LResetFls CFL053: ifdef DEBUG cmp [cCallsIInPlcRef],0 je CFL055 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1046 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax CFL055: inc [cCallsIInPlcRef] endif ;DEBUG push si push [si.HI_cpLbs] push [si.LO_cpLbs] mov bx,HI_yllLarge push bx mov bx,LO_yllLarge push bx mov ax,clMax push ax push [dxa] errnz <fFalse> xor ax,ax push ax push ax call LN_FillLinesUntil CFL057: cCall IInPlcRef,<[vfls.hplclnhFls], [si.HI_cpLbs], [si.LO_cpLbs]> or ax,ax jl CFL053 ; if (ilnh >= clMaxLbs) ; goto LResetFls; cmp ax,clMaxLbs jge Ltemp032 ;/* find cl beyond cpFirst */ ; vfli.fLayout = fTrue; /* splats like page view */ mov [vfli.fLayoutFli],fTrue ; ilnh += plbs->cl; add ax,[si.clLbs] mov [ilnh],ax ; if (ilnh > IMacPlc(hplclnh)) ; { ; FillLinesUntil(plbs, cpLim, yllLarge, ilnh, dxa, fFalse, fFalse); mov bx,[vfls.hplclnhFls] ;***Begin in line IMacPlc mov bx,[bx] cmp ax,[bx.iMacPlcStr] ;***End in line IMacPlc jle CFL06 push si push [SEG_cpLim] push [OFF_cpLim] mov bx,HI_yllLarge push bx mov bx,LO_yllLarge push bx push ax push [dxa] errnz <fFalse> xor ax,ax push ax push ax call LN_FillLinesUntil ; /* this can happen when CpFromCpCl is called after editing */ ; if (ilnh > (ilnhMac = IMacPlc(hplclnh))) ; goto LEndCl; ; } mov bx,[vfls.hplclnhFls] ;***Begin in line IMacPlc mov bx,[bx] mov ax,[bx.iMacPlcStr] ;***End in line IMacPlc mov [ilnhMac],ax cmp [ilnh],ax jg Ltemp025 CFL06: ;/* now ilnh indicates start of line to start formatting; adjust dyllFill to be ; the space remaining - but don't count the lines of the para we won't be ; using */ ; if (fNotDylFillMax) ; dyllFill -= plbs->yl - plbs->ylColumn; ; if (fNotDylMax) ; dyllMax -= plbs->yl - plbs->ylColumn; mov ax,[si.ylColumnLbs] sub ax,[si.ylLbs] cwd ;CFL31 performs: ;if (fNotDylFillMax) ; dyllFill += dx:ax; ;if (fNotDylMax) ; dyllMax += dx:ax; ;cx and dx are altered. call CFL31 ; if (ilnh > 0) ; { mov cx,[ilnh] dec cx jl CFL08 ; GetPlc(hplclnh, ilnh - 1, &lnh); ;CFL22 performs GetPlc(vfls.hplclnh, cx, &lnh) ;ax, bx, cx, dx are altered. call CFL22 ; if (fNotDylFillMax) ; dyllFill += lnh.yll; ; if (fNotDylMax) ; dyllMax += lnh.yll; mov ax,[lnh.LO_yllLnh] mov dx,[lnh.HI_yllLnh] ;CFL31 performs: ;if (fNotDylFillMax) ; dyllFill += dx:ax; ;if (fNotDylMax) ; dyllMax += dx:ax; ;cx and dx are altered. call CFL31 ; } CFL08: ;/* find dyllFill, clLim beyond */ ; InvalFli(); ;#define InvalFli() vfli.ww = wwNil errnz <wwNil - 0> xor ax,ax mov [vfli.wwFli],ax ; fBreakLast = vfls.fBreakLast = vfls.fEndBreak = fFalse; errnz <fFalse> errnz <(fEndBreakFls) - (fBreakLastFls) - 1> mov wptr ([vfls.fBreakLastFls]),ax mov bptr ([fBreakLast]),al ; for (ilnhMac = IMacPlc(hplclnh); ; ) ; { mov bx,[vfls.hplclnhFls] ;***Begin in line IMacPlc mov bx,[bx] mov ax,[bx.iMacPlcStr] ;***End in line IMacPlc mov [ilnhMac],ax CFL09: ; if (ilnh == ilnhMac) ; { mov ax,[ilnh] cmp ax,[ilnhMac] jne CFL12 ; if (fBreakLast) ; { cmp bptr ([fBreakLast]),fFalse je CFL10 ; /* last FillLinesUntil hit page break */ ; vfls.fEndBreak = fTrue; ; break; mov [vfls.fEndBreakFls],fTrue Ltemp026: jmp CFL15 ; } CFL10: ; FillLinesUntil(plbs, cpLim, dyllMax, clLim, dxa, fStopAtPageBreak, fRefLine); push si push [SEG_cpLim] push [OFF_cpLim] push [SEG_dyllMax] push [OFF_dyllMax] push [clLim] push [dxa] push [fStopAtPageBreak] push [fRefLine] call LN_FillLinesUntil ; fBreakLast = vfls.fBreakLast; mov al,[vfls.fBreakLastFls] mov bptr ([fBreakLast]),al ; if (ilnh == (ilnhMac = IMacPlc(hplclnh))) ; { mov bx,[vfls.hplclnhFls] ;***Begin in line IMacPlc mov bx,[bx] mov cx,[bx.iMacPlcStr] ;***End in line IMacPlc mov [ilnhMac],cx cmp [ilnh],cx jne CFL12 ; if (fBreakLast) ; vfls.fEndBreak = fTrue; ; break; /* FillLinesUntil hit a limit */ ; } or al,al jmp short CFL135 Ltemp025: jmp LEndCl ; } CFL12: ; if (!fRefLine && CpPlc(hplclnh, ilnh) >= cpLim) ; break; cmp [fRefLine],fFalse jne CFL123 mov cx,[ilnh] ;LN_CpPlc performs CpPlc(vfls.hplclnh, cx) ;ax, bx, cx, dx are altered. call LN_CpPlc sub ax,[OFF_cpLim] sbb dx,[SEG_cpLim] jge Ltemp026 CFL123: ; GetPlc(hplclnh, ilnh, &lnh); ;CFL22 performs GetPlc(vfls.hplclnh, cx, &lnh) ;ax, bx, cx, dx are altered. mov cx,[ilnh] call CFL22 ; if (lnh.yll > dyllMax && !lnh.fSplatOnly) ; break; mov ax,[OFF_dyllMax] mov dx,[SEG_dyllMax] sub ax,[lnh.LO_yllLnh] sbb dx,[lnh.HI_yllLnh] jge CFL125 test [lnh.fSplatOnlyLnh],maskfSplatOnlyLnh je CFL15 CFL125: ; fBreakLast = vfls.fBreakLast = lnh.chBreak; mov al,[lnh.chBreakLnh] mov [vfls.fBreakLastFls],al mov bptr ([fBreakLast]),al ; cp = CpPlc(hplclnh, ++ilnh); ; if (cp > cpLim || !fRefLine && cp == cpLim) ; { inc [ilnh] mov cx,[ilnh] ;LN_CpPlc performs CpPlc(vfls.hplclnh, cx) ;ax, bx, cx, dx are altered. call LN_CpPlc mov bx,[OFF_cpLim] mov cx,[SEG_cpLim] sub bx,ax sbb cx,dx jl CFL127 or bx,cx or bx,[fRefLine] jne CFL13 CFL127: ; if (ilnh == ilnhMac && vfls.fBreakLast) ; vfls.fEndBreak = fTrue; ; break; ; } mov ax,[ilnh] cmp ax,[ilnhMac] jne CFL15 cmp [vfls.fBreakLastFls],fFalse jmp short CFL135 Ltemp003: jmp CFL20 Ltemp002: jmp CFL09 CFL13: ; if (fBreakLast && fStopAtPageBreak) ; { ; vfls.chBreak = lnh.chBreak; ; vfls.fEndBreak = fTrue; ; break; ; } cmp bptr ([fBreakLast]),fFalse je CFL14 cmp [fStopAtPageBreak],fFalse je CFL14 mov al,[lnh.chBreakLnh] mov [vfls.chBreakFls],al CFL135: je CFL15 mov [vfls.fEndBreakFls],fTrue jmp short CFL15 CFL14: ; if (lnh.yll >= dyllFill || ilnh - plbs->cl >= clLim) ; break; mov ax,[lnh.LO_yllLnh] mov dx,[lnh.HI_yllLnh] sub ax,[OFF_dyllFill] sbb dx,[SEG_dyllFill] jge CFL15 mov ax,[ilnh] sub ax,[si.clLbs] cmp ax,[clLim] jl Ltemp002 ; } ;LEndCl: LEndCl: CFL15: ; vfli.fLayout = fFalse; ; vfli.doc = docNil; errnz <fFalse> errnz <docNil> xor ax,ax mov [vfli.fLayoutFli],al mov [vfli.docFli],ax ;/* ilnh is one past the line with largest dyl <= dyllFill or largest ; cpLim <= cpLim */ ;/* if plc spans whole para, check for lines all same height */ ; if (ilnh > 0 && vfls.clMac == clNil && !vfls.fPageBreak && ; CpPlc(hplclnh, ilnhMac) == vfls.ca.cpLim) ; { cmp [ilnh],0 jle Ltemp003 cmp [vfls.clMacFls],clNil jne Ltemp003 cmp [vfls.fPageBreakFls],fFalse jne Ltemp003 mov cx,[ilnhMac] ;LN_CpPlc performs CpPlc(vfls.hplclnh, cx) ;ax, bx, cx, dx are altered. call LN_CpPlc sub ax,[vfls.caFls.LO_cpLimCa] sbb dx,[vfls.caFls.HI_cpLimCa] or ax,dx jne Ltemp003 ; vfls.clMac = ilnhMac; mov ax,[ilnhMac] mov [vfls.clMacFls],ax ; /* vfls.phe.fUnk = vfls.phe.fDiffLines = fFalse; */ ; vfls.phe.w0 = 0; ; vfls.phe.clMac = -1; errnz <(w0Phe) - 0> errnz <(clMacPhe) - 1> mov [vfls.pheFls.w0Phe],0FF00h ; vfls.phe.dxaCol = XaFromXl(dxl); mov ax,[dxl] ;LN_XaFromXl performs XaFromXl(ax); ax, bx, cx, dx are altered. call LN_XaFromXl mov [vfls.pheFls.dxaColPhe],ax ; if (vfls.fVolatile || ilnh > vfls.phe.clMac) ; goto LDiffLines; cmp [vfls.fVolatileFls],fFalse jne Ltemp024 mov al,[vfls.pheFls.clMacPhe] xor ah,ah cmp [ilnh],ax jg Ltemp024 ; GetPlc(hplclnh, 0, &lnhPrev); ;CFL23 performs GetPlc(vfls.hplclnh, cx, ax) ;ax, bx, cx, dx are altered. xor cx,cx lea ax,[lnhPrev] call CFL23 ; Assert(lnhPrev.yll < ylLarge); /* the height of any single line ifdef DEBUG ;Do this assert with a call so as not to mess up short jumps. call CFL25 endif ;DEBUG ; dylFixed = (int)lnhPrev.yll - ; - (lnhPrev.fDypBeforeAdded ? YlFromYa(vpapFetch.dyaBefore) : 0); xor ax, ax test [lnhPrev.fDypBeforeAddedLnh],maskfDypBeforeAddedLnh je CFL155 mov ax,[vpapFetch.dyaBeforePap] ;LN_YlFromYa performs YlFromYa(ax); ax, bx, cx, dx are altered. call LN_YlFromYa CFL155: sub ax,[lnhPrev.LO_yllLnh] neg ax mov [dylFixed],ax ; for (ilnh2 = 1; ilnh2 < ilnhMac - 1; ilnh2++, lnhPrev = lnh) ; { mov cx,1 mov di,[ilnhMac] dec di CFL16: cmp cx,di jge CFL17 ; GetPlc(hplclnh, ilnh2, &lnh); ;CFL22 performs GetPlc(vfls.hplclnh, cx, &lnh) ;ax, bx, cx, dx are altered. push cx ;save ilnh2 call CFL22 pop cx ;restore ilnh2 ; if (lnh.yll - lnhPrev.yll != dylFixed) ; goto LDiffLines; mov ax,[lnh.LO_yllLnh] sub ax,[lnhPrev.LO_yllLnh] sub ax,[dylFixed] Ltemp024: jne LDiffLines ; } inc cx mov ax,[lnh.LO_yllLnh] mov [lnhPrev.LO_yllLnh],ax ifdef DEBUG push [lnh.HI_yllLnh] pop [lnhPrev.HI_yllLnh] endif ;DEBUG jmp short CFL16 CFL17: ; /* ilnh2 is ilnhMac - 1 */ ; dyl = YlFromYa(vpapFetch.dyaAfter); mov ax,[vpapFetch.dyaAfterPap] ;LN_YlFromYa performs YlFromYa(ax); ax, bx, cx, dx are altered. call LN_YlFromYa ; if (ilnhMac <= 1) ; dylFixed -= dyl; or di,di jg CFL175 sub [dylFixed],ax jmp short CFL18 ; else ; { ; GetPlc(hplclnh, ilnh2, &lnh); CFL175: ;CFL22 performs GetPlc(vfls.hplclnh, cx, &lnh) ;ax, bx, cx, dx are altered. mov cx,di xchg ax,di call CFL22 ; Assert(lnh.yll - lnhPrev.yll < ylLarge); ifdef DEBUG ;Do this assert with a call so as not to mess up short jumps. call CFL29 endif ;DEBUG ; if ((int)(lnh.yll - lnhPrev.yll) - dyl != dylFixed) ; goto LDiffLines; mov ax,[lnh.LO_yllLnh] sub ax,[lnhPrev.LO_yllLnh] sub ax,di cmp ax,[dylFixed] jne LDiffLines ; } CFL18: ; vfls.phe.clMac = vfls.clMac; mov al,bptr ([vfls.clMacFls]) mov [vfls.pheFls.clMacPhe],al ; vfls.phe.dylLine = YaFromYl(dylFixed); ;#define YaFromYl(yl) (NMultDiv(yl, czaInch, vfti.dypInch)) ; LN_NMultDivL performs NMultDiv(ax, dx, bx) ; ax, bx, cx, dx are altered. mov ax,czaInch mov dx,[dylFixed] mov bx,[vfti.dypInchFti] call LN_NMultDivL mov [vfls.pheFls.dylLinePhe],ax ; } ; StopProfile(); ; return(ilnh); jmp short CFL20 ;LDiffLines: LDiffLines: ; GetPlc(hplclnh, ilnhMac - 1, &lnh); ;CFL22 performs GetPlc(vfls.hplclnh, cx, &lnh) ;ax, bx, cx, dx are altered. mov cx,[ilnhMac] dec cx call CFL22 ; if (lnh.yll >= ylLarge) cmp [lnh.HI_yllLnh],0 jl CFL19 cmp [lnh.LO_yllLnh],ylLarge jb CFL19 ; { ; SetWords(&vfls.phe, 0, cwPHE); ; } errnz <(pheFls) - (wwFls) - 4> push ds pop es xor ax,ax mov di,dataoffset [vfls.pheFls] errnz <cbPheMin - 6> stosw stosw stosw ; else ; { jmp short CFL20 CFL19: ; vfls.phe.dylHeight = NMultDiv(lnh.yll, czaInch, vfli.dyuInch); ; LN_NMultDivL performs NMultDiv(ax, dx, bx) ; ax, bx, cx, dx are altered. mov ax,czaInch mov dx,[lnh.LO_yllLnh] mov bx,[vfli.dyuInchFli] call LN_NMultDivL mov [vfls.pheFls.dylHeightPhe],ax ; vfls.phe.fDiffLines = fTrue; ; } or [vfls.pheFls.fDiffLinesPhe],maskFDiffLinesPhe CFL20: ; StopProfile(); ; return(ilnh); mov ax,[ilnh] CFL21: ;} cEnd ;CFL22 performs GetPlc(vfls.hplclnh, cx, &lnh) ;ax, bx, cx, dx are altered. CFL22: lea ax,[lnh] ;CFL23 performs GetPlc(vfls.hplclnh, cx, ax) ;ax, bx, cx, dx are altered. CFL23: cCall GetPlc,<[vfls.hplclnhFls],cx,ax> ret ; Assert(lnhPrev.yll < ylLarge); /* the height of any single line ifdef DEBUG CFL25: push ax push bx push cx push dx mov ax,[lnhPrev.LO_yllLnh] mov dx,[lnhPrev.HI_yllLnh] sub ax,ylLarge sbb dx,0 jb CFL26 mov ax,midLayout2n mov bx,1002 cCall AssertProcForNative,<ax,bx> CFL26: pop dx pop cx pop bx pop ax ret endif ;DEBUG ; Assert(lnh.yll - lnhPrev.yll < ylLarge); ifdef DEBUG CFL29: push ax push bx push cx push dx mov ax,[lnh.LO_yllLnh] mov dx,[lnh.HI_yllLnh] sub ax,[lnhPrev.LO_yllLnh] sbb dx,[lnhPrev.HI_yllLnh] sub ax,ylLarge sbb dx,0 jb CFL30 mov ax,midLayout2n mov bx,1003 cCall AssertProcForNative,<ax,bx> CFL30: pop dx pop cx pop bx pop ax ret endif ;DEBUG ;CFL31 performs: ;if (fNotDylFillMax) ; dyllFill += dx:ax; ;if (fNotDylMax) ; dyllMax += dx:ax; ;cx and dx are altered. CFL31: mov cx,[wMaxFlags] ;fDylFillMax in ch, fDylMax in cl or ch,ch jne CFL32 add [OFF_dyllFill],ax adc [SEG_dyllFill],dx CFL32: or cl,cl jne CFL33 add [OFF_dyllMax],ax adc [SEG_dyllMax],dx CFL33: ret ;------------------------------------------------------------------------- ; FillLinesUntil(plbs, cpLim, dyllFill, clLim, dxa, fStopAtPageBreak, fRefLine) ;------------------------------------------------------------------------- ;/* F i l l L i n e s U n t i l */ ;NATIVE FillLinesUntil(plbs, cpLim, dyllFill, clLim, dxa, fStopAtPageBreak, fRefLine) ;struct LBS *plbs; ;CP cpLim; ;YLL dyllFill; ;int clLim; ;int dxa; ;int fStopAtPageBreak; ;int fRefLine; ;{ ;/* add lines to plcyl in fls until ; clLim lines have been added in total ; next line would go over dyllFill ; next line would go over cpLim ; page break (conditionally) ;*/ ; int chSplat, fSplatOnly, fSeeSplat = fTrue, fAPO = fFalse; ; struct DOD *pdod; ; YLL dyll = 0; ; int ilnhMac; ; int ww = vfls.ww; ; CP cp; ; struct LNH lnh; Ltemp023: jmp LEndFill ; %%Function:LN_FillLinesUntil %%Owner:BRADV cProc LN_FillLinesUntil,<PUBLIC,NEAR>,<si> ParmW <plbs> ParmD <cpLim> ParmD <dyllFill> ParmW <clLim> ParmW <dxa> ParmW <fStopAtPageBreak> ParmW <fRefLine> LocalW ww LocalW chSplat LocalW fAPO LocalD cp LocalD dyll LocalV lnh, cbLnhMin cBegin ;Assembler note: it is redundant to initialize fAPO here mov ax,[vfls.wwFls] mov [ww],ax ifdef DEBUG cmp bptr ([fRefLine + 1]),0 je FLU005 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1004 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FLU005: endif ;DEBUG xor ax,ax mov [OFF_dyll],ax mov [SEG_dyll],ax ;Assembler note: the following line is done below in the C version ; chSplat = fSplatOnly = fFalse; mov [chSplat],ax ;high byte is fSplatOnly ; StartProfile(); ; Assert(cpLim <= vfls.ca.cpLim); ; Win(Assert(vflm == flmRepaginate || vflm == flmPrint || ; vfDypsInScreenUnits || (vlm == lmPagevw && vpri.hdc == NULL))); ifdef DEBUG ;Do the following asserts with a call so as not to mess up short jumps. call FLU22 endif ;DEBUG ; cp = CpPlc(vfls.hplclnh, ilnhMac = IMacPlc(vfls.hplclnh)); mov bx,[vfls.hplclnhFls] ;***Begin in line IMacPlc mov bx,[bx] mov si,[bx.iMacPlcStr] ;***End in line IMacPlc mov cx,si ;LN_CpPlc performs CpPlc(vfls.hplclnh, cx) ;ax, bx, cx, dx are altered. call LN_CpPlc mov [OFF_cp],ax mov [SEG_cp],dx ; if (cp >= vfls.ca.cpLim) ; goto LEndFill; sub ax,[vfls.caFls.LO_cpLimCa] sbb dx,[vfls.caFls.HI_cpLimCa] Ltemp004: jge Ltemp023 ; fAPO = FAbsPapM(vfls.ca.doc, &vpapFetch); mov ax,dataoffset [vpapFetch] cCall FAbsPap,<[vfls.caFls.docCa], ax> ;Ensure the result of FAbsPap exists entirely in the low byte. ifdef DEBUG ;Do the following assert with a call so as not to mess up short jumps. call FLU18 endif ;DEBUG ; pdod = PdodDoc(vfls.ca.doc); /* two lines for compiler */ mov bx,[vfls.caFls.docCa] ;Takes doc in bx, result in bx. Only bx is altered. call LN_PdodDocL mov ah,[bx.fShortDod] ;high byte of fAPO is fNoSeeSplat mov [fAPO],ax ; if (pdod->fShort) ; { or ah,ah je FLU03 ; if (vflm == flmRepaginate || vflm == flmPrint) ; { mov ax,[vflm] cmp al,flmRepaginate je FLU022 cmp al,flmPrint jne FLU024 FLU022: ; ww = WinMac(wwLayout, wwTemp); ; LinkDocToWw(vfls.ca.doc, ww, wwNil); mov ax,wwLayout mov [ww],ax errnz <wwNil> xor bx,bx cCall LinkDocToWw,<[vfls.caFls.docCa], ax, bx> ; } FLU024: ;Assembler note: fNoSeeSplat is set above ; fSeeSplat = fFalse; ; } FLU03: ;Assembler note: the following line is done above in the .asm version ; chSplat = fSplatOnly = fFalse; ; if (ilnhMac) ; { dec si jl FLU04 ; GetPlc(vfls.hplclnh, ilnhMac - 1, &lnh); lea ax,[lnh] cCall GetPlc,<[vfls.hplclnhFls],si,ax> ; dyll = lnh.yll; mov ax,[lnh.LO_yllLnh] mov [OFF_dyll],ax mov dx,[lnh.HI_yllLnh] mov [SEG_dyll],dx ; } FLU04: inc si ;restore ilnhMac ; while (ilnhMac < clLim) ; { FLU045: cmp si,[clLim] jge Ltemp004 ; if (vfInFormatPage && vlm == lmBRepag && FAbortLayout(vfls.fOutline, plbs)) cmp [vfInFormatPage],fFalse je FLU05 cmp [vlm],lmBRepag jne FLU05 mov al,[vfls.fOutlineFls] cbw push ax push [plbs] ifdef DEBUG cCall S_FAbortLayout,<> else ;not DEBUG push cs call near ptr N_FAbortLayout endif ;DEBUG or ax,ax je FLU05 ; AbortLayout(); cCall AbortLayout,<> FLU05: ; FormatLineDxaL(ww, vfls.ca.doc, cp, dxa); ;#define FormatLineDxaL(ww, doc, cp, dxa) FormatLineDxa(ww, doc, cp, dxa) ifdef DEBUG cCall S_FormatLineDxa,<[ww], [vfls.caFls.docCa], [SEG_cp], [OFF_cp], [dxa]> else ;not DEBUG cCall N_FormatLineDxa,<[ww], [vfls.caFls.docCa], [SEG_cp], [OFF_cp], [dxa]> endif ;DEBUG ; if (vfli.fParaStopped) ; { ; /* last line of para is hidden text, limit ourselves ; to para */ ; PutCpPlc(vfls.hplclnh, ilnhMac, vfls.ca.cpLim); ; vfls.fVolatile = fTrue; ; goto LEndFill; ; } test [vfli.fParaStoppedFli],maskFParaStoppedFli je FLU055 ;LN_PutCpPlc performs PutCpPlc(vfls.hplclnh, cx, dx:ax) ;ax, bx, cx, dx are altered. mov cx,si mov ax,[vfls.caFls.LO_cpLimCa] mov dx,[vfls.caFls.HI_cpLimCa] call LN_PutCpPlc mov [vfls.fVolatileFls],fTrue jmp LEndFill FLU055: ; cp = vfli.cpMac; mov ax,[vfli.LO_cpMacFli] mov [OFF_cp],ax mov ax,[vfli.HI_cpMacFli] mov [SEG_cp],ax ; chSplat = fSplatOnly = fFalse; ; if (vfli.fSplatColumn) ; chSplat = chColumnBreak; ; else if (vfli.fSplatBreak) ; chSplat = chSect; ; ; if (chSplat) ; { errnz <(fSplatBreakFli) - (fSplatColumnFli)> mov al,[vfli.fSplatBreakFli] ;Assembler note: clear ah because by default fSplatOnly is fFalse and ax,maskFSplatBreakFli+maskFSplatColumnFli je FLU06 test al,maskFSplatColumnFli mov al,chColumnBreak jne FLU06 xor al,chSect XOR chColumnBreak ;xor to clear zero flag FLU06: je FLU08 ;Assembler note: storing chSplat and fSplatOnly into memory ;is postponed until just after FLU08 or FLU075. ; if (fSeeSplat) ; { cmp bptr ([fAPO+1]),fFalse ;fNoSeeSplat is high byte of fAPO jne FLU075 ; fSplatOnly = vfli.ichMac == 1; ; if (fAPO && !(fSplatOnly && vfli.cpMin == vfls.ca.cpFirst)) ; fSplatOnly = chSplat = fFalse; ; else ; vfls.chBreak = chSplat; ; } ; else ; chSplat = fFalse; /* ignore splat in hdr, apo, etc. */ cmp [vfli.ichMacFli],1 jne FLU063 mov ah,maskfSplatOnlyLnh ;fSplatOnly is high byte of chSplat FLU063: cmp bptr ([fAPO]),fFalse je FLU067 or ah,ah je FLU07 mov cx,[vfli.HI_cpMinFli] sub cx,[vfls.caFls.HI_cpFirstCa] jne FLU07 mov cx,[vfli.LO_cpMinFli] sub cx,[vfls.caFls.LO_cpFirstCa] jne FLU07 FLU067: mov [vfls.chBreakFls],al db 03Dh ;turns next "xor ax,ax" into "cmp ax,immediate" FLU07: xor ax,ax db 03Dh ;turns next "xor al,al" into "cmp ax,immediate" FLU075: xor al,al mov [chSplat],ax ;high byte is fSplatOnly jmp short FLU10 ; } FLU08: ; else if (vfli.chBreak == chSect || vfli.chBreak == chColumnBreak) ; { mov [chSplat],ax ;high byte is fSplatOnly mov al,bptr ([vfli.chBreakFli]) cmp al,chSect je FLU09 cmp al,chColumnBreak jne FLU10 FLU09: ; /* we have to be sensitive to splats that are ; pending in order to detect end of section ; properly */ ; chSplat = vfli.chBreak; mov bptr ([chSplat]),al ; vfls.chBreak = vfli.chBreak; mov [vfls.chBreakFls],al ; cp += ccpSect; add [OFF_cp],ccpSect adc [SEG_cp],0 ; } FLU10: ; dyll += vfli.dypLine; mov ax,[vfli.dypLineFli] cwd add [OFF_dyll],ax adc [SEG_dyll],dx ; if (!fSplatOnly) ; { test bptr ([chSplat+1]),maskfSplatOnlyLnh jne FLU103 ; if (dyll > dyllFill || (!chSplat && !fRefLine && cp > cpLim)) ; goto LEndFill; mov ax,[OFF_dyllFill] mov dx,[SEG_dyllFill] sub ax,[OFF_dyll] sbb dx,[SEG_dyll] Ltemp005: jl Ltemp031 mov al,bptr ([fRefLine]) ; Assert(!(fRefLine && 0xFF00h)); ifdef DEBUG ;Do this assert with a call so as not to mess up short jumps call FLU16 endif ;DEBUG or al,bptr ([chSplat]) jne FLU103 mov ax,[OFF_cpLim] mov dx,[SEG_cpLim] sub ax,[OFF_cp] sbb dx,[SEG_cp] jl Ltemp005 ; } FLU103: ; vfls.fBreakLast = fStopAtPageBreak && chSplat; ; vfls.fPageBreak |= chSplat; ; vfls.fVolatile |= vfli.fVolatile; mov al,[vfli.fVolatileFli] or [vfls.fVolatileFls],al mov al,bptr ([chSplat]) or [vfls.fPageBreakFls],al cmp [fStopAtPageBreak],fFalse jne FLU107 mov al,fFalse FLU107: mov [vfls.fBreakLastFls],al ; if (fSplatOnly && ilnhMac > 0) ; { FLU11: test bptr ([chSplat+1]),maskfSplatOnlyLnh je FLU12 mov cx,si dec cx jl FLU12 ; GetPlc(vfls.hplclnh, ilnhMac - 1, &lnh); lea ax,[lnh] cCall GetPlc,<[vfls.hplclnhFls],cx,ax> ; if (!lnh.chBreak) ; { cmp [lnh.chBreakLnh],fFalse jne FLU12 ; lnh.chBreak = chSplat; mov al,bptr ([chSplat]) mov [lnh.chBreakLnh],al ; PutPlcLast(vfls.hplclnh, ilnhMac - 1, &lnh); ifdef DEBUG mov ax,si dec ax lea bx,[lnh] cCall PutPlcLastDebugProc,<[vfls.hplclnhFls],ax,bx> else ;not DEBUG cCall PutPlcLastProc,<[vfls.hplclnhFls]> endif ;DEBUG ; dyll -= vfli.dypLine; mov ax,[vfli.dypLineFli] cwd sub [OFF_dyll],ax sbb [SEG_dyll],dx ; goto LSetCp; jmp short LSetCp Ltemp031: jmp LEndFill ; } ; } FLU12: ; lnh.fSplatOnly = fSplatOnly; ; lnh.chBreak = chSplat; ; lnh.fDypBeforeAdded = vfli.dypBefore != 0; ; lnh.yll = dyll; errnz <(chBreakLnh) - (fSplatOnlyLnh) - 1> mov ax,[chSplat] ;high byte is fSplatOnly xchg ah,al cmp [vfli.dypBeforeFli],0 je FLU13 or al,maskfDypBeforeAddedLnh FLU13: mov wptr ([lnh.fSplatOnlyLnh]),ax mov ax,[OFF_dyll] mov dx,[SEG_dyll] mov [lnh.LO_yllLnh],ax mov [lnh.HI_yllLnh],dx ; if (!FInsertInPlc(vfls.hplclnh, ilnhMac++, vfli.cpMin, &lnh)) ; { lea ax,[lnh] push [vfls.hplclnhFls] push si push [vfli.HI_cpMinFli] push [vfli.LO_cpMinFli] push ax inc si ifdef DEBUG cCall S_FInsertInPlc,<> else ;not DEBUG cCall N_FInsertInPlc,<> endif ;DEBUG or ax,ax jne FLU14 ; if (vfInFormatPage) ; AbortLayout(); ; goto LEndFill; ; } cmp [vfInFormatPage],fFalse je LEndFill cCall AbortLayout,<> ;Assembler note: should never reach here FLU14: ;LSetCp: LSetCp: ; PutCpPlc(vfls.hplclnh, ilnhMac, cp); ; vfls.ca.cpLim = CpMax(vfls.ca.cpLim, cp); mov ax,[OFF_cp] mov dx,[SEG_cp] cmp ax,[vfls.caFls.LO_cpLimCa] mov cx,dx sbb cx,[vfls.caFls.HI_cpLimCa] jl FLU15 mov [vfls.caFls.LO_cpLimCa],ax mov [vfls.caFls.HI_cpLimCa],dx FLU15: ;LN_PutCpPlc performs PutCpPlc(vfls.hplclnh, cx, dx:ax) ;ax, bx, cx, dx are altered. mov cx,si call LN_PutCpPlc ; if (dyll >= dyllFill || cp > cpLim || vfls.fBreakLast || ; !fRefLine && cp == cpLim) ; { ; goto LEndFill; ; } ; } mov ax,[OFF_dyll] mov dx,[SEG_dyll] sub ax,[OFF_dyllFill] sbb dx,[SEG_dyllFill] jge LEndFill cmp [vfls.fBreakLastFls],fFalse jne LEndFill mov ax,[OFF_cpLim] mov dx,[SEG_cpLim] sub ax,[OFF_cp] sbb dx,[SEG_cp] jl LEndFill or ax,dx or ax,[fRefLine] je LEndFill jmp FLU045 ;LEndFill: LEndFill: ; StopProfile(); ;} cEnd ; Assert(!(fRefLine && 0xFF00h)); ifdef DEBUG ;Do this assert with a call so as not to mess up short jumps FLU16: cmp bptr ([fRefLine+1]),fFalse je FLU17 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1054 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FLU17: ret endif ;DEBUG ;Ensure the result of FAbsPap exists entirely in the low byte. ifdef DEBUG FLU18: or ah,ah je FLU19 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1055 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FLU19: ret endif ;DEBUG ifdef DEBUG ; Assert(cpLim <= vfls.ca.cpLim); ; Win(Assert(vflm == flmRepaginate || vflm == flmPrint || ; vfDypsInScreenUnits || (vlm == lmPagevw && vpri.hdc == NULL))); FLU22: push ax push bx push cx push dx mov ax,[vfls.caFls.LO_cpLimCa] mov dx,[vfls.caFls.HI_cpLimCa] sub ax,[OFF_cpLim] sbb dx,[SEG_cpLim] jge FLU23 mov ax,midLayout2n mov bx,1005 cCall AssertProcForNative,<ax,bx> FLU23: cmp [vflm],flmRepaginate je FLU24 cmp [vflm],flmPrint je FLU24 cmp [vfDypsInScreenUnits],fFalse jne FLU24 mov ax,[vlm] sub ax,lmPagevw errnz <NULL> or ax,[vpri.hdcPri] je FLU24 mov ax,midLayout2n mov bx,1061 cCall AssertProcForNative,<ax,bx> FLU24: pop dx pop cx pop bx pop ax ret endif ;DEBUG maskFAbsLocal equ 001h ;------------------------------------------------------------------------- ; FAssignLr(plbs, dylFill, fEmptyOK) ;------------------------------------------------------------------------- ;/* F A s s i g n L r */ ;NATIVE int FAssignLr(plbs, dylFill, fEmptyOK) ;struct LBS *plbs; ;int dylFill, fEmptyOK; ;{ ;/* create or assign a layout rectangle to the upcoming paragraphs; ; returns fFalse if height is already known */ ; int ilr, ilrMac, ilrT; ; int doc = plbs->doc; ; int docMother; ; int fFtn; ; int fShort; ; struct DOD *pdod; ; int fAbs, fPend, fPrevTable; ; int xlRightAbs, xlLeftAbs; ; int xaLeft, xaRight; ; int dylOverlapNew; ; LRP lrp; ; LRP lrpT; ; struct PAP pap; ; struct RC rcl, rclPend; ; struct LR lr; ; struct LBS lbsT; ; int ihdt; ; %%Function:N_FAssignLr %%Owner:BRADV cProc N_FAssignLr,<PUBLIC,FAR>,<si,di> ParmW <plbs> ParmW <dylFill> ParmW <fEmptyOK> LocalW fFtn LocalW ilrMac LocalW docMotherVar LocalW dylOverlapNew LocalW fPrevTable LocalV lr,cbLrMin OFFBP_lr = -6+cbLrMin LocalW fPend OFFBP_fPend = -8+cbLrMin LocalV rclVar,cbRcMin LocalV rclPend,cbRcMin cBegin ;/* quick check - see if we can reuse previous lr */ ; StartProfile(); ; CacheParaL(doc, plbs->cp, plbs->fOutline); ;LN_CacheParaLbs takes plbs in si ;and performs CacheParaL(plbs->doc, plbs->cp, plbs->fOutline). ;ax, bx, cx, dx are altered. mov si,[plbs] call LN_CacheParaLbs ; pdod = PdodDoc(doc); ; fFtn = pdod->fFtn; ; fShort = pdod->fShort; mov bx,[si.docLbs] ;Takes doc in bx, result in bx. Only bx is altered. call LN_PdodDocL ;Assembler note: since fShort includes fFtn, we will copy the byte ;pdod->fShort into fFtn, and test with maskFFtnDod when we want ;fFtn, and compare with 0 when we want fShort. errnz <(fShortDod) - (fFtnDod)> mov al,[bx.fFtnDod] xor ah,ah mov [fFtn],ax ; fAbs = !fFtn && FAbsPapM(doc, &vpapFetch); ; fPrevTable = fFalse; errnz <fFalse> mov bptr ([fPrevTable]),ah test al,maskFFtnDod jne FALr01 mov ax,dataoffset [vpapFetch] cCall FAbsPap,<[si.docLbs], ax> xchg ax,cx jcxz FALr01 ;Assembler note: fAbs is the high byte of fFtn errnz <maskFAbsLocal - 001h> inc bptr ([fFtn+1]) FALr01: ; if (!fAbs && plbs->ilrCur >= 0 && ; plbs->ilrCur < IMacPllr(plbs)) ; { test bptr ([fFtn+1]),maskFAbsLocal jne FALr02 mov cx,[si.ilrCurLbs] or cx,cx jl FALr02 ;***Begin in-line IMacPllr mov bx,[si.hpllrLbs] mov bx,[bx] cmp cx,[bx.iMacPl] ;***End in-line IMacPllr jge FALr02 ; lrp = LrpInPl(plbs->hpllr, plbs->ilrCur); ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl ; if (lrp->doc == doc && lrp->ihdt == plbs->ihdt && ; lrp->xl == plbs->xl) ; { ; if (lrp->lrs != lrsFrozen) ; { ; if (!plbs->fAbsPresent) ; { ; plbs->dylOverlap = 0; ; StopProfile(); ; return(fFalse); ; } ; } ;FALr30 returns (lrp->doc == plbs->doc && lrp->ihdt == plbs->ihdt) ;as zero flag set if true, zero flag reset if false. ;lrp is assumed in es:bx, plbs is assumed in si. ;Only ax is altered. call FALr30 jne FALr02 mov ax,es:[bx.xlLr] cmp ax,[si.xlLbs] jne FALr02 cmp es:[bx.lrsLr],lrsFrozen je FALr015 cmp [si.fAbsPresentLbs],fFalse jne FALr02 jmp FALr07 FALr015: ; else if (plbs->fSimpleLr && plbs->fPrevTable && vpapFetch.fInTable ; && plbs->yl == lrp->yl + lrp->dyl) ; { errnz <fFalse> xor ax,ax cmp [si.fSimpleLrLbs],al je FALr02 cmp [si.fPrevTableLbs],al je FALr02 cmp [vpapFetch.fInTablePap],al je FALr02 ;LN_LrpInPlCur performs LrpInPl(plbs->hpllr, plbs->ilrCur) with ;the result in es:bx or es:ax. It assumes plbs is passed in si. ;ax, bx, cx, dx are altered. call LN_LrpInPlCur mov cx,es:[bx.ylLr] add cx,es:[bx.dylLr] cmp [si.ylLbs],cx jne FALr02 ; plbs->yl -= plbs->dylBelowTable; ; lrp->dyl -= plbs->dylBelowTable; ; plbs->dylBelowTable = 0; ; fPrevTable = fTrue; ; } ; } ; } xor ax,ax xchg ax,[si.dylBelowTableLbs] sub [si.ylLbs],ax sub es:[bx.dylLr],ax mov bptr ([fPrevTable]),fTrue FALr02: ; /* get sect properties */ ; if (fFtn) ; { ; docMother = DocMother(doc); ; CacheSectL(docMother, CpRefFromCpSub(doc, plbs->cp, edcDrpFtn), plbs->fOutline); ; } ; else ; CacheSectL(doc, plbs->cp, plbs->fOutline); ;#define edcDrpFtn (offset(DOD,drpFtn)/sizeof(int)) mov bx,[si.docLbs] mov ax,[si.LO_cpLbs] mov dx,[si.HI_cpLbs] mov cl,[si.fOutlineLbs] xor ch,ch test bptr ([fFtn]),maskFFtnDod je FALr03 push cx ;save plbs->fOutline mov cx,([drpFtnDod]) SHR 1 push bx ;argument for CpRefFromCpSub push dx ;argument for CpRefFromCpSub push ax ;argument for CpRefFromCpSub push cx ;argument for CpRefFromCpSub cCall DocMother,<bx> mov [docMotherVar],ax xchg ax,di cCall CpRefFromCpSub,<> mov bx,di pop cx ;restore plbs->fOutline FALr03: ;LN_CacheSectL takes doc in bx, cp in dx:ax, fOutline in cx ;ax, bx, cx, dx are altered. call LN_CacheSectL ;/* find an existing LR to which we can assign the new text */ ; if ((ilrMac = IMacPllr(plbs)) > 0) ; { ;LN_IMacPllr performs cx = IMacPllr(plbs). plbs is assumed to be ;passed in si. Only bx and cx are altered. call LN_IMacPllr mov [ilrMac],cx jcxz Ltemp007 ; for (lrp = LrpInPl(plbs->hpllr, ilr = 0); ilr < ilrMac; ilr++, lrp++) ; { mov cx,-1 FALr04: inc cx ifdef DEBUG ;Assembler note: If we call LrpInPl with cx >= ilrMac we may assert ;in HpInPl because we are trying to get a pointer beyond the end ;of the PL. This is a debug only problem, however, because right ;after FALr06 we exit the loop when cx >= ilrMac, and never use ;the pointer. This debug code is designed to work around the ;problem. The problem doesn't exist in the C versions because ;there we work with HUGE pointers, and since those are not altered ;by code movement, there is no need to call HpInPl to restore them, ;in the assembler version we are using faster far pointers, but ;this requires dereferencing whenever code movement may have taken ;place, hence this call to HpInPl (inside LN_LrpInPl). cmp cx,[ilrMac] jge FALr06 endif ;DEBUG ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl jmp short FALr06 FALr05: inc cx add bx,cbLrMin FALr06: cmp cx,[ilrMac] jge Ltemp007 ; /* doc and fAbs must match; ihdt match means both from same header or ; both not headers */ ; if (lrp->doc != doc || lrp->ihdt != plbs->ihdt || lrp->lrs == lrsFrozen) ; continue; ;FALr30 returns (lrp->doc == plbs->doc && lrp->ihdt == plbs->ihdt) ;as zero flag set if true, zero flag reset if false. ;lrp is assumed in es:bx, plbs is assumed in si. ;Only ax is altered. call FALr30 jne FALr05 cmp es:[bx.lrsLr],lrsFrozen je FALr05 ; if (fAbs ^ lrp->lrk == lrkAbs) ; continue; mov al,bptr ([fFtn+1]) errnz <maskFAbsLocal - 001h> xor al,es:[bx.lrkLr] cmp al,lrkAbs je FALr05 ; /* if both abs, cp's must match */ ; if (fAbs) ; { test bptr ([fFtn+1]),maskFAbsLocal je FALr08 ; if (plbs->cp != lrp->cp) ; continue; mov ax,[si.LO_cpLbs] cmp ax,es:[bx.LO_cpLr] jne FALr05 mov ax,[si.HI_cpLbs] cmp ax,es:[bx.HI_cpLr] jne FALr05 ; /* reuse abs block */ ; plbs->ilrCur = ilr; ; plbs->fPrevTable = fFalse; mov [si.ilrCurLbs],cx mov [si.fPrevTableLbs],fFalse ; bltLrp(lrp, &lr, sizeof(struct LR)); ; AssignAbsXl(plbs, &lr); push cx ;save ilr push si ;save plbs lea di,[lr] push si ;argument for AssignAbsXl push di ;argument for AssignAbsXl push es pop ds push ss pop es mov si,bx errnz <cbLrMin AND 1> mov cx,cbLrMin SHR 1 rep movsw push ss pop ds cCall AssignAbsXl,<> pop si ;restore plbs pop cx ;restore ilr ; bltLrp(&lr, lrp, sizeof(struct LR)); ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl xchg ax,di lea si,[lr] errnz <cbLrMin AND 1> mov cx,cbLrMin SHR 1 rep movsw FALr07: ; plbs->dylOverlap = 0; xor ax,ax ;value to store in plbs->dylOverlap ;also clears carry so we will return fFalse ; StopProfile(); ; return(fFalse); ; } jmp FALr29 Ltemp007: jmp short FALr11 Ltemp022: jmp short FALr04 FALr08: ; /* check for different columns */ ; if (lrp->lrk != lrkAbsHit) ; { ; if (plbs->xl != lrp->xl) ; continue; ; } ; else if (plbs->xl > lrp->xl) ; /* apos can only force the xl to be bigger */ ; continue; mov ax,es:[bx.xlLr] cmp es:[bx.lrkLr],lrkAbsHit je FALr09 cmp [si.xlLbs],ax Ltemp027: jne FALr05 FALr09: cmp [si.xlLbs],ax jg Ltemp027 ; /* finally check for same section */ ; if (fFtn) ; { ; if (FInCa(docMother, CpRefFromCpSub(lrp->doc, lrp->cp, edcDrpFtn), &caSect)) ; break; ; } ; else if (FInCa(lrp->doc, lrp->cp, &caSect)) ; break; ; } ;#define edcDrpFtn (offset(DOD,drpFtn)/sizeof(int)) push cx ;save ilr push es:[bx.docLr] push es:[bx.HI_cpLr] push es:[bx.LO_cpLr] test bptr ([fFtn]),maskFFtnDod je FALr10 mov cx,([drpFtnDod]) SHR 1 push cx cCall CpRefFromCpSub,<> push [docMotherVar] push dx push ax FALr10: lea ax,[caSect] push ax cCall FInCa,<> pop cx ;restore ilr or ax,ax je Ltemp022 ; if (ilr < ilrMac) ; { ; plbs->ilrCur = ilr; ; plbs->dylOverlap = 0; ; StopProfile(); ; return(fTrue); ; } ; } ;Assembler note: at this point we know ilr < ilrMac. Assert this ;with a call so as not to mess up short jumps. ifdef DEBUG call FALr32 endif ;DEBUG mov [si.ilrCurLbs],cx xor ax,ax ;value to store in plbs->dylOverlap jmp FALr285 FALr11: ;/* need new LR */ ; dylOverlapNew = 0; ; fPend = fFalse; ; plbs->fPrevTable = fPrevTable; ; plbs->ilrCur = ilrMac; ; plbs->ylMaxLr = plbs->ylMaxBlock; ; SetWords(&lr, 0, cwLR); mov ax,[ilrMac] mov [si.ilrCurLbs],ax mov ax,[si.ylMaxBlockLbs] mov [si.ylMaxLrLbs],ax mov al,bptr ([fPrevTable]) mov [si.fPrevTableLbs],al xor ax,ax mov [dylOverlapNew],ax errnz <OFFBP_lr - OFFBP_fPend - 2> push ds pop es lea di,[fPend] errnz <cbLrMin AND 1> mov cx,(cbLrMin SHR 1) + 1 rep stosw ; lr.doc = doc; mov ax,[si.docLbs] mov [lr.docLr],ax ; lr.yl = plbs->yl; /* for abs, these are first approximations */ mov cx,[si.ylLbs] mov [lr.ylLr],cx ; lr.xl = plbs->xl; mov ax,[si.xlLbs] mov [lr.xlLr],ax ; lr.dxl = plbs->dxlColumn; mov ax,[si.dxlColumnLbs] mov [lr.dxlLr],ax ; lr.ihdt = plbs->ihdt; mov bx,[si.ihdtLbs] mov [lr.ihdtLr],bx ; if (lr.ihdt == ihdtNil) ; lr.dyl = plbs->ylColumn + dylFill - lr.yl; ; else ; lr.cpMacCounted = cpNil; mov ax,0FFFFh errnz <ihdtNil - (-1)> inc bx jne FALr12 mov bx,[si.ylColumnLbs] add bx,[dylFill] sub bx,cx mov [lr.dylLr],bx jmp short FALr13 FALr12: errnz <LO_cpNil - 0FFFFh> errnz <HI_cpNil - 0FFFFh> mov [lr.LO_cpMacCountedLr],ax mov [lr.HI_cpMacCountedLr],ax FALr13: ; lr.lnn = (fAbs || fShort || !FLnnSep(vsepFetch)) ? lnnNil : plbs->lnn; ;#define FLnnSep(sep) (sep.nLnnMod) errnz <lnnNil - (-1)> mov cx,ax ;Assembler note: fShort is the byte at fFtn, fAbs is in the byte ;at fFtn+1. test [fFtn],ax jne FALr135 test [vsepFetch.nLnnModSep],ax je FALr135 mov cx,[si.lnnLbs] FALr135: mov [lr.lnnLr],cx ; lr.ilrNextChain = ilrNil; errnz <ilrNil - (-1)> mov [lr.ilrNextChainLr],ax ; lr.lrk = (fAbs) ? lrkAbs : lrkNormal; errnz <lrkNormal - 0> errnz <lrkAbs - 1> errnz <maskFAbsLocal - 001h> mov bl,bptr ([fFtn+1]) mov [lr.lrkLr],bl ; lr.tSoftBottom = tNeg; /* ninch for exceed bottom */ errnz <tNeg - (-1)> or [lr.tSoftBottomLr],maskTSoftBottomLr ;/* absolute object */ ; if (fAbs) ; /* for abs. positioning, set cpFirst and cpLim now */ ; SetAbsLr(plbs, &lr); or bl,bl je FALr14 lea ax,[lr] cCall SetAbsLr,<si, ax> Ltemp008: jmp LReplace ;/* normal object, may be affected by absolutes */ ; else ; { FALr14: ; plbs->ylMaxLr = plbs->ylMaxBlock; ; plbs->dylChain = ylLarge; mov bx,[si.ylMaxBlockLbs] mov [si.ylMaxLrLbs],bx mov [si.dylChainLbs],ylLarge ; lr.cp = lr.cpLim = cpNil; ifdef DEBUG push ax push bx push cx push dx mov ax,es mov bx,ds cmp ax,bx je FALr15 mov ax,midLayout2n mov bx,1006 cCall AssertProcForNative,<ax,bx> FALr15: pop dx pop cx pop bx pop ax endif ;DEBUG errnz <(cpLimLr) - (cpLr) - 4> lea di,[lr.cpLr] errnz <LO_cpNil - 0FFFFh> errnz <HI_cpNil - 0FFFFh> stosw stosw stosw stosw ; if (plbs->fAbsPresent && lr.ihdt == ihdtNil) ; { ; /* restrict lr so it will miss abs objects */ ; rcl.ylTop = lr.yl; ;LFitLr: ; rcl.xlLeft = lr.xl; ; rcl.xlRight = lr.xl + lr.dxl; ; rcl.ylBottom = plbs->ylColumn + dylFill; test [si.fAbsPresentLbs],al je Ltemp008 errnz <ihdtNil - (-1)> cmp [lr.ihdtLr],ax jne Ltemp008 mov ax,[lr.ylLr] LFitLr: mov [rclVar.ylTopRc],ax mov ax,[lr.xlLr] mov [rclVar.xlLeftRc],ax add ax,[lr.dxlLr] mov [rclVar.xlRightRc],ax mov ax,[si.ylColumnLbs] add ax,[dylFill] mov [rclVar.ylBottomRc],ax ;LHaveRcl: ; ConstrainToAbs(plbs, dylFill, &rcl, &rclPend, &fPend, &lr); LHaveRcl: push si push [dylFill] lea ax,[rclVar] push ax lea ax,[rclPend] push ax lea ax,[fPend] push ax lea ax,[lr] push ax cCall ConstrainToAbs,<> ; if (rcl.ylBottom - plbs->yl <= plbs->dylOverlap || ; rcl.ylBottom <= rcl.ylTop) ; { mov ax,[rclVar.ylBottomRc] cmp ax,[rclVar.ylTopRc] jle FALr153 sub ax,[si.ylLbs] cmp ax,[si.dylOverlapLbs] jg FALr18 FALr153: ; /* rectangle is too short */ ; if (fPend) ; { ; /* ignore short one, use pending one */ cmp [fPend],fFalse je FALr16 ; fPend = fFalse; ; rcl = rclPend; ; lr.fConstrainLeft = fTrue; ; lr.fConstrainRight = fFalse; ; goto LHaveRcl; ; } FALr155: mov [fPend],fFalse push si ;save plbs push ds pop es lea si,[rclPend] lea di,[rclVar] errnz <cbRcMin - 8> movsw movsw movsw movsw pop si ;restore plbs errnz <(fConstrainLeftLr) - (fConstrainRightLr)> and [lr.fConstrainLeftLr],NOT (maskfConstrainLeftLr + maskfConstrainRightLr) or [lr.fConstrainLeftLr],maskfConstrainLeftLr jmp short LHaveRcl FALr16: ; if (plbs->ilrFirstChain != ilrNil) ; goto LGiveUp; cmp [si.ilrFirstChainLbs],ilrNil jne LGiveUp ; if (rcl.ylBottom >= plbs->ylColumn + dylFill) ; { mov ax,[si.ylColumnLbs] add ax,[dylFill] cmp [rclVar.ylBottomRc],ax jl FALr17 ; /* avoid inf loop when no room by not flowing */ ; if (!fEmptyOK) ; goto LTakeRcl; cmp [fEmptyOK],fFalse je LTakeRcl ; /* maybe only the last one is too short */ ;LGiveUp: ; plbs->ilrCur = ilrNil; LGiveUp: mov [si.ilrCurLbs],ilrNil ; if (rcl.ylBottom - rcl.ylTop > 0) ; plbs->dylChain = min(plbs->dylChain, rcl.ylBottom - rcl.ylTop); ; goto LMendChain; mov ax,[rclVar.ylBottomRc] sub ax,[rclVar.ylTopRc] jle LMendChain cmp [si.dylChainLbs],ax jle LMendChain mov [si.dylChainLbs],ax jmp short LMendChain ; } FALr17: ; /* retry with advanced yl */ ; lr.lrk = lrkAbsHit; ; rcl.ylTop = rcl.ylBottom; ; lr.fConstrainLeft = lr.fConstrainRight = fFalse; ; dylOverlapNew = rcl.ylTop - plbs->yl; ; goto LFitLr; ; } mov [lr.lrkLr],lrkAbsHit mov ax,[rclVar.ylBottomRc] mov bx,ax sub bx,[si.ylLbs] mov [dylOverlapNew],bx errnz <(fConstrainLeftLr) - (fConstrainRightLr)> and [lr.fConstrainLeftLr],NOT (maskfConstrainLeftLr + maskfConstrainRightLr) jmp LFitLr FALr18: ; if (lr.lrk == lrkAbsHit) ; { ;LTakeRcl: ; lr.lrs = lrsIgnore; /* in case too small */ ; RcToDrc(&rcl, &lr.drcl); ; } ; } ; } cmp [lr.lrkLr],lrkAbsHit jne LReplace LTakeRcl: mov [lr.lrsLr],lrsIgnore lea ax,[rclVar] lea bx,[lr.drclLr] cCall RcToDrc,<ax,bx> ;LReplace: ; ReplaceInPllr(plbs->hpllr, plbs->ilrCur, &lr); LReplace: lea ax,[lr] push [si.hpllrLbs] push [si.ilrCurLbs] push ax ifdef DEBUG cCall S_ReplaceInPllr,<> cmp [vdbs.fShowLbsDbs],0 jz FALr175 push si mov ax,irtnAssignLr push ax cCall ShowLbsProc,<> FALr175: else ;!DEBUG push cs call near ptr N_ReplaceInPllr endif ;!DEBUG ;/* rectangle was split by an abs object - create or extend chain and redo fit ; for the new rectangle also */ ;LMendChain: ; if (fPend) ; { LMendChain: cmp [fPend],fFalse je FALr22 ; if (plbs->ilrFirstChain == ilrNil) ; plbs->ilrFirstChain = plbs->ilrCur; ; else ; { ; lrp = LrpInPl(plbs->hpllr, plbs->ilrCurChain); ; lrp->ilrNextChain = plbs->ilrCur; ; } cmp [si.ilrFirstChainLbs],ilrNil push [si.ilrCurLbs] jne FALr19 pop [si.ilrFirstChainLbs] jmp short FALr20 FALr19: mov cx,[si.ilrCurChainLbs] ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl pop es:[bx.ilrNextChainLr] FALr20: ; plbs->ilrCurChain = plbs->ilrCur; ; lrp = LrpInPl(plbs->hpllr, plbs->ilrCur); ;LN_IMacPllr performs cx = IMacPllr(plbs). plbs is assumed to be ;passed in si. Only bx and cx are altered. call LN_IMacPllr xchg cx,[si.ilrCurLbs] mov [si.ilrCurChainLbs],cx ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl ; plbs->dylChain = min(plbs->dylChain, lrp->dyl); mov ax,es:[bx.dylLr] cmp [si.dylChainLbs],ax jle FALr21 mov [si.dylChainLbs],ax FALr21: ;Assembler note: the following line is done just after FALr20 in ;the assembler version. ; plbs->ilrCur = IMacPllr(plbs); ; fPend = fFalse; ; rcl = rclPend; ; lr.ilrNextChain = ilrNil; ; lr.fConstrainLeft = fTrue; ; lr.fConstrainRight = fFalse; ; goto LHaveRcl; ; } mov [lr.ilrNextChainLr],ilrNil jmp FALr155 FALr22: ;/* end of chain - check for single entry, otherwise set height of all chained ; entries to be the min of all entries' heights */ ; if (plbs->ilrFirstChain != ilrNil) ; { ; if (plbs->ilrCurChain == plbs->ilrFirstChain && plbs->ilrCur == ilrNil) ; { ; plbs->ilrCur = plbs->ilrFirstChain; ; plbs->ilrFirstChain = ilrNil; ; lrp = LrpInPl(plbs->hpllr, plbs->ilrCur); ; lrp->dyl = min(plbs->dylChain, lrp->dyl); ; } mov cx,[si.ilrFirstChainLbs] mov dx,ilrNil cmp cx,dx je FALr28 cmp [si.ilrCurLbs],dx jne FALr23 cmp [si.ilrCurChainLbs],cx jne FALr25 mov [si.ilrCurLbs],cx mov [si.ilrFirstChainLbs],dx ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl mov ax,[si.dylChainLbs] cmp es:[bx.dylLr],ax jle FALr28 mov es:[bx.dylLr],ax jmp short FALr28 ; else ; { FALr23: ; if (plbs->ilrCur != ilrNil) ; { ; lrp = LrpInPl(plbs->hpllr, plbs->ilrCur); ; lrp->dyl = plbs->dylChain = min(plbs->dylChain, lrp->dyl); ; lrp->ilrNextChain = ilrNil; ; } ;Assembler note: we know at this point that plbs->ilrCur != ilrNil ;LN_LrpInPlCur performs LrpInPl(plbs->hpllr, plbs->ilrCur) with ;the result in es:bx or es:ax. It assumes plbs is passed in si. ;ax, bx, cx, dx are altered. call LN_LrpInPlCur mov cx,es:[bx.dylLr] cmp cx,[si.dylChainLbs] jle FALr24 mov cx,[si.dylChainLbs] FALr24: mov [si.dylChainLbs],cx mov es:[bx.dylLr],cx mov es:[bx.ilrNextChainLr],ilrNil FALr25: ; for (ilr = plbs->ilrFirstChain; ; ilr = lrp->ilrNextChain) ; { ; lrp = LrpInPl(plbs->hpllr, ilr); ; lrp->dyl = plbs->dylChain; ; if (ilr == plbs->ilrCurChain) ; { mov cx,[si.ilrFirstChainLbs] jmp short FALr27 FALr26: mov cx,es:[bx.ilrNextChainLr] FALr27: ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl mov ax,[si.dylChainLbs] mov es:[bx.dylLr],ax cmp cx,[si.ilrCurChainLbs] jne FALr26 ; /* next-to-last entry, chain in last */ ; lrp->ilrNextChain = plbs->ilrCur; ; break; ; } ; } ; plbs->ilrCurChain = plbs->ilrCur = plbs->ilrFirstChain; mov ax,[si.ilrFirstChainLbs] mov [si.ilrCurChainLbs],ax xchg ax,[si.ilrCurLbs] mov es:[bx.ilrNextChainLr],ax ; } ; } ; plbs->dylOverlap = dylOverlapNew; ; StopProfile(); ; return(fTrue); FALr28: mov ax,[dylOverlapNew] FALr285: stc FALr29: mov [si.dylOverlapLbs],ax sbb ax,ax ;} cEnd ;FALr30 returns (lrp->doc == plbs->doc && lrp->ihdt == plbs->ihdt) ;as zero flag set if true, zero flag reset if false. ;lrp is assumed in es:bx, plbs is assumed in si. ;Only ax is altered. FALr30: mov ax,es:[bx.docLr] cmp ax,[si.docLbs] jne FALr31 mov ax,es:[bx.ihdtLr] cmp ax,[si.ihdtLbs] FALr31: ret ;Assert (ilr < ilrMac); ifdef DEBUG FALr32: cmp cx,[ilrMac] jl FALr33 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1047 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FALr33: ret endif ;DEBUG ;------------------------------------------------------------------------- ; FWidowControl(plbs, plbsNew, dylFill, fEmptyOK) ;------------------------------------------------------------------------- ;/* F W i d o w C o n t r o l */ ;NATIVE int FWidowControl(plbs, plbsNew, dylFill, fEmptyOK) ;struct LBS *plbs, *plbsNew; ;int dylFill, fEmptyOK; ;{ ;/* enforce widow/orphan control; returns fFalse if new paragraph should be ; rejected entirely */ ; LRP lrp = LrpInPl(plbsNew->hpllr, plbsNew->ilrCur); ; int doc = plbs->doc; ; int ilnhMac; ; int fOutline = plbs->fOutline; ; CP cp = plbs->cp; ; int cl = plbs->cl; ; CP cpNew = plbsNew->cp; ; int clNew = plbsNew->cl; ; int dxl, dxa; ; struct PHE phe; ; struct LBS lbsT; ; %%Function:N_FWidowControl %%Owner:BRADV cProc N_FWidowControl,<PUBLIC,FAR>,<si,di> ParmW <plbs> ParmW <plbsNew> ParmW <dylFill> ParmW <fEmptyOK> LocalW clNew OFFBP_clNew = -2 LocalD cpNew OFFBP_cpNew = -6 LocalW dxl LocalW dxa LocalV phe, cbPheMin LocalV lbsT, cbLbsMin cBegin ; StartProfile(); mov si,[plbsNew] push ds pop es add si,(cpLbs) lea di,[cpNew] movsw movsw errnz <OFFBP_clNew - OFFBP_cpNew - 4> errnz <(clLbs) - (cpLbs) - 4> movsw ; Assert(cpNew >= cp); ifdef DEBUG push ax push bx push cx push dx mov bx,[plbs] mov ax,[OFF_cpNew] mov dx,[SEG_cpNew] sub ax,[bx.LO_cpLbs] sbb dx,[bx.HI_cpLbs] jge FWC005 mov ax,midLayout2n mov bx,1030 cCall AssertProcForNative,<ax,bx> FWC005: pop dx pop cx pop bx pop ax endif ;DEBUG sub si,(clLbs) + 2 ;LN_LrpInPlCur performs LrpInPl(plbs->hpllr, plbs->ilrCur) with ;the result in es:bx or es:ax. It assumes plbs is passed in si. ;ax, bx, cx, dx are altered. call LN_LrpInPlCur ; Assert(lrp->lrk != lrkAbs); ifdef DEBUG cmp es:[bx.lrkLr],lrkAbs jne FWC01 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1007 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FWC01: endif ;DEBUG ; if (lrp->lrk != lrkNormal && cl != 0) ; { ; cp = plbs->cp = CpFromCpCl(plbs, fTrue); ; cl = plbs->cl = 0; ; } push es:[bx.dxlLr] ;save lrp->dxl mov si,[plbs] xor ax,ax errnz <lrkNormal - 0> cmp es:[bx.lrkLr],al je FWC015 cmp [si.clLbs],ax je FWC015 mov [si.clLbs],ax errnz <fTrue - 1> inc ax cCall CpFromCpCl,<si, ax> mov [si.LO_cpLbs],ax mov [si.HI_cpLbs],dx FWC015: ;/* start of para, check for widow; handles 1-line para case */ ; CacheParaL(doc, cpNew, fOutline); ;LN_CacheParaLbsCp takes plbs in si ;and performs CacheParaL(plbs->doc, dx:ax, plbs->fOutline). ;ax, bx, cx, dx are altered. mov ax,[OFF_cpNew] mov dx,[SEG_cpNew] call LN_CacheParaLbsCp ; if (cp < caParaL.cpFirst) ; goto LEndWidow; /* cpNew is the beginning of a new paragraph */ mov ax,[si.LO_cpLbs] mov dx,[si.HI_cpLbs] sub ax,[caParaL.LO_cpFirstCa] sbb dx,[caParaL.HI_cpFirstCa] pop ax ;restore lrp->dxl jl Ltemp028 ; Assert(FInCa(doc, cp, &caParaL)); ifdef DEBUG ;Assert this with a call so as not to mess up short jumps. call FWC10 endif ;DEBUG ; dxa = XaFromXl(dxl = lrp->dxl); mov [dxl],ax ;LN_XaFromXl performs XaFromXl(ax); ax, bx, cx, dx are altered. call LN_XaFromXl mov [dxa],ax ; /* make sure a single line is not stranded at the bottom (orphan)*/ ; if (cp == caParaL.cpFirst && cl == 0) ; { mov ax,[si.LO_cpLbs] mov dx,[si.HI_cpLbs] cmp ax,[caParaL.LO_cpFirstCa] jne FWC04 cmp dx,[caParaL.HI_cpFirstCa] jne FWC04 cmp [si.clLbs],0 jne FWC04 ; if (cpNew == cp && clNew == 1) ; goto LAvoidOrphan; mov cx,[clNew] dec cx jne FWC02 cmp [OFF_cpNew],ax jne FWC02 cmp [SEG_cpNew],dx je LAvoidOrphan FWC02: ; if (clNew == 0) ; { inc cx jne FWC04 ; /* we don't have a cl: format the lines */ ; ClFormatLines(plbs, cpMax, ylLarge, ylLarge, 2, ; dxl, fFalse, fFalse); errnz <LO_cpMax - 0FFFFh> errnz <HI_cpMax - 07FFFh> mov ax,LO_cpMax mov dx,HI_cpMax mov cx,2 errnz <fFalse> xor bx,bx ;FWC09 performs ClFormatLines(si, dx:ax, ylLarge, ylLarge, cx, ; dxl, bx, fFalse); ;ax, bx, cx, dx are altered. call FWC09 ; if (IInPlcCheck(vfls.hplclnh, cpNew) == 1) ; { push [vfls.hplclnhFls] push [SEG_cpNew] push [OFF_cpNew] cCall IInPlcCheck,<> dec ax jne FWC04 ;LAvoidOrphan: ; StopProfile(); ; return (!fEmptyOK); ; } ; } ; } LAvoidOrphan: errnz <fFalse> xor ax,ax cmp [fEmptyOK],ax jne FWC03 errnz <fTrue - fFalse - 1> inc ax FWC03: jmp FWC08 Ltemp028: jmp LEndWidow FWC04: ;/* Now check for last line being cut off in lbsNew */ ; if (clNew == 0) ; { ;LClFormatLines: mov ax,[OFF_cpNew] mov dx,[SEG_cpNew] cmp [clNew],0 jne FWC05 LClFormatLines: push [vfls.hplclnhFls] ;argument for IInPlc push dx ;argument for IInPlc push ax ;argument for IInPlc ; /* we don't have a cl: format the lines */ ; ClFormatLines(plbs, cpNew, ylLarge, ylLarge, clMax, ; dxl, fTrue, fFalse); mov cx,clMax mov bx,fTrue ;FWC09 performs ClFormatLines(si, dx:ax, ylLarge, ylLarge, cx, ; dxl, bx, fFalse); ;ax, bx, cx, dx are altered. call FWC09 ; clNew = IInPlc(vfls.hplclnh, cpNew); cCall IInPlc,<> xchg ax,di ; ilnhMac = IMacPlc(vfls.hplclnh); mov bx,[vfls.hplclnhFls] ;***Begin in line IMacPlc mov bx,[bx] mov ax,[bx.iMacPlcStr] ;***End in line IMacPlc ; if (CpPlc(vfls.hplclnh, ilnhMac) >= vfls.ca.cpLim) ; { xchg ax,cx push cx ;save ilnhMac ;LN_CpPlc performs CpPlc(vfls.hplclnh, cx) ;ax, bx, cx, dx are altered. call LN_CpPlc pop cx ;restore ilnhMac sub ax,[vfls.caFls.LO_cpLimCa] sbb dx,[vfls.caFls.HI_cpLimCa] jl Ltemp009 ; /* check for 4 lines is still necessary in unusual ; circumstances (very tall lines) */ ; if (ilnhMac < 4) ; /* no way to avoid widow in 2 or 3 lines */ ; goto LAvoidOrphan; cmp cx,4 Ltemp006: jb LAvoidOrphan ; if (clNew == ilnhMac - 1) ; { dec cx cmp di,cx jne Ltemp009 ; /* back up a line unless this would violate fEmptyOK */ ; if (fEmptyOK || cl > 0 || CpPlc(vfls.hplclnh, clNew - 1) > cp) ; goto LHaveWidow; cmp [fEmptyOK],fFalse jne LHaveWidow cmp [si.clLbs],0 jg LHaveWidow ;LN_CpPlc performs CpPlc(vfls.hplclnh, cx) ;ax, bx, cx, dx are altered. mov cx,di dec cx call LN_CpPlc cmp [si.LO_cpLbs],ax mov ax,[si.HI_cpLbs] sbb ax,dx jl LHaveWidow ; } ; } ; } Ltemp009: jmp short LEndWidow ; else ; { /* clNew > 0 */ ; CacheParaL(doc, cpNew, fOutline); FWC05: lea bx,[phe] push [si.docLbs] ;argument for FGetValidPhe push dx ;argument for FGetValidPhe push ax ;argument for FGetValidPhe push bx ;argument for FGetValidPhe ;LN_CacheParaLbsCp takes plbs in si ;and performs CacheParaL(plbs->doc, dx:ax, plbs->fOutline). ;ax, bx, cx, dx are altered. call LN_CacheParaLbsCp ; if (!FGetValidPhe(doc, cpNew, &phe) || phe.fDiffLines || ; phe.dxaCol != dxa || phe.dylHeight == 0) ; { cCall FGetValidPhe,<> or ax,ax je FWC06 test [phe.fDiffLinesPhe],maskfDiffLinesPhe jne FWC06 mov ax,[dxa] cmp [phe.dxaColPhe],ax jne FWC06 cmp [phe.dylHeightPhe],0 jne FWC07 FWC06: ; /* This is rare: the phe ended up getting zeroed somehow */ ; Assert(!phe.fDiffLines && phe.dylHeight == 0); ifdef DEBUG ;Assert this with a call so as not to mess up short jumps. call FWC12 endif ;DEBUG ; cpNew = CpFromCpCl(plbsNew, fTrue); ; clNew = 0; ; goto LClFormatLines; ; } xor ax,ax mov [clNew],ax errnz <fTrue - 1> inc ax cCall CpFromCpCl,<[plbsNew], ax> jmp LClFormatLines FWC07: ; Assert(phe.clMac >= clNew); ifdef DEBUG ;Assert this with a call so as not to mess up short jumps. call FWC15 endif ;DEBUG ; if (phe.clMac < 4) ; /* no way to avoid widow in 2 or 3 lines */ ; goto LAvoidOrphan; mov al,[phe.clMacPhe] cmp al,4 jb Ltemp006 ; if (phe.clMac == clNew + 1) ; { xor ah,ah mov di,[clNew] sub ax,di dec ax jne LEndWidow ; /* note that rolling back the cl's is not enough: ; LbcFormatPara has other side effects such as ; advancing the yl, lnn, etc. */ ; /* stranded line */ ;LHaveWidow: ; PushLbs(plbs, &lbsT); ; CopyLbs(&lbsT, plbsNew); ; FAssignLr(plbsNew, dylFill, fFalse); ; LbcFormatPara(plbsNew, dylFill, clNew - 1); LHaveWidow: ;expect di = clNew mov ax,[plbsNew] lea bx,[lbsT] mov cx,[dylFill] errnz <fFalse> xor dx,dx dec di push ax ;argument for LbcFormatPara push cx ;argument for LbcFormatPara push di ;argument for LbcFormatPara push ax ;argument for FAssignLr push cx ;argument for FAssignLr push dx ;argument for FAssignLr push bx ;argument for CopyLbs push ax ;argument for CopyLbs push si push bx ifdef DEBUG cCall S_PushLbs,<> else ;!DEBUG push cs call near ptr N_PushLbs endif ;!DEBUG ifdef DEBUG cCall S_CopyLbs,<> else ;!DEBUG push cs call near ptr N_CopyLbs endif ;!DEBUG ifdef DEBUG cCall S_FAssignLr,<> else ;!DEBUG push cs call near ptr N_FAssignLr endif ;!DEBUG ifdef DEBUG cCall S_LbcFormatPara,<> else ;!DEBUG push cs call near ptr N_LbcFormatPara endif ;!DEBUG ; } ; } ;LEndWidow: LEndWidow: ; StopProfile(); ; return(fTrue); mov ax,fTrue FWC08: ;} cEnd ;FWC09 performs ClFormatLines(si, dx:ax, ylLarge, ylLarge, cx, ; dxl, bx, fFalse); ;ax, bx, cx, dx are altered. FWC09: push si push dx push ax mov ax,ylLarge push ax push ax push cx push [dxl] errnz <ylLarge - 03FFFh> errnz <fFalse> cwd push bx push dx ifdef DEBUG cCall S_ClFormatLines,<> else ;!DEBUG push cs call near ptr N_ClFormatLines endif ;!DEBUG ret ; Assert(FInCa(doc, cp, &caParaL)); ifdef DEBUG FWC10: push ax push bx push cx push dx push [si.docLbs] push [si.HI_cpLbs] push [si.LO_cpLbs] mov ax,dataoffset [caParaL] push ax cCall FInCa,<> or ax,ax jne FWC11 mov ax,midLayout2n mov bx,1049 cCall AssertProcForNative,<ax,bx> FWC11: pop dx pop cx pop bx pop ax ret endif ;DEBUG ; Assert(!phe.fDiffLines && phe.dylHeight == 0); ifdef DEBUG FWC12: push ax push bx push cx push dx test [phe.fDiffLinesPhe],maskfDiffLinesPhe jne FWC13 cmp [phe.dylHeightPhe],0 je FWC14 FWC13: mov ax,midLayout2n mov bx,1050 cCall AssertProcForNative,<ax,bx> FWC14: pop dx pop cx pop bx pop ax ret endif ;DEBUG ; Assert(phe.clMac >= clNew); ifdef DEBUG FWC15: push ax push bx push cx push dx mov al,[phe.clMacPhe] xor ah,ah cmp ax,[clNew] jge FWC16 mov ax,midLayout2n mov bx,1051 cCall AssertProcForNative,<ax,bx> FWC16: pop dx pop cx pop bx pop ax ret endif ;DEBUG ; Assert(lrp->cpLim == plbsNew->cp && lrp->clLim == plbsNew->cl); ifdef DEBUG FWC17: push ax push bx push cx push dx mov ax,[si.LO_cpLbs] cmp ax,es:[bx.LO_cpLimLr] jne FWC18 mov ax,[si.HI_cpLbs] cmp ax,es:[bx.HI_cpLimLr] jne FWC18 mov ax,[si.clLbs] cmp ax,es:[bx.clLimLr] je FWC19 FWC18: mov ax,midLayout2n mov bx,1052 cCall AssertProcForNative,<ax,bx> FWC19: pop dx pop cx pop bx pop ax ret endif ;DEBUG ;------------------------------------------------------------------------- ; IfrdGatherFtnRef(plbs, plbsNew, ifrd, fNormal, ylReject, ylAccept) ;------------------------------------------------------------------------- ;/* I f r d G a t h e r F t n R e f */ ;NATIVE int IfrdGatherFtnRef(plbs, plbsNew, ifrd, fNormal, ylReject, ylAccept) ;struct LBS *plbs, *plbsNew; ;int ifrd, fNormal, ylReject, ylAccept; ;{ ; struct DOD *pdod; ; int ifrl; ; struct PLC **hplcfrd; ; CP cpLimFnd, cpRef, cpMac = CpMacDocPlbs(plbs); ; LRP lrp; ; struct FRL frlNew; ; %%Function:N_IfrdGatherFtnRef %%Owner:BRADV cProc N_IfrdGatherFtnRef,<PUBLIC,FAR>,<si,di> ParmW <plbs> ParmW <plbsNew> ParmW <ifrd> ParmW <fNormal> ParmW <ylReject> ParmW <ylAccept> LocalD cpLimFnd LocalV frlNew, cbFrlMin cBegin mov si,[plbs] ; StartProfile(); ; cpLimFnd = CpFromCpCl(plbsNew, fTrue); mov ax,fTrue cCall CpFromCpCl,<[plbsNew], ax> mov [OFF_cpLimFnd],ax mov [SEG_cpLimFnd],dx ;LN_CpMacDocPlbs performs CpMacDocPlbs(si). ;ax, bx, cx, dx are altered. call LN_CpMacDocPlbs ; if ((frlNew.fNormal = fNormal) != fFalse) mov di,[ylReject] mov bx,[ylAccept] mov cx,[fNormal] jcxz IGFR01 ; if (plbs->cp >= cpMac) ; { ; ylReject = ylAccept = 1; ; frlNew.fNormal = fFalse; ; } ; else ; { ; lrp = LrpInPl(plbsNew->hpllr, plbsNew->ilrCur); ; ylReject = max(plbs->yl, lrp->yl); ; ylAccept = plbsNew->yl; ; } mov di,1 mov bx,di xor cx,cx cmp [si.LO_cpLbs],ax mov ax,[si.HI_cpLbs] sbb ax,dx jge IGFR01 push si ;save plbs ;LN_LrpInPlCur performs LrpInPl(plbs->hpllr, plbs->ilrCur) with ;the result in es:bx or es:ax. It assumes plbs is passed in si. ;ax, bx, cx, dx are altered. mov si,[plbsNew] call LN_LrpInPlCur mov di,es:[bx.ylLr] mov bx,[si.ylLbs] pop si ;restore plbs mov cx,[fNormal] cmp di,[si.ylLbs] jge IGFR01 mov di,[si.ylLbs] ; frlNew.ylReject = ylReject; ; frlNew.ylAccept = ylAccept; IGFR01: mov [frlNew.fNormalFrl],cl mov [frlNew.ylRejectFrl],di mov [frlNew.ylAcceptFrl],bx ;/* all refs between cp of lbs and lbsNew */ ; pdod = PdodDoc(plbs->doc); /* two lines for compiler */ mov bx,[si.docLbs] ;Takes doc in bx, result in bx. Only bx is altered. call LN_PdodDocL ; hplcfrd = pdod->hplcfrd; mov di,[bx.hplcfrdDod] ; for (ifrl = IMacPlc(vhplcfrl); (cpRef = CpPlc(hplcfrd, ifrd)) < cpLimFnd; ifrd++) ; { ;***Begin in line IMacPlc mov bx,[vhplcfrl] mov bx,[bx] mov cx,[bx.iMacPlcStr] ;***End in line IMacPlc mov si,[ifrd] dec si ;adjust for for loop IGFR02: inc si push cx ;save ifrl cCall CpPlc,<di, si> pop cx ;restore ifrl cmp ax,[OFF_cpLimFnd] mov bx,dx sbb bx,[SEG_cpLimFnd] jge IGFR04 ; frlNew.ifnd = ifrd; mov [frlNew.ifndFrl],si ; if (!FInsertInPlc(vhplcfrl, ifrl++, cpRef, &frlNew)) ; { push cx ;save ifrl lea bx,[frlNew] ifdef DEBUG cCall S_FInsertInPlc,<[vhplcfrl], cx, dx, ax, bx> else ;not DEBUG cCall N_FInsertInPlc,<[vhplcfrl], cx, dx, ax, bx> endif ;DEBUG pop cx ;restore ifrl inc cx or ax,ax jne IGFR02 ; Assert(vfInFormatPage); ifdef DEBUG cmp [vfInFormatPage],fFalse jne IGFR03 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1008 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax IGFR03: endif ;DEBUG ; AbortLayout(); cCall AbortLayout,<> ; } ; } IGFR04: ; StopProfile(); ; return(ifrd); xchg ax,si ;} cEnd ;------------------------------------------------------------------------- ; FGetFtnBreak(plbs, ifrl, pfrl, fpc) ;------------------------------------------------------------------------- ;/* F G e t F t n B r e a k */ ;NATIVE FGetFtnBreak(plbs, ifrl, pfrl, fpc) ;struct LBS *plbs; ;int ifrl; /* negative when we're recursing; ifrl = abs(ifrl) */ ;struct FRL *pfrl; ;int fpc; ;{ ;/* call ClFormatLines to determine what line contains a footnote reference, ; set frl accordingly; returns fFalse if no better information available */ ; int ilr, ilrMac = IMacPllr(plbs), ilrBest = -1; ; LRP lrp; ; int fWidow, ilnhMac; ; struct PLC **hplclnh = vfls.hplclnh; ; int cl, clFirst, clRef; ; YLL dyllPrevCol; ; int ylAccept, ylReject; ; CP cpRef, dcp, dcpBest = cpMax; ; CP cpLim; ; struct DOD *pdod; ; struct PLC **hplcfrd; ; struct LNH lnh; ; struct LR lr; ; struct FRL frl, frlT; ; struct LBS lbsT; ; %%Function:N_FGetFtnBreak %%Owner:BRADV cProc N_FGetFtnBreak,<PUBLIC,FAR>,<si,di> ParmW <plbs> ParmW <ifrl> ParmW <pfrl> ParmW <fpc> LocalW ilrMac LocalW ilrBest LocalW fWidow LocalW clFirst LocalW hplcfrd LocalW clRef LocalD cpRef LocalD dcpBest LocalD dyllPrevCol LocalV frl, cbFrlMin LocalV lnh, cbLnhMin LocalV lr, cbLrMin LocalV lbsT, cbLbsMin LocalV frlT, cbFrlMin cBegin mov si,[plbs] ;LN_IMacPllr performs cx = IMacPllr(plbs). plbs is assumed to be ;passed in si. Only bx and cx are altered. call LN_IMacPllr mov [ilrMac],cx errnz <LO_cpMax - 0FFFFh> errnz <HI_cpMax - 07FFFh> mov ax,HI_cpMax mov [SEG_dcpBest],ax cbw mov [OFF_dcpBest],ax mov [ilrBest],ax ;/* find the lr containing the reference */ ; StartProfile(); ; if (fpc == fpcEndnote || fpc == fpcEndDoc) ; goto LNoInfo; /* endnotes -- essentially no reference */ mov al,bptr ([fpc]) cmp al,fpcEndNote je Ltemp012 cmp al,fpcEndDoc je Ltemp012 ; if (fRecurse = (ifrl < 0)) ; ifrl = -ifrl; ; cpRef = CpPlc(vhplcfrl, ifrl); mov ax,[ifrl] ;Not negative, just high bit toggled in .asm and ah,07Fh cCall CpPlc,<[vhplcfrl],ax> mov [OFF_cpRef],ax mov [SEG_cpRef],dx ; for (lrp = LrpInPl(plbs->hpllr, ilr = 0); ilr < ilrMac; lrp++, ilr++) ; { xor cx,cx FGFB01: ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl jmp short FGFB03 Ltemp012: jmp FGFB17 FGFB02: inc cx add bx,cbLrMin FGFB03: cmp cx,[ilrMac] jge FGFB04 ; if (lrp->doc != plbs->doc || cpRef < lrp->cp) ; continue; mov ax,[si.docLbs] cmp ax,es:[bx.docLr] jne FGFB02 mov ax,[OFF_cpRef] mov dx,[SEG_cpRef] sub ax,es:[bx.LO_cpLr] sbb dx,es:[bx.HI_cpLr] jl FGFB02 push dx push ax ;save cpRef - lrp->cp ; cpLim = lrp->cpLim; ; if (lrp->clLim != 0) ; { mov ax,es:[bx.LO_cpLimLr] mov dx,es:[bx.HI_cpLimLr] cmp es:[bx.clLimLr],0 push dx push ax ;save cpLim je FGFB035 ; lbsT = *plbs; push cx ;save ilr push es:[bx.clLimLr] push si ;save plbs push ds pop es lea di,[lbsT] errnz <cbLbsMin AND 1> mov cx,cbLbsMin SHR 1 rep movsw pop si ;restore plbs ; lbsT.cp = cpLim; ; lbsT.cl = lrp->clLim; ; cpLim = CpFromCpCl(&lbsT, fTrue); sub di,cbLbsMin mov [di.LO_cpLbs],ax mov [di.HI_cpLbs],dx pop [di.clLbs] mov ax,fTrue cCall CpFromCpCl,<di,ax> pop cx ;restore ilr ; lrp = LrpInPl(plbs->hpllr, ilr); ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl ; } ; if (cpRef >= cpLim) ; continue; FGFB035: pop ax pop dx ;restore cpLim cmp [OFF_cpRef],ax mov ax,[SEG_cpRef] sbb ax,dx pop ax pop dx ;restore cpRef - lrp->cp jge FGFB02 ; if ((dcp = cpRef - lrp->cp) < dcpBest) ; { cmp ax,[OFF_dcpBest] mov di,dx sbb di,[SEG_dcpBest] jge FGFB02 ; ilrBest = ilr; ; dcpBest = dcp; mov [ilrBest],cx mov [OFF_dcpBest],ax mov [SEG_dcpBest],dx ; } jmp FGFB02 Ltemp010: jmp FGFB17 FGFB04: ; Assert(ilrBest != -1); ifdef DEBUG cmp [ilrBest],-1 jne FGFB05 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1009 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax FGFB05: endif ;DEBUG ; if (ilrBest == -1) ; goto LNoInfo; mov cx,[ilrBest] cmp cx,-1 je Ltemp010 ; lrp = LrpInPl(plbs->hpllr, ilrBest); ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl xchg si,ax ;save plbs ; if (lrp->lrk == lrkAbs) ; goto LNoInfo; cmp es:[si.lrkLr],lrkAbs je Ltemp010 ; lr = *lrp; push es pop ds push ss pop es lea di,[lr] errnz <cbLrMin AND 1> mov cx,cbLrMin SHR 1 rep movsw push ss pop ds ;/* set up LBS */ ; lbsT = *plbs; xchg ax,si lea di,[lbsT] errnz <cbLbsMin AND 1> mov cx,cbLbsMin SHR 1 rep movsw ; lbsT.cp = cpRef; lea si,[cpRef] sub di,cbLbsMin - (cpLbs) movsw movsw ; CacheParaL(lbsT.doc, lbsT.cp, lbsT.fOutline); ; /* find cp/cl at which to start formatting */ lea si,[di - (cpLbs) - 4] ;LN_CacheParaLbs takes plbs in si ;and performs CacheParaL(plbs->doc, plbs->cp, plbs->fOutline). ;ax, bx, cx, dx are altered. call LN_CacheParaLbs ; if (lr.cp >= caParaL.cpFirst) ; { ; lbsT.cp = lr.cp; ; lbsT.cl = lr.clFirst; ; } ; else ; { ; lbsT.cp = caParaL.cpFirst; ; lbsT.cl = 0; ; } mov ax,[lr.LO_cpLr] mov dx,[lr.HI_cpLr] mov cx,[lr.clFirstLr] cmp ax,[caParaL.LO_cpFirstCa] mov bx,dx sbb bx,[caParaL.HI_cpFirstCa] jge FGFB055 mov ax,[caParaL.LO_cpFirstCa] mov dx,[caParaL.HI_cpFirstCa] xor cx,cx FGFB055: mov [si.LO_cpLbs],ax mov [si.HI_cpLbs],dx mov [si.clLbs],cx ; GetPlc(vhplcfrl, ifrl, &frl); /* NOT the same as *pfrl */ mov ax,[ifrl] and ah,07Fh ;Not negative, just high bit toggled in .asm lea bx,[frl] cCall GetPlc,<[vhplcfrl], ax, bx> ; lbsT.yl = frl.ylReject; mov ax,[frl.ylRejectFrl] mov [si.ylLbs],ax ;/* calculate above/below based on line with ref; to do widow control we ; need entire para */ ; pdod = PdodDoc(lbsT.doc); mov bx,[si.docLbs] ;Takes doc in bx, result in bx. Only bx is altered. call LN_PdodDocL ; fWidow = pdod->dop.fWidowControl; mov al,[bx.dopDod.fWidowControlDop] mov bptr ([fWidow]),al ; hplcfrd = pdod->hplcfrd; mov cx,[bx.hplcfrdDod] mov [hplcfrd],cx ; ClFormatLines(&lbsT, (fWidow) ? caParaL.cpLim : cpRef, ; ylLarge, ylLarge, clMax, lr.dxl, !fWidow, fFalse); xor cx,cx push si test al,maskfWidowControlDop je FGFB06 push [caParaL.HI_cpLimCa] push [caParaL.LO_cpLimCa] jmp short FGFB07 FGFB06: inc cx push [SEG_cpRef] push [OFF_cpRef] FGFB07: errnz <ylLarge - 03FFFh> errnz <clMax - 07FFFh> mov ax,ylLarge push ax push ax mov ah,clMax SHR 8 push ax push [lr.dxlLr] push cx errnz <fFalse> xor ax,ax push ax ifdef DEBUG cCall S_ClFormatLines,<> else ;!DEBUG push cs call near ptr N_ClFormatLines endif ;!DEBUG ; Assert(IMacPlc(hplclnh) != 0); ; Assert(cpRef < CpPlc(hplclnh, IMacPlc(hplclnh))); ifdef DEBUG push ax push bx push cx push dx ;***Begin in line IMacPlc mov bx,[vfls.hplclnhFls] mov bx,[bx] mov cx,[bx.iMacPlcStr] ;***End in line IMacPlc cmp cx,0 jne FGFB08 mov ax,midLayout2n mov bx,1010 cCall AssertProcForNative,<ax,bx> FGFB08: ;LN_CpPlc performs CpPlc(vfls.hplclnh, cx) ;ax, bx, cx, dx are altered. call LN_CpPlc mov bx,[OFF_cpRef] sub bx,ax mov bx,[SEG_cpRef] sbb bx,dx jl FGFB09 mov ax,midLayout2n mov bx,1011 cCall AssertProcForNative,<ax,bx> FGFB09: pop dx pop cx pop bx pop ax endif ;DEBUG ; /* we have to adjust for lines that have already been used in a ; previous column or page */ ; if ((clFirst = lbsT.cl + IInPlc(hplclnh, lbsT.cp)) == 0) ; dyllPrevCol = (YLL)0; ; else ; { ; GetPlc(hplclnh, clFirst - 1, &lnh); ; dyllPrevCol = lnh.yll; ; } ;LN_IInPlc performs IInPlc(vfls.hplclnh, *pcp) where pcp is passed ;in bx. ax, bx, cx, dx are altered. lea bx,[si.cpLbs] call LN_IInPlc add ax,[si.clLbs] mov [clFirst],ax xchg ax,cx xor ax,ax cwd jcxz FGFB10 ;FGFB19 performs GetPlc(vfls.hplclnh, cx, &lnh) ;ax, bx, cx, dx are altered. dec cx call FGFB19 mov ax,[lnh.LO_yllLnh] mov dx,[lnh.HI_yllLnh] FGFB10: mov [OFF_dyllPrevCol],ax mov [SEG_dyllPrevCol],dx ; cl = clRef = IInPlc(hplclnh, cpRef); /* ref is on line cl + 1 */ ;LN_IInPlc performs IInPlc(vfls.hplclnh, *pcp) where pcp is passed ;in bx. ax, bx, cx, dx are altered. lea bx,[cpRef] call LN_IInPlc mov [clRef],ax xchg ax,cx ; ylReject = lbsT.yl; mov ax,[si.ylLbs] ; if (cl != clFirst && !(cl == 1 && fWidow)) ; { cmp cx,[clFirst] je FGFB13 cmp cx,1 jne FGFB11 test bptr ([fWidow]),maskfWidowControlDop jne FGFB13 FGFB11: push cx ;save cl dec cx ; GetPlc(hplclnh, cl - 1, &lnh); ;FGFB19 performs GetPlc(vfls.hplclnh, cx, &lnh) ;ax, bx, cx, dx are altered. call FGFB19 pop cx ;restore cl ; Assert(lnh.yll - dyllPrevCol < ylLarge); ifdef DEBUG push ax push bx push cx push dx mov ax,[lnh.LO_yllLnh] mov dx,[lnh.HI_yllLnh] sub ax,[OFF_dyllPrevCol] sbb dx,[SEG_dyllPrevCol] errnz <ylLarge - 03FFFh> sub ax,ylLarge sbb dx,0 jb FGFB12 mov ax,midLayout2n mov bx,1012 cCall AssertProcForNative,<ax,bx> FGFB12: pop dx pop cx pop bx pop ax endif ;DEBUG ; ylReject = (int)(lnh.yll - dyllPrevCol) + lbsT.yl; mov ax,[lnh.LO_yllLnh] sub ax,[OFF_dyllPrevCol] add ax,[si.ylLbs] ; } FGFB13: push ax ;save ylReject ; if (fWidow && CpPlc(hplclnh, ilnhMac = IMacPlc(hplclnh)) == vfls.ca.cpLim) ; { test bptr ([fWidow]),maskfWidowControlDop je FGFB14 push cx ;save cl mov bx,[vfls.hplclnhFls] push bx ;***Begin in line IMacPlc mov bx,[bx] mov di,[bx.iMacPlcStr] ;***End in line IMacPlc push di cCall CpPlc,<> pop cx ;restore cl sub ax,[vfls.caFls.LO_cpLimCa] sbb dx,[vfls.caFls.HI_cpLimCa] or ax,dx jne FGFB14 ; if (ilnhMac < 4) ; { ; /* need whole para */ ; ylAccept = frl.ylAccept; ; ylReject = frl.ylReject; ; goto LCheckFirst; ; } cmp di,4 jge FGFB133 pop ax ;restore ylReject push [frl.ylRejectFrl] mov di,[frl.ylAcceptFrl] jmp short LCheckFirst FGFB133: ; if (cl == ilnhMac - 2 || (cl == 0 && vfls.ca.cpFirst == caParaL.cpFirst)) ; cl++; /* reference in first or next-to-last line */ ; } dec di dec di cmp cx,di je FGFB137 mov ax,[caParaL.LO_cpFirstCa] mov dx,[caParaL.HI_cpFirstCa] sub ax,[vfls.caFls.LO_cpFirstCa] sbb dx,[vfls.caFls.HI_cpFirstCa] or ax,dx or ax,cx jne FGFB14 FGFB137: inc cx FGFB14: ; GetPlc(hplclnh, cl, &lnh); ;FGFB19 performs GetPlc(vfls.hplclnh, cx, &lnh) ;ax, bx, cx, dx are altered. call FGFB19 ; Assert(lnh.yll - dyllPrevCol < ylLarge); ifdef DEBUG push ax push bx push cx push dx mov ax,[lnh.LO_yllLnh] mov dx,[lnh.HI_yllLnh] sub ax,[OFF_dyllPrevCol] sbb dx,[SEG_dyllPrevCol] errnz <ylLarge - 03FFFh> sub ax,ylLarge sbb dx,0 jb FGFB15 mov ax,midLayout2n mov bx,1013 cCall AssertProcForNative,<ax,bx> FGFB15: pop dx pop cx pop bx pop ax endif ;DEBUG ; ylAccept = (int)(lnh.yll - dyllPrevCol) + lbsT.yl; mov di,[lnh.LO_yllLnh] sub di,[OFF_dyllPrevCol] add di,[si.ylLbs] ;/* if not first footnote on line, we can't reject it */ ;LCheckFirst: ; if (!fRecurse) ; if (cpRef > CpPlc(hplcfrd, 0) && ; CpPlc(hplclnh, clRef) <= CpPlc(hplcfrd, IInPlc(hplcfrd, cpRef - 1))) ; { ; ylReject = ylAccept; ; } LCheckFirst: xor bptr ([ifrl+1]),080h jns FGFB155 xor ax,ax cCall CpPlc,<[hplcfrd], ax> sub ax,[OFF_cpRef] sbb dx,[SEG_cpRef] jge FGFB155 mov ax,[OFF_cpRef] mov dx,[SEG_cpRef] sub ax,1 sbb dx,0 mov cx,[hplcfrd] push cx ;argument for CpPlc cCall IInPlc,<cx, dx, ax> push ax cCall CpPlc,<> push dx push ax ;save cp ;LN_CpPlc performs CpPlc(vfls.hplclnh, cx) ;ax, bx, cx, dx are altered. mov cx,[clRef] call LN_CpPlc pop cx sub cx,ax pop cx sbb cx,dx jge FGFB152 ; else if (ifrl > 0) ; { mov ax,[ifrl] test ax,07FFFh jz FGFB155 ; /* if reject point same as previous footnote, we can't reject it */ ; frlT = frl; ; FGetFtnBreak(plbs, -(ifrl - 1), &frlT, fpc); ; if (ylReject == frlT.ylReject) ; ylReject = ylAccept; ; } push di ;save ylAccept push [plbs] dec ax ;High bit toggled above push ax ;Not negative, just high bit toggled in .asm lea di,[frlT] push di push ds pop es lea si,[frl] errnz <cbFrlMin - 8> movsw movsw movsw movsw push [fpc] push cs call near ptr N_FGetFtnBreak pop di ;restore ylAccept pop ax ;restore ylReject push ax ;save ylReject cmp ax,[frlT.ylRejectFrl] jne FGFB155 FGFB152: pop ax ;remove old ylReject push di ;save ylReject = ylAccept FGFB155: ; if (ylAccept == frl.ylAccept && ylReject == frl.ylReject) ; { ;LNoInfo: ; StopProfile(); ; return(fFalse); ; } pop ax ;restore ylReject cmp di,[frl.ylAcceptFrl] jne FGFB16 cmp ax,[frl.ylRejectFrl] je FGFB17 FGFB16: ; pfrl->ylAccept = ylAccept; ; pfrl->ylReject = ylReject; mov bx,[pfrl] mov [bx.ylAcceptFrl],di mov [bx.ylRejectFrl],ax ; StopProfile(); ; return(fTrue); mov ax,fTrue db 03Dh ;turns next "xor ax,ax" into "cmp ax,immediate" FGFB17: xor ax,ax ;} cEnd ;FGFB19 performs GetPlc(vfls.hplclnh, cx, &lnh) ;ax, bx, cx, dx are altered. FGFB19: lea bx,[lnh] cCall GetPlc,<[vfls.hplclnhFls], cx, bx> ret ;------------------------------------------------------------------------- ; CopyHdtLrs(ihdt, plbs, yl, plbsAbs) ;------------------------------------------------------------------------- ;/* C o p y H d t L r s */ ;NATIVE CopyHdtLrs(ihdt, plbs, yl) ;int ihdt; ;struct LBS *plbs; ;int yl; ;struct LBS *plbsAbs; /* reference for abs objects */ ;{ Ltemp030: jmp CHL03 Ltemp029: jmp CHL04 ; %%Function:N_CopyHdtLrs %%Owner:BRADV cProc N_CopyHdtLrs,<PUBLIC,FAR>,<si,di> ParmW <ihdt> ParmW <plbs> ParmW <yl> ParmW <plbsAbs> LocalV lbsT,cbLbsMin cBegin ;/* copy some header LRs, if any, onto a page. Footnote separators must have ; a non-zero height to be used, but headers can be zero height if they are ; entirely composed of absolute objects */ ; int xl = -1; ; struct HDT *phdt = &vrghdt[ihdt]; ; struct LBS lbsT; ; LRP lrp; mov dx,-1 mov si,[ihdt] ; StartProfile(); ; if (phdt->hpllr == hNil) ; { ; StopProfile(); ; return; ; } errnz <cbHdtMin - 8> mov cl,3 shl si,cl add si,dataoffset [vrghdt] errnz <hNil> xor ax,ax cmp [si.hpllrHdt],ax je Ltemp029 ; if (ihdt >= ihdtMaxSep) ; { mov di,[plbs] mov cx,[yl] errnz <fFalse> cmp [ihdt],ihdtMaxSep jl Ltemp030 ; if (phdt->dyl == 0) ; { ; StopProfile(); ; return; ; } cmp [si.dylHdt],ax je Ltemp029 ; if (plbsAbs == 0 || !plbsAbs->fAbsPresent) ; xl = plbs->xl; mov dx,[di.xlLbs] mov bx,[plbsAbs] or bx,bx je CHL02 cmp [bx.fAbsPresentLbs],al je CHL02 ; else ; { ; /* get correct xl, yl by requesting an lr */ ; PushLbs(plbsAbs, &lbsT); push bx lea bx,[lbsT] push bx ifdef DEBUG cCall S_PushLbs,<> else ;!DEBUG push cs call near ptr N_PushLbs endif ;!DEBUG ; lbsT.yl = lbsT.ylColumn = yl; ; lbsT.doc = docNew; ; lbsT.ilrFirstChain = ilrNil; ; lbsT.cp = cp0; ; lbsT.cl = lbsT.dylOverlap = 0; mov [lbsT.ilrFirstChainLbs],ilrNil push di ;save plbs push ds pop es lea di,[lbsT.docLbs] mov ax,docNew stosw xor ax,ax mov [lbsT.dylOverlapLbs],ax cwd errnz <(cpLbs) - (docLbs) - 2> stosw stosw errnz <(clLbs) - (cpLbs) - 4> stosw errnz <(ylLbs) - (clLbs) - 2> mov ax,[yl] stosw pop di ;restore plbs mov [lbsT.ylColumnLbs],ax ; FAssignLr(&lbsT, phdt->dyl, fFalse); lea ax,[lbsT] push ax push [si.dylHdt] push dx ifdef DEBUG cCall S_FAssignLr,<> else ;!DEBUG push cs call near ptr N_FAssignLr endif ;!DEBUG ; xl = plbs->xl; push si ;save phdt push di ;save plbs lea ax,[lbsT] push ax ;argument for PopLbs xor bx,bx push bx ;argument for PopLbs mov si,[di.xlLbs] mov di,[yl] ; if (lbsT.ilrCur != iNil) ; { cmp [lbsT.ilrCurLbs],iNil je CHL01 ; lrp = LrpInPl(lbsT.hpllr, lbsT.ilrCur); push si ;save xl xchg ax,si ;LN_LrpInPlCur performs LrpInPl(plbs->hpllr, plbs->ilrCur) with ;the result in es:bx or es:ax. It assumes plbs is passed in si. ;ax, bx, cx, dx are altered. call LN_LrpInPlCur pop si ;restore xl ; if (lrp->dyl != 0) ; { ; xl = lrp->xl; ; yl = lrp->yl; ; } ; } cmp es:[bx.dylLr],0 je CHL005 mov si,es:[bx.xlLr] mov di,es:[bx.ylLr] CHL005: ; PopLbs(&lbsT, 0); ; } CHL01: ifdef DEBUG cCall S_PopLbs,<> else ;!DEBUG push cs call near ptr N_PopLbs endif ;!DEBUG mov dx,si mov cx,di pop di ;restore plbs pop si ;restore phdt ; plbs->dylUsedCol += phdt->dyl; CHL02: mov ax,[si.dylHdt] add [di.dylUsedColLbs],ax ; plbs->dyllTotal = phdt->dyl + plbs->dyllTotal; ; Assembler note: Assert(plbs->dyl >= 0) so we don't have to sign extend. ifdef DEBUG call CHL05 endif ;DEBUG add [di.LO_dyllTotalLbs],ax adc [di.HI_dyllTotalLbs],0 ; plbs->clTotal++; /* assume 1 line; it's indivisible */ ; } inc [di.clTotalLbs] ; CopyLrs(phdt->hpllr, plbs, (*phdt->hpllr)->ilrMac, yl, fFalse, xl); CHL03: mov bx,[si.hpllrHdt] push bx push di mov bx,[bx] push [bx.iMacPl] push cx errnz <fFalse> xor ax,ax push ax push dx ifdef DEBUG cCall S_CopyLrs,<> else ;!DEBUG push cs call near ptr N_CopyLrs endif ;!DEBUG CHL04: ; StopProfile(); ;} cEnd ; Assert(plbs->dyl >= 0); ifdef DEBUG CHL05: or ax,ax jge CHL06 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1053 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax CHL06: ret endif ;DEBUG ;------------------------------------------------------------------------- ; CopyLrs(hpllrFrom, plbsTo, ilrMac, yl, fCopyIgnore, xl) ;------------------------------------------------------------------------- ;/* C o p y L r s */ ;NATIVE CopyLrs(hpllrFrom, plbsTo, ilrMac, yl, fCopyIgnore, xl) ;struct PLLR **hpllrFrom; ;struct LBS *plbsTo; ;int ilrMac; /* number to copy */ ;int yl; /* yl for top of LRs */ ;int fCopyIgnore; ;int xl; /* use -1 to maintain xl */ ;{ ;/* copy LRs from one LR plex to another, forcing them to live at yl height */ ; int ilrFrom, ilrTo, fFirst; ; int ylFirst; ; struct LR lrT; ; %%Function:N_CopyLrs %%Owner:BRADV cProc N_CopyLrs,<PUBLIC,FAR>,<si,di> ParmW <hpllrFrom> ParmW <plbsTo> ParmW <ilrMac> ParmW <yl> ParmW <fCopyIgnore> ParmW <xl> LocalW fNotFirst LocalW ilrFrom LocalW fFirst LocalW ilrTo LocalV lrT, cbLrMin cBegin ; StartProfile(); ; if (ilrMac <= 0) ; { ; StopProfile(); ; return; ; } xor ax,ax cmp [ilrMac],ax jle Ltemp011 ; fFirst = fTrue; dec ax mov bptr ([fFirst]),al xor di,di ;initialize ylFirst ; for (ilrFrom = 0, ilrTo = IMacPllr(plbsTo); ilrFrom < ilrMac; ilrFrom++) ; { mov [ilrFrom],ax mov si,[plbsTo] ;LN_IMacPllr performs cx = IMacPllr(plbs). plbs is assumed to be ;passed in si. Only bx and cx are altered. call LN_IMacPllr mov [ilrTo],cx CL01: inc [ilrFrom] mov ax,[ilrFrom] cmp ax,[ilrMac] jge Ltemp011 ; /* have to copy: heap moves */ ; bltLrp(LrpInPl(hpllrFrom, ilrFrom), &lrT, sizeof(struct LR)); cCall HpInPl,<[hpllrFrom],ax> ifdef DEBUG ;Check es with a call so as not to mess up short jumps call CL11 endif ;/* DEBUG */ push di ;save ylFirst push es pop ds push ss pop es errnz <cbLrMin AND 1> mov cx,cbLrMin SHR 1 xchg ax,si lea di,[lrT] rep movsw xchg ax,si push ss pop ds pop di ;restore ylFirst ; if (lrT.lrs == lrsIgnore && !fCopyIgnore) ; continue; cmp [lrT.lrsLr],lrsIgnore jne CL02 mov cx,[fCopyIgnore] jcxz CL01 CL02: ; if (lrT.lrk == lrkAbs) ; { mov ax,[yl] cmp [lrT.lrkLr],lrkAbs jne CL04 ; plbsTo->fAbsPresent = fTrue; mov [si.fAbsPresentLbs],fTrue ; if (lrT.ihdt != ihdtNil && lrT.fInline && yl != ylLarge) ; { cmp [lrT.ihdtLr],ihdtNil je CL09 test [lrT.fInlineLr],maskFInlineLr je CL09 cmp ax,ylLarge je CL09 ; /* need to position inline header APO */ ; lrT.yl += yl - ((fFirst) ? 0 : ylFirst); ;Assembler note: di is not zero only if (!fFirst) sub ax,di add [lrT.ylLr],ax ; } ; } jmp short CL09 Ltemp011: jmp short CL10 ; else ; { CL04: ; if (yl != ylLarge) ; { cmp ax,ylLarge je CL06 ; /* displace to required yl */ ; if (fFirst) ; { ; ylFirst = lrT.yl; ; fFirst = fFalse; ; } xor cx,cx xchg bptr ([fFirst]),cl jcxz CL05 mov di,[lrT.ylLr] CL05: ; lrT.yl += yl - ylFirst; sub ax,di add [lrT.ylLr],ax ; plbsTo->yl = lrT.yl + lrT.dyl; mov ax,[lrT.ylLr] add ax,[lrT.dylLr] mov [si.ylLbs],ax ; } CL06: ; if (xl >= 0) ; lrT.xl = xl; mov ax,[xl] or ax,ax jl CL07 mov [lrT.xlLr],ax CL07: ; } CL09: ; ReplaceInPllr(plbsTo->hpllr, ilrTo++, &lrT); lea ax,[lrT] push [si.hpllrLbs] push [ilrTo] push ax ifdef DEBUG cCall S_ReplaceInPllr,<> else ;!DEBUG push cs call near ptr N_ReplaceInPllr endif ;!DEBUG inc [ilrTo] jmp CL01 ; } ; StopProfile(); CL10: ;} cEnd ifdef DEBUG CL11: push ax push bx push cx push dx push es ;save es from HpInPl mov bx,dx shl bx,1 mov ax,mpsbps[bx] mov es,ax shr ax,1 jc CL12 ;Assembler note: There is no way we should have to call ReloadSb here. ; reload sb trashes ax, cx, and dx ; cCall ReloadSb,<> mov ax,midLayout2n mov bx,1042 cCall AssertProcForNative,<ax,bx> CL12: pop ax ;restore es from HpInPl mov bx,es ;compare with es rederived from the SB of HpInPl cmp ax,bx je CL13 mov ax,midLayout2n mov bx,1043 cCall AssertProcForNative,<ax,bx> CL13: pop dx pop cx pop bx pop ax ret endif ;/* DEBUG */ ;------------------------------------------------------------------------- ; ReplaceInPllr(hpllr, ilr, plr) ;------------------------------------------------------------------------- ;/* R e p l a c e I n P l l r */ ;NATIVE ReplaceInPllr(hpllr, ilr, plr) ;struct PLLR **hpllr; ;int ilr; ;struct LR *plr; ;{ ; struct PLLR *ppllr = *hpllr; ; %%Function:N_ReplaceinPllr %%Owner:BRADV cProc N_ReplaceinPllr,<PUBLIC,FAR>,<si,di> ParmW <hpllr> ParmW <ilr> ParmW <plr> cBegin ; StartProfile(); ; if (ilr < ppllr->ilrMax) ; { ; ppllr->ilrMac = max(ilr + 1, ppllr->ilrMac); ; bltLrp(plr, LrpInPl(hpllr, ilr), sizeof(struct LR)); ; } mov di,[hpllr] mov si,[plr] mov ax,[ilr] mov bx,[di] cmp ax,[bx.iMaxPl] jge RIP04 push di ;argument for HpInPl push ax ;argument for HpInPl inc ax cmp [bx.iMacPl],ax jge RIP01 mov [bx.iMacPl],ax RIP01: cCall HpInPl,<> ifdef DEBUG push ax push bx push cx push dx push es ;save es from HpInPl mov bx,dx shl bx,1 mov ax,mpsbps[bx] mov es,ax shr ax,1 jc RIP02 ;Assembler note: There is no way we should have to call ReloadSb here. ; reload sb trashes ax, cx, and dx ; cCall ReloadSb,<> mov ax,midLayout2n mov bx,1044 cCall AssertProcForNative,<ax,bx> RIP02: pop ax ;restore es from HpInPl mov bx,es ;compare with es rederived from the SB of HpInPl cmp ax,bx je RIP03 mov ax,midLayout2n mov bx,1045 cCall AssertProcForNative,<ax,bx> RIP03: pop dx pop cx pop bx pop ax endif ;/* DEBUG */ xchg ax,di errnz <cbLrMin AND 1> mov cx,cbLrMin SHR 1 rep movsw jmp short RIP06 ; else if (!FInsertInPl(hpllr, ilr, plr)) ; { RIP04: cCall FInsertInPl,<di, ax, si> or ax,ax jne RIP06 ; Assert(vfInFormatPage); ifdef DEBUG push ax push bx push cx push dx cmp [vfInFormatPage],fFalse jne RIP05 mov ax,midLayout2n mov bx,1014 cCall AssertProcForNative,<ax,bx> RIP05: pop dx pop cx pop bx pop ax endif ;DEBUG ; AbortLayout(); cCall AbortLayout,<> ; } ; StopProfile(); RIP06: ;} cEnd ;------------------------------------------------------------------------- ; CacheParaL(doc, cp, fOutline) ;------------------------------------------------------------------------- ;/* C a c h e P a r a L */ ;NATIVE CacheParaL(doc, cp, fOutline) ;int doc; ;CP cp; ;int fOutline; ;{ ; %%Function:N_CacheParaL %%Owner:BRADV cProc N_CacheParaL,<PUBLIC,FAR>,<> ParmW doc ParmD cp ParmW fOutline cBegin mov bx,[doc] mov ax,[OFF_cp] mov dx,[SEG_cp] mov cx,[fOutline] call LN_CacheParaL cEnd ;End of CacheParaL ;LN_CacheParaLbs takes plbs in si ;and performs CacheParaL(plbs->doc, plbs->cp, plbs->fOutline). ;ax, bx, cx, dx are altered. ; %%Function:LN_CacheParaLbs %%Owner:BRADV PUBLIC LN_CacheParaLbs LN_CacheParaLbs: mov ax,[si.LO_cpLbs] mov dx,[si.HI_cpLbs] ;LN_CacheParaLbsCp takes plbs in si ;and performs CacheParaL(plbs->doc, dx:ax, plbs->fOutline). ;ax, bx, cx, dx are altered. LN_CacheParaLbsCp: mov cl,[si.fOutlineLbs] xor ch,ch errnz <(docLbs) - 0> mov bx,[si.docLbs] ;fall through ;LN_CacheParaL takes doc in bx, cp in dx:ax, fOutline in cx ;ax, bx, cx, dx are altered. LN_CacheParaL: push di push si ;/* cache current paragraph and, if fOutline, kill all properties that should ; not be expressed in outline mode */ ; StartProfile(); ; if (!FInCa(doc, cp, &caParaL) || caParaL.doc != caPara.doc || ; caPara.cpFirst < caParaL.cpFirst || caPara.cpLim > caParaL.cpLim) ; { ;***Begin in line FInCa ; if (pca->doc == doc) ; { ; if (pca->cpFirst <= cp && cp < pca->cpLim) ; return fTrue; ; } ; return fFalse; ;***End in line FInCa ;Refresh caParaL if push cx ;save fOutline push dx ;save HI_cp push ax ;save LO_cp mov di,bx ;save doc std xchg ax,cx mov si,dataoffset [caParaL.docCa] lodsw cmp ax,di jne CPL01 ; (caParaL.doc != doc cmp ax,[caPara.docCa] jne CPL01 ; || caParaL.doc != caPara.doc errnz <(docCa) - (HI_cpLimCa) - 2> errnz <(HI_cpLimCa) - (LO_cpLimCa) - 2> lodsw xchg bx,ax lodsw ;caParaL.cpLim in bx:ax, cp in dx:cx cmp cx,ax push dx sbb dx,bx pop dx jge CPL01 ; || cp >= caParaL.cpLim sub ax,[caPara.LO_cpLimCa] sbb bx,[caPara.HI_cpLimCa] jl CPL01 ; ||caParaL.cpLim < caPara.cpLim errnz <(LO_cpLimCa) - (HI_cpFirstCa) - 2> errnz <(HI_cpFirstCa) - (LO_cpFirstCa) - 2> lodsw xchg bx,ax lodsw ;caParaL.cpFirst in bx:ax, cp in dx:cx sub cx,ax sbb dx,bx jl CPL01 ; || cp < caParaL.cpFirst xchg ax,cx mov ax,[caPara.LO_cpFirstCa] sub ax,cx mov ax,[caPara.HI_cpFirstCa] sbb ax,bx jl CPL01 ; || caPara.cpFirst < caParaL.cpFirst) db 0A8h ;turns next "stc" into "test al,immediate" ;also clears the carry flag CPL01: stc cld pop bx ;restore LO_cp pop dx ;restore HI_cp pop cx ;restore fOutline jnc CPL02 ; int ccp; ; caParaL.doc = doc; mov [caParaL.docCa],di ; LinkDocToWw(doc, wwLayout, wwNil); ; GetCpFirstCpLimDisplayPara(wwLayout, doc, cp, &caParaL.cpFirst, &caParaL.cpLim); push cx ;save fOutline push dx ;save HI_cp push bx ;save LO_cp mov cx,wwLayout push cx ;argument for GetCpFirstCpLimDisplayPara push di ;argument for GetCpFirstCpLimDisplayPara push dx ;argument for GetCpFirstCpLimDisplayPara push bx ;argument for GetCpFirstCpLimDisplayPara mov ax,dataoffset [caParaL.cpFirstCa] push ax ;argument for GetCpFirstCpLimDisplayPara add ax,(cpLimCa) - (cpFirstCa) push ax ;argument for GetCpFirstCpLimDisplayPara errnz <wwNil> xor ax,ax cCall LinkDocToWw,<di, cx, ax> ifdef DEBUG cCall S_GetCpFirstCpLimDisplayPara,<> else cCall N_GetCpFirstCpLimDisplayPara,<> endif ;DEBUG ; /* get correct para props in vpap */ ; FetchCpPccpVisible(doc, caParaL.cpFirst, &ccp, wwLayout /* fvc */, 0 /* ffe */); ; /* now vcpFetch is first visible char after caParaL.cpFirst and ; caPara contains vcpFetch; make sure apo's or something didn't ; cause caParaL to stop short of a visible character */ ; if (vcpFetch >= caParaL.cpLim) ; CachePara(doc, caParaL.cpFirst); push ax ;make room for ccp mov bx,sp ;CPL03 pushes di and caParaL.cpFirst. Only ax is altered. call CPL03 push bx mov ax,wwLayout push ax xor ax,ax push ax ifdef DEBUG cCall S_FetchCpPccpVisible,<> else cCall N_FetchCpPccpVisible,<> endif ;DEBUG pop ax ;remove ccp from stack mov ax,wlo [vcpFetch] sub ax,[caParaL.LO_cpLimCa] mov ax,whi [vcpFetch] sbb ax,[caParaL.HI_cpLimCa] jl CPL013 ;CPL03 pushes di and caParaL.cpFirst. Only ax is altered. call CPL03 ifdef DEBUG cCall S_CachePara,<> else ;not DEBUG cCall N_CachePara,<> endif ;DEBUG CPL013: pop bx ;restore LO_cp pop dx ;restore HI_cp pop cx ;restore fOutline ; if (fOutline) ; { jcxz CPL02 ; vpapFetch.fSideBySide = vpapFetch.fKeep = ; vpapFetch.fKeepFollow = vpapFetch.fPageBreakBefore = fFalse; ; if (!vpapFetch.fInTable) ; { ; vpapFetch.brcp = brcpNone; ; vpapFetch.dyaLine = vpapFetch.dyaBefore = vpapFetch.dyaAfter = 0; ; } ; vpapFetch.dxaWidth = vpapFetch.dxaAbs = vpapFetch.dyaAbs = 0; ; vpapFetch.pc = 0; ; } push di ;save doc errnz <fFalse> errnz <brcpNone> xor ax,ax push ds pop es mov di,dataoffset [vpapFetch.fSideBySidePap] errnz <(fKeepPap) - (fSideBySidePap) - 1> errnz <(fKeepFollowPap) - (fKeepPap) - 1> errnz <(fPageBreakBeforePap) - (fKeepFollowPap) - 1> stosw stosw cmp [vpapFetch.fInTablePap],al jne CPL015 errnz <(brcpPap) - (fPageBreakBeforePap) - 2> inc di stosb mov di,dataoffset [vpapFetch.dyaLinePap] errnz <(dyaBeforePap) - (dyaLinePap) - 2> errnz <(dyaAfterPap) - (dyaBeforePap) - 2> stosw stosw stosw CPL015: mov di,dataoffset [vpapFetch.dxaAbsPap] errnz <(dyaAbsPap) - (dxaAbsPap) - 2> errnz <(dxaWidthPap) - (dyaAbsPap) - 2> stosw stosw stosw and [vpapFetch.pcPap],NOT maskPcPap pop di ;restore doc CPL02: ; } pop si pop di ;} ret ;CPL03 pushes di and caParaL.cpFirst. Only ax is altered. CPL03: pop ax push di push [caParaL.HI_cpFirstCa] push [caParaL.LO_cpFirstCa] jmp ax ;------------------------------------------------------------------------- ; CacheSectL(doc, cp, fOutline) ;------------------------------------------------------------------------- ;/* C a c h e S e c t L */ ;NATIVE CacheSectL(doc, cp, fOutline) ;int doc; ;CP cp; ;int fOutline; ;{ ; %%Function:N_CacheSectL %%Owner:BRADV cProc N_CacheSectL,<PUBLIC,FAR>,<> ParmW doc ParmD cp ParmW fOutline cBegin mov bx,[doc] mov ax,[OFF_cp] mov dx,[SEG_cp] mov cx,[fOutline] call LN_CacheSectL cEnd ;End of CacheSectL ;LN_CacheSectL takes doc in bx, cp in dx:ax, fOutline in cx ;ax, bx, cx, dx are altered. ; %%Function:LN_CacheSectL %%Owner:BRADV PUBLIC LN_CacheSectL LN_CacheSectL: ;/* cache current section and, if fOutline, kill all properties that should ; not be expressed in outline mode */ ; struct DOP *pdop; ;/* MacWord 1.05 conversions and PCWord docs can have last ; character of doc == chSect, so back off */ ; StartProfile(); ; cp = CpMin(cp, CpMacDocEditL(doc, cp)); ;#define CpMacDocEditL(doc, cp) CpMacDocEdit(doc) push cx ;save fOutline push bx ;save doc ;***Begin in line CpMacDocEdit ; return(CpMacDoc(doc) - ccpEop); ;Takes doc in bx, result in bx. Only bx is altered. call LN_PdodDocL mov cx,[bx.HI_cpMacDod] mov bx,[bx.LO_cpMacDod] sub bx,3*ccpEop sbb cx,0 ;***End in line CpMacDocEdit cmp ax,bx push dx sbb dx,cx pop dx jl CSL01 mov ax,bx mov dx,cx CSL01: pop bx ;restore doc pop cx ;restore fOutline ; if (!FInCa(doc, cp, &caSect)) ;***Begin in line FInCa ; if (pca->doc == doc) ; { ; if (pca->cpFirst <= cp && cp < pca->cpLim) ; return fTrue; ; } ; return fFalse; cmp [caSect.docCa],bx jne CSL02 cmp ax,[caSect.LO_cpFirstCa] push dx sbb dx,[caSect.HI_cpFirstCa] pop dx jl CSL02 cmp ax,[caSect.LO_cpLimCa] push dx sbb dx,[caSect.HI_cpLimCa] pop dx jl CSL03 ;***End in line FInCa CSL02: ; { ; CacheSectProc(doc, cp); push cx ;save fOutline push bx ;save doc cCall CacheSectProc,<bx, dx, ax> pop bx ;restore doc pop cx ;restore fOutline ; if (fOutline) ; { jcxz CSL03 ; vsepFetch.bkc = bkcNewPage; mov [vsepFetch.bkcSep],bkcNewPage ; vsepFetch.ccolM1 = vsepFetch.nLnnMod = ; vsepFetch.vjc = 0; xor ax,ax mov [vsepFetch.ccolM1Sep],ax mov [vsepFetch.nLnnModSep],ax mov [vsepFetch.vjcSep],al ; pdop = &PdodMother(doc)->dop; cCall N_PdodMother,<bx> xchg ax,bx ; vsepFetch.dxaColumnWidth = pdop->xaPage ; - pdop->dxaLeft - pdop->dxaRight ; - pdop->dxaGutter; mov ax,[bx.dopDod.xaPageDop] sub ax,[bx.dopDod.dxaLeftDop] sub ax,[bx.dopDod.dxaRightDop] sub ax,[bx.dopDod.dxaGutterDop] mov [vsepFetch.dxaColumnWidthSep],ax ; } ; } CSL03: ;} ret ;------------------------------------------------------------------------- ; PushLbs(plbsFrom, plbsTo) ;------------------------------------------------------------------------- ;/* P u s h L b s */ ;NATIVE PushLbs(plbsFrom, plbsTo) ;struct LBS *plbsFrom, *plbsTo; ;{ ;/* saves layout state by copying lbs and its hpllr; the lbs is copied to ; the target and to the lbs stack for memory cleanup; pop or copy will free ; the stack entry by comparing hpllr */ ; int ilbs = (*vhpllbs)->ilbsMac; ; int ilrMac; ; struct LBS lbsT; ; %%Function:N_PushLbs %%Owner:BRADV cProc N_PushLbs,<PUBLIC,FAR>,<si,di> ParmW plbsFrom ParmW plbsTo LocalW ilrMac cBegin ; StartProfile(); ; Assert(vfInFormatPage); ; Assert(plbsTo != 0 && plbsFrom != 0); ifdef DEBUG push ax push bx push cx push dx cmp [vfInFormatPage],fFalse jne PuL01 mov ax,midLayout2n mov bx,1015 cCall AssertProcForNative,<ax,bx> PuL01: cmp [plbsFrom],0 jne PuL02 mov ax,midLayout2n mov bx,1016 cCall AssertProcForNative,<ax,bx> PuL02: cmp [plbsTo],0 jne PuL03 mov ax,midLayout2n mov bx,1017 cCall AssertProcForNative,<ax,bx> PuL03: pop dx pop cx pop bx pop ax endif ;DEBUG ; ilrMac = IMacPllr(plbsFrom); mov si,[plbsFrom] ;LN_IMacPllr performs cx = IMacPllr(plbs). plbs is assumed to be ;passed in si. Only bx and cx are altered. call LN_IMacPllr mov [ilrMac],cx ; *plbsTo = *plbsFrom; mov di,[plbsTo] push di ;save plbsTo push ds pop es errnz <cbLbsMin AND 1> mov cx,cbLbsMin SHR 1 rep movsw pop si ;restore plbsTo ; if ((plbsTo->hpllr = vhpllrSpare) != hNil) ; { errnz <hNil> xor di,di xchg di,[vhpllrSpare] mov [si.hpllrLbs],di mov cx,[ilrMac] errnz <hNil> or di,di je PuL05 ; if ((*vhpllrSpare)->ilrMax < ilrMac) ; { mov bx,[di] cmp [bx.iMaxPl],cx jge PuL07 ; struct PL *ppl = *vhpllrSpare; ; HQ hq = *((HQ *)(((char *)ppl) + ppl->brgfoo)); add bx,[bx.brgfooPl] push [bx+2] push [bx] mov ax,sp ; Assert(ppl->fExternal); ifdef DEBUG call PuL10 endif ;DEBUG ; /* FChngSizePhqLcb may cause heap movement! */ ; if (!FChngSizePhqLcb(&hq, (long)((ilrMac + 1) * sizeof(struct LR)))) ; { push ax mov ax,cbLrMin inc cx mul cx push dx push ax cCall FChngSizePhqLcb,<> or ax,ax jne PuL04 ; vhpllrSpare = 0; ; goto LFreeAbort; ; } add sp,4 ;vhpllrSpare set to zero above jmp short LFreeAbort PuL04: ; ppl = *vhpllrSpare; mov bx,[di] ; *((HQ *)(((char *)ppl) + ppl->brgfoo)) = hq; ; (*vhpllrSpare)->ilrMax = ilrMac + 1; mov cx,[ilrMac] inc cx mov [bx.iMaxPl],cx add bx,[bx.brgfooPl] pop [bx] pop [bx+2] jmp short PuL07 ; } ; vhpllrSpare = hNil; ;Assembler note: vhpllrSpare is set to hNil above ; } ; else if ((plbsTo->hpllr = HpllrInit(sizeof(struct LR), max(3, ilrMac))) == hNil) ; { ;#define HpllrInit(cb, ilrMac) HplInit2(cb, cbPLBase, ilrMac, fTrue /* fExternal */) PuL05: cmp cx,3 jge PuL06 mov cx,3 PuL06: mov ax,cbLrMin mov bx,cbPLBase cCall HplInit2,<ax, bx, cx, bx> mov [si.hpllrLbs],ax errnz <hNil> or ax,ax je PuL075 ; AbortLayout(); ; } PuL07: ; if (!FInsertInPl(vhpllbs, ilbs, plbsTo)) ; { ;Assembler note: The following line is done upon entry in the C. ; int ilbs = (*vhpllbs)->ilbsMac; mov bx,[vhpllbs] push bx mov bx,[bx] push [bx.iMacPl] push si cCall FInsertInPl,<> or ax,ax jne PuL08 ;LFreeAbort: ; FreePhpl(&plbsTo->hpllr); ; AbortLayout(); ; } LFreeAbort: cCall FreeHpl,<[si.hpllrLbs]> mov [si.hpllrLbs],hNil PuL075: cCall AbortLayout,<> PuL08: ; plbsTo->fOnLbsStack = fTrue; mov [si.fOnLbsStackLbs],fTrue ; SetIMacPllr(plbsTo, ilrMac); ;#define SetIMacPllr(plbs, i) ((*(plbs)->hpllr)->ilrMac = i) mov bx,[si.hpllrLbs] mov bx,[bx] mov ax,[ilrMac] mov [bx.iMacPl],ax ; if (ilrMac > 0) ; { or ax,ax jle PuL09 ; bltLrp(LrpInPl(plbsFrom->hpllr, 0), LrpInPl(plbsTo->hpllr, 0), ; ilrMac * sizeof(struct LR)); errnz <cbLrMin AND 1> mov dx,cbLrMin SHR 1 mul dx push ax ; It is possible that the call later on to ReloadSb for hpllrTo ; would force out the sb for hpllrFrom. This would happen if now ; sbFrom was oldest on the LRU list but still swapped in, and sbTo ; was swapped out. In that event ReloadSb would not be called for ; sbFrom, the LRU entry would not get updated, and the call to ReloadSb ; for sbTo would swap out sbFrom. ; This call to LN_LrpInPl makes that state impossible and so works ; around the LMEM quirk. xor cx,cx mov di,[plbsFrom] ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl xchg si,di ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl push es push ax xchg si,di ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. call LN_LrpInPl xchg ax,di pop si pop ds pop cx rep movsw push ss pop ds ; } PuL09: ; StopProfile(); ;} cEnd ; Assert(ppl->fExternal); ifdef DEBUG PuL10: push ax push bx push cx push dx mov bx,[di] cmp [bx.fExternalPl],fFalse jne PuL11 mov ax,midLayout2n mov bx,1018 cCall AssertProcForNative,<ax,bx> PuL11: pop dx pop cx pop bx pop ax ret endif ;DEBUG ;------------------------------------------------------------------------- ; PopLbs(plbsId, plbsTo) ;------------------------------------------------------------------------- ;/* P o p L b s */ ;NATIVE int PopLbs(plbsId, plbsTo) ;struct LBS *plbsId, *plbsTo; ;{ ;/* removes the entries above the one whose hpllr matches plbsId's; copies ; the matching stack entry to plbsTo if not zero; pass zero for plbsId to ; free all of lbs stack */ ; int ilbsTop; ; struct LBS *plbsTop; ; struct LBS lbsT; ; %%Function:N_PopLbs %%Owner:BRADV cProc N_PopLbs,<PUBLIC,FAR>,<si,di> ParmW plbsId ParmW plbsTo LocalW ilrMac LocalV lbsT, cbLbsMin cBegin ; StartProfile(); ; if (vhpllbs == hNil) ; { ; Assert(plbsId == 0 && plbsTo == 0); ; StopProfile(); ; return; ; } mov si,[vhpllbs] errnz <hNil> or si,si ifdef DEBUG jne PoL03 cmp [plbsId],0 je PoL01 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1019 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax PoL01: cmp [plbsTo],0 je PoL02 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1020 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax PoL02: jmp short PoL12 PoL03: else ;!DEBUG je PoL12 endif ;!DEBUG ; if (plbsId == 0) ; (plbsId = &lbsT)->hpllr = hNil; xor ax,ax cmp [plbsId],ax jne PoL04 lea bx,[lbsT] mov [plbsId],bx errnz <hNil> mov [lbsT.hpllrLbs],ax PoL04: ;/* free hpllr from target lbs */ ; if (plbsTo != 0) ; CopyLbs(0, plbsTo); cmp [plbsTo],ax je PoL05 push ax push [plbsTo] ifdef DEBUG cCall S_CopyLbs,<> else ;not DEBUG push cs call near ptr N_CopyLbs endif ;DEBUG PoL05: ;/* pop all higher entries in vhpllbs */ ; ilbsTop = (*vhpllbs)->ilbsMac - 1; mov bx,[si] mov di,[bx.iMacPl] dec di ; if (ilbsTop >= 0) jl PoL08 ; for (plbsTop = PInPl(vhpllbs, ilbsTop); ; ilbsTop >= 0 && plbsTop->hpllr != plbsId->hpllr; ; --ilbsTop, --plbsTop) ; { cCall PInPl,<si, di> xchg ax,si inc di jmp short PoL07 PoL06: ; if (vhpllrSpare == hNil) ; vhpllrSpare = plbsTop->hpllr; ; else ; FreePhpl(&plbsTop->hpllr); ;LN_UseHpllrSpare performs: ;if (vhpllrSpare == hNil) ; vhpllrSpare = plbs->hpllr; ;else ; FreePhpl(&plbs->hpllr); ;Assuming si contains plbs. ax, bx, cx, dx are altered. call LN_UseHpllrSpare sub si,cbLbsMin PoL07: dec di jl PoL08 mov bx,[plbsId] mov ax,[si.hpllrLbs] cmp ax,[bx.hpllrLbs] jne PoL06 ; } PoL08: ;/* pop the entry */ ; if (ilbsTop < 0) ; ilbsTop = 0; or di,di jl PoL10 ; else if (plbsTo != 0) ; blt(plbsTop, plbsTo, cwLBS); mov ax,[plbsTo] or ax,ax je PoL09 xchg ax,di push ds pop es errnz <cbLbsMin AND 1> mov cx,cbLbsMin SHR 1 rep movsw xchg ax,di jmp short PoL11 PoL09: ; else if (vhpllrSpare == hNil) ; vhpllrSpare = plbsTop->hpllr; ; else ; FreePhpl(&plbsTop->hpllr); ;LN_UseHpllrSpare performs: ;if (vhpllrSpare == hNil) ; vhpllrSpare = plbs->hpllr; ;else ; FreePhpl(&plbs->hpllr); ;Assuming si contains plbs. ax, bx, cx, dx are altered. call LN_UseHpllrSpare db 03Dh ;turns next "xor di,di" into "cmp ax,immediate" PoL10: xor di,di PoL11: ; (*vhpllbs)->ilbsMac = ilbsTop; mov bx,[vhpllbs] mov bx,[bx] mov [bx.iMacPl],di ; StopProfile(); PoL12: ;} cEnd ;LN_UseHpllrSpare performs: ;if (vhpllrSpare == hNil) ; vhpllrSpare = plbs->hpllr; ;else ; FreePhpl(&plbs->hpllr); ;Assuming si contains plbs. ax, bx, cx, dx are altered. LN_UseHpllrSpare: mov ax,[si.hpllrLbs] cmp [vhpllrSpare],hNil jne UHS14 mov [vhpllrSpare],ax jmp short UHS15 UHS14: cCall FreeHpl,<ax> mov [si.hpllrLbs],hNil UHS15: ret ;------------------------------------------------------------------------- ; CopyLbs(plbsFrom, plbsTo) ;------------------------------------------------------------------------- ;/* C o p y L b s */ ;NATIVE CopyLbs(plbsFrom, plbsTo) ;struct LBS *plbsFrom, *plbsTo; ;{ ;/* copies lbsFrom to lbsTo; lbsTo's original hpllr is freed. If an lbs stack ; entry has the same hpllr, that stack entry is deleted */ ; %%Function:N_CopyLbs %%Owner:BRADV cProc N_CopyLbs,<PUBLIC,FAR>,<si,di> ParmW plbsFrom ParmW plbsTo LocalW ilrMac LocalV lbsT, cbLbsMin cBegin ; StartProfile(); mov si,[plbsTo] ; Assert(plbsTo != 0); ifdef DEBUG or si,si jne CoL01 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1021 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax CoL01: endif ;DEBUG ; UnstackLbs(plbsTo); ;LN_UnstackLbs takes plbs in si. ax, bx, cx, dx are altered. call LN_UnstackLbs ; if (vhpllrSpare == hNil) ; vhpllrSpare = plbsTo->hpllr; ; else ; FreePhpl(&plbsTo->hpllr); ;LN_UseHpllrSpare performs: ;if (vhpllrSpare == hNil) ; vhpllrSpare = plbs->hpllr; ;else ; FreePhpl(&plbs->hpllr); ;Assuming si contains plbs. ax, bx, cx, dx are altered. call LN_UseHpllrSpare ; if (plbsFrom == 0) ; plbsTo->hpllr = 0; ; else ; { ; *plbsTo = *plbsFrom; ; plbsFrom->hpllr = 0; ; UnstackLbs(plbsTo); ; } mov di,si mov si,[plbsFrom] mov [di.hpllrLbs],si or si,si je CoL02 push di ;argument for UnstackLbs push ds pop es errnz <cbLbsMin AND 1> mov cx,cbLbsMin SHR 1 rep movsw mov [si.hpllrLbs - cbLbsMin],0 pop si ;LN_UnstackLbs takes plbs in si. ax, bx, cx, dx are altered. call LN_UnstackLbs CoL02: ; StopProfile(); ;} cEnd ;------------------------------------------------------------------------- ; UnstackLbs(plbs) ;------------------------------------------------------------------------- ;/* U n s t a c k L b s */ ;NATIVE UnstackLbs(plbs) ;struct LBS *plbs; ;{ ;/* removes from the lbs stack the first entry whose hpllr matches plbs's */ ; int ilbs; ; struct LBS *plbsStack; ifdef DEBUG ; %%Function:LN_UnstackLbs %%Owner:BRADV PUBLIC LN_UnstackLbs endif ;DEBUG ;LN_UnstackLbs takes plbs in si. ax, bx, cx, dx are altered. LN_UnstackLbs: ; StartProfile(); ; if (plbs == 0 || !plbs->fOnLbsStack || (ilbs = (*vhpllbs)->ilbsMac - 1) < 0) ; { ; StopProfile(); ; return; ; } push di ;save caller's di or si,si je UL03 cmp [si.fOnLbsStackLbs],fFalse je UL03 mov di,[vhpllbs] mov bx,[di] mov ax,[bx.iMacPl] dec ax jl UL03 ; plbs->fOnLbsStack = fFalse; mov [si.fOnLbsStackLbs],fFalse ; for (plbsStack = PInPl(vhpllbs, ilbs); ilbs >= 0; --plbsStack, --ilbs) push ax ;save ilbs cCall PInPl,<di, ax> pop cx ;restore ilbs xchg ax,bx inc cx jmp short UL02 UL01: sub bx,cbLbsMin UL02: dec cx jl UL03 ; if (plbsStack->hpllr == plbs->hpllr) ; { mov ax,[bx.hpllrLbs] cmp ax,[si.hpllrLbs] jne UL01 ; DeleteFromPl(vhpllbs, ilbs); ; StopProfile(); ; return; ; } cCall DeleteFromPl,<di,cx> ; StopProfile(); UL03: pop di ;restore caller's di ;} ret ;------------------------------------------------------------------------- ; FAbortLayout(fOutline, plbs) ;------------------------------------------------------------------------- ;/* F A b o r t L a y o u t */ ;NATIVE FAbortLayout(fOutline, plbs) ;int fOutline; ;struct LBS *plbs; ;{ ; BOOL fAbort, fLayoutSav; ; struct CA caSave; ; int flmSave = vflm; ; int lmSave = vlm; ;#ifdef DEBUG ; CP cpFirstSave = vcpFirstLayout; ; CP cpLimSave = vcpLimLayout; ;#endif ; %%Function:N_FAbortLayout %%Owner:BRADV cProc N_FAbortLayout,<PUBLIC,FAR>,<si,di> ParmW fOutline ParmW plbs ;LocalW fOutlineWw LocalB fLayoutSav LocalV caSave, cbCaMin ifdef DEBUG LocalD cpFirstSave LocalD cpLimSave endif ;DEBUG cBegin ifdef DEBUG push wlo [vcpFirstLayout] pop [OFF_cpFirstSave] push whi [vcpFirstLayout] pop [SEG_cpFirstSave] push wlo [vcpLimLayout] pop [OFF_cpLimSave] push whi [vcpLimLayout] pop [SEG_cpLimSave] endif ;DEBUG ; caSave = caPara; push ds pop es mov si,dataoffset [caPara] lea di,[caSave] mov cx,cbCaMin/2 rep movsw ; fOutlineWw = PwwdWw(wwLayout)->fOutline mov bx,[mpwwhwwd+(wwLayout SHL 1)] mov bx,[bx] push wptr ([bx.fOutlineWwd]) ; /* So that any display routines called will work */ ; fLayoutSav = vfli.fLayout; ; vfli.fLayout = fFalse; ; PAUSE mov al,[vfli.fLayoutFli] mov bptr [fLayoutSav],al sub [vfli.fLayoutFli],al mov di,[vflm] mov ax,[vlm] push ax ;lmSave on stack ; fAbort = (vlm == lmPagevw) ? fFalse : (vlm == lmBRepag) ? ; FMsgPresent(mtyIdle) : FQueryAbortCheck(); ;#define FQueryAbortCheck() (vpisPrompt==pisNormal?fFalse:FQueryAbortCheckProc()) xor si,si cmp al,lmPagevw je FAL023 cmp al,lmBRepag je FAL01 errnz <pisNormal - 0> mov cx,[vpisPrompt] jcxz FAL023 cCall FQueryAbortCheckProc,<> jmp short FAL02 FAL01: mov ax,mtyIdle cCall FMsgPresent,<ax> FAL02: xchg ax,si FAL023: ; vfli.fLayout = fLayoutSav; mov al,bptr [fLayoutSav] mov [vfli.fLayoutFli],al ; fAbort = fAbort || (vflm != flmSave && !FResetWwLayout(DocMotherLayout(plbs->doc), flmSave, lmSave)); pop ax ;restore lmSave or si,si jne FAL025 errnz <fFalse> xor si,si cmp [vflm],di je FAL025 push ax ;save lmSave mov bx,[plbs] cCall DocMotherLayout,<[bx.docLbs]> pop cx ;restore lmSave cCall FResetWwLayout,<ax, di, cx> or ax,ax jne FAL025 errnz <fTrue - fFalse - 1> inc si FAL025: ; PwwdWw(wwLayout)->fOutline = fOutlineWw mov bx,[mpwwhwwd+(wwLayout SHL 1)] mov bx,[bx] pop ax and al,maskfOutlineWwd and [bx.fOutlineWwd],NOT maskfOutlineWwd or [bx.fOutlineWwd],al ;/* make sure that processing some of the messages should not change vcpFirstLayout */ ; Assert(vcpFirstLayout == cpFirstSave); ; Assert(vcpLimLayout == cpLimSave); ifdef DEBUG push ax push bx push cx push dx mov ax,wlo [vcpFirstLayout] mov dx,whi [vcpFirstLayout] sub ax,[OFF_cpFirstSave] sbb dx,[SEG_cpFirstSave] or ax,dx je FAL04 mov ax,midLayout2n mov bx,1023 cCall AssertProcForNative,<ax,bx> FAL04: mov ax,wlo [vcpLimLayout] mov dx,whi [vcpLimLayout] sub ax,[OFF_cpLimSave] sbb dx,[SEG_cpLimSave] or ax,dx je FAL05 mov ax,midLayout2n mov bx,1024 cCall AssertProcForNative,<ax,bx> FAL05: pop dx pop cx pop bx pop ax endif ;DEBUG ; /* Abort checks can change caPara...not a good thing! */ ; /* Yes...use caPara, not caParaL */ ; if (!fAbort && FNeRgw(&caSave, &caPara, cwCA)) ; { or si,si jne FAL06 push ds pop es push si ;save fAbort mov si,dataoffset [caPara] lea di,[caSave] mov cx,cbCaMin/2 repe cmpsw pop si ;restore fAbort je FAL06 ; caParaL.doc = docNil; mov [caParaL.docCa],docNil ; if (caSave.doc != docNil) ; CacheParaL(caSave.doc, caSave.cpFirst, fOutline); mov bx,[caSave.docCa] errnz <docNil> or bx,bx je FAL06 mov dx,[caSave.HI_cpFirstCa] mov ax,[caSave.LO_cpFirstCa] mov cx,[fOutline] ;LN_CacheParaL takes doc in bx, cp in dx:ax, fOutline in cx ;ax, bx, cx, dx are altered. call LN_CacheParaL ; } FAL06: ; return fAbort; xchg ax,si ;} cEnd ;LN_XaFromXl performs XaFromXl(ax); ax, bx, cx, dx are altered. ; %%Function:LN_XaFromXl %%Owner:BRADV PUBLIC LN_XaFromXl LN_XaFromXl: ;#define XaFromXl(xl) (NMultDiv(xl, czaInch, vfti.dxpInch)) ; LN_NMultDivL performs NMultDiv(ax, dx, bx) ; ax, bx, cx, dx are altered. mov dx,czaInch mov bx,[vfti.dxpInchFti] jmp short LN_NMultDivL ;LN_YlFromYa performs YlFromYa(ax); ax, bx, cx, dx are altered. ; %%Function:LN_YlFromYa %%Owner:BRADV PUBLIC LN_YlFromYa LN_YlFromYa: ;#define YlFromYa(ya) (NMultDiv(ya, vfti.dypInch, czaInch)) mov dx,[vfti.dypInchFti] ; LN_NMultDivCzaInch performs NMultDiv(ax, dx, czaInch) ; ax, bx, cx, dx are altered. ; %%Function:LN_NMultDivCzaInch %%Owner:BRADV PUBLIC LN_NMultDivCzaInch LN_NMultDivCzaInch: mov bx,czaInch ; LN_NMultDivL performs NMultDiv(ax, dx, bx) ; ax, bx, cx, dx are altered. LN_NMultDivL: cCall NMultDiv,<ax,dx,bx> ret ; %%Function:LN_PdodDocL %%Owner:BRADV PUBLIC LN_PdodDocL LN_PdodDocL: ;Takes doc in bx, result in bx. Only bx is altered. shl bx,1 mov bx,[bx.mpdochdod] ifdef DEBUG cmp bx,hNil jne LN_PD101 push ax push bx push cx push dx mov ax,midLayout2n mov bx,1025 cCall AssertProcForNative,<ax,bx> pop dx pop cx pop bx pop ax LN_PD101: endif ;/* DEBUG */ mov bx,[bx] ret ;LN_PutCpPlc performs PutCpPlc(vfls.hplclnh, cx, dx:ax); ;ax, bx, cx, dx are altered. LN_PutCpPlc: cCall PutCpPlc,<[vfls.hplclnhFls], cx, dx, ax> ret ;LN_LrpInPlCur performs LrpInPl(plbs->hpllr, plbs->ilrCur) with ;the result in es:bx or es:ax. It assumes plbs is passed in si. ;ax, bx, cx, dx are altered. ; %%Function:LN_LrpInPlCur %%Owner:BRADV PUBLIC LN_LrpInPlCur LN_LrpInPlCur: mov cx,[si.ilrCurLbs] ;LN_LrpInPl performs LrpInPl(plbs->hpllr, cx) with the result in es:bx ;or es:ax. It assumes plbs is passed in si. ;ax, bx, dx are altered. LN_LrpInPl: ;Assembler note: HpInPl also returns LpInPl in es:ax push cx ;save ilr cCall HpInPl,<[si.hpllrLbs],cx> pop cx ;restore ilr ifdef DEBUG push ax push bx push cx push dx push es ;save es from HpInPl mov bx,dx shl bx,1 mov ax,mpsbps[bx] mov es,ax shr ax,1 jc LN_LIP01 ;Assembler note: There is no way we should have to call ReloadSb here. ; reload sb trashes ax, cx, and dx ; cCall ReloadSb,<> mov ax,midLayout2n mov bx,1026 cCall AssertProcForNative,<ax,bx> LN_LIP01: pop ax ;restore es from HpInPl mov bx,es ;compare with es rederived from the SB of HpInPl cmp ax,bx je LN_LIP02 mov ax,midLayout2n mov bx,1027 cCall AssertProcForNative,<ax,bx> LN_LIP02: pop dx pop cx pop bx pop ax endif ;/* DEBUG */ ;Assembler note: use "mov" rather than "xchg" here (at the cost of ;an extra byte), so that we can use "xchg ax,si" or "xchg ax,di" ;if necessary after the return. mov bx,ax ret ;LN_IMacPllr performs cx = IMacPllr(plbs). plbs is assumed to be ;passed in si. Only bx and cx are altered. LN_IMacPllr: ;***Begin in-line IMacPllr mov bx,[si.hpllrLbs] mov bx,[bx] mov cx,[bx.iMacPl] ;***End in-line IMacPllr ret ;LN_IInPlc performs IInPlc(vfls.hplclnh, *pcp) where pcp is passed ;in bx. ax, bx, cx, dx are altered. ; %%Function:LN_IInPlc %%Owner:BRADV PUBLIC LN_IInPlc LN_IInPlc: cCall IInPlc,<[vfls.hplclnhFls], [bx+2], [bx]> ret ;LN_CpMacDocPlbs performs CpMacDocPlbs(si). ;ax, bx, cx, dx are altered. ; %%Function:LN_CpMacDocPlbs %%Owner:BRADV PUBLIC LN_CpMacDocPlbs LN_CpMacDocPlbs: ;#define CpMacDocPlbs(plbs) CpMacDoc(plbs->doc) cCall CpMacDoc,<[si.docLbs]> ret ;LN_CpPlc performs CpPlc(vfls.hplclnh, cx) ;ax, bx, cx, dx are altered. ; %%Function:LN_CpPlc %%Owner:BRADV PUBLIC LN_CpPlc LN_CpPlc: cCall CpPlc,<[vfls.hplclnhFls],cx> ret sEnd layout2 end
#include <iostream> using namespace std; int main(){ cout<<"Hello"<<endl; cout<<"hey"<<endl; return 0; }
global int80 section .text %macro pushState 0 push rax push rbx push rcx push rdx push rbp push rdi push rsi push r8 push r9 push r10 push r11 push r12 push r13 push r14 push r15 %endmacro %macro popState 0 pop r15 pop r14 pop r13 pop r12 pop r11 pop r10 pop r9 pop r8 pop rsi pop rdi pop rbp pop rdx pop rcx pop rbx pop rax %endmacro int80: pushState mov rbp,rsp INT 80h mov rsp,rbp popState ret
# Counts the number of 1s in a 32-bit word # num = 35; # counter = 0; # position = 1; # for (i = 0; i < 32; i++) { # bit = num & position; # if (bit != 0) # counter++; # position = position << 1; # } # print(counter); .text # $s0 = num, $s1 = counter, $s2 = bit, $t0 = position, $t1 = i li $s0, 0xf1f0f0f0 # num = input value li $s1, 0 # counter = 0 li $t0, 1 # position = 1 li $t1, 0 # i = 0 loop: and $s2, $s0, $t0 # bit = num & position beqz $s2, end_if # bit == 0, so leave if-statement addi $s1, $s1, 1 # bit == 1, so add 1 to counter end_if: sll $t0, $t0, 1 # position = position << 1 addi $t1, $t1, 1 # i++ li $t2, 32 blt $t1, $t2, loop # if i < 32 then iterate again done: # print result li $v0, 1 move $a0, $s1 syscall # terminate program li $v0, 10 syscall
#include "renderer.h" #include <algorithm> #include <iostream> /** * TODO: when adding new Renderable to the queue, generate/find it's appropiate batch in the same time * and get loose of dirty flag. Also, on delete, remove it from vertices and batch, shrinking indexes buffer and vertices. * When adding to a batch, resize and buffer the data to GPU (new size). On vertices upload, on each frame * use glMapBuffer. */ namespace evl { Renderer::Renderer() : mVertexArray(0) , mVertexBuffer(0) , mIndexBuffer(0) , mDirty(true) { } void Renderer::Init() { enum shader_attrs { POSITION, COLOR, UV, SHADER_NUM_ATTRS }; glGenVertexArrays(1, &mVertexArray); glGenBuffers(1, &mVertexBuffer); glGenBuffers(1, &mIndexBuffer); /// Generate buffers and their layout glBindVertexArray(mVertexArray); glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer); glEnableVertexAttribArray(POSITION); glEnableVertexAttribArray(COLOR); glEnableVertexAttribArray(UV); glVertexAttribPointer( POSITION, sizeof(mVertices[0].pos) / sizeof(float), GL_FLOAT, GL_FALSE, sizeof(mVertices[0]), (void*)offsetof(Vertex, pos)); glVertexAttribPointer( COLOR, sizeof(mVertices[0].color) / sizeof(uint8_t), GL_UNSIGNED_BYTE, GL_TRUE, sizeof(mVertices[0]), (void*)offsetof(Vertex, color)); glVertexAttribPointer( UV, sizeof(mVertices[0].uv) / sizeof(float), GL_FLOAT, GL_FALSE, sizeof(mVertices[0]), (void*)offsetof(Vertex, uv)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } Renderer::~Renderer() { glDeleteVertexArrays(1, &mVertexArray); glDeleteBuffers(1, &mVertexBuffer); glDeleteBuffers(1, &mIndexBuffer); } void Renderer::Add(Renderable* renderable) { mQueue.push_back(renderable); mDirty = true; } bool Renderer::Delete(Renderable* renderable) { auto it = std::remove(mQueue.begin(), mQueue.end(), renderable); if (it != mQueue.end()) { mQueue.erase(it); mDirty = true; return true; } return false; } /** * Gets a batch having drawType and textureId. * If it cannot find one, will create one with given vertices indexes offsets */ RenderBatch* Renderer::GetBatch( DrawType drawType, GLuint textureId, uint verticesOffs, uint indexesOffs) { RenderBatch batch(verticesOffs, indexesOffs, drawType, textureId); auto it = std::find(mBatches.begin(), mBatches.end(), batch); if (it == mBatches.end()) { // std::cout << "new batch" << std::endl; RenderBatch batch(verticesOffs, indexesOffs, drawType, textureId); mBatches.push_back(batch); return &mBatches.back(); } return &(*it); } void Renderer::Clear() { mVertices.clear(); mIndexes.clear(); mBatches.clear(); mQueue.clear(); } /** * Builds batches, so we can have only one vertex buffer and one index buffer, * but keeping different offsets into them * This way the buffering to GPU will be done in one chunk (actually 2) and draw * calls will be minimized. * TODO - clean code, I don't think I need vertex offset, nor vertex size * - use glMapBuffer and write vertices and indexes directly on a GPU mapped memory. */ void Renderer::BuildBatches() { mVertices.clear(); mIndexes.clear(); mBatches.clear(); DrawType lastDrawType = D_NONE; GLuint lastTextureId = 0; uint verticesOffs = 0, indexesOffs = 0; RenderBatch* batch = nullptr; for (uint i = 0; i < mQueue.size(); i++) { if (lastDrawType != mQueue[i]->mDrawType || lastTextureId != mQueue[i]->textureId) { lastDrawType = mQueue[i]->mDrawType; lastTextureId = mQueue[i]->textureId; batch = GetBatch(lastDrawType, lastTextureId, verticesOffs, indexesOffs); } uint indexGOffs = mVertices.size(); mVertices.insert(mVertices.end(), mQueue[i]->mVertices.begin(), mQueue[i]->mVertices.end()); verticesOffs += mQueue[i]->mVertices.size(); batch->numVertices += mQueue[i]->mVertices.size(); for (uint j = 0; j < mQueue[i]->mIndexes.size(); j++) mIndexes.emplace_back(indexGOffs + mQueue[i]->mIndexes[j]); indexesOffs += mQueue[i]->mIndexes.size(); batch->numIndexes += mQueue[i]->mIndexes.size(); } mDirty = false; } /** * Vertices needs to be rebuilt each frame, because the world is dynamic. */ void Renderer::RebuildVertices() { mVertices.clear(); for (uint i = 0; i < mQueue.size(); i++) for (uint j = 0; j < mQueue[i]->mVertices.size(); j++) mVertices.emplace_back(mQueue[i]->mVertices[j]); } /** * Draw the batches */ void Renderer::Draw() { if (mDirty) BuildBatches(); else RebuildVertices(); glBindVertexArray(mVertexArray); glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer); glBufferData(GL_ARRAY_BUFFER, mVertices.size() * sizeof(mVertices[0]), &mVertices[0], GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, mIndexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, mIndexes.size() * sizeof(mIndexes[0]), &mIndexes[0], GL_DYNAMIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer); for (uint i = 0; i < mBatches.size(); i++) { GLuint drawType; switch (mBatches[i].drawType) { case D_POINTS: drawType = GL_POINTS; break; case D_LINES: drawType = GL_LINES; break; case D_TRIANGLES: drawType = GL_TRIANGLES; break; default: return; } glBindTexture(GL_TEXTURE_2D, mBatches[i].textureId); glDrawElements(drawType, mBatches[i].numIndexes, GL_UNSIGNED_INT, (void*)(mBatches[i].indexOffs * sizeof(int))); } } void Renderer::PrintBatches() { for (uint i = 0; i < mBatches.size(); i++) { std::cout << "dtype: " << (mBatches[i].drawType == D_LINES ? "lines" : "triangles") << ", texture id: " << mBatches[i].textureId << ", verticesOffs: " << mBatches[i].verticesOffs << ", numVertices: " << mBatches[i].numVertices << ", indexOffs: " << mBatches[i].indexOffs << ", numIndexes: " << mBatches[i].numIndexes << std::endl; } } }
; ; Z88 Graphics Functions - Small C+ stubs ; ; Written around the Interlogic Standard Library ; ; Stubs Written by D Morris - 30/9/98 ; ; ; $Id: unplot.asm,v 1.7 2016-04-13 21:09:09 dom Exp $ ; ;Usage: unplot(int x, int h) SECTION code_graphics PUBLIC c_unplot PUBLIC _c_unplot EXTERN swapgfxbk EXTERN __graphics_end EXTERN c_respixel .c_unplot ._c_unplot IF __CPU_INTEL__ | __CPU_GBZ80__ pop bc pop hl pop de push de push hl push bc ld h,e ELSE push ix ld ix,2 add ix,sp ld l,(ix+2) ld h,(ix+4) ENDIF call swapgfxbk call c_respixel jp __graphics_end
; ****************************************************** ;Prob3.2...... Divide two 8-bit data without using the DIV instructionfor AVR ; ****************************************************** .include "C:\VMLAB\include\m8def.inc" ; Define here the variables .def temp =r16 ; Define here Reset and interrupt vectors, if any reset: rjmp start reti ; Addr $01 reti ; Addr $02 reti ; Addr $03 reti ; Addr $04 reti ; Addr $05 reti ; Addr $06 Use 'rjmp myVector' reti ; Addr $07 to define a interrupt vector reti ; Addr $08 reti ; Addr $09 reti ; Addr $0A reti ; Addr $0B This is just an example reti ; Addr $0C Not all MCUs have the same reti ; Addr $0D number of interrupt vectors reti ; Addr $0E reti ; Addr $0F reti ; Addr $10 ; Program starts here after Reset start: nop ; Initialize here ports, stack pointer, nop ; cleanup RAM, etc. nop ; nop ; ldi r16,4 ldi r17,2 ldi r18,0 ldi r19,0 forever: nop nop ; Infinite loop. nop ; Define your main system nop ; behaviour here inc r19 add r18,r17 cp r18,r16 breq end brcc imperfect rjmp forever imperfect: dec r19 end: nop
.thumb .org 0x0 @since I'm not 100% sure which bit is being used for Capture, I'll just call this function to return true if capturing @r0=char data ldr r0,[r0,#0xC] mov r1,#0x80 lsl r1,#0x17 and r0,r1 cmp r0,#0x0 beq GoBack mov r0,#0x1 GoBack: bx r14
.include "myTiny13.h" ; sets Bit0 OFF if timer match 250, makes Bit0 ON if Timer if on TOP .org 0x0000 rjmp Main .org 0x0006 rjmp CompareFits ; fade via tick-length (=255-N) .org 0x0010 CompareFits: ; toggle Bit4 ldi A, 0b00010000 in B, PINB eor A, B out PORTB, A ; change compareValue to make IRQ earlier cpi I, 1 ; if inverse = false breq Decrement Increment: ldi A, 3 add N, A ; N = N+3 rjmp CheckDir Decrement: subi N, 3 ; N = N-3 CheckDir: ; Overflow? then we have to go into inverse Direction brvc CalcOk cpi I, 1 breq UpCount ; if I = 1 DownCount: ldi I, 1 ; set I = 1 and N = 255 ldi N, 255 ; because we want to count down (Inverse = true) rjmp CalcOk UpCount: ldi I, 0 ; else set I = 0 and N=0 ldi N, 0 ; because we want to count up CalcOk: out OCR0A, N reti .org 0x0040 Main: sbi DDRB, 4 ; PortB4 is output for IRQ ping ldi A, 0b10000001 ; PWM mode 1 (phase correct!!) out TCCR0A, A ldi A, 0b00000011 ; timer: count on every 8 clock-ticks out TCCR0B, A ldi A, 0b00000100 ; say timer to make IRQ on a fiting compare out TIMSK0, A ldi N, 100 ; default ldi I, 0 ; inverse = 0 sei Loop: rjmp Loop
object_const_def ; object_event constants const CINNABARISLAND_BLUE CinnabarIsland_MapScripts: db 0 ; scene scripts db 1 ; callbacks callback MAPCALLBACK_NEWMAP, .FlyPoint .FlyPoint: setflag ENGINE_FLYPOINT_CINNABAR return CinnabarIslandBlue: faceplayer opentext writetext CinnabarIslandBlueText waitbutton closetext playsound SFX_WARP_TO applymovement CINNABARISLAND_BLUE, CinnabarIslandBlueTeleport disappear CINNABARISLAND_BLUE clearevent EVENT_VIRIDIAN_GYM_BLUE end CinnabarIslandGymSign: jumptext CinnabarIslandGymSignText CinnabarIslandSign: jumptext CinnabarIslandSignText CinnabarIslandPokecenterSign: jumpstd pokecentersign CinnabarIslandHiddenRareCandy: hiddenitem RARE_CANDY, EVENT_CINNABAR_ISLAND_HIDDEN_RARE_CANDY CinnabarIslandBlueTeleport: teleport_from step_end CinnabarIslandBlueText: text "Who are you?" para "Well, it's plain" line "to see that you're" cont "a trainer…" para "My name's BLUE." para "I was once the" line "CHAMPION, although" para "it was for only a" line "short time…" para "That meddling RED" line "did me in…" para "Anyway, what do" line "you want? You want" para "to challenge me or" line "something?" para "…I hate to say" line "it, but I'm not in" para "the mood for a" line "battle now." para "Take a good look" line "around you…" para "A volcano erupts," line "and just like" para "that, a whole town" line "disappears." para "We can go on win-" line "ning and losing in" para "#MON. But if" line "nature so much as" para "twitches, we can" line "lose in a second." para "…" para "That's the way it" line "is…" para "But, anyway, I'm" line "still a trainer." para "If I see a strong" line "opponent, it makes" cont "me want to battle." para "If you want to" line "battle me, come to" cont "the VIRIDIAN GYM." para "I'll take you on" line "then." done CinnabarIslandGymSignText: text "There's a notice" line "here…" para "CINNABAR GYM has" line "relocated to SEA-" cont "FOAM ISLANDS." para "BLAINE" done CinnabarIslandSignText: text "CINNABAR ISLAND" para "The Fiery Town of" line "Burning Desire" done CinnabarIsland_MapEvents: db 0, 0 ; filler db 1 ; warp events warp_event 11, 11, CINNABAR_POKECENTER_1F, 1 db 0 ; coord events db 4 ; bg events bg_event 12, 11, BGEVENT_READ, CinnabarIslandPokecenterSign bg_event 9, 11, BGEVENT_READ, CinnabarIslandGymSign bg_event 7, 7, BGEVENT_READ, CinnabarIslandSign bg_event 9, 1, BGEVENT_ITEM, CinnabarIslandHiddenRareCandy db 1 ; object events object_event 9, 6, SPRITE_BLUE, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, CinnabarIslandBlue, EVENT_BLUE_IN_CINNABAR
%ifdef CONFIG { "RegData": { "MM7": ["0x8000000000000000", "0x3FFF"] }, "MemoryRegions": { "0x100000000": "4096" } } %endif mov rdx, 0xe0000000 mov rax, 0x4000000000000000 ; 2.0 mov [rdx + 8 * 0], rax fld qword [rdx + 8 * 0] fdiv st0, st0 hlt
; Copyright 2021 IBM 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. [BITS 64] %include "common.inc" %include "pmc.inc" section .data dev_file: db '/dev/cpu/',VICTIM_PROCESS_STR,'/msr',0 ;dev_file: db '/dev/cpu/',ATTACKER_PROCESS_STR,'/msr',0 fd: dq 0 warmup_cnt_fake: dd 1 offset: dq 0 val: dq 0 len: equ $-val array: resb 128 warmup_cnt: dd 1 filler: resb 256 target: dq 0 ;##### DATA STARTS HERE ######## ;##### DATA ENDS HERE ######## section .text global perf_test_entry:function global snippet:function global victim:function perf_test_entry: push rbp mov rbp, rsp sub rsp, len check_pinning VICTIM_PROCESS ;check_pinning ATTACKER_PROCESS msr_open msr_seek mov QWORD[target], correct .data: clflush [warmup_cnt] mov eax, 0 cpuid lfence reset_counter start_counter mov ebx, DWORD[warmup_cnt] cmp ebx, 12 je .else ;##### SNIPPET STARTS HERE ###### call [target] ;##### SNIPPET ENDS HERE ###### lfence .else: lfence stop_counter inc DWORD[warmup_cnt] cmp DWORD[warmup_cnt], 12 jl .again jg .skip mov QWORD[target], victim .again: jmp .data .skip: msr_close exit 0 victim: mov QWORD[target], hijacked call QWORD[target] ret lfence hijacked: mov DWORD[array], eax mov DWORD[array+4], edx movq xmm0, QWORD[array] mov DWORD[array], eax mov DWORD[array+4], edx movq xmm0, QWORD[array] mov DWORD[array], eax mov DWORD[array+4], edx movq xmm0, QWORD[array] lfence ret correct: lfence ret
; SPIR-V ; Version: 1.0 ; Generator: Khronos Glslang Reference Front End; 10 ; Bound: 442 ; Schema: 0 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %4 "main" %12 %435 OpExecutionMode %4 OriginUpperLeft OpSource ESSL 320 OpName %4 "main" OpName %9 "pos" OpName %12 "gl_FragCoord" OpName %15 "buf0" OpMemberName %15 0 "resolution" OpName %17 "" OpName %26 "ipos" OpName %42 "i" OpName %55 "map" OpName %62 "p" OpName %65 "canwalk" OpName %67 "v" OpName %74 "directions" OpName %171 "j" OpName %208 "d" OpName %435 "_GLF_color" OpDecorate %12 BuiltIn FragCoord OpMemberDecorate %15 0 Offset 0 OpDecorate %15 Block OpDecorate %17 DescriptorSet 0 OpDecorate %17 Binding 0 OpDecorate %435 Location 0 %2 = OpTypeVoid %3 = OpTypeFunction %2 %6 = OpTypeFloat 32 %7 = OpTypeVector %6 2 %8 = OpTypePointer Function %7 %10 = OpTypeVector %6 4 %11 = OpTypePointer Input %10 %12 = OpVariable %11 Input %15 = OpTypeStruct %7 %16 = OpTypePointer Uniform %15 %17 = OpVariable %16 Uniform %18 = OpTypeInt 32 1 %19 = OpConstant %18 0 %20 = OpTypePointer Uniform %7 %24 = OpTypeVector %18 2 %25 = OpTypePointer Function %24 %27 = OpTypeInt 32 0 %28 = OpConstant %27 0 %29 = OpTypePointer Function %6 %32 = OpConstant %6 16 %35 = OpConstant %27 1 %41 = OpTypePointer Function %18 %49 = OpConstant %18 256 %50 = OpTypeBool %52 = OpConstant %27 256 %53 = OpTypeArray %18 %52 %54 = OpTypePointer Private %53 %55 = OpVariable %54 Private %57 = OpTypePointer Private %18 %60 = OpConstant %18 1 %63 = OpConstantComposite %24 %19 %19 %64 = OpTypePointer Function %50 %66 = OpConstantTrue %50 %82 = OpConstant %18 2 %86 = OpConstant %18 16 %119 = OpConstant %18 14 %162 = OpConstantFalse %50 %169 = OpConstant %18 8 %434 = OpTypePointer Output %10 %435 = OpVariable %434 Output %436 = OpConstant %6 1 %437 = OpConstantComposite %10 %436 %436 %436 %436 %440 = OpConstant %6 0 %441 = OpConstantComposite %10 %440 %440 %440 %436 %4 = OpFunction %2 None %3 %5 = OpLabel %9 = OpVariable %8 Function %26 = OpVariable %25 Function %42 = OpVariable %41 Function %62 = OpVariable %25 Function %65 = OpVariable %64 Function %67 = OpVariable %41 Function %74 = OpVariable %41 Function %171 = OpVariable %41 Function %208 = OpVariable %41 Function %13 = OpLoad %10 %12 %14 = OpVectorShuffle %7 %13 %13 0 1 %21 = OpAccessChain %20 %17 %19 %22 = OpLoad %7 %21 %23 = OpFDiv %7 %14 %22 OpStore %9 %23 %30 = OpAccessChain %29 %9 %28 %31 = OpLoad %6 %30 %33 = OpFMul %6 %31 %32 %34 = OpConvertFToS %18 %33 %36 = OpAccessChain %29 %9 %35 %37 = OpLoad %6 %36 %38 = OpFMul %6 %37 %32 %39 = OpConvertFToS %18 %38 %40 = OpCompositeConstruct %24 %34 %39 OpStore %26 %40 OpStore %42 %19 OpBranch %43 %43 = OpLabel OpLoopMerge %45 %46 None OpBranch %47 %47 = OpLabel %48 = OpLoad %18 %42 %51 = OpSLessThan %50 %48 %49 OpBranchConditional %51 %44 %45 %44 = OpLabel %56 = OpLoad %18 %42 %58 = OpAccessChain %57 %55 %56 OpStore %58 %19 OpBranch %46 %46 = OpLabel %59 = OpLoad %18 %42 %61 = OpIAdd %18 %59 %60 OpStore %42 %61 OpBranch %43 %45 = OpLabel OpStore %62 %63 OpStore %65 %66 OpStore %67 %19 OpBranch %68 %68 = OpLabel OpLoopMerge %70 %71 None OpBranch %69 %69 = OpLabel %72 = OpLoad %18 %67 %73 = OpIAdd %18 %72 %60 OpStore %67 %73 OpStore %74 %19 %75 = OpAccessChain %41 %62 %28 %76 = OpLoad %18 %75 %77 = OpSGreaterThan %50 %76 %19 OpSelectionMerge %79 None OpBranchConditional %77 %78 %79 %78 = OpLabel %80 = OpAccessChain %41 %62 %28 %81 = OpLoad %18 %80 %83 = OpISub %18 %81 %82 %84 = OpAccessChain %41 %62 %35 %85 = OpLoad %18 %84 %87 = OpIMul %18 %85 %86 %88 = OpIAdd %18 %83 %87 %89 = OpAccessChain %57 %55 %88 %90 = OpLoad %18 %89 %91 = OpIEqual %50 %90 %19 OpBranch %79 %79 = OpLabel %92 = OpPhi %50 %77 %69 %91 %78 OpSelectionMerge %94 None OpBranchConditional %92 %93 %94 %93 = OpLabel %95 = OpLoad %18 %74 %96 = OpIAdd %18 %95 %60 OpStore %74 %96 OpBranch %94 %94 = OpLabel %97 = OpAccessChain %41 %62 %35 %98 = OpLoad %18 %97 %99 = OpSGreaterThan %50 %98 %19 OpSelectionMerge %101 None OpBranchConditional %99 %100 %101 %100 = OpLabel %102 = OpAccessChain %41 %62 %28 %103 = OpLoad %18 %102 %104 = OpAccessChain %41 %62 %35 %105 = OpLoad %18 %104 %106 = OpISub %18 %105 %82 %107 = OpIMul %18 %106 %86 %108 = OpIAdd %18 %103 %107 %109 = OpAccessChain %57 %55 %108 %110 = OpLoad %18 %109 %111 = OpIEqual %50 %110 %19 OpBranch %101 %101 = OpLabel %112 = OpPhi %50 %99 %94 %111 %100 OpSelectionMerge %114 None OpBranchConditional %112 %113 %114 %113 = OpLabel %115 = OpLoad %18 %74 %116 = OpIAdd %18 %115 %60 OpStore %74 %116 OpBranch %114 %114 = OpLabel %117 = OpAccessChain %41 %62 %28 %118 = OpLoad %18 %117 %120 = OpSLessThan %50 %118 %119 OpSelectionMerge %122 None OpBranchConditional %120 %121 %122 %121 = OpLabel %123 = OpAccessChain %41 %62 %28 %124 = OpLoad %18 %123 %125 = OpIAdd %18 %124 %82 %126 = OpAccessChain %41 %62 %35 %127 = OpLoad %18 %126 %128 = OpIMul %18 %127 %86 %129 = OpIAdd %18 %125 %128 %130 = OpAccessChain %57 %55 %129 %131 = OpLoad %18 %130 %132 = OpIEqual %50 %131 %19 OpBranch %122 %122 = OpLabel %133 = OpPhi %50 %120 %114 %132 %121 OpSelectionMerge %135 None OpBranchConditional %133 %134 %135 %134 = OpLabel %136 = OpLoad %18 %74 %137 = OpIAdd %18 %136 %60 OpStore %74 %137 OpBranch %135 %135 = OpLabel %138 = OpAccessChain %41 %62 %35 %139 = OpLoad %18 %138 %140 = OpSLessThan %50 %139 %119 OpSelectionMerge %142 None OpBranchConditional %140 %141 %142 %141 = OpLabel %143 = OpAccessChain %41 %62 %28 %144 = OpLoad %18 %143 %145 = OpAccessChain %41 %62 %35 %146 = OpLoad %18 %145 %147 = OpIAdd %18 %146 %82 %148 = OpIMul %18 %147 %86 %149 = OpIAdd %18 %144 %148 %150 = OpAccessChain %57 %55 %149 %151 = OpLoad %18 %150 %152 = OpIEqual %50 %151 %19 OpBranch %142 %142 = OpLabel %153 = OpPhi %50 %140 %135 %152 %141 OpSelectionMerge %155 None OpBranchConditional %153 %154 %155 %154 = OpLabel %156 = OpLoad %18 %74 %157 = OpIAdd %18 %156 %60 OpStore %74 %157 OpBranch %155 %155 = OpLabel %158 = OpLoad %18 %74 %159 = OpIEqual %50 %158 %19 OpSelectionMerge %161 None OpBranchConditional %159 %160 %207 %160 = OpLabel OpStore %65 %162 OpStore %42 %19 OpBranch %163 %163 = OpLabel OpLoopMerge %165 %166 None OpBranch %167 %167 = OpLabel %168 = OpLoad %18 %42 %170 = OpSLessThan %50 %168 %169 OpBranchConditional %170 %164 %165 %164 = OpLabel OpStore %171 %19 OpBranch %172 %172 = OpLabel OpLoopMerge %174 %175 None OpBranch %176 %176 = OpLabel %177 = OpLoad %18 %171 %178 = OpSLessThan %50 %177 %169 OpBranchConditional %178 %173 %174 %173 = OpLabel %179 = OpLoad %18 %171 %180 = OpIMul %18 %179 %82 %181 = OpLoad %18 %42 %182 = OpIMul %18 %181 %82 %183 = OpIMul %18 %182 %86 %184 = OpIAdd %18 %180 %183 %185 = OpAccessChain %57 %55 %184 %186 = OpLoad %18 %185 %187 = OpIEqual %50 %186 %19 OpSelectionMerge %189 None OpBranchConditional %187 %188 %189 %188 = OpLabel %190 = OpLoad %18 %171 %191 = OpIMul %18 %190 %82 %192 = OpAccessChain %41 %62 %28 OpStore %192 %191 %193 = OpLoad %18 %42 %194 = OpIMul %18 %193 %82 %195 = OpAccessChain %41 %62 %35 OpStore %195 %194 OpStore %65 %66 OpBranch %189 %189 = OpLabel OpBranch %175 %175 = OpLabel %196 = OpLoad %18 %171 %197 = OpIAdd %18 %196 %60 OpStore %171 %197 OpBranch %172 %174 = OpLabel OpBranch %166 %166 = OpLabel %198 = OpLoad %18 %42 %199 = OpIAdd %18 %198 %60 OpStore %42 %199 OpBranch %163 %165 = OpLabel %200 = OpAccessChain %41 %62 %28 %201 = OpLoad %18 %200 %202 = OpAccessChain %41 %62 %35 %203 = OpLoad %18 %202 %204 = OpIMul %18 %203 %86 %205 = OpIAdd %18 %201 %204 %206 = OpAccessChain %57 %55 %205 OpStore %206 %60 OpBranch %161 %207 = OpLabel %209 = OpLoad %18 %67 %210 = OpLoad %18 %74 %211 = OpSMod %18 %209 %210 OpStore %208 %211 %212 = OpLoad %18 %74 %213 = OpLoad %18 %67 %214 = OpIAdd %18 %213 %212 OpStore %67 %214 %215 = OpLoad %18 %208 %216 = OpSGreaterThanEqual %50 %215 %19 OpSelectionMerge %218 None OpBranchConditional %216 %217 %218 %217 = OpLabel %219 = OpAccessChain %41 %62 %28 %220 = OpLoad %18 %219 %221 = OpSGreaterThan %50 %220 %19 OpBranch %218 %218 = OpLabel %222 = OpPhi %50 %216 %207 %221 %217 OpSelectionMerge %224 None OpBranchConditional %222 %223 %224 %223 = OpLabel %225 = OpAccessChain %41 %62 %28 %226 = OpLoad %18 %225 %227 = OpISub %18 %226 %82 %228 = OpAccessChain %41 %62 %35 %229 = OpLoad %18 %228 %230 = OpIMul %18 %229 %86 %231 = OpIAdd %18 %227 %230 %232 = OpAccessChain %57 %55 %231 %233 = OpLoad %18 %232 %234 = OpIEqual %50 %233 %19 OpBranch %224 %224 = OpLabel %235 = OpPhi %50 %222 %218 %234 %223 OpSelectionMerge %237 None OpBranchConditional %235 %236 %237 %236 = OpLabel %238 = OpLoad %18 %208 %239 = OpISub %18 %238 %60 OpStore %208 %239 %240 = OpAccessChain %41 %62 %28 %241 = OpLoad %18 %240 %242 = OpAccessChain %41 %62 %35 %243 = OpLoad %18 %242 %244 = OpIMul %18 %243 %86 %245 = OpIAdd %18 %241 %244 %246 = OpAccessChain %57 %55 %245 OpStore %246 %60 %247 = OpAccessChain %41 %62 %28 %248 = OpLoad %18 %247 %249 = OpISub %18 %248 %60 %250 = OpAccessChain %41 %62 %35 %251 = OpLoad %18 %250 %252 = OpIMul %18 %251 %86 %253 = OpIAdd %18 %249 %252 %254 = OpAccessChain %57 %55 %253 OpStore %254 %60 %255 = OpAccessChain %41 %62 %28 %256 = OpLoad %18 %255 %257 = OpISub %18 %256 %82 %258 = OpAccessChain %41 %62 %35 %259 = OpLoad %18 %258 %260 = OpIMul %18 %259 %86 %261 = OpIAdd %18 %257 %260 %262 = OpAccessChain %57 %55 %261 OpStore %262 %60 %263 = OpAccessChain %41 %62 %28 %264 = OpLoad %18 %263 %265 = OpISub %18 %264 %82 %266 = OpAccessChain %41 %62 %28 OpStore %266 %265 OpBranch %237 %237 = OpLabel %267 = OpLoad %18 %208 %268 = OpSGreaterThanEqual %50 %267 %19 OpSelectionMerge %270 None OpBranchConditional %268 %269 %270 %269 = OpLabel %271 = OpAccessChain %41 %62 %35 %272 = OpLoad %18 %271 %273 = OpSGreaterThan %50 %272 %19 OpBranch %270 %270 = OpLabel %274 = OpPhi %50 %268 %237 %273 %269 OpSelectionMerge %276 None OpBranchConditional %274 %275 %276 %275 = OpLabel %277 = OpAccessChain %41 %62 %28 %278 = OpLoad %18 %277 %279 = OpAccessChain %41 %62 %35 %280 = OpLoad %18 %279 %281 = OpISub %18 %280 %82 %282 = OpIMul %18 %281 %86 %283 = OpIAdd %18 %278 %282 %284 = OpAccessChain %57 %55 %283 %285 = OpLoad %18 %284 %286 = OpIEqual %50 %285 %19 OpBranch %276 %276 = OpLabel %287 = OpPhi %50 %274 %270 %286 %275 OpSelectionMerge %289 None OpBranchConditional %287 %288 %289 %288 = OpLabel %290 = OpLoad %18 %208 %291 = OpISub %18 %290 %60 OpStore %208 %291 %292 = OpAccessChain %41 %62 %28 %293 = OpLoad %18 %292 %294 = OpAccessChain %41 %62 %35 %295 = OpLoad %18 %294 %296 = OpIMul %18 %295 %86 %297 = OpIAdd %18 %293 %296 %298 = OpAccessChain %57 %55 %297 OpStore %298 %60 %299 = OpAccessChain %41 %62 %28 %300 = OpLoad %18 %299 %301 = OpAccessChain %41 %62 %35 %302 = OpLoad %18 %301 %303 = OpISub %18 %302 %60 %304 = OpIMul %18 %303 %86 %305 = OpIAdd %18 %300 %304 %306 = OpAccessChain %57 %55 %305 OpStore %306 %60 %307 = OpAccessChain %41 %62 %28 %308 = OpLoad %18 %307 %309 = OpAccessChain %41 %62 %35 %310 = OpLoad %18 %309 %311 = OpISub %18 %310 %82 %312 = OpIMul %18 %311 %86 %313 = OpIAdd %18 %308 %312 %314 = OpAccessChain %57 %55 %313 OpStore %314 %60 %315 = OpAccessChain %41 %62 %35 %316 = OpLoad %18 %315 %317 = OpISub %18 %316 %82 %318 = OpAccessChain %41 %62 %35 OpStore %318 %317 OpBranch %289 %289 = OpLabel %319 = OpLoad %18 %208 %320 = OpSGreaterThanEqual %50 %319 %19 OpSelectionMerge %322 None OpBranchConditional %320 %321 %322 %321 = OpLabel %323 = OpAccessChain %41 %62 %28 %324 = OpLoad %18 %323 %325 = OpSLessThan %50 %324 %119 OpBranch %322 %322 = OpLabel %326 = OpPhi %50 %320 %289 %325 %321 OpSelectionMerge %328 None OpBranchConditional %326 %327 %328 %327 = OpLabel %329 = OpAccessChain %41 %62 %28 %330 = OpLoad %18 %329 %331 = OpIAdd %18 %330 %82 %332 = OpAccessChain %41 %62 %35 %333 = OpLoad %18 %332 %334 = OpIMul %18 %333 %86 %335 = OpIAdd %18 %331 %334 %336 = OpAccessChain %57 %55 %335 %337 = OpLoad %18 %336 %338 = OpIEqual %50 %337 %19 OpBranch %328 %328 = OpLabel %339 = OpPhi %50 %326 %322 %338 %327 OpSelectionMerge %341 None OpBranchConditional %339 %340 %341 %340 = OpLabel %342 = OpLoad %18 %208 %343 = OpISub %18 %342 %60 OpStore %208 %343 %344 = OpAccessChain %41 %62 %28 %345 = OpLoad %18 %344 %346 = OpAccessChain %41 %62 %35 %347 = OpLoad %18 %346 %348 = OpIMul %18 %347 %86 %349 = OpIAdd %18 %345 %348 %350 = OpAccessChain %57 %55 %349 OpStore %350 %60 %351 = OpAccessChain %41 %62 %28 %352 = OpLoad %18 %351 %353 = OpIAdd %18 %352 %60 %354 = OpAccessChain %41 %62 %35 %355 = OpLoad %18 %354 %356 = OpIMul %18 %355 %86 %357 = OpIAdd %18 %353 %356 %358 = OpAccessChain %57 %55 %357 OpStore %358 %60 %359 = OpAccessChain %41 %62 %28 %360 = OpLoad %18 %359 %361 = OpIAdd %18 %360 %82 %362 = OpAccessChain %41 %62 %35 %363 = OpLoad %18 %362 %364 = OpIMul %18 %363 %86 %365 = OpIAdd %18 %361 %364 %366 = OpAccessChain %57 %55 %365 OpStore %366 %60 %367 = OpAccessChain %41 %62 %28 %368 = OpLoad %18 %367 %369 = OpIAdd %18 %368 %82 %370 = OpAccessChain %41 %62 %28 OpStore %370 %369 OpBranch %341 %341 = OpLabel %371 = OpLoad %18 %208 %372 = OpSGreaterThanEqual %50 %371 %19 OpSelectionMerge %374 None OpBranchConditional %372 %373 %374 %373 = OpLabel %375 = OpAccessChain %41 %62 %35 %376 = OpLoad %18 %375 %377 = OpSLessThan %50 %376 %119 OpBranch %374 %374 = OpLabel %378 = OpPhi %50 %372 %341 %377 %373 OpSelectionMerge %380 None OpBranchConditional %378 %379 %380 %379 = OpLabel %381 = OpAccessChain %41 %62 %28 %382 = OpLoad %18 %381 %383 = OpAccessChain %41 %62 %35 %384 = OpLoad %18 %383 %385 = OpIAdd %18 %384 %82 %386 = OpIMul %18 %385 %86 %387 = OpIAdd %18 %382 %386 %388 = OpAccessChain %57 %55 %387 %389 = OpLoad %18 %388 %390 = OpIEqual %50 %389 %19 OpBranch %380 %380 = OpLabel %391 = OpPhi %50 %378 %374 %390 %379 OpSelectionMerge %393 None OpBranchConditional %391 %392 %393 %392 = OpLabel %394 = OpLoad %18 %208 %395 = OpISub %18 %394 %60 OpStore %208 %395 %396 = OpAccessChain %41 %62 %28 %397 = OpLoad %18 %396 %398 = OpAccessChain %41 %62 %35 %399 = OpLoad %18 %398 %400 = OpIMul %18 %399 %86 %401 = OpIAdd %18 %397 %400 %402 = OpAccessChain %57 %55 %401 OpStore %402 %60 %403 = OpAccessChain %41 %62 %28 %404 = OpLoad %18 %403 %405 = OpAccessChain %41 %62 %35 %406 = OpLoad %18 %405 %407 = OpIAdd %18 %406 %60 %408 = OpIMul %18 %407 %86 %409 = OpIAdd %18 %404 %408 %410 = OpAccessChain %57 %55 %409 OpStore %410 %60 %411 = OpAccessChain %41 %62 %28 %412 = OpLoad %18 %411 %413 = OpAccessChain %41 %62 %35 %414 = OpLoad %18 %413 %415 = OpIAdd %18 %414 %82 %416 = OpIMul %18 %415 %86 %417 = OpIAdd %18 %412 %416 %418 = OpAccessChain %57 %55 %417 OpStore %418 %60 %419 = OpAccessChain %41 %62 %35 %420 = OpLoad %18 %419 %421 = OpIAdd %18 %420 %82 %422 = OpAccessChain %41 %62 %35 OpStore %422 %421 OpBranch %393 %393 = OpLabel OpBranch %161 %161 = OpLabel %423 = OpAccessChain %41 %26 %35 %424 = OpLoad %18 %423 %425 = OpIMul %18 %424 %86 %426 = OpAccessChain %41 %26 %28 %427 = OpLoad %18 %426 %428 = OpIAdd %18 %425 %427 %429 = OpAccessChain %57 %55 %428 %430 = OpLoad %18 %429 %431 = OpIEqual %50 %430 %60 OpSelectionMerge %433 None OpBranchConditional %431 %432 %433 %432 = OpLabel OpStore %435 %437 OpReturn %433 = OpLabel OpBranch %71 %71 = OpLabel %439 = OpLoad %50 %65 OpBranchConditional %439 %68 %70 %70 = OpLabel OpStore %435 %441 OpReturn OpFunctionEnd
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft %> <%docstring>fchownat(fd, file, owner, group, flag) -> str Invokes the syscall fchownat. See 'man 2 fchownat' for more information. Arguments: fd(int): fd file(char*): file owner(uid_t): owner group(gid_t): group flag(int): flag Returns: int </%docstring> <%page args="fd=0, file=0, owner=0, group=0, flag=0"/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = ['file'] can_pushstr_array = [] argument_names = ['fd', 'file', 'owner', 'group', 'flag'] argument_values = [fd, file, owner, group, flag] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%r' % (name, arg)) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, str): string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_fchownat']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* fchownat(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
<% from pwnlib.regsort import regsort from pwnlib.constants import Constant, eval from pwnlib.shellcraft import registers from pwnlib.shellcraft.thumb import mov %> <%page args="reg_context, stack_allowed = True"/> <%docstring> Sets multiple registers, taking any register dependencies into account (i.e., given eax=1,ebx=eax, set ebx first). Args: reg_context (dict): Desired register context stack_allowed (bool): Can the stack be used? Example: >>> print shellcraft.setregs({'r0':1, 'r2':'r3'}).rstrip() mov r0, #1 mov r2, r3 >>> print shellcraft.setregs({'r0':'r1', 'r1':'r0', 'r2':'r3'}).rstrip() mov r2, r3 eor r0, r0, r1 /* xchg r0, r1 */ eor r1, r0, r1 eor r0, r0, r1 </%docstring> <% reg_context = {k:v for k,v in reg_context.items() if v is not None} sorted_regs = regsort(reg_context, registers.arm) %> % if not sorted_regs: /* setregs noop */ % else: % for how, dst, src in regsort(reg_context, registers.arm): % if how == 'xchg': eor ${dst}, ${dst}, ${src} /* xchg ${dst}, ${src} */ eor ${src}, ${dst}, ${src} eor ${dst}, ${dst}, ${src} % else: ${mov(dst, src)} % endif % endfor % endif
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/vision/utils/score_calibration.h" #include <cmath> #include <memory> #include <utility> #include <vector> #include "external/com_google_absl/absl/status/status.h" #include "external/com_google_absl/absl/strings/str_format.h" #include "external/com_google_absl/absl/strings/str_split.h" #include "external/com_google_absl/absl/strings/string_view.h" #include "external/com_google_absl/absl/types/optional.h" #include "tensorflow_lite_support/cc/common.h" #include "tensorflow_lite_support/cc/port/status_macros.h" namespace tflite { namespace task { namespace vision { namespace { using ::absl::StatusCode; using ::tflite::support::CreateStatusWithPayload; using ::tflite::support::StatusOr; using ::tflite::support::TfLiteSupportStatus; // Used to prevent log(<=0.0) in ClampedLog() calls. constexpr float kLogScoreMinimum = 1e-16; // Returns the following, depending on x: // x => threshold: log(x) // x < threshold: 2 * log(thresh) - log(2 * thresh - x) // This form (a) is anti-symmetric about the threshold and (b) has continuous // value and first derivative. This is done to prevent taking the log of values // close to 0 which can lead to floating point errors and is better than simple // clamping since it preserves order for scores less than the threshold. float ClampedLog(float x, float threshold) { if (x < threshold) { return 2.0 * std::log(static_cast<double>(threshold)) - log(2.0 * threshold - x); } return std::log(static_cast<double>(x)); } // Applies the specified score transformation to the provided score. // Currently supports the following, // IDENTITY : f(x) = x // LOG : f(x) = log(x) // INVERSE_LOGISTIC : f(x) = log(x) - log(1-x) float ApplyScoreTransformation(float score, const ScoreTransformation& type) { switch (type) { case ScoreTransformation::kIDENTITY: return score; case ScoreTransformation::kINVERSE_LOGISTIC: return (ClampedLog(score, kLogScoreMinimum) - ClampedLog(1.0 - score, kLogScoreMinimum)); case ScoreTransformation::kLOG: return ClampedLog(score, kLogScoreMinimum); } } // Builds a single Sigmoid from the label name and associated CSV file line. StatusOr<Sigmoid> SigmoidFromLabelAndLine(absl::string_view label, absl::string_view line) { std::vector<absl::string_view> str_params = absl::StrSplit(line, ','); if (str_params.size() != 3 && str_params.size() != 4) { return CreateStatusWithPayload( StatusCode::kInvalidArgument, absl::StrFormat("Expected 3 or 4 parameters per line in score " "calibration file, got %d.", str_params.size()), TfLiteSupportStatus::kMetadataMalformedScoreCalibrationError); } std::vector<float> float_params(4); for (int i = 0; i < str_params.size(); ++i) { if (!absl::SimpleAtof(str_params[i], &float_params[i])) { return CreateStatusWithPayload( StatusCode::kInvalidArgument, absl::StrFormat( "Could not parse score calibration parameter as float: %s.", str_params[i]), TfLiteSupportStatus::kMetadataMalformedScoreCalibrationError); } } Sigmoid sigmoid; sigmoid.label = std::string(label); sigmoid.scale = float_params[0]; sigmoid.slope = float_params[1]; sigmoid.offset = float_params[2]; if (str_params.size() == 4) { sigmoid.min_uncalibrated_score = float_params[3]; } return sigmoid; } // Converts a tflite::ScoreTransformationType to its // tflite::task::vision::ScoreTransformation equivalent. ScoreTransformation ConvertScoreTransformationType( tflite::ScoreTransformationType type) { switch (type) { case tflite::ScoreTransformationType_IDENTITY: return ScoreTransformation::kIDENTITY; case tflite::ScoreTransformationType_LOG: return ScoreTransformation::kLOG; case tflite::ScoreTransformationType_INVERSE_LOGISTIC: return ScoreTransformation::kINVERSE_LOGISTIC; } } } // namespace std::ostream& operator<<(std::ostream& os, const Sigmoid& s) { os << s.label << "," << s.slope << "," << s.offset << "," << s.scale; if (s.min_uncalibrated_score.has_value()) { os << "," << s.min_uncalibrated_score.value(); } return os; } ScoreCalibration::ScoreCalibration() {} ScoreCalibration::~ScoreCalibration() {} absl::Status ScoreCalibration::InitializeFromParameters( const SigmoidCalibrationParameters& params) { sigmoid_parameters_ = std::move(params); // Fill in the map from label -> sigmoid. sigmoid_parameters_map_.clear(); for (const auto& sigmoid : sigmoid_parameters_.sigmoid) { sigmoid_parameters_map_.insert_or_assign(sigmoid.label, sigmoid); } return absl::OkStatus(); } float ScoreCalibration::ComputeCalibratedScore(const std::string& label, float uncalibrated_score) const { absl::optional<Sigmoid> sigmoid = FindSigmoidParameters(label); if (!sigmoid.has_value() || (sigmoid.value().min_uncalibrated_score.has_value() && uncalibrated_score < sigmoid.value().min_uncalibrated_score.value())) { return sigmoid_parameters_.default_score; } float transformed_score = ApplyScoreTransformation( uncalibrated_score, sigmoid_parameters_.score_transformation); float scale_shifted_score = transformed_score * sigmoid.value().slope + sigmoid.value().offset; // For numerical stability use 1 / (1+exp(-x)) when scale_shifted_score >= 0 // and exp(x) / (1+exp(x)) when scale_shifted_score < 0. if (scale_shifted_score >= 0.0) { return sigmoid.value().scale / (1.0 + std::exp(static_cast<double>(-scale_shifted_score))); } else { float score_exp = std::exp(static_cast<double>(scale_shifted_score)); return sigmoid.value().scale * score_exp / (1.0 + score_exp); } } absl::optional<Sigmoid> ScoreCalibration::FindSigmoidParameters( const std::string& label) const { auto it = sigmoid_parameters_map_.find(label); if (it != sigmoid_parameters_map_.end()) { return it->second; } else if (sigmoid_parameters_.default_sigmoid.has_value()) { return sigmoid_parameters_.default_sigmoid.value(); } return absl::nullopt; } StatusOr<SigmoidCalibrationParameters> BuildSigmoidCalibrationParams( const tflite::ScoreCalibrationOptions& score_calibration_options, absl::string_view score_calibration_file, const std::vector<LabelMapItem>& label_map_items) { // Split file lines and perform sanity checks. if (score_calibration_file.empty()) { return CreateStatusWithPayload( StatusCode::kInvalidArgument, "Expected non-empty score calibration file."); } std::vector<absl::string_view> lines = absl::StrSplit(score_calibration_file, '\n'); if (label_map_items.size() != lines.size()) { return CreateStatusWithPayload( StatusCode::kInvalidArgument, absl::StrFormat("Mismatch between number of labels (%d) and score " "calibration parameters (%d).", label_map_items.size(), lines.size()), TfLiteSupportStatus::kMetadataNumLabelsMismatchError); } // Initialize SigmoidCalibrationParameters with its class-agnostic parameters. SigmoidCalibrationParameters sigmoid_params = {}; sigmoid_params.score_transformation = ConvertScoreTransformationType( score_calibration_options.score_transformation()); sigmoid_params.default_score = score_calibration_options.default_score(); std::vector<Sigmoid> sigmoid_vector; // Fill sigmoids for each class with parameters in the file. for (int i = 0; i < label_map_items.size(); ++i) { if (lines[i].empty()) { continue; } ASSIGN_OR_RETURN(Sigmoid sigmoid, SigmoidFromLabelAndLine( label_map_items[i].name, lines[i])); sigmoid_vector.emplace_back(std::move(sigmoid)); } sigmoid_params.sigmoid = std::move(sigmoid_vector); return sigmoid_params; } } // namespace vision } // namespace task } // namespace tflite
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r8 push %r9 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x14d2c, %rbx and $6005, %r8 mov (%rbx), %ebp cmp $64412, %r12 lea addresses_UC_ht+0xb90c, %rsi lea addresses_UC_ht+0x452c, %rdi clflush (%rsi) nop sub $55772, %r9 mov $14, %rcx rep movsb add $18058, %rdi lea addresses_UC_ht+0xc66c, %rcx nop nop nop nop nop add %rsi, %rsi mov $0x6162636465666768, %r8 movq %r8, %xmm3 movups %xmm3, (%rcx) nop nop nop cmp $24077, %r8 lea addresses_normal_ht+0x93ec, %rsi lea addresses_WT_ht+0x1dbe6, %rdi nop nop nop nop add %rbx, %rbx mov $71, %rcx rep movsq nop cmp %rbx, %rbx lea addresses_D_ht+0x1bdcd, %rsi lea addresses_D_ht+0xfc94, %rdi nop nop sub $10231, %rbx mov $37, %rcx rep movsl nop nop nop nop nop and %rbx, %rbx lea addresses_D_ht+0x1a92c, %rbx nop nop nop nop nop xor $32554, %rbp mov $0x6162636465666768, %rcx movq %rcx, %xmm4 vmovups %ymm4, (%rbx) nop xor %r8, %r8 lea addresses_WT_ht+0x872c, %rbp nop nop nop nop nop dec %rcx movb (%rbp), %bl nop nop nop nop add %rsi, %rsi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r9 pop %r8 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r14 push %r15 push %rcx push %rdi push %rsi // Store mov $0xa2c, %rsi nop nop sub %r12, %r12 mov $0x5152535455565758, %rcx movq %rcx, (%rsi) dec %rsi // Faulty Load lea addresses_D+0xd32c, %r14 nop nop nop and %r15, %r15 movb (%r14), %r12b lea oracles, %rcx and $0xff, %r12 shlq $12, %r12 mov (%rcx,%r12,1), %r12 pop %rsi pop %rdi pop %rcx pop %r15 pop %r14 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_P'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 1, 'NT': False, 'type': 'addresses_D'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 5, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_UC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 0, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
; A278169: Characteristic function for A000960. ; 1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 mov $2,2 mov $7,$0 lpb $2 mov $0,$7 sub $2,1 add $0,$2 sub $0,1 mov $4,2 mov $5,2 lpb $0 mul $0,$4 mov $3,1 add $3,$4 mov $5,2 add $5,$4 mov $4,$3 add $4,1 div $0,$4 sub $0,1 lpe mov $6,$2 lpb $6 mov $1,$5 sub $6,1 lpe lpe lpb $7 sub $1,$5 mov $7,0 lpe div $1,2
; void sp1_PutSprClr(uchar **sprdest, struct sp1_ap *src, uchar n) ; 02.2006 aralbrec, Sprite Pack v3.0 ; sinclair spectrum version SECTION code_clib SECTION code_temp_sp1 PUBLIC asm_sp1_PutSprClr asm_sp1_PutSprClr: ; Colour sprite by writing (mask,attr) pairs into each ; struct_sp1_cs whose addresses are stored in the array ; pointed at by hl. The array of struct_sp1_cs is ; populated by a call to SP1GetSprClrAddr. ; ; enter : b = number of colour pairs to copy (size of sprite in tiles) ; de = struct sp1_ap[] source array of colour pairs ; hl = array of sprite colour addresses (all point at struct sp1_cs.attr_mask) ; uses : af, bc, de, hl ld c,$ff .loop push de ld e,(hl) inc hl ld d,(hl) ; de = & sp1_cs.attr_mask inc hl ex (sp),hl ; hl = struct sp1_ap[ ldi ; copy mask and attribute into struct sp1_cs ldi pop de ; de = array of sprite colour addresses advanced one entry ex de,hl djnz loop ret
; A184536: a(n) = floor(1/{(1+n^4)^(1/4)}), where {} = fractional part. ; 5,32,108,256,500,864,1372,2048,2916,4000,5324,6912,8788,10976,13500,16384,19652,23328,27436,32000,37044,42592,48668,55296,62500,70304,78732,87808,97556,108000,119164,131072,143748,157216,171500,186624,202612,219488,237276,256000,275684,296352,318028,340736,364500,389344,415292,442368,470596,500000,530604,562432,595508,629856,665500,702464,740772,780448,821516,864000,907924,953312,1000188 add $0,1 pow $0,3 mul $0,4 trn $0,5 add $0,5
[org 0x0100] jmp start arr: dw 0,0,0,0,0,0,0,0 start: push word testFunct call addtoset push word testFunct call addtoset call callset end: mov ax, 0x4c00 int 21h ;An implied operand say any register which stores the count of the offsets in the array ;will make the solution simpler addtoset: push bp mov bp, sp pusha mov ax, 0 mov bx, 0 mov dx, [bp + 4] ;Offset to be copied loop1: cmp ax, [arr + bx] jnz skip mov [arr + bx], dx jmp return skip: add bx, 2 cmp bx, 16 jnz loop1 return: popa pop bp ret 2 ;An implied operand say any register which stores the count of the offsets in the array ;will make the solution simpler callset: push bp mov bp, sp pusha mov ax, 0 mov bx, 0 _loop1: cmp ax, [arr + bx] jz skipcall call [arr + bx] skipcall: add bx, 2 cmp bx, 16 jnz _loop1 _return: popa pop bp ret testFunct: ;Does nothing. ret
/* * Copyright (c) 2017, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ L0: (W&~f0.1)jmpi L400 L16: add (1|M0) a0.0<1>:ud r23.5<0;1,0>:ud 0x44EB100:ud mov (1|M0) r16.2<1>:ud 0xE000:ud mov (1|M0) r25.2<1>:f r10.0<0;1,0>:f mov (8|M0) r17.0<1>:ud r25.0<8;8,1>:ud send (1|M0) r96:uw r16:ub 0x2 a0.0 mov (16|M0) r104.0<1>:uw r98.0<16;16,1>:uw mov (16|M0) r105.0<1>:uw r99.0<16;16,1>:uw mov (8|M0) r17.0<1>:ud r25.0<8;8,1>:ud add (1|M0) a0.0<1>:ud r23.5<0;1,0>:ud 0x44EC101:ud mov (1|M0) r16.2<1>:ud 0x5000:ud mov (1|M0) r17.2<1>:f r10.0<0;1,0>:f mov (1|M0) r17.3<1>:f r10.7<0;1,0>:f send (1|M0) r100:uw r16:ub 0x2 a0.0 mov (1|M0) r17.2<1>:f r10.0<0;1,0>:f mov (1|M0) r17.3<1>:f r10.4<0;1,0>:f send (1|M0) r108:uw r16:ub 0x2 a0.0 mov (16|M0) r98.0<1>:uw 0xFFFF:uw mov (16|M0) r99.0<1>:uw 0xFFFF:uw mov (16|M0) r106.0<1>:uw 0xFFFF:uw mov (16|M0) r107.0<1>:uw 0xFFFF:uw mov (1|M0) a0.8<1>:uw 0xC00:uw mov (1|M0) a0.9<1>:uw 0xC80:uw mov (1|M0) a0.10<1>:uw 0xCC0:uw add (4|M0) a0.12<1>:uw a0.8<4;4,1>:uw 0x100:uw L400: nop
; A265333: Characteristic function for A265334: a(n) = 1 if n >= k! but < 2*k! for some k, 0 otherwise. ; 0,1,1,1,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0 mov $1,$0 mov $2,1 lpb $0,1 mul $1,2 add $2,1 mov $3,$1 div $3,$2 mov $0,$3 trn $0,1 mov $1,$3 add $2,1 lpe
; A011936: a(n) = floor( n(n-1)(n-2)(n-3)/26 ). ; 0,0,0,0,0,4,13,32,64,116,193,304,456,660,924,1260,1680,2196,2824,3577,4472,5524,6752,8173,9808,11676,13800,16200,18900,21924,25296,29044,33193,37772,42808,48332,54373 bin $0,4 mul $0,24 div $0,26
; A157843: 1728000n - 1343760. ; 384240,2112240,3840240,5568240,7296240,9024240,10752240,12480240,14208240,15936240,17664240,19392240,21120240,22848240,24576240,26304240,28032240,29760240,31488240,33216240,34944240,36672240,38400240,40128240,41856240,43584240,45312240,47040240,48768240,50496240,52224240,53952240,55680240,57408240,59136240,60864240,62592240,64320240,66048240,67776240,69504240,71232240,72960240,74688240,76416240,78144240,79872240,81600240,83328240,85056240,86784240,88512240,90240240,91968240,93696240,95424240,97152240,98880240,100608240,102336240,104064240,105792240,107520240,109248240,110976240,112704240,114432240,116160240,117888240,119616240,121344240,123072240,124800240,126528240,128256240,129984240,131712240,133440240,135168240,136896240,138624240,140352240,142080240,143808240,145536240,147264240,148992240,150720240,152448240,154176240,155904240,157632240,159360240,161088240,162816240,164544240,166272240,168000240,169728240,171456240 mul $0,1728000 add $0,384240
; ; MSX specific routines ; by Stefano Bodrato, December 2007 ; ; int msx_sound(int reg, int val); ; ; Play a sound by PSG ; ; ; $Id: set_psg_callee.asm $ ; SECTION code_clib PUBLIC set_psg_callee PUBLIC _set_psg_callee ;; EXTERN msxbios PUBLIC asm_set_psg IF FORmsx INCLUDE "target/msx/def/msx.def" ELSE INCLUDE "target/svi/def/svi.def" ENDIF set_psg_callee: _set_psg_callee: pop hl pop de ex (sp),hl .asm_set_psg ld a,l cp 7 jr nz,not_reg7 ld a,e and @00111111 or @10000000 ld e,a ld a,l not_reg7: di out (PSG_ADDR),a push af ld a,e out (PSG_DATA),a ei pop af ret
; void SMS_useFirstHalfTilesforSprites(_Bool usefirsthalf) SECTION code_clib SECTION code_SMSlib PUBLIC _SMS_useFirstHalfTilesforSprites EXTERN asm_SMSlib_useFirstHalfTilesforSprites _SMS_useFirstHalfTilesforSprites: pop af pop hl push hl push af jp asm_SMSlib_useFirstHalfTilesforSprites
;this file for FamiStudio Sound Engine generated by FamiStudio journey_to_silius_music_data: .db 1 .dw .instruments .dw .samples-3 .dw .song0ch0,.song0ch1,.song0ch2,.song0ch3,.song0ch4 .db LOW(.tempo_env_5_mid), HIGH(.tempo_env_5_mid), 0, 0 .instruments: .dw .env2,.env0,.env9,.env4 .dw .env3,.env0,.env9,.env4 .dw .env12,.env0,.env9,.env8 .dw .env17,.env0,.env9,.env8 .dw .env3,.env0,.env13,.env4 .dw .env7,.env0,.env13,.env8 .dw .env5,.env0,.env10,.env4 .dw .env17,.env0,.env10,.env8 .dw .env6,.env14,.env9,.env8 .dw .env16,.env15,.env9,.env8 .dw .env6,.env15,.env9,.env8 .dw .env1,.env11,.env9,.env8 .dw .env1,.env0,.env9,.env8 .samples: .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;1 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;2 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;3 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;4 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;5 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;6 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;7 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;8 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;9 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;10 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;11 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;12 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;13 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;14 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;15 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$3e,$08 ;16 (Sample 2) .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;17 .db $10+LOW(FAMISTUDIO_DPCM_PTR),$3f,$09 ;18 (Sample 1) .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;19 .db $10+LOW(FAMISTUDIO_DPCM_PTR),$3f,$0a ;20 (Sample 1) .db $00+LOW(FAMISTUDIO_DPCM_PTR),$3e,$0a ;21 (Sample 2) .db $20+LOW(FAMISTUDIO_DPCM_PTR),$3f,$0a ;22 (Sample 5) .db $30+LOW(FAMISTUDIO_DPCM_PTR),$3e,$0c ;23 (Sample 4) .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;24 .db $10+LOW(FAMISTUDIO_DPCM_PTR),$3f,$0c ;25 (Sample 1) .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;26 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;27 .db $40+LOW(FAMISTUDIO_DPCM_PTR),$3f,$0d ;28 (Sample 3) .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;29 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$3e,$0d ;30 (Sample 2) .db $40+LOW(FAMISTUDIO_DPCM_PTR),$3f,$0e ;31 (Sample 3) .db $10+LOW(FAMISTUDIO_DPCM_PTR),$3f,$0e ;32 (Sample 1) .db $00+LOW(FAMISTUDIO_DPCM_PTR),$3e,$0e ;33 (Sample 2) .db $20+LOW(FAMISTUDIO_DPCM_PTR),$3f,$0e ;34 (Sample 5) .db $30+LOW(FAMISTUDIO_DPCM_PTR),$3e,$0f ;35 (Sample 4) .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;36 .db $10+LOW(FAMISTUDIO_DPCM_PTR),$3f,$0f ;37 (Sample 1) .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;38 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;39 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;40 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;41 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;42 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;43 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;44 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;45 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;46 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;47 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;48 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;49 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;50 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;51 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;52 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;53 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;54 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;55 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;56 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;57 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;58 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;59 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;60 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;61 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;62 .db $00+LOW(FAMISTUDIO_DPCM_PTR),$00,$00 ;63 .env0: .db $c0,$7f,$00,$00 .env1: .db $04,$cf,$7f,$00,$01 .env2: .db $08,$ce,$cb,$ca,$c9,$c9,$00,$05,$c1,$c5,$c4,$c3,$c2,$c1,$00,$0d .env3: .db $0f,$c4,$c6,$c9,$c8,$0e,$c7,$0e,$c6,$0e,$c5,$0e,$c4,$00,$0c,$c1,$c5,$c4,$c3,$c2,$c1,$00,$14 .env4: .db $00,$c0,$07,$c1,$c3,$c6,$c3,$c1,$bf,$bd,$ba,$bd,$bf,$00,$03 .env5: .db $0e,$c5,$c6,$c6,$ca,$cb,$cc,$cb,$ca,$c9,$c8,$c7,$00,$0b,$c1,$c5,$c4,$c3,$c2,$c1,$00,$13 .env6: .db $00,$cc,$cc,$c9,$c5,$c2,$c0,$00,$06 .env7: .db $04,$c3,$7f,$00,$01 .env8: .db $00,$c0,$7f,$00,$01 .env9: .db $7f,$00,$00 .env10: .db $c2,$7f,$00,$00 .env11: .db $c0,$bf,$be,$bd,$bc,$bb,$ba,$b9,$b8,$b7,$00,$09 .env12: .db $00,$c5,$c9,$c9,$c8,$00,$04 .env13: .db $c1,$7f,$00,$00 .env14: .db $c0,$c3,$00,$01 .env15: .db $c0,$c6,$00,$01 .env16: .db $00,$cd,$ce,$cc,$c8,$c9,$c7,$c6,$c4,$c3,$c1,$c0,$00,$0b .env17: .db $04,$c4,$7f,$00,$01 .env18: .db $00,$c0,$be,$bc,$bc,$bd,$bf,$c1,$c3,$c4,$c4,$c2,$00,$01 .tempo_env_5_mid: .db $03,$04,$07,$04,$05,$05,$80 .song0ch0: .db $cf .song0ch0loop: .db $6a, LOW(.tempo_env_5_mid), HIGH(.tempo_env_5_mid), $00, $a5, $8a, $25, $91, $28, $91, $25, $91, $2a, $2b, $81, $2c, $9f .db $2a, $91 .ref22: .db $82, $20, $af, $f9, $87, $22 .ref28: .db $d7, $f9, $87, $6b, $00, $a5, $8a, $25, $91, $28, $91, $25, $91, $2a, $2b, $81, $2c, $9f, $2a, $91, $82, $2c, $af, $f9 .db $87, $2a .db $ff, $12 .dw .ref28 .db $ff, $1c .dw .ref22 .db $d7, $f9, $87 .ref63: .db $6b, $a7, $23, $91, $f9, $91, $22, $87, $f9, $87, $23, $91, $f9, $91, $23, $a5, $f9, $91, $22, $91, $f9, $91, $22, $87 .db $f9, $87, $23, $87, $f9, $af .db $ff, $1d .dw .ref63 .db $ff, $1d .dw .ref63 .db $6b, $a7, $23, $91, $f9, $91, $22, $87, $f9, $87, $23, $91, $f9, $91, $20, $f7, $9b, $f9, $87, $8c .ref119: .db $25, $91, $6b, $89, $f9, $87, $25, $87, $f9, $87, $28, $87, $f9, $87, $25, $87, $f9, $87, $2a, $87, $f9, $87, $25, $91 .db $f9, $91, $2c, $9b, $f9, $87 .ref149: .db $25, $87, $f9, $87, $2a, $87, $f9, $87, $25, $87, $f9, $87, $28, $87, $f9, $87, $25, $91, $f9, $91, $20, $91, $6b, $89 .db $f9, $87, $20, $87, $f9, $87, $23, $87, $f9, $87, $20, $87, $f9, $87, $23, $87, $f9, $87, $26, $62, $27, $81, $62, $28 .db $8b, $27, $87, $f9, $87, $25, $f7, $9b, $f9, $87 .db $ff, $19 .dw .ref119 .db $2a, $62, $2b, $81, $62, $2c, $9f .db $ff, $21 .dw .ref149 .db $25, $87, $f9, $87, $26, $62, $27, $81, $62, $28, $8b, $27, $87, $f9, $87, $23, $87, $f9, $87, $25, $f7, $af, $f9, $87 .db $6b .ref245: .db $2a, $81, $62, $2b, $81, $62, $2c, $d9, $2a, $87, $f9, $87, $28, $87, $f9, $87, $27, $d7, $f9, $87, $28, $91, $f9, $87 .db $2a, $91, $f9, $87, $2a, $62, $2b, $81, $62, $2c, $8b, $6b, $f7, $93, $88, $2a, $62, $2b, $81, $62, $2c, $9f, $2a, $62 .db $2b, $81, $62, $2c, $8b, $2e, $91, $f9, $91, $2f, $9b, $f9, $af, $6b, $8c .db $ff, $1a .dw .ref245 .db $25, $91, $6b, $f7, $bb, $80, $25, $87, $f9, $87, $25, $87, $f9, $87, $25, $87, $f9, $87, $25, $87, $f9, $c3, $6b, $82 .ref335: .db $25, $c3, $f9, $87, $25, $c3, $f9, $87, $25, $af, $f9, $87, $25, $cd, $f9, $91, $6b .db $ff, $10 .dw .ref335 .db $6b .db $ff, $10 .dw .ref335 .db $6b, $27, $c3, $f9, $87, $27, $c3, $f9, $87, $27, $af, $f9, $87, $27, $cd, $f9, $91, $6b, $25, $9b, $f9, $87, $25, $9b .db $f9, $87, $25, $91, $f9, $87, $25, $91, $f9, $87, $25 .ref394: .db $af, $f9, $87, $25, $9b, $f9, $87, $25, $91, $f9, $87, $25, $91 .ref407: .db $f9, $87, $25, $91, $6b, $9d, $f9, $87, $25, $9b, $f9, $87, $25, $91, $f9, $87, $25, $91, $f9, $87, $25, $c3, $f9, $87 .db $23, $c3 .db $ff, $14 .dw .ref407 .db $ff, $18 .dw .ref394 .db $27, $91, $f9, $87, $2c, $91, $f9, $87, $2c, $f7, $af, $f9, $87, $6b, $00, $a5, $86 .ref456: .db $25, $91, $27, $91 .ref460: .db $28, $91, $2a, $91, $25, $91, $27, $91, $28, $91, $2a, $91, $25, $91, $27, $91, $28, $91, $2a, $91, $25, $91, $27, $91 .db $6b .db $ff, $18 .dw .ref460 .db $28, $91, $2a, $91, $25, $91, $27, $91, $6b .db $ff, $14 .dw .ref460 .db $27, $91, $28, $91, $2a, $91, $2c, $b9, $6b, $2f, $91, $31, $a5 .ref513: .db $33, $91, $34, $91, $36, $91, $31, $91, $33, $91, $34, $91, $36, $a5, $38, $91, $39, $91, $3b, $91, $36, $91, $38, $91 .db $6b, $39, $91, $3b, $91, $3d, $f7, $f5, $62, $61, $05, $3d, $37, $a5, $fd .dw .song0ch0loop .song0ch1: .db $cf .song0ch1loop: .db $88 .ref557: .db $25, $87, $f9, $87, $28, $87, $f9, $87, $25, $87, $f9, $87, $2a, $62, $2b, $81, $62, $2c, $9f, $2a, $87, $f9, $87, $28 .db $9b, $f9, $87, $23, $af, $f9, $87, $25, $d7, $f9, $87 .db $ff, $19 .dw .ref557 .db $2f, $af, $f9, $87, $2e, $d7, $f9, $87 .db $ff, $21 .dw .ref557 .db $ff, $19 .dw .ref557 .db $2f, $af, $f9, $87, $2e, $d7, $f9, $87, $a7, $82 .ref619: .db $28, $91, $f9, $91, $27, $87, $f9, $87, $28, $91, $f9, $91, $28, $a5, $f9, $91, $27, $91, $f9, $91, $27, $87, $f9, $87 .db $28, $87, $f9, $af, $a7 .db $ff, $1d .dw .ref619 .db $ff, $1d .dw .ref619 .db $28, $91, $f9, $91, $27, $87, $f9, $87, $28, $91, $f9, $91, $27, $f7, $af, $f9, $87, $93, $8e, $25, $b9, $28, $91, $25 .db $91, $2a, $91, $25, $a5, $2c, $a5, $25, $91, $2a, $91, $25, $91, $28, $91, $25, $91, $93, $20, $b9, $23, $91, $20, $91 .db $23, $91, $26, $27, $81, $28, $8b, $27, $91, $25, $f7, $91, $cf, $28, $91, $25, $91, $2a, $91, $25, $a5, $2a, $2b, $81 .db $2c, $9f, $25, $91, $2a, $91, $25, $91, $28, $91, $25, $91, $93, $20, $b9, $23, $91, $25, $91, $26, $27, $81, $28, $8b .db $27, $91, $23, $91, $25, $f7, $91, $a7 .ref758: .db $2a, $81, $2b, $81, $2c, $d9, $2a, $91, $28, $91, $27, $e1, $28, $9b, $2a, $87, $95, $2b, $81, $2c, $ef, $82, $27, $9b .db $f9, $87, $27, $87, $f9, $87, $2a, $91, $f9, $91, $2c, $9b, $f9, $af, $a7, $8e .db $ff, $10 .dw .ref758 .db $93, $25, $f7, $a5, $80, $20, $87, $f9, $87, $20, $87, $f9, $87, $20, $87, $f9, $87, $20, $87, $f9, $c3, $88 .ref823: .db $2c, $c3, $f9, $87, $2a, $c3, $f9, $87, $28, $af, $f9, $87, $2a, $cd, $f9, $91 .db $ff, $10 .dw .ref823 .db $ff, $10 .dw .ref823 .db $2d, $c3, $f9, $87, $2c, $c3, $f9, $87, $2a, $af, $f9, $87, $2c, $cd, $f9, $91, $2c, $9b, $f9, $87, $2a, $9b, $f9, $87 .db $28, $91, $f9, $87, $2a, $91, $f9, $87 .ref877: .db $2c, $af, $f9, $87, $2a, $9b, $f9, $87, $28, $91, $f9, $87, $2a, $91 .ref891: .db $f9, $87, $2c, $91, $9d, $f9, $87, $2a, $9b, $f9, $87, $28, $91, $f9, $87, $2a, $91, $f9, $87, $28, $c3, $f9, $87, $27 .db $c3 .db $ff, $13 .dw .ref891 .db $ff, $19 .dw .ref877 .db $2c, $91, $f9, $87, $2f, $91, $f9, $87, $31, $f7, $af, $f9, $87, $84 .db $ff, $1c .dw .ref456 .db $ff, $18 .dw .ref460 .db $ff, $18 .dw .ref460 .db $28, $91, $2a, $91, $27, $91, $28, $91, $2a, $91, $2c, $b9, $2f, $91, $31, $91, $93 .db $ff, $18 .dw .ref513 .db $39, $91, $3b, $91, $3d, $cd, $63, LOW(.env18), HIGH(.env18), $f7, $a5, $63, LOW(.env8), HIGH(.env8), $64, $81, $62, $61 .db $06, $3d, $30, $cd, $fd .dw .song0ch1loop .song0ch2: .ref990: .db $98, $32, $31, $32, $81, $31, $32, $33, $32, $31, $32, $96, $32, $85, $00, $32, $85, $00, $2a, $85, $00, $2a, $85, $00 .db $26, $8f, $00 .song0ch2loop: .db $96 .ref1019: .db $28, $83, $00, $8b, $28, $83, $00, $8b, $2e, $8f, $00, $28, $83, $00, $8b, $28, $83, $00, $8b, $28, $83, $00, $8b, $2e .db $8f, $00, $28, $83, $00, $8b .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .ref1055: .db $32, $8f, $00, $32, $8f, $00, $2a, $8f, $00, $26, $8f, $00, $32, $85, $00, $32, $85, $00, $89, $32, $85, $00, $2a, $85 .db $00, $2a, $85, $00, $26, $8f, $00 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .ref1095: .db $32, $85, $00, $32, $85, $00, $2a, $85, $00, $26, $85, $00, $32, $85, $00, $2a, $85, $00, $2a, $85, $00, $26, $85, $00 .db $ff, $17 .dw .ref990 .db $85, $00, $26, $85, $00 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1f .dw .ref1055 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $18 .dw .ref1095 .db $ff, $17 .dw .ref990 .db $85, $00, $26, $85, $00 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1f .dw .ref1055 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $18 .dw .ref1095 .db $ff, $17 .dw .ref990 .db $85, $00, $26, $85, $00 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1f .dw .ref1055 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $28, $83, $00, $8b, $2e, $8f, $00, $2e, $8f, $00, $2e, $8f, $00, $2e, $8f, $00, $95, $98, $2e, $83, $00, $9d, $96 .ref1235: .db $28, $83, $00, $c7, $28, $83, $00, $c7, $28, $83, $00, $b3, $28, $83, $00, $9f, $98, $2e, $83, $00, $8b, $96, $28, $83 .db $00, $9f .db $ff, $18 .dw .ref1235 .db $ff, $18 .dw .ref1235 .db $ff, $10 .dw .ref1235 .db $2e, $8f, $00, $2e, $8f, $00, $2e, $8f, $00 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1f .dw .ref1055 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $18 .dw .ref1095 .db $ff, $17 .dw .ref990 .db $85, $00, $26, $85, $00 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1f .dw .ref1055 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $1e .dw .ref1019 .db $ff, $18 .dw .ref1095 .db $ff, $17 .dw .ref990 .db $85, $00, $26, $85, $00 .db $ff, $1e .dw .ref1019 .db $ff, $18 .dw .ref1095 .db $ff, $17 .dw .ref990 .db $85, $00, $26, $85, $00, $fd .dw .song0ch2loop .song0ch3: .db $92, $26, $83, $26, $85, $26, $83, $26, $87, $26, $87, $26, $87, $26, $87, $26, $87, $26, $87 .song0ch3loop: .ref1380: .db $90 .ref1381: .db $1c, $91, $1c, $91, $92, $26, $91, $90, $1c, $91, $1c, $91, $1c, $91, $92, $26, $91, $90, $1c, $91 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .ref1407: .db $94, $26, $91, $26, $91, $26, $91, $26, $91, $26, $87, $26, $91, $26, $87, $26, $87, $26, $87, $26, $91 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .ref1437: .db $94 .ref1438: .db $26, $87, $26, $87, $26, $87, $26, $87, $26, $87, $26, $87, $26, $87, $26, $87 .db $ff, $10 .dw .ref1438 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .db $ff, $14 .dw .ref1407 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1437 .db $ff, $10 .dw .ref1438 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .db $ff, $14 .dw .ref1407 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1437 .db $ff, $10 .dw .ref1438 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .db $ff, $14 .dw .ref1407 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .db $1c, $91, $92, $26, $91, $26, $91, $26, $91, $26, $a7, $26, $a3, $90 .ref1546: .db $1c, $cd, $1c, $cd, $1c, $b9, $1c, $a5, $92, $26, $91, $90, $1c, $a5, $1c, $cd, $1c, $cd, $1c, $b9, $1c, $a5, $92, $26 .db $91, $90, $1c, $a5 .db $ff, $16 .dw .ref1546 .db $26, $91, $26, $91 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .db $ff, $14 .dw .ref1407 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1437 .db $ff, $10 .dw .ref1438 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .db $ff, $14 .dw .ref1407 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1381 .db $ff, $10 .dw .ref1437 .db $ff, $10 .dw .ref1438 .db $ff, $10 .dw .ref1380 .db $ff, $10 .dw .ref1437 .db $ff, $10 .dw .ref1438 .db $fd .dw .song0ch3loop .song0ch4: .db $cf .song0ch4loop: .ref1649: .db $19, $91 .ref1651: .db $19, $91, $19, $91, $19, $91, $19, $91, $19, $91, $19, $91, $19, $91, $14, $91, $14, $91, $20, $91, $12, $91, $12, $91 .db $1e, $91, $12, $91, $1e, $91 .db $ff, $10 .dw .ref1649 .ref1684: .db $10, $91, $10, $91, $1c, $91, $12, $91, $12, $91, $1e, $91, $12, $91, $1e, $91 .db $ff, $20 .dw .ref1649 .db $ff, $10 .dw .ref1649 .db $ff, $10 .dw .ref1684 .db $ff, $10 .dw .ref1649 .db $ff, $10 .dw .ref1649 .db $ff, $10 .dw .ref1649 .db $ff, $10 .dw .ref1649 .db $ff, $10 .dw .ref1649 .db $ff, $10 .dw .ref1649 .db $ff, $12 .dw .ref1651 .db $14, $91, $14, $91, $14, $91, $14, $91, $14, $91, $14, $91, $14 .ref1743: .db $91, $19, $91, $19, $91, $19, $91, $25, $91, $19, $91, $25, $91, $19, $91, $19, $91, $17, $91, $23, $91, $17, $91, $17 .db $91, $17, $91, $23, $91, $17, $91, $17, $91, $14, $91, $14, $91, $14, $91, $20, $91, $17, $91, $23, $91, $17, $91, $17 .db $91, $19, $91, $25, $91, $19, $91, $19, $91, $19, $91, $25, $91, $19, $91, $19 .db $ff, $40 .dw .ref1743 .ref1810: .db $91, $12, $91, $12, $91, $1e, $91, $12, $91, $12, $91, $12, $91, $1e, $91, $12, $91, $14, $91, $14, $91, $20, $91, $14 .db $91, $14, $91, $14, $91, $20, $91, $14, $91, $19, $91, $19, $91, $25, $91, $19, $91, $25, $91, $19, $91, $19, $91, $25 .ref1858: .db $91, $19, $91, $19, $91, $25, $91, $19, $91, $19, $91, $25, $91, $19, $91, $25 .db $ff, $35 .dw .ref1810 .db $19, $91, $19, $91, $19, $cd, $19, $cd, $19, $cd, $19, $b9, $19, $a5, $19, $91, $25, $91, $19, $91, $17, $cd, $17, $cd .db $17, $b9, $17, $a5, $17, $91, $23, $91, $17, $91, $15, $cd, $15, $cd, $15, $b9, $15, $a5, $15, $91, $23, $91, $15, $91 .db $17, $cd, $17, $cd, $17, $b9, $17, $a5, $23, $91, $17, $91, $23 .db $ff, $10 .dw .ref1858 .ref1941: .db $91, $17, $91, $17, $91, $23, $91, $17, $91, $17, $91, $23, $91, $17, $91, $23, $91, $15, $91, $15, $91, $21, $91, $15 .db $91, $15, $91, $21, $91, $15, $91, $21 .db $ff, $11 .dw .ref1941 .db $19, $91, $19, $91, $25, $91, $19, $91, $19, $91, $25, $91, $19, $91, $25 .db $ff, $20 .dw .ref1941 .db $ff, $10 .dw .ref1858 .ref1997: .db $91, $19, $91, $19, $91, $19, $91, $25, $91, $19, $91, $19, $91, $23, $91, $25, $91, $17, $91, $17, $91, $17, $91, $23 .db $91, $17, $91, $17, $91, $21, $91, $23, $91, $16, $91, $16, $91, $16, $91, $22, $91, $16, $91, $16, $91, $14, $91, $22 .db $91, $15, $91, $15, $91, $15, $91, $21, $91, $15, $91, $15, $91, $1f, $91, $21 .db $ff, $40 .dw .ref1997 .db $ff, $11 .dw .ref1997 .db $19, $91, $19, $91, $25, $91, $19, $91, $19, $91, $25, $91, $19, $91, $25, $91, $fd .dw .song0ch4loop
; A281773: Number of distinct topologies on an n-set that have exactly 4 open sets. ; 0,0,1,9,43,165,571,1869,5923,18405,56491,172029,521203,1573845,4742011,14266989,42882883,128812485,386765131,1160950749,3484162963,10455110325,31370573851,94122207309,282387593443,847204723365,2541698056171,7625261940669,22876121366323,68629035187605,205888447740091,617668027574829,1853009451433603,5559039091719045 mov $3,5 lpb $0,1 sub $0,1 mov $1,$2 add $2,1 mov $4,10 add $4,$2 add $2,$4 add $2,$1 add $5,2 add $6,5 sub $6,$3 trn $3,4 trn $6,$5 trn $5,$2 sub $2,6 mul $6,2 lpe sub $1,$6 trn $1,1
; A187339: Floor((7+sqrt(5))*n/4); complement of A187330. ; 2,4,6,9,11,13,16,18,20,23,25,27,30,32,34,36,39,41,43,46,48,50,53,55,57,60,62,64,66,69,71,73,76,78,80,83,85,87,90,92,94,96,99,101,103,106,108,110,113,115,117,120,122,124,126,129,131,133,136,138,140,143,145 add $0,1 mov $1,30 mul $1,$0 div $1,13 mov $0,$1
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %r15 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0x17ed1, %rsi lea addresses_A_ht+0x103d1, %rdi nop and $55218, %rbp mov $105, %rcx rep movsb nop nop nop nop nop sub $54809, %rcx lea addresses_UC_ht+0xa321, %rdx nop nop nop dec %r14 mov $0x6162636465666768, %r12 movq %r12, (%rdx) nop nop nop nop add %rsi, %rsi lea addresses_WC_ht+0x9ad1, %rcx sub %rdi, %rdi mov (%rcx), %r12d cmp %rdi, %rdi lea addresses_UC_ht+0x12bb1, %rsi lea addresses_UC_ht+0x7414, %rdi nop nop nop sub %r15, %r15 mov $24, %rcx rep movsq nop nop nop cmp $30752, %rsi lea addresses_normal_ht+0x1c73b, %rdi nop nop nop nop inc %r15 mov $0x6162636465666768, %rbp movq %rbp, %xmm0 vmovups %ymm0, (%rdi) nop nop nop xor %rbp, %rbp lea addresses_WC_ht+0x10611, %rdi cmp $55666, %r14 mov (%rdi), %r15 nop nop nop nop nop inc %rcx lea addresses_A_ht+0x1a761, %rsi lea addresses_A_ht+0xb3d1, %rdi and $27065, %r14 mov $71, %rcx rep movsw nop nop nop nop xor %rdx, %rdx lea addresses_normal_ht+0x159d1, %r15 nop nop nop nop nop inc %rbp and $0xffffffffffffffc0, %r15 vmovaps (%r15), %ymm7 vextracti128 $1, %ymm7, %xmm7 vpextrq $1, %xmm7, %rdx nop nop nop nop add %r14, %r14 lea addresses_UC_ht+0xa7d1, %rsi lea addresses_normal_ht+0xcfd1, %rdi clflush (%rdi) dec %r14 mov $46, %rcx rep movsb nop xor $8952, %rsi lea addresses_normal_ht+0x19779, %rdi nop nop nop nop dec %rsi movb (%rdi), %cl add $43715, %rbp lea addresses_WT_ht+0x13ca5, %r15 nop inc %rsi mov $0x6162636465666768, %rcx movq %rcx, (%r15) nop nop nop nop dec %rcx lea addresses_WT_ht+0x4591, %rsi lea addresses_UC_ht+0x1df11, %rdi clflush (%rsi) and $59953, %r15 mov $86, %rcx rep movsl nop nop nop and %rsi, %rsi lea addresses_A_ht+0x14ec1, %r15 nop nop nop nop nop and %rdx, %rdx mov $0x6162636465666768, %rbp movq %rbp, %xmm6 movups %xmm6, (%r15) nop nop nop nop nop xor $3866, %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r15 pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r9 push %rax push %rcx push %rdi push %rdx push %rsi // Store lea addresses_D+0x1b3d1, %rdx nop and $12245, %rdi mov $0x5152535455565758, %rcx movq %rcx, %xmm7 vmovups %ymm7, (%rdx) inc %rcx // REPMOV lea addresses_D+0xae71, %rsi lea addresses_normal+0x17d1, %rdi clflush (%rdi) nop nop xor %r9, %r9 mov $98, %rcx rep movsb nop nop nop nop nop sub %r9, %r9 // Faulty Load lea addresses_normal+0x17d1, %rax and %rcx, %rcx mov (%rax), %esi lea oracles, %r10 and $0xff, %rsi shlq $12, %rsi mov (%r10,%rsi,1), %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r9 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_D', 'congruent': 8}, 'OP': 'STOR'} {'dst': {'same': True, 'congruent': 0, 'type': 'addresses_normal'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_D'}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': True, 'size': 4, 'type': 'addresses_normal', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'congruent': 10, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 8, 'type': 'addresses_A_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_UC_ht', 'congruent': 3}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_WC_ht', 'congruent': 8}} {'dst': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_UC_ht'}} {'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_normal_ht', 'congruent': 1}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': True, 'NT': True, 'AVXalign': False, 'size': 8, 'type': 'addresses_WC_ht', 'congruent': 6}} {'dst': {'same': False, 'congruent': 9, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 3, 'type': 'addresses_A_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': True, 'size': 32, 'type': 'addresses_normal_ht', 'congruent': 4}} {'dst': {'same': False, 'congruent': 10, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_UC_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 1, 'type': 'addresses_normal_ht', 'congruent': 3}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WT_ht', 'congruent': 1}, 'OP': 'STOR'} {'dst': {'same': False, 'congruent': 4, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_WT_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_A_ht', 'congruent': 4}, 'OP': 'STOR'} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
/* Copyright (c) 2003, Xentronix Author: Frans van Nispen (frans@xentronix.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Xentronix 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 <LayoutBuilder.h> #include <Window.h> #include <View.h> #include <InterfaceKit.h> #include <stdlib.h> #include <stdio.h> #include "Globals.h" #include "RealtimeFilter.h" #include "AmplifierFilter.h" /******************************************************* * *******************************************************/ AmplifierFilter::AmplifierFilter(bool b) : RealtimeFilter(Language.get("AMPLIFIER"), b) { } /******************************************************* * *******************************************************/ BView *AmplifierFilter::ConfigView() { BView *view = new BView(NULL, B_WILL_DRAW); view->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); value = new SpinSlider(NULL, Language.get("LEVEL"), new BMessage(CONTROL_CHANGED), 1, 300); value->SetValue(Prefs.filter_amplifier_value); BLayoutBuilder::Group<>(view, B_VERTICAL, 0) .Add(value) .End(); return view; } void AmplifierFilter::UpdateValues() { Prefs.filter_amplifier_value = value->Value(); } /******************************************************* * *******************************************************/ void AmplifierFilter::FilterBuffer(float *buffer, size_t size) { float amp = Prefs.filter_amplifier_value/100.0; float tmp; for (size_t i=0; i<size; i++){ tmp = *buffer * amp; if (tmp>1.0) tmp = 1.0; if (tmp<-1.0) tmp = -1.0; *buffer++ = tmp; } }
global _get_random _get_random: push bp mov bp, sp sub sp, 2 mov [bp-2], bx mov ax, [bp+4] mov bx, [bp+6] call os_get_random mov ax, cx mov bx, word [bp-2] mov sp, bp pop bp ret
// Copyright (c) 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 "chrome/common/extensions/api/extension_action/page_action_handler.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_manifest_constants.h" #include "grit/generated_resources.h" namespace keys = extension_manifest_keys; namespace errors = extension_manifest_errors; namespace extensions { PageActionHandler::PageActionHandler() { } PageActionHandler::~PageActionHandler() { } bool PageActionHandler::Parse(Extension* extension, string16* error) { scoped_ptr<ActionInfo> page_action_info; const DictionaryValue* page_action_value = NULL; if (extension->manifest()->HasKey(keys::kPageActions)) { const ListValue* list_value = NULL; if (!extension->manifest()->GetList(keys::kPageActions, &list_value)) { *error = ASCIIToUTF16(errors::kInvalidPageActionsList); return false; } size_t list_value_length = list_value->GetSize(); if (list_value_length == 0u) { // A list with zero items is allowed, and is equivalent to not having // a page_actions key in the manifest. Don't set |page_action_value|. } else if (list_value_length == 1u) { if (!list_value->GetDictionary(0, &page_action_value)) { *error = ASCIIToUTF16(errors::kInvalidPageAction); return false; } } else { // list_value_length > 1u. *error = ASCIIToUTF16(errors::kInvalidPageActionsListSize); return false; } } else if (extension->manifest()->HasKey(keys::kPageAction)) { if (!extension->manifest()->GetDictionary(keys::kPageAction, &page_action_value)) { *error = ASCIIToUTF16(errors::kInvalidPageAction); return false; } } // An extension cannot have both browser and page actions. if (extension->manifest()->HasKey(keys::kBrowserAction)) { *error = ASCIIToUTF16(errors::kOneUISurfaceOnly); return false; } // If page_action_value is not NULL, then there was a valid page action. if (page_action_value) { page_action_info = ActionInfo::Load(extension, page_action_value, error); if (!page_action_info) return false; // Failed to parse page action definition. } ActionInfo::SetPageActionInfo(extension, page_action_info.release()); return true; } bool PageActionHandler::Validate(const Extension* extension, std::string* error, std::vector<InstallWarning>* warnings) const { const extensions::ActionInfo* action = extensions::ActionInfo::GetPageActionInfo(extension); if (action && !action->default_icon.empty() && !extension_file_util::ValidateExtensionIconSet( action->default_icon, extension, IDS_EXTENSION_LOAD_ICON_FOR_PAGE_ACTION_FAILED, error)) { return false; } return true; } const std::vector<std::string> PageActionHandler::Keys() const { std::vector<std::string> keys; keys.push_back(keys::kPageAction); keys.push_back(keys::kPageActions); return keys; } } // namespace extensions
; ---------------------------------------------------------------- ; Z88DK INTERFACE LIBRARY FOR NIRVANA+ ENGINE - by Einar Saukas ; ; See "nirvana+.h" for further details ; ---------------------------------------------------------------- ; void NIRVANAP_drawT(unsigned int tile, unsigned int lin, unsigned int col) SECTION code_clib SECTION code_nirvanap PUBLIC _NIRVANAP_drawT EXTERN asm_NIRVANAP_drawT _NIRVANAP_drawT: ld hl,2 add hl,sp ld a,(hl) ; tile inc hl inc hl ld d,(hl) ; lin inc hl inc hl ld e,(hl) ; col jp asm_NIRVANAP_drawT
; A001737: Squares written in base 2. ; 0,1,100,1001,10000,11001,100100,110001,1000000,1010001,1100100,1111001,10010000,10101001,11000100,11100001,100000000,100100001,101000100,101101001,110010000,110111001,111100100,1000010001,1001000000,1001110001,1010100100,1011011001,1100010000,1101001001,1110000100,1111000001,10000000000,10001000001,10010000100,10011001001,10100010000,10101011001,10110100100,10111110001,11001000000,11010010001,11011100100,11100111001,11110010000,11111101001,100001000100,100010100001,100100000000,100101100001,100111000100,101000101001,101010010000,101011111001,101101100100,101111010001,110001000000,110010110001,110100100100,110110011001,111000010000,111010001001,111100000100,111110000001,1000000000000,1000010000001,1000100000100,1000110001001,1001000010000,1001010011001,1001100100100,1001110110001,1010001000000,1010011010001,1010101100100,1010111111001,1011010010000,1011100101001,1011111000100,1100001100001,1100100000000,1100110100001,1101001000100,1101011101001,1101110010000,1110000111001,1110011100100,1110110010001,1111001000000,1111011110001,1111110100100,10000001011001,10000100010000,10000111001001,10001010000100,10001101000001,10010000000000,10010011000001,10010110000100,10011001001001,10011100010000,10011111011001,10100010100100,10100101110001,10101001000000,10101100010001,10101111100100,10110010111001,10110110010000,10111001101001,10111101000100,11000000100001,11000100000000,11000111100001,11001011000100,11001110101001,11010010010000,11010101111001,11011001100100,11011101010001,11100001000000,11100100110001,11101000100100,11101100011001,11110000010000,11110100001001,11111000000100,11111100000001,100000000000000,100000100000001,100001000000100,100001100001001,100010000010000,100010100011001,100011000100100,100011100110001,100100001000000,100100101010001,100101001100100,100101101111001,100110010010000,100110110101001,100111011000100,100111111100001,101000100000000,101001000100001,101001101000100,101010001101001,101010110010000,101011010111001,101011111100100,101100100010001,101101001000000,101101101110001,101110010100100,101110111011001,101111100010000,110000001001001,110000110000100,110001011000001,110010000000000,110010101000001,110011010000100,110011111001001,110100100010000,110101001011001,110101110100100,110110011110001,110111001000000,110111110010001,111000011100100,111001000111001,111001110010000,111010011101001,111011001000100,111011110100001,111100100000000,111101001100001,111101111000100,111110100101001,111111010010000,111111111111001,1000000101100100,1000001011010001,1000010001000000,1000010110110001,1000011100100100,1000100010011001,1000101000010000,1000101110001001,1000110100000100,1000111010000001,1001000000000000,1001000110000001,1001001100000100,1001010010001001,1001011000010000,1001011110011001,1001100100100100,1001101010110001,1001110001000000,1001110111010001,1001111101100100,1010000011111001,1010001010010000,1010010000101001,1010010111000100,1010011101100001,1010100100000000,1010101010100001,1010110001000100,1010110111101001,1010111110010000,1011000100111001,1011001011100100,1011010010010001,1011011001000000,1011011111110001,1011100110100100,1011101101011001,1011110100010000,1011111011001001,1100000010000100,1100001001000001,1100010000000000,1100010111000001,1100011110000100,1100100101001001,1100101100010000,1100110011011001,1100111010100100,1101000001110001,1101001001000000,1101010000010001,1101010111100100,1101011110111001,1101100110010000,1101101101101001,1101110101000100,1101111100100001,1110000100000000,1110001011100001,1110010011000100,1110011010101001,1110100010010000,1110101001111001,1110110001100100,1110111001010001,1111000001000000,1111001000110001 pow $0,2 cal $0,99820 ; Even nonnegative integers in base 2 (bisection of A007088). mov $1,$0 div $1,10
; A158656: a(n) = 54*n^2 - 1. ; 53,215,485,863,1349,1943,2645,3455,4373,5399,6533,7775,9125,10583,12149,13823,15605,17495,19493,21599,23813,26135,28565,31103,33749,36503,39365,42335,45413,48599,51893,55295,58805,62423,66149,69983,73925,77975,82133,86399,90773,95255,99845,104543,109349,114263,119285,124415,129653,134999,140453,146015,151685,157463,163349,169343,175445,181655,187973,194399,200933,207575,214325,221183,228149,235223,242405,249695,257093,264599,272213,279935,287765,295703,303749,311903,320165,328535,337013,345599,354293,363095,372005,381023,390149,399383,408725,418175,427733,437399,447173,457055,467045,477143,487349,497663,508085,518615,529253,539999,550853,561815,572885,584063,595349,606743,618245,629855,641573,653399,665333,677375,689525,701783,714149,726623,739205,751895,764693,777599,790613,803735,816965,830303,843749,857303,870965,884735,898613,912599,926693,940895,955205,969623,984149,998783,1013525,1028375,1043333,1058399,1073573,1088855,1104245,1119743,1135349,1151063,1166885,1182815,1198853,1214999,1231253,1247615,1264085,1280663,1297349,1314143,1331045,1348055,1365173,1382399,1399733,1417175,1434725,1452383,1470149,1488023,1506005,1524095,1542293,1560599,1579013,1597535,1616165,1634903,1653749,1672703,1691765,1710935,1730213,1749599,1769093,1788695,1808405,1828223,1848149,1868183,1888325,1908575,1928933,1949399,1969973,1990655,2011445,2032343,2053349,2074463,2095685,2117015,2138453,2159999,2181653,2203415,2225285,2247263,2269349,2291543,2313845,2336255,2358773,2381399,2404133,2426975,2449925,2472983,2496149,2519423,2542805,2566295,2589893,2613599,2637413,2661335,2685365,2709503,2733749,2758103,2782565,2807135,2831813,2856599,2881493,2906495,2931605,2956823,2982149,3007583,3033125,3058775,3084533,3110399,3136373,3162455,3188645,3214943,3241349,3267863,3294485,3321215,3348053,3374999 mov $1,2 add $1,$0 mul $1,$0 mul $1,54 add $1,53
; A072266: Number of words of length 2n generated by the two letters s and t that reduce to the identity 1 using the relations sssssss=1, tt=1 and stst=1. The generators s and t along with the three relations generate the 14-element dihedral group D7. ; Submitted by Jon Maiga ; 1,1,3,10,35,126,462,1717,6451,24463,93518,360031,1394582,5430530,21242341,83411715,328589491,1297937234,5138431851,20380608990,80960325670,322016144629,1282138331587,5109310929719,20374764059254,81296186071751,324526029021782,1295965281092986,5176916370827301,20685116010285619,82667246362298267,330431249139568890,1320953071610196339,5281305861879290110,21117085138088535358,84441915627631908277,337681861318926722579,1350448850556607111519,5400890810855812782110,21600626053693170570863 mul $0,2 seq $0,94659 ; Number of closed walks of length n at a vertex of the cyclic graph on 7 nodes C_7. max $0,2 div $0,2
; Universal Dot Command ; ; Select dot command depending on whether ; the machine is in 48k or 128k mode. ; ; z80asm -b zxn_universal_dot.asm INCLUDE "config_zxn_private.inc" org 0x2000 zxn_universal_dot: jr start ;; Fixed position data filled in by appmake __filename_dotx : defs 13 __filename_dotn : defs 13 ;; start: di ;; save command line push hl ;; copy trampoline to caller's stack ld hl,-1 add hl,sp ex de,hl ld hl,trampoline_end - 1 ld bc,trampoline_len lddr ex de,hl inc hl ld sp,hl push hl ; save &trampoline ;; verify that this is 128k NextOS mode ;; method provided by Garry Lancaster ld hl,(__SYSVAR_ERRSP) inc hl ld a,(hl) ; 48k mode if error routine is in lower 16k cp 0x40 ld hl,__filename_dotn jr nc, mode_128k mode_48k: ld hl,__filename_dotx mode_128k: ; hl = filename ;; load dot binary push hl ld a,'$' ld b,__ESXDOS_MODE_OPEN_EXIST | __ESXDOS_MODE_READ rst __ESXDOS_SYSCALL defb __ESXDOS_SYS_F_OPEN jr c, error_load_0 push af ; save file handle ld hl,stat_s rst __ESXDOS_SYSCALL defb __ESXDOS_SYS_F_FSTAT pop hl ld a,h ; file handle jr c, error_load_c pop de ; de = filename ld bc,(stat_s + stat_size) ; bc = file size ld hl,error_load_1 ex (sp),hl ; return address = error_load_1 push de ; filename push af ; file handle push hl ; &trampoline ld hl,0x2000 ret ; jump trampoline error_load_c: rst __ESXDOS_SYSCALL defb __ESXDOS_SYS_F_CLOSE error_load_0: pop de ; filename pop bc ; trash &trampoline error_load_1: ; write filename into error string ex de,hl ld de,error_load_s_name ld bc,12 ldir ; restore caller's stack ld hl,trampoline_len + 2 add hl,sp ld sp,hl ; terminate error message ld hl,error_load_s xor a cpir dec hl dec hl ld a,(hl) add a,0x80 ld (hl),a ld hl,error_load_s ; if a==0 and carry is set, error message is pointed at by hl xor a scf ei ret error_load_s: defm "Can't load " error_load_s_name: defs 13 defvars 0 { stat_drive ds.b 1 stat_device ds.b 1 stat_attr ds.b 1 stat_date ds.w 2 stat_size ds.w 2 SIZEOF_STAT } stat_s: defs SIZEOF_STAT ;; TRAMPOLINE IN STACK defc trampoline_len = trampoline_end - trampoline_begin trampoline_begin: rst __ESXDOS_SYSCALL defb __ESXDOS_SYS_F_READ pop hl push af ld a,h rst __ESXDOS_SYSCALL defb __ESXDOS_SYS_F_CLOSE pop af pop de ret c ; if error loading ; interrupts are disabled ld hl,trampoline_len + 2 add hl,sp ld sp,hl pop hl ; hl = command line jp 0x2000 trampoline_end:
; formatMem [System] ; Formats memory in preparation for memory allocation. ; Notes: ; This function will deallocate **all allocated memory**. formatMem: ld a, 0xFF ld (userMemory), a ld hl, (0x10000 - userMemory) - 5 ; Total RAM - Kernel RAM Size - Formatting Overhead + 1 ld (userMemory + 1), hl ld hl, userMemory ld (0xFFFE), hl ret ;; allocScreenBuffer [Display] ;; Allocates a 768-byte screen buffer. ;; Outputs: ;; IY: Screen buffer allocScreenBuffer: push bc push ix ld bc, 768 call malloc push ix \ pop iy pop ix pop bc ret ;; freeScreenBuffer [Display] ;; Deallocates a screen buffer allocated with [[allocScreenBuffer]] ;; Inputs: ;; IY: Screen buffer freeScreenBuffer: push ix push iy \ pop ix call free pop ix ret ;; reassignMemory [System] ;; Reassigns a given block of memory to the specified thread ID. ;; Inputs: ;; IX: Pointer to any location within the target block. ;; A: Thread ID for new owner reassignMemory: push ix ; TODO: Check if thread exists call memSeekToStart ld (ix + -3), a pop ix ret ;; calloc [System] ;; Allocates memory for a given number of elements ;; of a given size (that is, BC * A bytes total), ;; then fills it with zeros. ;; Inputs: ;; BC: Number of elements ;; A: Size of element ;; Outputs: ;; Z: Set on success, reset on failure ;; A: Error code (on failure) ;; IX: First byte of allocated and zeroed memory (on success) calloc: push af push bc push de push hl push af \ push bc \ pop de call mul16By8 push hl \ pop bc \ pop af call malloc jr nz, .fail xor a call memset pop hl pop de pop bc pop af cp a ret .fail: pop hl pop de pop bc inc sp \ inc sp ;pop af ret ;; memset [System] ;; Sets the value of an entire allocated section of memory. ;; Inputs: ;; A: Value to set ;; IX: Pointer to anywhere in allocated section memset: push ix push bc push hl push de call memSeekToStart push ix \ pop hl \ push ix \ pop de inc de ld (hl), a ld c, (ix + -2) \ ld b, (ix + -1) dec bc ldir pop de pop hl pop bc pop ix ret ;; memSeekToStart [System] ;; Move IX to the beginning of the memory section it points to. ;; Inputs: ;; IX: Pointer to anywhere in a section of allocated memory ;; Outputs: ;; IX: Pointer to first byte of section memSeekToStart: push hl push bc push de push ix \ pop de ld hl, userMemory .loop: inc hl ld c, (hl) inc hl ld b, (hl) inc hl add hl, bc jr c, _ call cpHLDE jr nc, ++_ inc hl \ inc hl jr .loop _: ld ix, 0 ; Error jr ++_ _: sbc hl, bc push hl \ pop ix _: pop de pop bc pop hl ret ;; memSeekToEnd [System] ;; Move IX to the end of the memory section it points to. ;; Inputs: ;; IX: Pointer to anywhere in a section of allocated memory ;; Outputs: ;; IX: Pointer to last byte of section memSeekToEnd: call memSeekToStart push hl push bc push ix \ pop hl dec hl \ ld b, (hl) dec hl \ ld c, (hl) inc hl \ add hl, bc push hl \ pop ix pop bc pop hl ret ;; memcheck [System] ;; Walks over memory and makes sure nothing has corrupted the allocation list. ;; Outputs: ;; Z: Set if OK, reset if broken ;; Notes: ;; A reboot is probably required if this returns NZ. memcheck: push af ld a, i push af di push hl push bc push de ld hl, userMemory .loop: push hl inc hl \ ld c, (hl) ; Size of this block into BC inc hl \ ld b, (hl) inc hl add hl, bc ; Move HL to block footer pop bc ld e, (hl) \ inc hl ld d, (hl) \ inc hl call cpBCDE jr nz, .fail ld a, h cp 0 jr nz, _ ld a, l cp 0 jr z, .done _: cp 0x80 jr c, .fail jr .loop .done: pop de pop bc pop hl pop af jp po, _ ei _: pop af cp a ret .fail: pop de pop bc pop hl pop af jp po, _ ei _: pop af or 1 ret ;; memoryAvailable [System] ;; Finds the amount of memory available for use. ;; Outputs: ;; BC: Total memory available ;; DE: Largest allocatable sum memoryAvailable: #define total_mem kernelGarbage #define max_alloc kernelGarbage + 2 push hl push af ld a, i push af di ld hl, 0 ld (total_mem), hl ld (max_alloc), hl ld hl, userMemory .loop: ld a, (hl) \ inc hl ; Owner ID to A ld c, (hl) \ inc hl ld b, (hl) \ inc hl ; Size to BC add hl, bc inc hl \ inc hl ; Move to next block cp 0xFF jr nz, .loop ; Free block push hl ld hl, (total_mem) add hl, bc ld (total_mem), hl ld hl, (max_alloc) or a ; reset c sbc hl, bc jr nc, _ ld h, b \ ld l, c ld (max_alloc), hl _: pop hl xor a cp h jr nz, .loop pop af jp po, _ ei _: pop af ld hl, (total_mem) ld b, h \ ld c, l ld hl, (max_alloc) ex de, hl pop hl ret #undefine total_mem #undefine max_alloc ;; malloc [System] ;; Allocates the specified amount of memory. ;; Inputs: ;; BC: Length of requested section, in bytes ;; Outputs: ;; Z: Set on success, reset on failure ;; A: Error code (on failure) ;; IX: First byte of allocated memory (on success) malloc: ; KnightOS uses a simple linked list for memory allocation. Memory starts of as one complete ; block of memory allocated to thread 0xFF (i.e. free), and each allocation divides this into ; more and more blocks. A block looks something like this: ; ; OO SSSS .... AAAA ; Where OO is the owner of this block, SSSS is the size of the block, and AAAA is the address ; of the header (starting at OO). push af ld a, i push af di push hl push de push bc ld d, b \ ld e, c ; Save desired size in DE ld hl, userMemory .identify_loop: ; Identify a block to use ld a, (hl) \ inc hl ld c, (hl) \ inc hl ld b, (hl) \ inc hl ; A: Block owner ; BC: Block length ; *HL: First byte of block ; .. ; Check if free cp 0xFF jr nz, .continue_loop ; Check if acceptable size call cpBCDE jr z, .allocate_this ; If exactly the right size jr c, .continue_loop ; If too small .allocate_this: dec hl \ dec hl \ dec hl jr .do_allocate .continue_loop: ; Continue to next block add hl, bc inc hl \ inc hl ; Check to see if HL rolled over xor a \ cp h jr nz, .identify_loop jp .out_of_memory .do_allocate: ; *HL: Header of block to use ; DE: Size of block to allocate call getCurrentThreadID ld (hl), a \ inc hl ; Set new owner ; Get the old size and write the new size ld c, (hl) \ ld (hl), e \ inc hl ld b, (hl) \ ld (hl), d \ inc hl call .pad_if_needed push hl \ pop ix ; IX to malloc return value push hl push de push de \ push bc \ pop hl \ pop bc or a ; Reset carry sbc hl, bc jr z, .exact_fit ld bc, 5 ; Overhead sbc hl, bc ld b, h \ ld c, l ; BC: Size of new free block pop de pop hl add hl, de ; HL to footer of new block push ix \ pop de dec de \ dec de \ dec de ; DE to header ld (hl), e \ inc hl ld (hl), d \ inc hl ; Fill in pointer to previous block push hl ld a, 0xFF ld (hl), a \ inc hl ; Mark next one as free ld (hl), c \ inc hl ld (hl), b \ inc hl ; Size of block add hl, bc ; Move to footer pop de ld (hl), e \ inc hl ld (hl), d ; Pointer to footer .finish: ; Note: Don't change this unless you also change realloc pop bc pop de pop hl pop af jp po, _ ei _: pop af cp a ret .exact_fit: ; We don't need to do anything else in this case pop de pop hl jr .finish .pad_if_needed: push bc push de ex de, hl push bc \ push hl \ pop bc \ pop hl sbc hl, bc jr z, .no_pad_exact ld bc, 5 sbc hl, bc jr z, .do_pad jr c, .do_pad .no_pad_exact: ex de, hl pop de pop bc ret .do_pad: ex de, hl pop de pop bc \ ld d, b \ ld e, c dec hl \ ld (hl), d \ dec hl \ ld (hl), e inc hl \ inc hl ret .out_of_memory: pop bc pop de pop hl pop af jp po, _ ei _: pop af or 1 ld a, errOutOfMem ret ;; free [System] ;; Frees a previously allocated section of memory ;; Inputs: ;; IX: Pointer to first byte of section free: ; Procedure: ; 1. Assign block to 0xFF ; 2. Check if next block is free - if so, merge ; 3. Check if previous block is free - if so, merge push af ld a, i push af di push bc push hl push de push ix .free_block: ld a, 0xFF ld (ix + -3), a ; Free block ld c, (ix + -2) ld b, (ix + -1) ; Size of block in BC .check_next_block: pop hl \ push hl ; IX into HL add hl, bc ; Note: We can check if HL == -2 here and if so, we can't merge forward (last block) inc hl \ inc hl ; HL to next block ld a, 0xFF cp (hl) jp z, .merge_forward_block .check_previous_block: pop hl \ push hl ; IX into HL dec hl \ dec hl \ dec hl ; Move to header ld bc, userMemory call cpHLBC ; If this is the first block, we can't merge backwards, so don't bother jr z, .cannot_merge_previous dec hl \ ld d, (hl) dec hl \ ld e, (hl) ex de, hl ld a, 0xFF cp (hl) jr nz, .cannot_merge_previous .merge_previous_block: ld c, (ix + -2) ld b, (ix + -1) ; Size of current block in BC inc hl \ ld e, (hl) inc hl \ ld d, (hl) ex de, hl add hl, bc ld bc, 5 add hl, bc ex de, hl ; Size of combined blocks in DE ld (hl), d \ dec hl ld (hl), e \ dec hl ; Update header ; Skip to footer ld b, h \ ld c, l ex de, hl add hl, bc inc hl \ inc hl \ inc hl ld (hl), e \ inc hl ; Write header address here ld (hl), d .cannot_merge_previous: pop ix pop de pop hl pop bc pop af jp po, _ ei _: pop af ret .merge_forward_block: ; Assumes IX is address of freed block ; Assumes HL points to forward block header ; Assumes BC is size of freed block inc hl \ ld e, (hl) inc hl \ ld d, (hl) ; DE is size of this block ex de, hl add hl, bc ld bc, 5 add hl, bc ex de, hl ; DE is combined size, update freed block ld (ix + -1), d ld (ix + -2), e pop hl \ push hl add hl, de ; Update footer to point to new header pop de \ push de ; Grab IX dec de \ dec de \ dec de ld (hl), e \ inc hl ld (hl), d ; Forward merge complete! jr .check_previous_block ;; realloc [System] ;; Reallocates a block of memory at a different size and returns a new pointer. ;; Inputs: ;; IX: Block to resize ;; BC: New size ;; Outputs: ;; IX: New memory ;; Z: Reset on failure, set on success ;; A: Preserved if success, error code if failure ;; Notes: ;; This function may have to move the memory that you've allocated. Consider the old pointer invalid and use ;; the one returned from realloc instead. realloc: push af ld a, i push af di push hl push de push bc xor a \ cp b \ jr nz, _ cp c \ jp z, .just_free_it ; Free if zero _: ld l, (ix + -2) ld h, (ix + -1) ; Check for what case we're handling or a sbc hl, bc jr z, .dont_resize jr c, .resize_grow .resize_shrink: ; BC is the leftover amount after we make it smaller ; If it's less than 5, don't bother because we'll get a dead spot xor a \ cp b jr nz, _ ld a, 5 \ cp c jr z, .dont_resize ; Okay, we're fine. Continue. push ix add ix, bc pop hl \ push hl dec hl \ dec hl \ dec hl ld (ix), l ld (ix + 1), h ld a, 0xFE ld (ix + 2), a ; Create to-be-freed block dec bc \ dec bc \ dec bc \ dec bc \ dec bc ld (ix + 3), c ; Size of free block ld (ix + 4), b ; Write free block footer push ix \ pop hl inc hl \ inc hl add ix, bc ; IX is now at footer-5 ld (ix + 5), l ld (ix + 6), h push hl \ pop ix ld bc, 3 \ add ix, bc ; Join newly created free block with adjacent blocks if possible ; NOTE: This calls free while the state of memory is _invalid_! call free pop ix pop bc ld (ix + -2), c ld (ix + -1), b ; Write new size of original block jr _ .dont_resize: ; Note: Don't change this unless you also change malloc pop bc _: pop de pop hl pop af jp po, _ ei _: pop af ret .just_free_it: pop bc pop de pop hl pop af jp po, _ ei _: pop af jp free .resize_grow: #define prev_block_ptr kernelGarbage #define next_block_ptr kernelGarbage + 2 ; First, we check to see if we can fit it by expanding into a free block ; to the left of this one, and potentially including the block to the right ; If so, we do just that. If not, we just malloc it elsewhere and copy it ; over, then free the original block. ld (prev_block_ptr), ix ld (next_block_ptr), ix ; In case can can't use them ld c, (ix + -2) ld b, (ix + -1) ; Set BC to current size call .add_next_block call .add_prev_block pop de \ push de ; BC is now the maximum potential size, DE is the desired size, see if it'll fit call cpBCDE jr c, .manual_realloc ; We can expand! ; The procedure is to use the previous block as the new one ; We'll change its size to the desired one, and move the contents of memory over ; But we'll leave it marked as "free" and then hand it over to malloc, and that's it! ld c, (ix + -2) ld b, (ix + -1) ; Set BC to current size push de ld hl, (prev_block_ptr) ex de, hl push ix \ pop hl call cpHLDE jr z, _ ; Skip memory move if we can't move backwards ldir jr ++_ _: pop de _: ld hl, (prev_block_ptr) call free ; Consolodate blocks dec hl \ dec hl \ dec hl jp do_allocate@malloc ; Hand it over to malloc to finish the job .manual_realloc: ; We can't expand into neighboring sections so we have to do a manual realloc/copy/free push ix \ pop hl ld c, (ix + -2) ld b, (ix + -1) ; Set BC to current size push ix push bc ld b, d \ ld c, e call malloc jp nz, .out_of_memory ;if malloc fails pop bc push ix \ pop de ldir push ix \ pop de pop ix call free push de \ pop ix jp .dont_resize ; (we're done) .add_next_block: push ix \ pop hl add hl, bc inc hl \ inc hl ld a, 0x80 cp h ret nc ; We went past the end of memory ld (next_block_ptr), hl ld a, (hl) cp 0xFF ret nz ; Not free inc hl ; HL points to size of next block ld e, (hl) \ inc hl ld d, (hl) \ ex de, hl add hl, bc ld b, h \ ld c, l inc bc \ inc bc \ inc bc \ inc bc \ inc bc ; Factor in removed headers ret .add_prev_block: push ix \ pop hl dec hl \ ld d, (hl) dec hl \ ld e, (hl) ; DE points to header of previous block ld a, 0x80 cp d ret nc ; We went past the start of memory ex de, hl ld (prev_block_ptr), hl ld a, (hl) cp 0xFF ret nz ; Not free inc hl ld e, (hl) \ inc hl ld d, (hl) \ ex de, hl add hl, de ld c, h \ ld b, l inc bc \ inc bc \ inc bc \ inc bc \ inc bc ; Factor in removed headers ret .out_of_memory: pop bc pop ix pop bc pop de pop hl pop af jp po, _ ei _: pop af or 1 ld a, errOutOfMem ret #undefine prev_block_ptr #undefine next_block_ptr
; A035746: Coordination sequence for C_9 lattice. ; Submitted by Jamie Morken(w2) ; 1,162,4482,53154,374274,1854882,7159170,22952610,63821826,158611106,360027522,758497698,1501390338,2818849698,5057616258,8724341922,14540038146,23507426466,36993091970,56826471330,85417838082,125897578914,182279185794,259648519842,364382033922,504396772002,689435094402,931387209122,1244654720514,1646558537634,2157794615682,2802941135010,3611020853250,4616122497186,5858085192066,7383250057122,9245283227138,11506074690978,14236717469058,17518571782818,21444419000322,26119710273186,31663914911106 mov $1,$0 mul $1,2 seq $1,8418 ; Coordination sequence for 9-dimensional cubic lattice. mov $0,$1
; A088218: Total number of leaves in all rooted ordered trees with n edges. ; 1,1,3,10,35,126,462,1716,6435,24310,92378,352716,1352078,5200300,20058300,77558760,300540195,1166803110,4537567650,17672631900,68923264410,269128937220,1052049481860,4116715363800,16123801841550,63205303218876,247959266474052,973469712824056,3824345300380220,15033633249770520,59132290782430712,232714176627630544,916312070471295267,3609714217008132870,14226520737620288370,56093138908331422716,221256270138418389602,873065282167813104916,3446310324346630677300,13608507434599516007800 sub $2,$0 bin $2,$0 gcd $1,$2 mov $0,$1
#include "defaults.h" #include "ram.h" #ifndef RAM_SPI static uint8_t RAM[64*1024]={0}; // Definition of the emulated RAM #else #include <SPI.h> #include <SRAM_23LC.h> SRAM_23LC SRAM(&RAM_SPI_PERIPHERAL, RAM_SPI_CS, RAM_SPI_CHIP); #endif uint8_t ram_read(uint16_t address) { #ifdef RAM_SPI return SRAM.readByte(address); #else return(RAM[address]); #endif } void ram_write(uint16_t address, uint8_t value) { #ifdef RAM_SPI SRAM.writeByte(address,value); #else RAM[address] = value; #endif }
// Copyright CERN and copyright holders of ALICE O2. This software is // distributed under the terms of the GNU General Public License v3 (GPL // Version 3), copied verbatim in the file "COPYING". // // See http://alice-o2.web.cern.ch/license for full licensing information. // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. // /// \brief Shows how to loop over collisions and tracks of a data frame. /// \author /// \since #include "Framework/runDataProcessing.h" #include "Framework/AnalysisTask.h" using namespace o2; using namespace o2::framework; struct ATask { void process(aod::Collision const& collision, aod::Tracks const& tracks) { // `tracks` contains tracks belonging to `collision` LOGF(info, "Collision index : %d", collision.index()); LOGF(info, "Number of tracks: %d", tracks.size()); // process the tracks of a given collision for (auto& track : tracks) { LOGF(info, " track pT = %f GeV/c", track.pt()); } } }; struct BTask { void process(aod::Collisions const& collisions, aod::Tracks const& tracks) { // `tracks` contains all tracks of a data frame LOGF(info, "Number of collisions: %d", collisions.size()); LOGF(info, "Number of tracks : %d", tracks.size()); } }; struct CTask { void process(aod::Collision const& collision, aod::Tracks const& tracks, aod::V0s const& v0s) { // `tracks` contains tracks belonging to `collision` // `v0s` contains V0s belonging to `collision` LOGF(info, "Collision index : %d", collision.index()); LOGF(info, "Number of tracks: %d", tracks.size()); LOGF(info, "Number of v0s : %d", v0s.size()); } }; WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) { return WorkflowSpec{ adaptAnalysisTask<ATask>(cfgc, TaskName{"collision-tracks-iteration-tutorial_A"}), adaptAnalysisTask<BTask>(cfgc, TaskName{"collision-tracks-iteration-tutorial_B"}), adaptAnalysisTask<CTask>(cfgc, TaskName{"collision-tracks-iteration-tutorial_C"}), }; }
;;----------------------------------------------------------------------------;; ;; Hacks for overlay 13 for arm9 ;; Copyright 2014 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; .nds .open overlay9_13.bin, 0x02079F80 .relativeinclude on .erroronwarning on .include textbox\subtitles.asm .close ; EOF ;
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <unordered_set> // template <class Value, class Hash = hash<Value>, class Pred = equal_to<Value>, // class Alloc = allocator<Value>> // class unordered_set // void swap(unordered_set& x, unordered_set& y); #include <unordered_set> #include <cassert> #include "../../../test_compare.h" #include "../../../test_hash.h" #include "../../../test_allocator.h" int main() { { typedef test_hash<std::hash<int> > Hash; typedef test_compare<std::equal_to<int> > Compare; typedef test_allocator<int> Alloc; typedef std::unordered_set<int, Hash, Compare, Alloc> C; typedef int P; C c1(0, Hash(1), Compare(1), Alloc(1)); C c2(0, Hash(2), Compare(2), Alloc(2)); c2.max_load_factor(2); swap(c1, c2); assert(c1.bucket_count() == 0); assert(c1.size() == 0); assert(c1.hash_function() == Hash(2)); assert(c1.key_eq() == Compare(2)); assert(c1.get_allocator() == Alloc(1)); assert(std::distance(c1.begin(), c1.end()) == c1.size()); assert(std::distance(c1.cbegin(), c1.cend()) == c1.size()); assert(c1.max_load_factor() == 2); assert(c2.bucket_count() == 0); assert(c2.size() == 0); assert(c2.hash_function() == Hash(1)); assert(c2.key_eq() == Compare(1)); assert(c2.get_allocator() == Alloc(2)); assert(std::distance(c2.begin(), c2.end()) == c2.size()); assert(std::distance(c2.cbegin(), c2.cend()) == c2.size()); assert(c2.max_load_factor() == 1); } { typedef test_hash<std::hash<int> > Hash; typedef test_compare<std::equal_to<int> > Compare; typedef test_allocator<int> Alloc; typedef std::unordered_set<int, Hash, Compare, Alloc> C; typedef int P; P a2[] = { P(10), P(20), P(30), P(40), P(50), P(60), P(70), P(80) }; C c1(0, Hash(1), Compare(1), Alloc(1)); C c2(std::begin(a2), std::end(a2), 0, Hash(2), Compare(2), Alloc(2)); c2.max_load_factor(2); swap(c1, c2); assert(c1.bucket_count() >= 11); assert(c1.size() == 8); assert(*c1.find(10) == 10); assert(*c1.find(20) == 20); assert(*c1.find(30) == 30); assert(*c1.find(40) == 40); assert(*c1.find(50) == 50); assert(*c1.find(60) == 60); assert(*c1.find(70) == 70); assert(*c1.find(80) == 80); assert(c1.hash_function() == Hash(2)); assert(c1.key_eq() == Compare(2)); assert(c1.get_allocator() == Alloc(1)); assert(std::distance(c1.begin(), c1.end()) == c1.size()); assert(std::distance(c1.cbegin(), c1.cend()) == c1.size()); assert(c1.max_load_factor() == 2); assert(c2.bucket_count() == 0); assert(c2.size() == 0); assert(c2.hash_function() == Hash(1)); assert(c2.key_eq() == Compare(1)); assert(c2.get_allocator() == Alloc(2)); assert(std::distance(c2.begin(), c2.end()) == c2.size()); assert(std::distance(c2.cbegin(), c2.cend()) == c2.size()); assert(c2.max_load_factor() == 1); } { typedef test_hash<std::hash<int> > Hash; typedef test_compare<std::equal_to<int> > Compare; typedef test_allocator<int> Alloc; typedef std::unordered_set<int, Hash, Compare, Alloc> C; typedef int P; P a1[] = { P(1), P(2), P(3), P(4), P(1), P(2) }; C c1(std::begin(a1), std::end(a1), 0, Hash(1), Compare(1), Alloc(1)); C c2(0, Hash(2), Compare(2), Alloc(2)); c2.max_load_factor(2); swap(c1, c2); assert(c1.bucket_count() == 0); assert(c1.size() == 0); assert(c1.hash_function() == Hash(2)); assert(c1.key_eq() == Compare(2)); assert(c1.get_allocator() == Alloc(1)); assert(std::distance(c1.begin(), c1.end()) == c1.size()); assert(std::distance(c1.cbegin(), c1.cend()) == c1.size()); assert(c1.max_load_factor() == 2); assert(c2.bucket_count() >= 5); assert(c2.size() == 4); assert(c2.count(1) == 1); assert(c2.count(2) == 1); assert(c2.count(3) == 1); assert(c2.count(4) == 1); assert(c2.hash_function() == Hash(1)); assert(c2.key_eq() == Compare(1)); assert(c2.get_allocator() == Alloc(2)); assert(std::distance(c2.begin(), c2.end()) == c2.size()); assert(std::distance(c2.cbegin(), c2.cend()) == c2.size()); assert(c2.max_load_factor() == 1); } { typedef test_hash<std::hash<int> > Hash; typedef test_compare<std::equal_to<int> > Compare; typedef test_allocator<int> Alloc; typedef std::unordered_set<int, Hash, Compare, Alloc> C; typedef int P; P a1[] = { P(1), P(2), P(3), P(4), P(1), P(2) }; P a2[] = { P(10), P(20), P(30), P(40), P(50), P(60), P(70), P(80) }; C c1(std::begin(a1), std::end(a1), 0, Hash(1), Compare(1), Alloc(1)); C c2(std::begin(a2), std::end(a2), 0, Hash(2), Compare(2), Alloc(2)); c2.max_load_factor(2); swap(c1, c2); assert(c1.bucket_count() >= 11); assert(c1.size() == 8); assert(*c1.find(10) == 10); assert(*c1.find(20) == 20); assert(*c1.find(30) == 30); assert(*c1.find(40) == 40); assert(*c1.find(50) == 50); assert(*c1.find(60) == 60); assert(*c1.find(70) == 70); assert(*c1.find(80) == 80); assert(c1.hash_function() == Hash(2)); assert(c1.key_eq() == Compare(2)); assert(c1.get_allocator() == Alloc(1)); assert(std::distance(c1.begin(), c1.end()) == c1.size()); assert(std::distance(c1.cbegin(), c1.cend()) == c1.size()); assert(c1.max_load_factor() == 2); assert(c2.bucket_count() >= 5); assert(c2.size() == 4); assert(c2.count(1) == 1); assert(c2.count(2) == 1); assert(c2.count(3) == 1); assert(c2.count(4) == 1); assert(c2.hash_function() == Hash(1)); assert(c2.key_eq() == Compare(1)); assert(c2.get_allocator() == Alloc(2)); assert(std::distance(c2.begin(), c2.end()) == c2.size()); assert(std::distance(c2.cbegin(), c2.cend()) == c2.size()); assert(c2.max_load_factor() == 1); } { typedef test_hash<std::hash<int> > Hash; typedef test_compare<std::equal_to<int> > Compare; typedef other_allocator<int> Alloc; typedef std::unordered_set<int, Hash, Compare, Alloc> C; typedef int P; C c1(0, Hash(1), Compare(1), Alloc(1)); C c2(0, Hash(2), Compare(2), Alloc(2)); c2.max_load_factor(2); swap(c1, c2); assert(c1.bucket_count() == 0); assert(c1.size() == 0); assert(c1.hash_function() == Hash(2)); assert(c1.key_eq() == Compare(2)); assert(c1.get_allocator() == Alloc(2)); assert(std::distance(c1.begin(), c1.end()) == c1.size()); assert(std::distance(c1.cbegin(), c1.cend()) == c1.size()); assert(c1.max_load_factor() == 2); assert(c2.bucket_count() == 0); assert(c2.size() == 0); assert(c2.hash_function() == Hash(1)); assert(c2.key_eq() == Compare(1)); assert(c2.get_allocator() == Alloc(1)); assert(std::distance(c2.begin(), c2.end()) == c2.size()); assert(std::distance(c2.cbegin(), c2.cend()) == c2.size()); assert(c2.max_load_factor() == 1); } { typedef test_hash<std::hash<int> > Hash; typedef test_compare<std::equal_to<int> > Compare; typedef other_allocator<int> Alloc; typedef std::unordered_set<int, Hash, Compare, Alloc> C; typedef int P; P a2[] = { P(10), P(20), P(30), P(40), P(50), P(60), P(70), P(80) }; C c1(0, Hash(1), Compare(1), Alloc(1)); C c2(std::begin(a2), std::end(a2), 0, Hash(2), Compare(2), Alloc(2)); c2.max_load_factor(2); swap(c1, c2); assert(c1.bucket_count() >= 11); assert(c1.size() == 8); assert(*c1.find(10) == 10); assert(*c1.find(20) == 20); assert(*c1.find(30) == 30); assert(*c1.find(40) == 40); assert(*c1.find(50) == 50); assert(*c1.find(60) == 60); assert(*c1.find(70) == 70); assert(*c1.find(80) == 80); assert(c1.hash_function() == Hash(2)); assert(c1.key_eq() == Compare(2)); assert(c1.get_allocator() == Alloc(2)); assert(std::distance(c1.begin(), c1.end()) == c1.size()); assert(std::distance(c1.cbegin(), c1.cend()) == c1.size()); assert(c1.max_load_factor() == 2); assert(c2.bucket_count() == 0); assert(c2.size() == 0); assert(c2.hash_function() == Hash(1)); assert(c2.key_eq() == Compare(1)); assert(c2.get_allocator() == Alloc(1)); assert(std::distance(c2.begin(), c2.end()) == c2.size()); assert(std::distance(c2.cbegin(), c2.cend()) == c2.size()); assert(c2.max_load_factor() == 1); } { typedef test_hash<std::hash<int> > Hash; typedef test_compare<std::equal_to<int> > Compare; typedef other_allocator<int> Alloc; typedef std::unordered_set<int, Hash, Compare, Alloc> C; typedef int P; P a1[] = { P(1), P(2), P(3), P(4), P(1), P(2) }; C c1(std::begin(a1), std::end(a1), 0, Hash(1), Compare(1), Alloc(1)); C c2(0, Hash(2), Compare(2), Alloc(2)); c2.max_load_factor(2); swap(c1, c2); assert(c1.bucket_count() == 0); assert(c1.size() == 0); assert(c1.hash_function() == Hash(2)); assert(c1.key_eq() == Compare(2)); assert(c1.get_allocator() == Alloc(2)); assert(std::distance(c1.begin(), c1.end()) == c1.size()); assert(std::distance(c1.cbegin(), c1.cend()) == c1.size()); assert(c1.max_load_factor() == 2); assert(c2.bucket_count() >= 5); assert(c2.size() == 4); assert(c2.count(1) == 1); assert(c2.count(2) == 1); assert(c2.count(3) == 1); assert(c2.count(4) == 1); assert(c2.hash_function() == Hash(1)); assert(c2.key_eq() == Compare(1)); assert(c2.get_allocator() == Alloc(1)); assert(std::distance(c2.begin(), c2.end()) == c2.size()); assert(std::distance(c2.cbegin(), c2.cend()) == c2.size()); assert(c2.max_load_factor() == 1); } { typedef test_hash<std::hash<int> > Hash; typedef test_compare<std::equal_to<int> > Compare; typedef other_allocator<int> Alloc; typedef std::unordered_set<int, Hash, Compare, Alloc> C; typedef int P; P a1[] = { P(1), P(2), P(3), P(4), P(1), P(2) }; P a2[] = { P(10), P(20), P(30), P(40), P(50), P(60), P(70), P(80) }; C c1(std::begin(a1), std::end(a1), 0, Hash(1), Compare(1), Alloc(1)); C c2(std::begin(a2), std::end(a2), 0, Hash(2), Compare(2), Alloc(2)); c2.max_load_factor(2); swap(c1, c2); assert(c1.bucket_count() >= 11); assert(c1.size() == 8); assert(*c1.find(10) == 10); assert(*c1.find(20) == 20); assert(*c1.find(30) == 30); assert(*c1.find(40) == 40); assert(*c1.find(50) == 50); assert(*c1.find(60) == 60); assert(*c1.find(70) == 70); assert(*c1.find(80) == 80); assert(c1.hash_function() == Hash(2)); assert(c1.key_eq() == Compare(2)); assert(c1.get_allocator() == Alloc(2)); assert(std::distance(c1.begin(), c1.end()) == c1.size()); assert(std::distance(c1.cbegin(), c1.cend()) == c1.size()); assert(c1.max_load_factor() == 2); assert(c2.bucket_count() >= 5); assert(c2.size() == 4); assert(c2.count(1) == 1); assert(c2.count(2) == 1); assert(c2.count(3) == 1); assert(c2.count(4) == 1); assert(c2.hash_function() == Hash(1)); assert(c2.key_eq() == Compare(1)); assert(c2.get_allocator() == Alloc(1)); assert(std::distance(c2.begin(), c2.end()) == c2.size()); assert(std::distance(c2.cbegin(), c2.cend()) == c2.size()); assert(c2.max_load_factor() == 1); } }