text stringlengths 1 1.05M |
|---|
.device ATtiny10
; +====+
; PWMA/PB0 |* | PB3 (RESET)
; GND | | Vcc
; PWMB/PB1 | | PB2 (CLKO)
; +====+
.fuses rstdisbl
.eq SREG = 0x3F ; Status Register
.eq SPH = 0x3E ; Stack Pointer Register (high byte)
.eq SPL = 0x3D ; Stack Pointer Register (low byte)
.eq PUEB = 0x03 ; Port B Pull-up Enable Control Register
.eq PORTB = 0x02 ; Port B Data Register
.eq DDRB = 0x01 ; Port B Data Direction Register
.eq PINB = 0x00 ; Port B Input Pins
.eq TCCR0A = 0x2E ; Timer/Counter0 Control Register A
.eq TCCR0B = 0x2D ; Timer/Counter0 Control Register B
.eq TIMSK0 = 0x2B ; Timer/Counter Interrupt Mask Register 0
.eq ICR0L = 0x22 ; Input Capture Register Low Byte
.eq ICR0H = 0x23 ; Input Capture Register High Byte
.eq OCR0BL = 0x24 ; Compare Register B Low Byte
.eq OCR0BH = 0x25 ; Compare Register B High Byte
.eq OCR0AL = 0x26 ; Compare Register A Low Byte
.eq OCR0AH = 0x27 ; Compare Register A High Byte
.DSEG
AL: .BYTE 1
BL: .BYTE 1
TAL: .BYTE 1
TAH: .BYTE 1
TBL: .BYTE 1
TBH: .BYTE 1
flags: .BYTE 1
.CSEG
.org 0
;Interrupt vector table
rjmp reset ; All Resets
reti ; External Interrupt Request 0
reti ; Pin Change Interrupt Request 0
reti ; Timer/Counter0 Input Capture
rjmp timer_ofl ; Timer/Counter0 Overflow
reti ; Timer/Counter0 Compare Match A
reti ; Timer/Counter0 Compare Match B
reti ; Analog Comparator
reti ; Watchdog Time-out
reti ; VCC Voltage Level Monitor
reti ; ADC Conversion Complete
reset:
; Set Stack Pointer (SP)
ldi r16, 0x00
out SPH, r16
ldi r16, 0x5F
out SPL, r16
; Set clock to 4MHz
ldi r16, 0xD8 ; Unprotect CLKPSR reg
out CCP, r16
ldi r16, 1 ; Divide by 2
out CLKPSR, r16
; Calibrate Oscillator
ldi r16, 0xA3 ; ATTiny10 Value
out OSCCAL, r16
; Setup I/O Port
ldi r16, 0x07 ; PB0, PB1 and PB2 are outputs
out DDRB, r16
ldi r16, 0x08 ; Pullup PB3
out PUEB, r16
; Setup Timer for 16 bit Fast PWM
ldi r16,0xA2 ; Set A&B on Bottom, Clear on Match
out TCCR0A, r16
ldi r16, 0x19 ; PWM mode 0xE, timer clock = 4 MHz / 1
out TCCR0B, r16
ldi r16, 0xFF ; Set TOP to 0xFFFF
out ICR0H, r16
out ICR0L, r16
; Set OCR0A to 6000 Dec
ldi r16, (6000 >> 8)
out OCR0AH, r16
ldi r16, (6000 & 0xFF)
out OCR0AL, r16
; Set OCR0B to 6000 Dec
ldi r16, (6000 >> 8)
out OCR0BH, r16
ldi r16, (6000 & 0xFF)
out OCR0BL, r16
; Reset Flags
sub r16, r16
sts flags, r16
; Setup Timer overflow interrupt
ldi r16, 0x01 ; enable overflow interrupt
out TIMSK0, r16
sei ; enable interrupts
loop:
; process received characters at 9600 baud
rcall receive
mov r16, r17
andi r17, 0x3F
andi r16, 0xC0
cpi r16, 0x00 ; Set AL
breq setAL
cpi r16, 0x40 ; Set AH
breq setAH
cpi r16, 0x80 ; Set BL
breq setBL
cpi r16, 0xC0 ; Set BH
breq setBH
rjmp loop
;
setAL:
sts AL, r17
rjmp loop
setBL:
sts BL, r17
rjmp loop
;
setAH:
lds r16, AL
rcall combine
; save new OCR0A values for interrupt
cli
sts TAL, r17
sts TAH, r18
lds r16, flags
ori r16, 0x01 ; Set update flag
sts flags, r16
sei
rjmp loop
;
setBH:
lds r16, BL
rcall combine
; save new OCR0B values for interrupt
cli
sts TBL, r17
sts TBH, r18
lds r16, flags
ori r16, 0x02 ; Set update flag
sts flags, r16
sei
rjmp loop
;
combine:
sub r18, r18 ; r18 = 0
; combine 6 bits AH (r17) and AL (r16) values into 12 bit value
lsl r17 ; r17 = -543210-
lsl r17 ; r17 = 543210--
lsl r17 ; r17 = 43210---, c = 5
rol r18 ; r18 = -------5
lsl r17 ; r17 = 3210----, c = 4
rol r18 ; r18 = ------54
lsl r17 ; r17 = 210-----, c = 3
rol r18 ; r18 = -----543
lsl r17 ; r17 = 10------, c = 2
rol r18 ; r18 = ----5432
; r18:r17 is now ----5432:10------
add r17, r16
; r18:r17 << 1
lsl r17
rol r18
; Add 2000 Dec to r18:r17
ldi r16, (2000 & 0xFF)
add r17, r16
ldi r16, (2000 >> 8)
adc r18, r16
ret
;
receive:
; wait for start pulse on PB3
ldi r17, 0x00 ; clear serial input register
wait:
sbic PINB, PINB3
rjmp wait
rcall halfdelay
sbic PINB, PINB3 ; verify start bit
rjmp wait
; sample 8 bits
rcall bitdelay
sbic PINB, PINB3 ; bit 0
ori r17, 0x01
rcall bitdelay
sbic PINB, PINB3 ; bit 1
ori r17, 0x02
rcall bitdelay
sbic PINB, PINB3 ; bit 2
ori r17, 0x04
rcall bitdelay
sbic PINB, PINB3 ; bit 3
ori r17, 0x08
rcall bitdelay
sbic PINB, PINB3 ; bit 4
ori r17, 0x10
rcall bitdelay
sbic PINB, PINB3 ; bit 5
ori r17, 0x20
rcall bitdelay
sbic PINB, PINB3 ; bit 6
ori r17, 0x40
rcall bitdelay
sbic PINB, PINB3 ; bit 7
ori r17, 0x80
rcall bitdelay
sbis PINB, PINB3 ; verify stop bit
rjmp wait
ret
;
bitdelay:
ldi r16, 0x86
bitLoop:
dec r16
brne bitLoop
ret
;
halfdelay:
ldi r16, 0x43
halfLoop:
dec r16
brne halfLoop
ret
;
timer_ofl:
; Overflow (TOP) interrupt handler (~60 Hz)
push r16
in r16, SREG
push r16
lds r16, flags
andi r16, 0x01
breq skipTA
; Update OCR0AH & OCR0AL registers
lds r16, TAH
out OCR0AH, r16
lds r16, TAL
out OCR0AL, r16
skipTA:
lds r16, flags
andi r16, 0x02
breq skipTB
; Update OCR0BH & OCR0BL registers
lds r16, TBH
out OCR0BH, r16
lds r16, TBL
out OCR0BL, r16
skipTB:
pop r16
out SREG, r16
pop r16
reti
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/predictor/lane_sequence/lane_sequence_predictor.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
namespace apollo {
namespace prediction {
class LaneSequencePredictorTest : public KMLMapBasedTest {
public:
virtual void SetUp() {
std::string file =
"modules/prediction/testdata/single_perception_vehicle_onlane.pb.txt";
apollo::common::util::GetProtoFromFile(file, &perception_obstacles_);
}
protected:
apollo::perception::PerceptionObstacles perception_obstacles_;
};
TEST_F(LaneSequencePredictorTest, OnLaneCase) {
EXPECT_DOUBLE_EQ(perception_obstacles_.header().timestamp_sec(),
1501183430.161906);
apollo::perception::PerceptionObstacle perception_obstacle =
perception_obstacles_.perception_obstacle(0);
EXPECT_EQ(perception_obstacle.id(), 1);
MLPEvaluator mlp_evaluator;
ObstaclesContainer container;
container.Insert(perception_obstacles_);
container.BuildLaneGraph();
Obstacle* obstacle_ptr = container.GetObstacle(1);
EXPECT_TRUE(obstacle_ptr != nullptr);
mlp_evaluator.Evaluate(obstacle_ptr);
LaneSequencePredictor predictor;
predictor.Predict(obstacle_ptr);
EXPECT_EQ(predictor.NumOfTrajectories(), 1);
}
} // namespace prediction
} // namespace apollo
|
; CALLER linkage for function pointers
XLIB outp
LIB outp_callee
XREF ASMDISP_OUTP_CALLEE
.outp
pop af
pop de
pop bc
push bc
push de
push af
jp outp_callee + ASMDISP_OUTP_CALLEE
|
/** @file kmp_stats_timing.cpp
* Timing functions
*/
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include "kmp_stats_timing.h"
using namespace std;
#if KMP_OS_LINUX
# if KMP_MIC
double tsc_tick_count::tick_time()
{
// pretty bad assumption of 1GHz clock for MIC
return 1/((double)1000*1.e6);
}
# else
# include <string.h>
// Extract the value from the CPUID information
double tsc_tick_count::tick_time()
{
static double result = 0.0;
if (result == 0.0)
{
int cpuinfo[4];
char brand[256];
__cpuid(cpuinfo, 0x80000000);
memset(brand, 0, sizeof(brand));
int ids = cpuinfo[0];
for (unsigned int i=2; i<(ids^0x80000000)+2; i++)
__cpuid(brand+(i-2)*sizeof(cpuinfo), i | 0x80000000);
char * start = &brand[0];
for (;*start == ' '; start++)
;
char * end = brand + KMP_STRLEN(brand) - 3;
uint64_t multiplier;
if (*end == 'M') multiplier = 1000LL*1000LL;
else if (*end == 'G') multiplier = 1000LL*1000LL*1000LL;
else if (*end == 'T') multiplier = 1000LL*1000LL*1000LL*1000LL;
else
{
cout << "Error determining multiplier '" << *end << "'\n";
exit (-1);
}
*end = 0;
while (*end != ' ') end--;
end++;
double freq = strtod(end, &start);
if (freq == 0.0)
{
cout << "Error calculating frequency " << end << "\n";
exit (-1);
}
result = ((double)1.0)/(freq * multiplier);
}
return result;
}
# endif
#endif
static bool useSI = true;
// Return a formatted string after normalising the value into
// engineering style and using a suitable unit prefix (e.g. ms, us, ns).
std::string formatSI(double interval, int width, char unit)
{
std::stringstream os;
if (useSI)
{
// Preserve accuracy for small numbers, since we only multiply and the positive powers
// of ten are precisely representable.
static struct { double scale; char prefix; } ranges[] = {
{1.e12,'f'},
{1.e9, 'p'},
{1.e6, 'n'},
{1.e3, 'u'},
{1.0, 'm'},
{1.e-3,' '},
{1.e-6,'k'},
{1.e-9,'M'},
{1.e-12,'G'},
{1.e-15,'T'},
{1.e-18,'P'},
{1.e-21,'E'},
{1.e-24,'Z'},
{1.e-27,'Y'}
};
if (interval == 0.0)
{
os << std::setw(width-3) << std::right << "0.00" << std::setw(3) << unit;
return os.str();
}
bool negative = false;
if (interval < 0.0)
{
negative = true;
interval = -interval;
}
for (int i=0; i<(int)(sizeof(ranges)/sizeof(ranges[0])); i++)
{
if (interval*ranges[i].scale < 1.e0)
{
interval = interval * 1000.e0 * ranges[i].scale;
os << std::fixed << std::setprecision(2) << std::setw(width-3) << std::right <<
(negative ? -interval : interval) << std::setw(2) << ranges[i].prefix << std::setw(1) << unit;
return os.str();
}
}
}
os << std::setprecision(2) << std::fixed << std::right << std::setw(width-3) << interval << std::setw(3) << unit;
return os.str();
}
tsc_tick_count::tsc_interval_t computeLastInLastOutInterval(timePair * times, int nTimes)
{
timePair lastTimes = times[0];
tsc_tick_count * startp = lastTimes.get_startp();
tsc_tick_count * endp = lastTimes.get_endp();
for (int i=1; i<nTimes; i++)
{
(*startp) = startp->later(times[i].get_start());
(*endp) = endp->later (times[i].get_end());
}
return lastTimes.duration();
}
std::string timePair::format() const
{
std::ostringstream oss;
oss << start.getValue() << ":" << end.getValue() << " = " << (end-start).getValue();
return oss.str();
}
|
; A083036: Partial sums of A083035.
; 1,1,1,2,3,3,4,5,5,5,6,6,6,7,8,8,8,9,9,9,10,11,11,12,13,13,13,14,15,15,16,17,17,17,18,18,18,19,20,20,21,22,22,22,23,24,24,25,26,26,26,27,27,27,28,29,29,29,30,30,30,31,32,32,33,34,34,34,35,35,35,36,37,37,37,38
mov $2,$0
add $2,1
mov $4,$0
lpb $2
mov $0,$4
sub $2,1
sub $0,$2
add $0,1
pow $0,2
sub $3,$3
lpb $0
add $3,1
sub $0,$3
lpe
mod $3,2
add $1,$3
lpe
|
%define BPM 100
%include "../src/sointu.inc"
BEGIN_PATTERNS
PATTERN 64, HLD, HLD, HLD, HLD, HLD, HLD, HLD, 0, 0, 0, 0, 0, 0, 0, 0,
END_PATTERNS
BEGIN_TRACKS
TRACK VOICES(1),0
END_TRACKS
BEGIN_PATCH
BEGIN_INSTRUMENT VOICES(1) ; Instrument0
SU_LOADVAL MONO,VALUE(32)
SU_LOADVAL MONO,VALUE(128)
SU_ADD MONO
SU_OUT STEREO,GAIN(128)
END_INSTRUMENT
END_PATCH
%include "../src/sointu.asm"
|
// 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.
// String functions
#include "arrow/util/value_parsing.h"
extern "C" {
#include <algorithm>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "./types.h"
FORCE_INLINE
gdv_int32 octet_length_utf8(const gdv_utf8 input, gdv_int32 length) { return length; }
FORCE_INLINE
gdv_int32 bit_length_utf8(const gdv_utf8 input, gdv_int32 length) { return length * 8; }
FORCE_INLINE
gdv_int32 octet_length_binary(const gdv_binary input, gdv_int32 length) { return length; }
FORCE_INLINE
gdv_int32 bit_length_binary(const gdv_binary input, gdv_int32 length) {
return length * 8;
}
FORCE_INLINE
int match_string(const char* input, gdv_int32 input_len, gdv_int32 start_pos,
const char* delim, gdv_int32 delim_len) {
for (int i = start_pos; i < input_len; i++) {
int left_chars = input_len - i;
if ((left_chars >= delim_len) && memcmp(input + i, delim, delim_len) == 0) {
return i + delim_len;
}
}
return -1;
}
FORCE_INLINE
gdv_int32 mem_compare(const char* left, gdv_int32 left_len, const char* right,
gdv_int32 right_len) {
int min = left_len;
if (right_len < min) {
min = right_len;
}
int cmp_ret = memcmp(left, right, min);
if (cmp_ret != 0) {
return cmp_ret;
} else {
return left_len - right_len;
}
}
// Expand inner macro for all varlen types.
#define VAR_LEN_OP_TYPES(INNER, NAME, OP) \
INNER(NAME, utf8, OP) \
INNER(NAME, binary, OP)
// Relational binary fns : left, right params are same, return is bool.
#define BINARY_RELATIONAL(NAME, TYPE, OP) \
FORCE_INLINE \
bool NAME##_##TYPE##_##TYPE(const gdv_##TYPE left, gdv_int32 left_len, \
const gdv_##TYPE right, gdv_int32 right_len) { \
return mem_compare(left, left_len, right, right_len) OP 0; \
}
VAR_LEN_OP_TYPES(BINARY_RELATIONAL, equal, ==)
VAR_LEN_OP_TYPES(BINARY_RELATIONAL, not_equal, !=)
VAR_LEN_OP_TYPES(BINARY_RELATIONAL, less_than, <)
VAR_LEN_OP_TYPES(BINARY_RELATIONAL, less_than_or_equal_to, <=)
VAR_LEN_OP_TYPES(BINARY_RELATIONAL, greater_than, >)
VAR_LEN_OP_TYPES(BINARY_RELATIONAL, greater_than_or_equal_to, >=)
#undef BINARY_RELATIONAL
#undef VAR_LEN_OP_TYPES
// Expand inner macro for all varlen types.
#define VAR_LEN_TYPES(INNER, NAME) \
INNER(NAME, utf8) \
INNER(NAME, binary)
FORCE_INLINE
int to_binary_from_hex(char ch) {
if (ch >= 'A' && ch <= 'F') {
return 10 + (ch - 'A');
} else if (ch >= 'a' && ch <= 'f') {
return 10 + (ch - 'a');
}
return ch - '0';
}
FORCE_INLINE
bool starts_with_utf8_utf8(const char* data, gdv_int32 data_len, const char* prefix,
gdv_int32 prefix_len) {
return ((data_len >= prefix_len) && (memcmp(data, prefix, prefix_len) == 0));
}
FORCE_INLINE
bool ends_with_utf8_utf8(const char* data, gdv_int32 data_len, const char* suffix,
gdv_int32 suffix_len) {
return ((data_len >= suffix_len) &&
(memcmp(data + data_len - suffix_len, suffix, suffix_len) == 0));
}
FORCE_INLINE
bool is_substr_utf8_utf8(const char* data, int32_t data_len, const char* substr,
int32_t substr_len) {
for (int32_t i = 0; i <= data_len - substr_len; ++i) {
if (memcmp(data + i, substr, substr_len) == 0) {
return true;
}
}
return false;
}
FORCE_INLINE
gdv_int32 utf8_char_length(char c) {
if ((signed char)c >= 0) { // 1-byte char (0x00 ~ 0x7F)
return 1;
} else if ((c & 0xE0) == 0xC0) { // 2-byte char
return 2;
} else if ((c & 0xF0) == 0xE0) { // 3-byte char
return 3;
} else if ((c & 0xF8) == 0xF0) { // 4-byte char
return 4;
}
// invalid char
return 0;
}
FORCE_INLINE
void set_error_for_invalid_utf(int64_t execution_context, char val) {
char const* fmt = "unexpected byte \\%02hhx encountered while decoding utf8 string";
int size = static_cast<int>(strlen(fmt)) + 64;
char* error = reinterpret_cast<char*>(malloc(size));
snprintf(error, size, fmt, (unsigned char)val);
gdv_fn_context_set_error_msg(execution_context, error);
free(error);
}
FORCE_INLINE
bool validate_utf8_following_bytes(const char* data, int32_t data_len,
int32_t char_index) {
for (int j = 1; j < data_len; ++j) {
if ((data[char_index + j] & 0xC0) != 0x80) { // bytes following head-byte of glyph
return false;
}
}
return true;
}
// Count the number of utf8 characters
// return 0 for invalid/incomplete input byte sequences
FORCE_INLINE
gdv_int32 utf8_length(gdv_int64 context, const char* data, gdv_int32 data_len) {
int char_len = 0;
int count = 0;
for (int i = 0; i < data_len; i += char_len) {
char_len = utf8_char_length(data[i]);
if (char_len == 0 || i + char_len > data_len) { // invalid byte or incomplete glyph
set_error_for_invalid_utf(context, data[i]);
return 0;
}
for (int j = 1; j < char_len; ++j) {
if ((data[i + j] & 0xC0) != 0x80) { // bytes following head-byte of glyph
set_error_for_invalid_utf(context, data[i + j]);
return 0;
}
}
++count;
}
return count;
}
// Count the number of utf8 characters, ignoring invalid char, considering size 1
FORCE_INLINE
gdv_int32 utf8_length_ignore_invalid(const char* data, gdv_int32 data_len) {
int char_len = 0;
int count = 0;
for (int i = 0; i < data_len; i += char_len) {
char_len = utf8_char_length(data[i]);
if (char_len == 0 || i + char_len > data_len) { // invalid byte or incomplete glyph
// if invalid byte or incomplete glyph, ignore it
char_len = 1;
}
for (int j = 1; j < char_len; ++j) {
if ((data[i + j] & 0xC0) != 0x80) { // bytes following head-byte of glyph
char_len += 1;
}
}
++count;
}
return count;
}
// Get the byte position corresponding to a character position for a non-empty utf8
// sequence
FORCE_INLINE
gdv_int32 utf8_byte_pos(gdv_int64 context, const char* str, gdv_int32 str_len,
gdv_int32 char_pos) {
int char_len = 0;
int byte_index = 0;
for (gdv_int32 char_index = 0; char_index < char_pos && byte_index < str_len;
char_index++) {
char_len = utf8_char_length(str[byte_index]);
if (char_len == 0 ||
byte_index + char_len > str_len) { // invalid byte or incomplete glyph
set_error_for_invalid_utf(context, str[byte_index]);
return -1;
}
byte_index += char_len;
}
return byte_index;
}
#define UTF8_LENGTH(NAME, TYPE) \
FORCE_INLINE \
gdv_int32 NAME##_##TYPE(gdv_int64 context, gdv_##TYPE in, gdv_int32 in_len) { \
return utf8_length(context, in, in_len); \
}
UTF8_LENGTH(char_length, utf8)
UTF8_LENGTH(length, utf8)
UTF8_LENGTH(lengthUtf8, binary)
// Reverse a utf8 sequence
FORCE_INLINE
const char* reverse_utf8(gdv_int64 context, const char* data, gdv_int32 data_len,
int32_t* out_len) {
if (data_len == 0) {
*out_len = 0;
return "";
}
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, data_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
gdv_int32 char_len;
for (gdv_int32 i = 0; i < data_len; i += char_len) {
char_len = utf8_char_length(data[i]);
if (char_len == 0 || i + char_len > data_len) { // invalid byte or incomplete glyph
set_error_for_invalid_utf(context, data[i]);
*out_len = 0;
return "";
}
for (gdv_int32 j = 0; j < char_len; ++j) {
if (j > 0 && (data[i + j] & 0xC0) != 0x80) { // bytes following head-byte of glyph
set_error_for_invalid_utf(context, data[i + j]);
*out_len = 0;
return "";
}
ret[data_len - i - char_len + j] = data[i + j];
}
}
*out_len = data_len;
return ret;
}
// Trims whitespaces from the left end of the input utf8 sequence
FORCE_INLINE
const char* ltrim_utf8(gdv_int64 context, const char* data, gdv_int32 data_len,
int32_t* out_len) {
if (data_len == 0) {
*out_len = 0;
return "";
}
gdv_int32 start = 0;
// start denotes the first position of non-space characters in the input string
while (start < data_len && data[start] == ' ') {
++start;
}
*out_len = data_len - start;
return data + start;
}
// Trims whitespaces from the right end of the input utf8 sequence
FORCE_INLINE
const char* rtrim_utf8(gdv_int64 context, const char* data, gdv_int32 data_len,
int32_t* out_len) {
if (data_len == 0) {
*out_len = 0;
return "";
}
gdv_int32 end = data_len - 1;
// end denotes the last position of non-space characters in the input string
while (end >= 0 && data[end] == ' ') {
--end;
}
*out_len = end + 1;
return data;
}
// Trims whitespaces from both the ends of the input utf8 sequence
FORCE_INLINE
const char* btrim_utf8(gdv_int64 context, const char* data, gdv_int32 data_len,
int32_t* out_len) {
if (data_len == 0) {
*out_len = 0;
return "";
}
gdv_int32 start = 0, end = data_len - 1;
// start and end denote the first and last positions of non-space
// characters in the input string respectively
while (start <= end && data[start] == ' ') {
++start;
}
while (end >= start && data[end] == ' ') {
--end;
}
// string has some leading/trailing spaces and some non-space characters
*out_len = end - start + 1;
return data + start;
}
// Trims characters present in the trim text from the left end of the base text
FORCE_INLINE
const char* ltrim_utf8_utf8(gdv_int64 context, const char* basetext,
gdv_int32 basetext_len, const char* trimtext,
gdv_int32 trimtext_len, int32_t* out_len) {
if (basetext_len == 0) {
*out_len = 0;
return "";
} else if (trimtext_len == 0) {
*out_len = basetext_len;
return basetext;
}
gdv_int32 start_ptr, char_len;
// scan the base text from left to right and increment the start pointer till
// there is a character which is not present in the trim text
for (start_ptr = 0; start_ptr < basetext_len; start_ptr += char_len) {
char_len = utf8_char_length(basetext[start_ptr]);
if (char_len == 0 || start_ptr + char_len > basetext_len) {
// invalid byte or incomplete glyph
set_error_for_invalid_utf(context, basetext[start_ptr]);
*out_len = 0;
return "";
}
if (!is_substr_utf8_utf8(trimtext, trimtext_len, basetext + start_ptr, char_len)) {
break;
}
}
*out_len = basetext_len - start_ptr;
return basetext + start_ptr;
}
// Trims characters present in the trim text from the right end of the base text
FORCE_INLINE
const char* rtrim_utf8_utf8(gdv_int64 context, const char* basetext,
gdv_int32 basetext_len, const char* trimtext,
gdv_int32 trimtext_len, int32_t* out_len) {
if (basetext_len == 0) {
*out_len = 0;
return "";
} else if (trimtext_len == 0) {
*out_len = basetext_len;
return basetext;
}
gdv_int32 char_len, end_ptr, byte_cnt = 1;
// scan the base text from right to left and decrement the end pointer till
// there is a character which is not present in the trim text
for (end_ptr = basetext_len - 1; end_ptr >= 0; --end_ptr) {
char_len = utf8_char_length(basetext[end_ptr]);
if (char_len == 0) { // trailing bytes of multibyte character
++byte_cnt;
continue;
}
// this is the first byte of a character, hence check if char_len = char_cnt
if (byte_cnt != char_len) { // invalid byte or incomplete glyph
set_error_for_invalid_utf(context, basetext[end_ptr]);
*out_len = 0;
return "";
}
byte_cnt = 1; // reset the counter*/
if (!is_substr_utf8_utf8(trimtext, trimtext_len, basetext + end_ptr, char_len)) {
break;
}
}
// when all characters in the basetext are part of the trimtext
if (end_ptr == -1) {
*out_len = 0;
return "";
}
end_ptr += utf8_char_length(basetext[end_ptr]); // point to the next character
*out_len = end_ptr;
return basetext;
}
// Trims characters present in the trim text from both ends of the base text
FORCE_INLINE
const char* btrim_utf8_utf8(gdv_int64 context, const char* basetext,
gdv_int32 basetext_len, const char* trimtext,
gdv_int32 trimtext_len, int32_t* out_len) {
if (basetext_len == 0) {
*out_len = 0;
return "";
} else if (trimtext_len == 0) {
*out_len = basetext_len;
return basetext;
}
gdv_int32 start_ptr, end_ptr, char_len, byte_cnt = 1;
// scan the base text from left to right and increment the start and decrement the
// end pointers till there are characters which are not present in the trim text
for (start_ptr = 0; start_ptr < basetext_len; start_ptr += char_len) {
char_len = utf8_char_length(basetext[start_ptr]);
if (char_len == 0 || start_ptr + char_len > basetext_len) {
// invalid byte or incomplete glyph
set_error_for_invalid_utf(context, basetext[start_ptr]);
*out_len = 0;
return "";
}
if (!is_substr_utf8_utf8(trimtext, trimtext_len, basetext + start_ptr, char_len)) {
break;
}
}
for (end_ptr = basetext_len - 1; end_ptr >= start_ptr; --end_ptr) {
char_len = utf8_char_length(basetext[end_ptr]);
if (char_len == 0) { // trailing byte in multibyte character
++byte_cnt;
continue;
}
// this is the first byte of a character, hence check if char_len = char_cnt
if (byte_cnt != char_len) { // invalid byte or incomplete glyph
set_error_for_invalid_utf(context, basetext[end_ptr]);
*out_len = 0;
return "";
}
byte_cnt = 1; // reset the counter*/
if (!is_substr_utf8_utf8(trimtext, trimtext_len, basetext + end_ptr, char_len)) {
break;
}
}
// when all characters are trimmed, start_ptr has been incremented to basetext_len and
// end_ptr still points to basetext_len - 1, hence we need to handle this case
if (start_ptr > end_ptr) {
*out_len = 0;
return "";
}
end_ptr += utf8_char_length(basetext[end_ptr]); // point to the next character
*out_len = end_ptr - start_ptr;
return basetext + start_ptr;
}
FORCE_INLINE
gdv_boolean compare_lower_strings(const char* base_str, gdv_int32 base_str_len,
const char* str, gdv_int32 str_len) {
if (base_str_len != str_len) {
return false;
}
for (int i = 0; i < str_len; i++) {
// convert char to lower
char cur = str[i];
// 'A' - 'Z' : 0x41 - 0x5a
// 'a' - 'z' : 0x61 - 0x7a
if (cur >= 0x41 && cur <= 0x5a) {
cur = static_cast<char>(cur + 0x20);
}
// if the character does not match, break the flow
if (cur != base_str[i]) break;
// if the character matches and it is the last iteration, return true
if (i == str_len - 1) return true;
}
return false;
}
// Try to cast the received string ('0', '1', 'true', 'false'), ignoring leading
// and trailing spaces, also ignoring lower and upper case.
FORCE_INLINE
gdv_boolean castBIT_utf8(gdv_int64 context, const char* data, gdv_int32 data_len) {
if (data_len <= 0) {
gdv_fn_context_set_error_msg(context, "Invalid value for boolean.");
return false;
}
// trim leading and trailing spaces
int32_t trimmed_len;
int32_t start = 0, end = data_len - 1;
while (start <= end && data[start] == ' ') {
++start;
}
while (end >= start && data[end] == ' ') {
--end;
}
trimmed_len = end - start + 1;
const char* trimmed_data = data + start;
// compare received string with the valid bool string values '1', '0', 'true', 'false'
if (trimmed_len == 1) {
// case for '0' and '1' value
if (trimmed_data[0] == '1') return true;
if (trimmed_data[0] == '0') return false;
} else if (trimmed_len == 4) {
// case for matching 'true'
if (compare_lower_strings("true", 4, trimmed_data, trimmed_len)) return true;
} else if (trimmed_len == 5) {
// case for matching 'false'
if (compare_lower_strings("false", 5, trimmed_data, trimmed_len)) return false;
}
// if no 'true', 'false', '0' or '1' value is found, set an error
gdv_fn_context_set_error_msg(context, "Invalid value for boolean.");
return false;
}
FORCE_INLINE
const char* castVARCHAR_bool_int64(gdv_int64 context, gdv_boolean value,
gdv_int64 out_len, gdv_int32* out_length) {
gdv_int32 len = static_cast<gdv_int32>(out_len);
if (len < 0) {
gdv_fn_context_set_error_msg(context, "Output buffer length can't be negative");
*out_length = 0;
return "";
}
const char* out =
reinterpret_cast<const char*>(gdv_fn_context_arena_malloc(context, 5));
out = value ? "true" : "false";
*out_length = value ? ((len > 4) ? 4 : len) : ((len > 5) ? 5 : len);
return out;
}
// Truncates the string to given length
#define CAST_VARCHAR_FROM_VARLEN_TYPE(TYPE) \
FORCE_INLINE \
const char* castVARCHAR_##TYPE##_int64(gdv_int64 context, const char* data, \
gdv_int32 data_len, int64_t out_len, \
int32_t* out_length) { \
int32_t len = static_cast<int32_t>(out_len); \
\
if (len < 0) { \
gdv_fn_context_set_error_msg(context, "Output buffer length can't be negative"); \
*out_length = 0; \
return ""; \
} \
\
if (len >= data_len || len == 0) { \
*out_length = data_len; \
return data; \
} \
\
int32_t remaining = len; \
int32_t index = 0; \
bool is_multibyte = false; \
do { \
/* In utf8, MSB of a single byte unicode char is always 0, \
* whereas for a multibyte character the MSB of each byte is 1. \
* So for a single byte char, a bitwise-and with x80 (10000000) will be 0 \
* and it won't be 0 for bytes of a multibyte char. \
*/ \
char* data_ptr = const_cast<char*>(data); \
\
/* advance byte by byte till the 8-byte boundary then advance 8 bytes */ \
auto num_bytes = reinterpret_cast<uintptr_t>(data_ptr) & 0x07; \
num_bytes = (8 - num_bytes) & 0x07; \
while (num_bytes > 0) { \
uint8_t* ptr = reinterpret_cast<uint8_t*>(data_ptr + index); \
if ((*ptr & 0x80) != 0) { \
is_multibyte = true; \
break; \
} \
index++; \
remaining--; \
num_bytes--; \
} \
if (is_multibyte) break; \
while (remaining >= 8) { \
uint64_t* ptr = reinterpret_cast<uint64_t*>(data_ptr + index); \
if ((*ptr & 0x8080808080808080) != 0) { \
is_multibyte = true; \
break; \
} \
index += 8; \
remaining -= 8; \
} \
if (is_multibyte) break; \
if (remaining >= 4) { \
uint32_t* ptr = reinterpret_cast<uint32_t*>(data_ptr + index); \
if ((*ptr & 0x80808080) != 0) break; \
index += 4; \
remaining -= 4; \
} \
while (remaining > 0) { \
uint8_t* ptr = reinterpret_cast<uint8_t*>(data_ptr + index); \
if ((*ptr & 0x80) != 0) { \
is_multibyte = true; \
break; \
} \
index++; \
remaining--; \
} \
if (is_multibyte) break; \
/* reached here; all are single byte characters */ \
*out_length = len; \
return data; \
} while (false); \
\
/* detected multibyte utf8 characters; slow path */ \
int32_t byte_pos = \
utf8_byte_pos(context, data + index, data_len - index, len - index); \
if (byte_pos < 0) { \
*out_length = 0; \
return ""; \
} \
\
*out_length = index + byte_pos; \
return data; \
}
CAST_VARCHAR_FROM_VARLEN_TYPE(utf8)
CAST_VARCHAR_FROM_VARLEN_TYPE(binary)
#undef CAST_VARCHAR_FROM_VARLEN_TYPE
// Add functions for castVARBINARY
#define CAST_VARBINARY_FROM_STRING_AND_BINARY(TYPE) \
GANDIVA_EXPORT \
const char* castVARBINARY_##TYPE##_int64(gdv_int64 context, const char* data, \
gdv_int32 data_len, int64_t out_len, \
int32_t* out_length) { \
int32_t len = static_cast<int32_t>(out_len); \
if (len < 0) { \
gdv_fn_context_set_error_msg(context, "Output buffer length can't be negative"); \
*out_length = 0; \
return ""; \
} \
\
if (len >= data_len || len == 0) { \
*out_length = data_len; \
} else { \
*out_length = len; \
} \
return data; \
}
CAST_VARBINARY_FROM_STRING_AND_BINARY(utf8)
CAST_VARBINARY_FROM_STRING_AND_BINARY(binary)
#undef CAST_VARBINARY_FROM_STRING_AND_BINARY
#define IS_NULL(NAME, TYPE) \
FORCE_INLINE \
bool NAME##_##TYPE(gdv_##TYPE in, gdv_int32 len, gdv_boolean is_valid) { \
return !is_valid; \
}
VAR_LEN_TYPES(IS_NULL, isnull)
#undef IS_NULL
#define IS_NOT_NULL(NAME, TYPE) \
FORCE_INLINE \
bool NAME##_##TYPE(gdv_##TYPE in, gdv_int32 len, gdv_boolean is_valid) { \
return is_valid; \
}
VAR_LEN_TYPES(IS_NOT_NULL, isnotnull)
#undef IS_NOT_NULL
#undef VAR_LEN_TYPES
/*
We follow Oracle semantics for offset:
- If position is positive, then the first glyph in the substring is determined by
counting that many glyphs forward from the beginning of the input. (i.e., for position ==
1 the first glyph in the substring will be identical to the first glyph in the input)
- If position is negative, then the first glyph in the substring is determined by
counting that many glyphs backward from the end of the input. (i.e., for position == -1
the first glyph in the substring will be identical to the last glyph in the input)
- If position is 0 then it is treated as 1.
*/
FORCE_INLINE
const char* substr_utf8_int64_int64(gdv_int64 context, const char* input,
gdv_int32 in_data_len, gdv_int64 position,
gdv_int64 substring_length, gdv_int32* out_data_len) {
if (substring_length <= 0 || input == nullptr || in_data_len <= 0) {
*out_data_len = 0;
return "";
}
gdv_int64 in_glyphs_count =
static_cast<gdv_int64>(utf8_length(context, input, in_data_len));
// in_glyphs_count is zero if input has invalid glyphs
if (in_glyphs_count == 0) {
*out_data_len = 0;
return "";
}
gdv_int64 from_glyph; // from_glyph==0 indicates the first glyph of the input
if (position > 0) {
from_glyph = position - 1;
} else if (position < 0) {
from_glyph = in_glyphs_count + position;
} else {
from_glyph = 0;
}
if (from_glyph < 0 || from_glyph >= in_glyphs_count) {
*out_data_len = 0;
return "";
}
gdv_int64 out_glyphs_count = substring_length;
if (substring_length > in_glyphs_count - from_glyph) {
out_glyphs_count = in_glyphs_count - from_glyph;
}
gdv_int64 in_data_len64 = static_cast<gdv_int64>(in_data_len);
gdv_int64 start_pos = 0;
gdv_int64 end_pos = in_data_len64;
gdv_int64 current_glyph = 0;
gdv_int64 pos = 0;
while (pos < in_data_len64) {
if (current_glyph == from_glyph) {
start_pos = pos;
}
pos += static_cast<gdv_int64>(utf8_char_length(input[pos]));
if (current_glyph - from_glyph + 1 == out_glyphs_count) {
end_pos = pos;
}
current_glyph++;
}
if (end_pos > in_data_len64 || end_pos > INT_MAX) {
end_pos = in_data_len64;
}
*out_data_len = static_cast<gdv_int32>(end_pos - start_pos);
char* ret =
reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_data_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_data_len = 0;
return "";
}
memcpy(ret, input + start_pos, *out_data_len);
return ret;
}
FORCE_INLINE
const char* substr_utf8_int64(gdv_int64 context, const char* input, gdv_int32 in_len,
gdv_int64 offset64, gdv_int32* out_len) {
return substr_utf8_int64_int64(context, input, in_len, offset64, in_len, out_len);
}
FORCE_INLINE
const char* concat_utf8_utf8(gdv_int64 context, const char* left, gdv_int32 left_len,
bool left_validity, const char* right, gdv_int32 right_len,
bool right_validity, gdv_int32* out_len) {
if (!left_validity) {
left_len = 0;
}
if (!right_validity) {
right_len = 0;
}
return concatOperator_utf8_utf8(context, left, left_len, right, right_len, out_len);
}
FORCE_INLINE
const char* concatOperator_utf8_utf8(gdv_int64 context, const char* left,
gdv_int32 left_len, const char* right,
gdv_int32 right_len, gdv_int32* out_len) {
*out_len = left_len + right_len;
if (*out_len <= 0) {
*out_len = 0;
return "";
}
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, left, left_len);
memcpy(ret + left_len, right, right_len);
return ret;
}
FORCE_INLINE
const char* concat_utf8_utf8_utf8(gdv_int64 context, const char* in1, gdv_int32 in1_len,
bool in1_validity, const char* in2, gdv_int32 in2_len,
bool in2_validity, const char* in3, gdv_int32 in3_len,
bool in3_validity, gdv_int32* out_len) {
if (!in1_validity) {
in1_len = 0;
}
if (!in2_validity) {
in2_len = 0;
}
if (!in3_validity) {
in3_len = 0;
}
return concatOperator_utf8_utf8_utf8(context, in1, in1_len, in2, in2_len, in3, in3_len,
out_len);
}
FORCE_INLINE
const char* concatOperator_utf8_utf8_utf8(gdv_int64 context, const char* in1,
gdv_int32 in1_len, const char* in2,
gdv_int32 in2_len, const char* in3,
gdv_int32 in3_len, gdv_int32* out_len) {
*out_len = in1_len + in2_len + in3_len;
if (*out_len <= 0) {
*out_len = 0;
return "";
}
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, in1, in1_len);
memcpy(ret + in1_len, in2, in2_len);
memcpy(ret + in1_len + in2_len, in3, in3_len);
return ret;
}
FORCE_INLINE
const char* concat_utf8_utf8_utf8_utf8(gdv_int64 context, const char* in1,
gdv_int32 in1_len, bool in1_validity,
const char* in2, gdv_int32 in2_len,
bool in2_validity, const char* in3,
gdv_int32 in3_len, bool in3_validity,
const char* in4, gdv_int32 in4_len,
bool in4_validity, gdv_int32* out_len) {
if (!in1_validity) {
in1_len = 0;
}
if (!in2_validity) {
in2_len = 0;
}
if (!in3_validity) {
in3_len = 0;
}
if (!in4_validity) {
in4_len = 0;
}
return concatOperator_utf8_utf8_utf8_utf8(context, in1, in1_len, in2, in2_len, in3,
in3_len, in4, in4_len, out_len);
}
FORCE_INLINE
const char* concatOperator_utf8_utf8_utf8_utf8(gdv_int64 context, const char* in1,
gdv_int32 in1_len, const char* in2,
gdv_int32 in2_len, const char* in3,
gdv_int32 in3_len, const char* in4,
gdv_int32 in4_len, gdv_int32* out_len) {
*out_len = in1_len + in2_len + in3_len + in4_len;
if (*out_len <= 0) {
*out_len = 0;
return "";
}
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, in1, in1_len);
memcpy(ret + in1_len, in2, in2_len);
memcpy(ret + in1_len + in2_len, in3, in3_len);
memcpy(ret + in1_len + in2_len + in3_len, in4, in4_len);
return ret;
}
FORCE_INLINE
const char* concat_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, bool in1_validity,
const char* in2, gdv_int32 in2_len, bool in2_validity, const char* in3,
gdv_int32 in3_len, bool in3_validity, const char* in4, gdv_int32 in4_len,
bool in4_validity, const char* in5, gdv_int32 in5_len, bool in5_validity,
gdv_int32* out_len) {
if (!in1_validity) {
in1_len = 0;
}
if (!in2_validity) {
in2_len = 0;
}
if (!in3_validity) {
in3_len = 0;
}
if (!in4_validity) {
in4_len = 0;
}
if (!in5_validity) {
in5_len = 0;
}
return concatOperator_utf8_utf8_utf8_utf8_utf8(context, in1, in1_len, in2, in2_len, in3,
in3_len, in4, in4_len, in5, in5_len,
out_len);
}
FORCE_INLINE
const char* concatOperator_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, const char* in2,
gdv_int32 in2_len, const char* in3, gdv_int32 in3_len, const char* in4,
gdv_int32 in4_len, const char* in5, gdv_int32 in5_len, gdv_int32* out_len) {
*out_len = in1_len + in2_len + in3_len + in4_len + in5_len;
if (*out_len <= 0) {
*out_len = 0;
return "";
}
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, in1, in1_len);
memcpy(ret + in1_len, in2, in2_len);
memcpy(ret + in1_len + in2_len, in3, in3_len);
memcpy(ret + in1_len + in2_len + in3_len, in4, in4_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len, in5, in5_len);
return ret;
}
FORCE_INLINE
const char* concat_utf8_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, bool in1_validity,
const char* in2, gdv_int32 in2_len, bool in2_validity, const char* in3,
gdv_int32 in3_len, bool in3_validity, const char* in4, gdv_int32 in4_len,
bool in4_validity, const char* in5, gdv_int32 in5_len, bool in5_validity,
const char* in6, gdv_int32 in6_len, bool in6_validity, gdv_int32* out_len) {
if (!in1_validity) {
in1_len = 0;
}
if (!in2_validity) {
in2_len = 0;
}
if (!in3_validity) {
in3_len = 0;
}
if (!in4_validity) {
in4_len = 0;
}
if (!in5_validity) {
in5_len = 0;
}
if (!in6_validity) {
in6_len = 0;
}
return concatOperator_utf8_utf8_utf8_utf8_utf8_utf8(context, in1, in1_len, in2, in2_len,
in3, in3_len, in4, in4_len, in5,
in5_len, in6, in6_len, out_len);
}
FORCE_INLINE
const char* concatOperator_utf8_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, const char* in2,
gdv_int32 in2_len, const char* in3, gdv_int32 in3_len, const char* in4,
gdv_int32 in4_len, const char* in5, gdv_int32 in5_len, const char* in6,
gdv_int32 in6_len, gdv_int32* out_len) {
*out_len = in1_len + in2_len + in3_len + in4_len + in5_len + in6_len;
if (*out_len <= 0) {
*out_len = 0;
return "";
}
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, in1, in1_len);
memcpy(ret + in1_len, in2, in2_len);
memcpy(ret + in1_len + in2_len, in3, in3_len);
memcpy(ret + in1_len + in2_len + in3_len, in4, in4_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len, in5, in5_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len, in6, in6_len);
return ret;
}
FORCE_INLINE
const char* concat_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, bool in1_validity,
const char* in2, gdv_int32 in2_len, bool in2_validity, const char* in3,
gdv_int32 in3_len, bool in3_validity, const char* in4, gdv_int32 in4_len,
bool in4_validity, const char* in5, gdv_int32 in5_len, bool in5_validity,
const char* in6, gdv_int32 in6_len, bool in6_validity, const char* in7,
gdv_int32 in7_len, bool in7_validity, gdv_int32* out_len) {
if (!in1_validity) {
in1_len = 0;
}
if (!in2_validity) {
in2_len = 0;
}
if (!in3_validity) {
in3_len = 0;
}
if (!in4_validity) {
in4_len = 0;
}
if (!in5_validity) {
in5_len = 0;
}
if (!in6_validity) {
in6_len = 0;
}
if (!in7_validity) {
in7_len = 0;
}
return concatOperator_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
context, in1, in1_len, in2, in2_len, in3, in3_len, in4, in4_len, in5, in5_len, in6,
in6_len, in7, in7_len, out_len);
}
FORCE_INLINE
const char* concatOperator_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, const char* in2,
gdv_int32 in2_len, const char* in3, gdv_int32 in3_len, const char* in4,
gdv_int32 in4_len, const char* in5, gdv_int32 in5_len, const char* in6,
gdv_int32 in6_len, const char* in7, gdv_int32 in7_len, gdv_int32* out_len) {
*out_len = in1_len + in2_len + in3_len + in4_len + in5_len + in6_len + in7_len;
if (*out_len <= 0) {
*out_len = 0;
return "";
}
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, in1, in1_len);
memcpy(ret + in1_len, in2, in2_len);
memcpy(ret + in1_len + in2_len, in3, in3_len);
memcpy(ret + in1_len + in2_len + in3_len, in4, in4_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len, in5, in5_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len, in6, in6_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len + in6_len, in7, in7_len);
return ret;
}
FORCE_INLINE
const char* concat_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, bool in1_validity,
const char* in2, gdv_int32 in2_len, bool in2_validity, const char* in3,
gdv_int32 in3_len, bool in3_validity, const char* in4, gdv_int32 in4_len,
bool in4_validity, const char* in5, gdv_int32 in5_len, bool in5_validity,
const char* in6, gdv_int32 in6_len, bool in6_validity, const char* in7,
gdv_int32 in7_len, bool in7_validity, const char* in8, gdv_int32 in8_len,
bool in8_validity, gdv_int32* out_len) {
if (!in1_validity) {
in1_len = 0;
}
if (!in2_validity) {
in2_len = 0;
}
if (!in3_validity) {
in3_len = 0;
}
if (!in4_validity) {
in4_len = 0;
}
if (!in5_validity) {
in5_len = 0;
}
if (!in6_validity) {
in6_len = 0;
}
if (!in7_validity) {
in7_len = 0;
}
if (!in8_validity) {
in8_len = 0;
}
return concatOperator_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
context, in1, in1_len, in2, in2_len, in3, in3_len, in4, in4_len, in5, in5_len, in6,
in6_len, in7, in7_len, in8, in8_len, out_len);
}
FORCE_INLINE
const char* concatOperator_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, const char* in2,
gdv_int32 in2_len, const char* in3, gdv_int32 in3_len, const char* in4,
gdv_int32 in4_len, const char* in5, gdv_int32 in5_len, const char* in6,
gdv_int32 in6_len, const char* in7, gdv_int32 in7_len, const char* in8,
gdv_int32 in8_len, gdv_int32* out_len) {
*out_len =
in1_len + in2_len + in3_len + in4_len + in5_len + in6_len + in7_len + in8_len;
if (*out_len <= 0) {
*out_len = 0;
return "";
}
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, in1, in1_len);
memcpy(ret + in1_len, in2, in2_len);
memcpy(ret + in1_len + in2_len, in3, in3_len);
memcpy(ret + in1_len + in2_len + in3_len, in4, in4_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len, in5, in5_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len, in6, in6_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len + in6_len, in7, in7_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len + in6_len + in7_len, in8,
in8_len);
return ret;
}
FORCE_INLINE
const char* concat_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, bool in1_validity,
const char* in2, gdv_int32 in2_len, bool in2_validity, const char* in3,
gdv_int32 in3_len, bool in3_validity, const char* in4, gdv_int32 in4_len,
bool in4_validity, const char* in5, gdv_int32 in5_len, bool in5_validity,
const char* in6, gdv_int32 in6_len, bool in6_validity, const char* in7,
gdv_int32 in7_len, bool in7_validity, const char* in8, gdv_int32 in8_len,
bool in8_validity, const char* in9, gdv_int32 in9_len, bool in9_validity,
gdv_int32* out_len) {
if (!in1_validity) {
in1_len = 0;
}
if (!in2_validity) {
in2_len = 0;
}
if (!in3_validity) {
in3_len = 0;
}
if (!in4_validity) {
in4_len = 0;
}
if (!in5_validity) {
in5_len = 0;
}
if (!in6_validity) {
in6_len = 0;
}
if (!in7_validity) {
in7_len = 0;
}
if (!in8_validity) {
in8_len = 0;
}
if (!in9_validity) {
in9_len = 0;
}
return concatOperator_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
context, in1, in1_len, in2, in2_len, in3, in3_len, in4, in4_len, in5, in5_len, in6,
in6_len, in7, in7_len, in8, in8_len, in9, in9_len, out_len);
}
FORCE_INLINE
const char* concatOperator_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, const char* in2,
gdv_int32 in2_len, const char* in3, gdv_int32 in3_len, const char* in4,
gdv_int32 in4_len, const char* in5, gdv_int32 in5_len, const char* in6,
gdv_int32 in6_len, const char* in7, gdv_int32 in7_len, const char* in8,
gdv_int32 in8_len, const char* in9, gdv_int32 in9_len, gdv_int32* out_len) {
*out_len = in1_len + in2_len + in3_len + in4_len + in5_len + in6_len + in7_len +
in8_len + in9_len;
if (*out_len <= 0) {
*out_len = 0;
return "";
}
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, in1, in1_len);
memcpy(ret + in1_len, in2, in2_len);
memcpy(ret + in1_len + in2_len, in3, in3_len);
memcpy(ret + in1_len + in2_len + in3_len, in4, in4_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len, in5, in5_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len, in6, in6_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len + in6_len, in7, in7_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len + in6_len + in7_len, in8,
in8_len);
memcpy(
ret + in1_len + in2_len + in3_len + in4_len + in5_len + in6_len + in7_len + in8_len,
in9, in9_len);
return ret;
}
FORCE_INLINE
const char* concat_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, bool in1_validity,
const char* in2, gdv_int32 in2_len, bool in2_validity, const char* in3,
gdv_int32 in3_len, bool in3_validity, const char* in4, gdv_int32 in4_len,
bool in4_validity, const char* in5, gdv_int32 in5_len, bool in5_validity,
const char* in6, gdv_int32 in6_len, bool in6_validity, const char* in7,
gdv_int32 in7_len, bool in7_validity, const char* in8, gdv_int32 in8_len,
bool in8_validity, const char* in9, gdv_int32 in9_len, bool in9_validity,
const char* in10, gdv_int32 in10_len, bool in10_validity, gdv_int32* out_len) {
if (!in1_validity) {
in1_len = 0;
}
if (!in2_validity) {
in2_len = 0;
}
if (!in3_validity) {
in3_len = 0;
}
if (!in4_validity) {
in4_len = 0;
}
if (!in5_validity) {
in5_len = 0;
}
if (!in6_validity) {
in6_len = 0;
}
if (!in7_validity) {
in7_len = 0;
}
if (!in8_validity) {
in8_len = 0;
}
if (!in9_validity) {
in9_len = 0;
}
if (!in10_validity) {
in10_len = 0;
}
return concatOperator_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
context, in1, in1_len, in2, in2_len, in3, in3_len, in4, in4_len, in5, in5_len, in6,
in6_len, in7, in7_len, in8, in8_len, in9, in9_len, in10, in10_len, out_len);
}
FORCE_INLINE
const char* concatOperator_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8_utf8(
gdv_int64 context, const char* in1, gdv_int32 in1_len, const char* in2,
gdv_int32 in2_len, const char* in3, gdv_int32 in3_len, const char* in4,
gdv_int32 in4_len, const char* in5, gdv_int32 in5_len, const char* in6,
gdv_int32 in6_len, const char* in7, gdv_int32 in7_len, const char* in8,
gdv_int32 in8_len, const char* in9, gdv_int32 in9_len, const char* in10,
gdv_int32 in10_len, gdv_int32* out_len) {
*out_len = in1_len + in2_len + in3_len + in4_len + in5_len + in6_len + in7_len +
in8_len + in9_len + in10_len;
if (*out_len <= 0) {
*out_len = 0;
return "";
}
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, in1, in1_len);
memcpy(ret + in1_len, in2, in2_len);
memcpy(ret + in1_len + in2_len, in3, in3_len);
memcpy(ret + in1_len + in2_len + in3_len, in4, in4_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len, in5, in5_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len, in6, in6_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len + in6_len, in7, in7_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len + in6_len + in7_len, in8,
in8_len);
memcpy(
ret + in1_len + in2_len + in3_len + in4_len + in5_len + in6_len + in7_len + in8_len,
in9, in9_len);
memcpy(ret + in1_len + in2_len + in3_len + in4_len + in5_len + in6_len + in7_len +
in8_len + in9_len,
in10, in10_len);
return ret;
}
// Returns the numeric value of the first character of str.
GANDIVA_EXPORT
gdv_int32 ascii_utf8(const char* data, gdv_int32 data_len) {
if (data_len == 0) {
return 0;
}
return static_cast<gdv_int32>(data[0]);
}
FORCE_INLINE
const char* convert_fromUTF8_binary(gdv_int64 context, const char* bin_in, gdv_int32 len,
gdv_int32* out_len) {
*out_len = len;
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, bin_in, *out_len);
return ret;
}
FORCE_INLINE
const char* convert_replace_invalid_fromUTF8_binary(int64_t context, const char* text_in,
int32_t text_len,
const char* char_to_replace,
int32_t char_to_replace_len,
int32_t* out_len) {
if (char_to_replace_len > 1) {
gdv_fn_context_set_error_msg(context, "Replacement of multiple bytes not supported");
*out_len = 0;
return "";
}
// actually the convert_replace function replaces invalid chars with an ASCII
// character so the output length will be the same as the input length
*out_len = text_len;
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
int32_t valid_bytes_to_cpy = 0;
int32_t out_byte_counter = 0;
int32_t in_byte_counter = 0;
int32_t char_len;
// scan the base text from left to right and increment the start pointer till
// looking for invalid chars to substitute
for (int text_index = 0; text_index < text_len; text_index += char_len) {
char_len = utf8_char_length(text_in[text_index]);
// only memory copy the bytes when detect invalid char
if (char_len == 0 || text_index + char_len > text_len ||
!validate_utf8_following_bytes(text_in, char_len, text_index)) {
// define char_len = 1 to increase text_index by 1 (as ASCII char fits in 1 byte)
char_len = 1;
// first copy the valid bytes until now and then replace the invalid character
memcpy(ret + out_byte_counter, text_in + in_byte_counter, valid_bytes_to_cpy);
// if the replacement char is empty, the invalid char should be ignored
if (char_to_replace_len == 0) {
out_byte_counter += valid_bytes_to_cpy;
} else {
ret[out_byte_counter + valid_bytes_to_cpy] = char_to_replace[0];
out_byte_counter += valid_bytes_to_cpy + char_len;
}
in_byte_counter += valid_bytes_to_cpy + char_len;
valid_bytes_to_cpy = 0;
continue;
}
valid_bytes_to_cpy += char_len;
}
// if invalid chars were not found, return the original string
if (out_byte_counter == 0) return text_in;
// if there are still valid bytes to copy, do it
if (valid_bytes_to_cpy != 0) {
memcpy(ret + out_byte_counter, text_in + in_byte_counter, valid_bytes_to_cpy);
}
// the out length will be the out bytes copied + the missing end bytes copied
*out_len = valid_bytes_to_cpy + out_byte_counter;
return ret;
}
// The function reverse a char array in-place
static inline void reverse_char_buf(char* buf, int32_t len) {
char temp;
for (int32_t i = 0; i < len / 2; i++) {
int32_t pos_swp = len - (1 + i);
temp = buf[pos_swp];
buf[pos_swp] = buf[i];
buf[i] = temp;
}
}
// Converts a double variable to binary
FORCE_INLINE
const char* convert_toDOUBLE(int64_t context, double value, int32_t* out_len) {
*out_len = sizeof(value);
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context,
"Could not allocate memory for the output string");
*out_len = 0;
return "";
}
memcpy(ret, &value, *out_len);
return ret;
}
FORCE_INLINE
const char* convert_toDOUBLE_be(int64_t context, double value, int32_t* out_len) {
// The function behaves like convert_toDOUBLE, but always return the result
// in big endian format
char* ret = const_cast<char*>(convert_toDOUBLE(context, value, out_len));
#if ARROW_LITTLE_ENDIAN
reverse_char_buf(ret, *out_len);
#endif
return ret;
}
// Converts a float variable to binary
FORCE_INLINE
const char* convert_toFLOAT(int64_t context, float value, int32_t* out_len) {
*out_len = sizeof(value);
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context,
"Could not allocate memory for the output string");
*out_len = 0;
return "";
}
memcpy(ret, &value, *out_len);
return ret;
}
FORCE_INLINE
const char* convert_toFLOAT_be(int64_t context, float value, int32_t* out_len) {
// The function behaves like convert_toFLOAT, but always return the result
// in big endian format
char* ret = const_cast<char*>(convert_toFLOAT(context, value, out_len));
#if ARROW_LITTLE_ENDIAN
reverse_char_buf(ret, *out_len);
#endif
return ret;
}
// Converts a bigint(int with 64 bits) variable to binary
FORCE_INLINE
const char* convert_toBIGINT(int64_t context, int64_t value, int32_t* out_len) {
*out_len = sizeof(value);
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context,
"Could not allocate memory for the output string");
*out_len = 0;
return "";
}
memcpy(ret, &value, *out_len);
return ret;
}
FORCE_INLINE
const char* convert_toBIGINT_be(int64_t context, int64_t value, int32_t* out_len) {
// The function behaves like convert_toBIGINT, but always return the result
// in big endian format
char* ret = const_cast<char*>(convert_toBIGINT(context, value, out_len));
#if ARROW_LITTLE_ENDIAN
reverse_char_buf(ret, *out_len);
#endif
return ret;
}
// Converts an integer(with 32 bits) variable to binary
FORCE_INLINE
const char* convert_toINT(int64_t context, int32_t value, int32_t* out_len) {
*out_len = sizeof(value);
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context,
"Could not allocate memory for the output string");
*out_len = 0;
return "";
}
memcpy(ret, &value, *out_len);
return ret;
}
FORCE_INLINE
const char* convert_toINT_be(int64_t context, int32_t value, int32_t* out_len) {
// The function behaves like convert_toINT, but always return the result
// in big endian format
char* ret = const_cast<char*>(convert_toINT(context, value, out_len));
#if ARROW_LITTLE_ENDIAN
reverse_char_buf(ret, *out_len);
#endif
return ret;
}
// Converts a boolean variable to binary
FORCE_INLINE
const char* convert_toBOOLEAN(int64_t context, bool value, int32_t* out_len) {
*out_len = sizeof(value);
char* ret = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context,
"Could not allocate memory for the output string");
*out_len = 0;
return "";
}
memcpy(ret, &value, *out_len);
return ret;
}
// Converts a time variable to binary
FORCE_INLINE
const char* convert_toTIME_EPOCH(int64_t context, int32_t value, int32_t* out_len) {
return convert_toINT(context, value, out_len);
}
FORCE_INLINE
const char* convert_toTIME_EPOCH_be(int64_t context, int32_t value, int32_t* out_len) {
// The function behaves as convert_toTIME_EPOCH, but
// returns the bytes in big endian format
return convert_toINT_be(context, value, out_len);
}
// Converts a timestamp variable to binary
FORCE_INLINE
const char* convert_toTIMESTAMP_EPOCH(int64_t context, int64_t timestamp,
int32_t* out_len) {
return convert_toBIGINT(context, timestamp, out_len);
}
FORCE_INLINE
const char* convert_toTIMESTAMP_EPOCH_be(int64_t context, int64_t timestamp,
int32_t* out_len) {
// The function behaves as convert_toTIMESTAMP_EPOCH, but
// returns the bytes in big endian format
return convert_toBIGINT_be(context, timestamp, out_len);
}
// Converts a date variable to binary
FORCE_INLINE
const char* convert_toDATE_EPOCH(int64_t context, int64_t date, int32_t* out_len) {
return convert_toBIGINT(context, date, out_len);
}
FORCE_INLINE
const char* convert_toDATE_EPOCH_be(int64_t context, int64_t date, int32_t* out_len) {
// The function behaves as convert_toDATE_EPOCH, but
// returns the bytes in big endian format
return convert_toBIGINT_be(context, date, out_len);
}
// Converts a string variable to binary
FORCE_INLINE
const char* convert_toUTF8(int64_t context, const char* value, int32_t value_len,
int32_t* out_len) {
*out_len = value_len;
return value;
}
// Search for a string within another string
FORCE_INLINE
gdv_int32 locate_utf8_utf8(gdv_int64 context, const char* sub_str, gdv_int32 sub_str_len,
const char* str, gdv_int32 str_len) {
return locate_utf8_utf8_int32(context, sub_str, sub_str_len, str, str_len, 1);
}
// Search for a string within another string starting at position start-pos (1-indexed)
FORCE_INLINE
gdv_int32 locate_utf8_utf8_int32(gdv_int64 context, const char* sub_str,
gdv_int32 sub_str_len, const char* str,
gdv_int32 str_len, gdv_int32 start_pos) {
if (start_pos < 1) {
gdv_fn_context_set_error_msg(context, "Start position must be greater than 0");
return 0;
}
if (str_len == 0 || sub_str_len == 0) {
return 0;
}
gdv_int32 byte_pos = utf8_byte_pos(context, str, str_len, start_pos - 1);
if (byte_pos < 0 || byte_pos >= str_len) {
return 0;
}
for (gdv_int32 i = byte_pos; i <= str_len - sub_str_len; ++i) {
if (memcmp(str + i, sub_str, sub_str_len) == 0) {
return utf8_length(context, str, i) + 1;
}
}
return 0;
}
FORCE_INLINE
const char* replace_with_max_len_utf8_utf8_utf8(gdv_int64 context, const char* text,
gdv_int32 text_len, const char* from_str,
gdv_int32 from_str_len,
const char* to_str, gdv_int32 to_str_len,
gdv_int32 max_length,
gdv_int32* out_len) {
// if from_str is empty or its length exceeds that of original string,
// return the original string
if (from_str_len <= 0 || from_str_len > text_len) {
*out_len = text_len;
return text;
}
bool found = false;
gdv_int32 text_index = 0;
char* out;
gdv_int32 out_index = 0;
gdv_int32 last_match_index =
0; // defer copying string from last_match_index till next match is found
for (; text_index <= text_len - from_str_len;) {
if (memcmp(text + text_index, from_str, from_str_len) == 0) {
if (out_index + text_index - last_match_index + to_str_len > max_length) {
gdv_fn_context_set_error_msg(context, "Buffer overflow for output string");
*out_len = 0;
return "";
}
if (!found) {
// found match for first time
out = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, max_length));
if (out == nullptr) {
gdv_fn_context_set_error_msg(context,
"Could not allocate memory for output string");
*out_len = 0;
return "";
}
found = true;
}
// first copy the part deferred till now
memcpy(out + out_index, text + last_match_index, (text_index - last_match_index));
out_index += text_index - last_match_index;
// then copy the target string
memcpy(out + out_index, to_str, to_str_len);
out_index += to_str_len;
text_index += from_str_len;
last_match_index = text_index;
} else {
text_index++;
}
}
if (!found) {
*out_len = text_len;
return text;
}
if (out_index + text_len - last_match_index > max_length) {
gdv_fn_context_set_error_msg(context, "Buffer overflow for output string");
*out_len = 0;
return "";
}
memcpy(out + out_index, text + last_match_index, text_len - last_match_index);
out_index += text_len - last_match_index;
*out_len = out_index;
return out;
}
FORCE_INLINE
const char* replace_utf8_utf8_utf8(gdv_int64 context, const char* text,
gdv_int32 text_len, const char* from_str,
gdv_int32 from_str_len, const char* to_str,
gdv_int32 to_str_len, gdv_int32* out_len) {
return replace_with_max_len_utf8_utf8_utf8(context, text, text_len, from_str,
from_str_len, to_str, to_str_len, 65535,
out_len);
}
FORCE_INLINE
const char* lpad_utf8_int32_utf8(gdv_int64 context, const char* text, gdv_int32 text_len,
gdv_int32 return_length, const char* fill_text,
gdv_int32 fill_text_len, gdv_int32* out_len) {
// if the text length or the defined return length (number of characters to return)
// is <=0, then return an empty string.
if (text_len == 0 || return_length <= 0) {
*out_len = 0;
return "";
}
// count the number of utf8 characters on text, ignoring invalid bytes
int text_char_count = utf8_length_ignore_invalid(text, text_len);
if (return_length == text_char_count ||
(return_length > text_char_count && fill_text_len == 0)) {
// case where the return length is same as the text's length, or if it need to
// fill into text but "fill_text" is empty, then return text directly.
*out_len = text_len;
return text;
} else if (return_length < text_char_count) {
// case where it truncates the result on return length.
*out_len = utf8_byte_pos(context, text, text_len, return_length);
return text;
} else {
// case (return_length > text_char_count)
// case where it needs to copy "fill_text" on the string left. The total number
// of chars to copy is given by (return_length - text_char_count)
char* ret =
reinterpret_cast<gdv_binary>(gdv_fn_context_arena_malloc(context, return_length));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context,
"Could not allocate memory for output string");
*out_len = 0;
return "";
}
// try to fulfill the return string with the "fill_text" continuously
int32_t copied_chars_count = 0;
int32_t copied_chars_position = 0;
while (copied_chars_count < return_length - text_char_count) {
int32_t char_len;
int32_t fill_index;
// for each char, evaluate its length to consider it when mem copying
for (fill_index = 0; fill_index < fill_text_len; fill_index += char_len) {
if (copied_chars_count >= return_length - text_char_count) {
break;
}
char_len = utf8_char_length(fill_text[fill_index]);
// ignore invalid char on the fill text, considering it as size 1
if (char_len == 0) char_len += 1;
copied_chars_count++;
}
memcpy(ret + copied_chars_position, fill_text, fill_index);
copied_chars_position += fill_index;
}
// after fulfilling the text, copy the main string
memcpy(ret + copied_chars_position, text, text_len);
*out_len = copied_chars_position + text_len;
return ret;
}
}
FORCE_INLINE
const char* rpad_utf8_int32_utf8(gdv_int64 context, const char* text, gdv_int32 text_len,
gdv_int32 return_length, const char* fill_text,
gdv_int32 fill_text_len, gdv_int32* out_len) {
// if the text length or the defined return length (number of characters to return)
// is <=0, then return an empty string.
if (text_len == 0 || return_length <= 0) {
*out_len = 0;
return "";
}
// count the number of utf8 characters on text, ignoring invalid bytes
int text_char_count = utf8_length_ignore_invalid(text, text_len);
if (return_length == text_char_count ||
(return_length > text_char_count && fill_text_len == 0)) {
// case where the return length is same as the text's length, or if it need to
// fill into text but "fill_text" is empty, then return text directly.
*out_len = text_len;
return text;
} else if (return_length < text_char_count) {
// case where it truncates the result on return length.
*out_len = utf8_byte_pos(context, text, text_len, return_length);
return text;
} else {
// case (return_length > text_char_count)
// case where it needs to copy "fill_text" on the string right
char* ret =
reinterpret_cast<gdv_binary>(gdv_fn_context_arena_malloc(context, return_length));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context,
"Could not allocate memory for output string");
*out_len = 0;
return "";
}
// fulfill the initial text copying the main input string
memcpy(ret, text, text_len);
// try to fulfill the return string with the "fill_text" continuously
int32_t copied_chars_count = 0;
int32_t copied_chars_position = 0;
while (text_char_count + copied_chars_count < return_length) {
int32_t char_len;
int32_t fill_length;
// for each char, evaluate its length to consider it when mem copying
for (fill_length = 0; fill_length < fill_text_len; fill_length += char_len) {
if (text_char_count + copied_chars_count >= return_length) {
break;
}
char_len = utf8_char_length(fill_text[fill_length]);
// ignore invalid char on the fill text, considering it as size 1
if (char_len == 0) char_len += 1;
copied_chars_count++;
}
memcpy(ret + text_len + copied_chars_position, fill_text, fill_length);
copied_chars_position += fill_length;
}
*out_len = copied_chars_position + text_len;
return ret;
}
}
FORCE_INLINE
const char* lpad_utf8_int32(gdv_int64 context, const char* text, gdv_int32 text_len,
gdv_int32 return_length, gdv_int32* out_len) {
return lpad_utf8_int32_utf8(context, text, text_len, return_length, " ", 1, out_len);
}
FORCE_INLINE
const char* rpad_utf8_int32(gdv_int64 context, const char* text, gdv_int32 text_len,
gdv_int32 return_length, gdv_int32* out_len) {
return rpad_utf8_int32_utf8(context, text, text_len, return_length, " ", 1, out_len);
}
FORCE_INLINE
const char* split_part(gdv_int64 context, const char* text, gdv_int32 text_len,
const char* delimiter, gdv_int32 delim_len, gdv_int32 index,
gdv_int32* out_len) {
*out_len = 0;
if (index < 1) {
char error_message[100];
snprintf(error_message, sizeof(error_message),
"Index in split_part must be positive, value provided was %d", index);
gdv_fn_context_set_error_msg(context, error_message);
return "";
}
if (delim_len == 0 || text_len == 0) {
// output will just be text if no delimiter is provided
*out_len = text_len;
return text;
}
int i = 0, match_no = 1;
while (i < text_len) {
// find the position where delimiter matched for the first time
int match_pos = match_string(text, text_len, i, delimiter, delim_len);
if (match_pos == -1 && match_no != index) {
// reached the end without finding a match.
return "";
} else {
// Found a match. If the match number is index then return this match
if (match_no == index) {
int end_pos = match_pos - delim_len;
if (match_pos == -1) {
// end position should be last position of the string as we have the last
// delimiter
end_pos = text_len;
}
*out_len = end_pos - i;
char* out_str =
reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, *out_len));
if (out_str == nullptr) {
gdv_fn_context_set_error_msg(context,
"Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(out_str, text + i, *out_len);
return out_str;
} else {
i = match_pos;
match_no++;
}
}
}
return "";
}
// Returns the x leftmost characters of a given string. Cases:
// LEFT("TestString", 10) => "TestString"
// LEFT("TestString", 3) => "Tes"
// LEFT("TestString", -3) => "TestStr"
FORCE_INLINE
const char* left_utf8_int32(gdv_int64 context, const char* text, gdv_int32 text_len,
gdv_int32 number, gdv_int32* out_len) {
// returns the 'number' left most characters of a given text
if (text_len == 0 || number == 0) {
*out_len = 0;
return "";
}
// iterate over the utf8 string validating each character
int char_len;
int char_count = 0;
int byte_index = 0;
for (int i = 0; i < text_len; i += char_len) {
char_len = utf8_char_length(text[i]);
if (char_len == 0 || i + char_len > text_len) { // invalid byte or incomplete glyph
set_error_for_invalid_utf(context, text[i]);
*out_len = 0;
return "";
}
for (int j = 1; j < char_len; ++j) {
if ((text[i + j] & 0xC0) != 0x80) { // bytes following head-byte of glyph
set_error_for_invalid_utf(context, text[i + j]);
*out_len = 0;
return "";
}
}
byte_index += char_len;
++char_count;
// Define the rules to stop the iteration over the string
// case where left('abc', 5) -> 'abc'
if (number > 0 && char_count == number) break;
// case where left('abc', -5) ==> ''
if (number < 0 && char_count == number + text_len) break;
}
*out_len = byte_index;
return text;
}
// Returns the x rightmost characters of a given string. Cases:
// RIGHT("TestString", 10) => "TestString"
// RIGHT("TestString", 3) => "ing"
// RIGHT("TestString", -3) => "tString"
FORCE_INLINE
const char* right_utf8_int32(gdv_int64 context, const char* text, gdv_int32 text_len,
gdv_int32 number, gdv_int32* out_len) {
// returns the 'number' left most characters of a given text
if (text_len == 0 || number == 0) {
*out_len = 0;
return "";
}
// initially counts the number of utf8 characters in the defined text
int32_t char_count = utf8_length(context, text, text_len);
// char_count is zero if input has invalid utf8 char
if (char_count == 0) {
*out_len = 0;
return "";
}
int32_t start_char_pos; // the char result start position (inclusive)
int32_t end_char_len; // the char result end position (inclusive)
if (number > 0) {
// case where right('abc', 5) ==> 'abc' start_char_pos=1.
start_char_pos = (char_count > number) ? char_count - number : 0;
end_char_len = char_count - start_char_pos;
} else {
start_char_pos = number * -1;
end_char_len = char_count - start_char_pos;
}
// calculate the start byte position and the output length
int32_t start_byte_pos = utf8_byte_pos(context, text, text_len, start_char_pos);
*out_len = utf8_byte_pos(context, text, text_len, end_char_len);
// try to allocate memory for the response
char* ret =
reinterpret_cast<gdv_binary>(gdv_fn_context_arena_malloc(context, *out_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
memcpy(ret, text + start_byte_pos, *out_len);
return ret;
}
FORCE_INLINE
const char* binary_string(gdv_int64 context, const char* text, gdv_int32 text_len,
gdv_int32* out_len) {
gdv_binary ret =
reinterpret_cast<gdv_binary>(gdv_fn_context_arena_malloc(context, text_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
if (text_len == 0) {
*out_len = 0;
return "";
}
// converting hex encoded string to normal string
int j = 0;
for (int i = 0; i < text_len; i++, j++) {
if (text[i] == '\\' && i + 3 < text_len &&
(text[i + 1] == 'x' || text[i + 1] == 'X')) {
char hd1 = text[i + 2];
char hd2 = text[i + 3];
if (isxdigit(hd1) && isxdigit(hd2)) {
// [a-fA-F0-9]
ret[j] = to_binary_from_hex(hd1) * 16 + to_binary_from_hex(hd2);
i += 3;
} else {
ret[j] = text[i];
}
} else {
ret[j] = text[i];
}
}
*out_len = j;
return ret;
}
// Produces the binary representation of a string y characters long derived by starting
// at offset 'x' and considering the defined length 'y'. Notice that the offset index
// may be a negative number (starting from the end of the string), or a positive number
// starting on index 1. Cases:
// BYTE_SUBSTR("TestString", 1, 10) => "TestString"
// BYTE_SUBSTR("TestString", 5, 10) => "String"
// BYTE_SUBSTR("TestString", -6, 10) => "String"
// BYTE_SUBSTR("TestString", -600, 10) => "TestString"
FORCE_INLINE
const char* byte_substr_binary_int32_int32(gdv_int64 context, const char* text,
gdv_int32 text_len, gdv_int32 offset,
gdv_int32 length, gdv_int32* out_len) {
// the first offset position for a string is 1, so not consider offset == 0
// also, the length should be always a positive number
if (text_len == 0 || offset == 0 || length <= 0) {
*out_len = 0;
return "";
}
char* ret =
reinterpret_cast<gdv_binary>(gdv_fn_context_arena_malloc(context, text_len));
if (ret == nullptr) {
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
*out_len = 0;
return "";
}
int32_t startPos = 0;
if (offset >= 0) {
startPos = offset - 1;
} else if (text_len + offset >= 0) {
startPos = text_len + offset;
}
// calculate end position from length and truncate to upper value bounds
if (startPos + length > text_len) {
*out_len = text_len - startPos;
} else {
*out_len = length;
}
memcpy(ret, text + startPos, *out_len);
return ret;
}
} // extern "C"
|
; A081406: a(n) = (n+1)*a(n-3), a(0)=a(1)=a(2)=1 for n>1.
; 1,1,1,4,5,6,28,40,54,280,440,648,3640,6160,9720,58240,104720,174960,1106560,2094400,3674160,24344320,48171200,88179840,608608000,1252451200,2380855680,17041024000,36321084800,71425670400,528271744000,1162274713600,2357047123200,17961239296000,40679614976000,84853696435200,664565853952000,1545825369088000,3309294160972800
add $0,1
mov $2,1
lpb $0
mov $3,2
add $3,$2
mul $2,$0
trn $0,3
mul $3,5
mov $1,$3
lpe
sub $1,15
div $1,5
add $1,1
|
; A202391: Indices of the smallest of four consecutive triangular numbers summing up to a square.
; 5,39,237,1391,8117,47319,275805,1607519,9369317,54608391,318281037,1855077839,10812186005,63018038199,367296043197,2140758220991,12477253282757,72722761475559,423859315570605,2470433131948079
mul $0,2
mov $1,5
mov $4,4
lpb $0,1
sub $0,1
mov $2,$1
add $3,$4
add $3,$1
add $1,2
sub $1,$2
add $3,4
add $1,$3
mov $4,$2
lpe
|
#include "../../include/graphics/CTextureAtlas.h"
#include "../../include/core/IGraphicsContext.h"
#include "../../include/core/IResourceManager.h"
#include "../../include/core/CBaseFileSystem.h"
#include "../../include/utils/Utils.h"
#include "../../include/graphics/CBaseTexture2D.h"
#include "../../include/graphics/IAtlasSubTexture.h"
#include "../../include/core/IFile.h"
#include "../../include/platform/CYAMLFile.h"
#include "stringUtils.hpp"
#include <cassert>
#include <algorithm>
#include <stack>
#include <cmath>
namespace TDEngine2
{
CTextureAtlas::TTextureAtlasEntry::TTextureAtlasEntry(const std::string& name, const TRectI32& rect, const CTextureAtlas::TTextureAtlasEntry::TRawTextureData& texture):
mName(name),
mRect(rect),
mIsRawData(true)
{
mData.mRawTexture = texture;
}
CTextureAtlas::TTextureAtlasEntry::TTextureAtlasEntry(const std::string& name, const TRectI32& rect, ITexture2D* pTexture) :
mName(name),
mRect(rect),
mIsRawData(false)
{
mData.mpTexture = pTexture;
}
CTextureAtlas::CTextureAtlas() :
CBaseResource(), mTextureResourceHandle(TResourceId::Invalid)
{
}
E_RESULT_CODE CTextureAtlas::Init(IResourceManager* pResourceManager, IGraphicsContext* pGraphicsContext, const std::string& name)
{
E_RESULT_CODE result = _init(pResourceManager, name);
if (result != RC_OK)
{
return result;
}
if (!pGraphicsContext)
{
return RC_INVALID_ARGS;
}
mpGraphicsContext = pGraphicsContext;
mIsInitialized = true;
return RC_OK;
}
E_RESULT_CODE CTextureAtlas::Init(IResourceManager* pResourceManager, IGraphicsContext* pGraphicsContext, const std::string& name,
const TTexture2DParameters& params)
{
E_RESULT_CODE result = _init(pResourceManager, name);
if (result != RC_OK)
{
return result;
}
if (!pGraphicsContext || !params.mHeight || !params.mWidth)
{
return RC_INVALID_ARGS;
}
mpGraphicsContext = pGraphicsContext;
/// \note create a texture using the resource manager
if (TResourceId::Invalid == (mTextureResourceHandle = pResourceManager->Create<ITexture2D>(name + "_Tex", params)))
{
return RC_FAIL;
}
mWidth = params.mWidth;
mHeight = params.mHeight;
mIsInitialized = true;
return RC_OK;
}
E_RESULT_CODE CTextureAtlas::Reset()
{
mPendingData.clear();
mAtlasEntities.clear();
/// \todo
return RC_OK;
}
E_RESULT_CODE CTextureAtlas::AddRawTexture(const std::string& name, U32 width, U32 height, E_FORMAT_TYPE format, const U8* pData)
{
if (!mIsInitialized)
{
return RC_FAIL;
}
if (name.empty() || (format == FT_UNKNOWN) || !pData)
{
return RC_INVALID_ARGS;
}
/// \note check whether the texture's data is already within the atlas or not
if (std::find_if(mPendingData.cbegin(), mPendingData.cend(), [&name](const TTextureAtlasEntry& entry)
{
return entry.mName == name;
}) != mPendingData.cend())
{
return RC_FAIL;
}
/// \note add a new entry
TRectI32 textureRect { 0, 0, static_cast<I32>(width), static_cast<I32>(height) };
TTextureAtlasEntry rootEntry { name, textureRect, { pData, format } };
mPendingData.push_back(rootEntry);
return RC_OK;
}
E_RESULT_CODE CTextureAtlas::AddTexture(TResourceId textureHandle)
{
if (TResourceId::Invalid == textureHandle)
{
return RC_INVALID_ARGS;
}
ITexture2D* pTextureResource = mpResourceManager->GetResource<ITexture2D>(textureHandle);
if (!pTextureResource)
{
return RC_FAIL;
}
const std::string textureName = dynamic_cast<IResource*>(pTextureResource)->GetName();
/// \note check whether the texture's data is already within the atlas or not
if (std::find_if(mPendingData.cbegin(), mPendingData.cend(), [&textureName](const TTextureAtlasEntry& entry) { return entry.mName == textureName; }) != mPendingData.cend() ||
mAtlasEntities.find(textureName) != mAtlasEntities.cend())
{
return RC_FAIL;
}
/// \note add a new entry
TRectI32 textureRect{ 0, 0, static_cast<I32>(pTextureResource->GetWidth()), static_cast<I32>(pTextureResource->GetHeight()) };
TTextureAtlasEntry rootEntry{ textureName, textureRect, pTextureResource };
mPendingData.push_back(rootEntry);
return RC_OK;
}
E_RESULT_CODE CTextureAtlas::RemoveTexture(const std::string& name)
{
if (name.empty())
{
return RC_INVALID_ARGS;
}
auto it = std::find_if(mPendingData.cbegin(), mPendingData.cend(), [&name](const TTextureAtlasEntry& entry) { return entry.mName == name; });
if (it == mPendingData.cend())
{
if (mAtlasEntities.find(name) == mAtlasEntities.cend())
{
return RC_FAIL;
}
mAtlasEntities.erase(name);
return RC_OK;
}
mPendingData.erase(it);
if (mAtlasEntities.find(name) != mAtlasEntities.cend())
{
mAtlasEntities.erase(name);
}
return RC_OK;
}
E_RESULT_CODE CTextureAtlas::Bake()
{
if (!mIsInitialized)
{
return RC_FAIL;
}
/// \note sort all entries by their sizes
std::sort(mPendingData.begin(), mPendingData.end(), [](const TTextureAtlasEntry& left, const TTextureAtlasEntry& right)
{
TRectI32 leftRect = left.mRect;
TRectI32 rightRect = right.mRect;
return (leftRect.width > rightRect.width) && (leftRect.height > rightRect.height);
});
ITexture2D* pAtlasInternalTexture = mpResourceManager->GetResource<ITexture2D>(mTextureResourceHandle);
/// \note while there is enough space within the atlas pack next entry
TAtlasAreaEntry root;
root.mBounds = {0, 0, static_cast<I32>(pAtlasInternalTexture->GetWidth()), static_cast<I32>(pAtlasInternalTexture->GetHeight())};
std::stack<TAtlasAreaEntry*> areasToCheck;
TAtlasAreaEntry* pCurrSubdivisionEntry = nullptr;
auto dataIter = mPendingData.cbegin();
TRectI32 firstRect, secondRect, thirdRect;
bool hasInsertionFailed = false;
auto calcMetric = [](const TRectI32& textureSizes, const TRectI32& areaSizes) -> F32
{
F32 dx = fabs(static_cast<F32>(areaSizes.width - textureSizes.width));
F32 dy = fabs(static_cast<F32>(areaSizes.height - textureSizes.height));
return sqrt(dx * dx + dy * dy);
};
while (dataIter != mPendingData.cend())
{
areasToCheck.push(&root);
while (!areasToCheck.empty())
{
hasInsertionFailed = false;
pCurrSubdivisionEntry = areasToCheck.top();
areasToCheck.pop();
/// \note traverse down to leaves, 'cause the rect is already filled up
if (pCurrSubdivisionEntry->mTextureEntryId < (std::numeric_limits<U32>::max)())
{
auto pLeftChild = pCurrSubdivisionEntry->mpLeft.get();
auto pRightChild = pCurrSubdivisionEntry->mpRight.get();
/// \note choose the branch based on minimal error between its sizes and sizes of an inserted texture
F32 leftChildMetric = calcMetric(dataIter->mRect, pLeftChild->mBounds);
F32 rightChildMetric = calcMetric(dataIter->mRect, pRightChild->mBounds);
areasToCheck.push(leftChildMetric < rightChildMetric ? pRightChild : pLeftChild);
areasToCheck.push(leftChildMetric < rightChildMetric ? pLeftChild : pRightChild);
continue;
}
/// \note if current texture fits into the area, fill it up
if (pCurrSubdivisionEntry->mBounds.width >= dataIter->mRect.width &&
pCurrSubdivisionEntry->mBounds.height >= dataIter->mRect.height)
{
pCurrSubdivisionEntry->mTextureEntryId = std::distance(mPendingData.cbegin(), dataIter);
F32 dx = static_cast<F32>(pCurrSubdivisionEntry->mBounds.width - dataIter->mRect.width);
F32 dy = static_cast<F32>(pCurrSubdivisionEntry->mBounds.height - dataIter->mRect.height);
bool isVerticalSlice = (dx > dy) || fabs(dx - dy) < 1e-3f;
/// \note divide the area into sub areas based on filled space
std::tie(firstRect, secondRect) = SplitRectWithLine(pCurrSubdivisionEntry->mBounds,
isVerticalSlice ? TVector2(static_cast<F32>(dataIter->mRect.width), 0.0f) : TVector2(0.0f, static_cast<F32>(dataIter->mRect.height)),
isVerticalSlice);
std::tie(thirdRect, firstRect) = SplitRectWithLine(firstRect,
!isVerticalSlice ? TVector2(static_cast<F32>(dataIter->mRect.width), 0.0f) : TVector2(0.0f, static_cast<F32>(dataIter->mRect.height)),
!isVerticalSlice);
pCurrSubdivisionEntry->mpLeft = std::make_unique<TAtlasAreaEntry>();
pCurrSubdivisionEntry->mpLeft->mBounds = firstRect;
pCurrSubdivisionEntry->mpRight = std::make_unique<TAtlasAreaEntry>();
pCurrSubdivisionEntry->mpRight->mBounds = secondRect;
++dataIter;
break;
}
hasInsertionFailed = true;
}
/// \note there is no enough free space in texture atlas anymore
if (areasToCheck.empty() && hasInsertionFailed)
{
break;
}
/// \note clean up the stack
while (!areasToCheck.empty())
{
areasToCheck.pop();
}
}
/// \note write down all data into atlas's texture
areasToCheck.push(&root);
TTextureAtlasEntry* pCurrTextureEntry = nullptr;
TRectI32 textureRect;
while (!areasToCheck.empty())
{
pCurrSubdivisionEntry = areasToCheck.top();
areasToCheck.pop();
if (!pCurrSubdivisionEntry || pCurrSubdivisionEntry->mTextureEntryId == (std::numeric_limits<U32>::max)())
{
continue;
}
pCurrTextureEntry = &mPendingData[pCurrSubdivisionEntry->mTextureEntryId];
textureRect = { pCurrSubdivisionEntry->mBounds.x,
pCurrSubdivisionEntry->mBounds.y,
pCurrTextureEntry->mRect.width,
pCurrTextureEntry->mRect.height };
mAtlasEntities[pCurrTextureEntry->mName] = textureRect;
if (!pCurrTextureEntry->mIsRawData)
{
auto&& textureData = pCurrTextureEntry->mData.mpTexture->GetInternalData();
E_RESULT_CODE result = pAtlasInternalTexture->WriteData(textureRect, &textureData.front());
TDE2_ASSERT(result == RC_OK);
}
else
{
E_RESULT_CODE result = pAtlasInternalTexture->WriteData(textureRect, pCurrTextureEntry->mData.mRawTexture.mpData);
TDE2_ASSERT(result == RC_OK);
}
areasToCheck.push(pCurrSubdivisionEntry->mpLeft.get());
areasToCheck.push(pCurrSubdivisionEntry->mpRight.get());
}
return hasInsertionFailed ? RC_FAIL : RC_OK;
}
E_RESULT_CODE CTextureAtlas::Save(IArchiveWriter* pWriter)
{
if (!pWriter)
{
return RC_INVALID_ARGS;
}
ITexture2D* pAtlasInternalTexture = mpResourceManager->GetResource<ITexture2D>(mTextureResourceHandle);
/// \note save texture atlas into an image file
/// \todo for now we save all atlases as png files, but it should be replaced with general solution
// ->Get<IImageFileWriter>(pFileSystem->Open<IImageFileWriter>(mName + "_Tex.png", true).Get())->Write(pAtlasInternalTexture);
PANIC_ON_FAILURE(pWriter->SetString("name", mName));
E_RESULT_CODE result = RC_OK;
/// \note write texture's information
{
if ((result = pWriter->BeginGroup("texture_resource")) != RC_OK)
{
return result;
}
PANIC_ON_FAILURE(pWriter->SetUInt32("width", pAtlasInternalTexture->GetWidth()));
PANIC_ON_FAILURE(pWriter->SetUInt32("height", pAtlasInternalTexture->GetHeight()));
PANIC_ON_FAILURE(pWriter->SetUInt32("channels_count", CFormatUtils::GetNumOfChannelsOfFormat(pAtlasInternalTexture->GetFormat())));
if ((result = pWriter->EndGroup()) != RC_OK)
{
return result;
}
}
if ((result = pWriter->BeginGroup("textures_list", true)) != RC_OK)
{
return result;
}
TRectI32 currBounds;
for (auto currTextureEntity : mAtlasEntities)
{
currBounds = currTextureEntity.second;
if ((result = pWriter->BeginGroup(Wrench::StringUtils::GetEmptyStr())) != RC_OK)
{
return result;
}
PANIC_ON_FAILURE(pWriter->SetString("name", currTextureEntity.first));
{
if ((result = pWriter->BeginGroup("bounds")) != RC_OK)
{
return result;
}
PANIC_ON_FAILURE(pWriter->SetInt32("x", currBounds.x));
PANIC_ON_FAILURE(pWriter->SetInt32("y", currBounds.y));
PANIC_ON_FAILURE(pWriter->SetInt32("width", currBounds.width));
PANIC_ON_FAILURE(pWriter->SetInt32("height",currBounds.height));
if ((result = pWriter->EndGroup()) != RC_OK)
{
return result;
}
}
if ((result = pWriter->EndGroup()) != RC_OK)
{
return result;
}
}
if ((result = pWriter->EndGroup()) != RC_OK)
{
return result;
}
return RC_OK;
}
E_RESULT_CODE CTextureAtlas::Serialize(IFileSystem* pFileSystem, ITextureAtlas* pTextureAtlas, const std::string& filename)
{
if (!pFileSystem || !pTextureAtlas || filename.empty())
{
return RC_INVALID_ARGS;
}
ITexture2D* pAtlasInternalTexture = pTextureAtlas->GetTexture();
IResource* pAtlasResource = dynamic_cast<IResource*>(pTextureAtlas);
if (!pAtlasResource)
{
return RC_FAIL;
}
std::string atlasName = pAtlasResource->GetName();
atlasName = atlasName.substr(0, atlasName.find_last_of('.'));
/// \note save texture atlas into an image file
/// \todo for now we save all atlases as png files, but it should be replaced with general solution
pFileSystem->Get<IImageFileWriter>(pFileSystem->Open<IImageFileWriter>(atlasName + "_Tex.png", true).Get())->Write(pAtlasInternalTexture);
/// \note try to create YAML file with the given name
if (auto archiveHandle = pFileSystem->Open<IYAMLFileWriter>(filename, true))
{
if (auto pArchiveFile = pFileSystem->Get<IYAMLFileWriter>(archiveHandle.Get()))
{
CDeferOperation _([pArchiveFile] { pArchiveFile->Close(); });
return pTextureAtlas->Save(pArchiveFile);
}
}
return RC_FAIL;
}
E_RESULT_CODE CTextureAtlas::Load(IArchiveReader* pReader)
{
if (!pReader)
{
return RC_INVALID_ARGS;
}
E_RESULT_CODE result = RC_OK;
/// \note load texture based on read parameters
mName = pReader->GetString("name");
/// \todo for now we save all atlases as png files, but it should be replaced with general solution
mTextureResourceHandle = mpResourceManager->Load<ITexture2D>(mName + "_Tex.png", E_RESOURCE_LOADING_POLICY::SYNCED);
/// \todo ansynchronously update sizes of the atlas when the texture has been loaded
_updateAtlasSizes(mpResourceManager->GetResource(mTextureResourceHandle));
if ((result = pReader->BeginGroup("textures_list")) != RC_OK)
{
return result;
}
std::string currEntryName;
TRectI32 currBounds;
while (pReader->HasNextItem())
{
if ((result = pReader->BeginGroup(Wrench::StringUtils::GetEmptyStr())) != RC_OK)
{
return result;
}
currEntryName = pReader->GetString("name");
// \note read bounds information
{
if ((result = pReader->BeginGroup("bounds")) != RC_OK)
{
return result;
}
currBounds.x = pReader->GetInt32("x");
currBounds.y = pReader->GetInt32("y");
currBounds.width = pReader->GetInt32("width");
currBounds.height = pReader->GetInt32("height");
if ((result = pReader->EndGroup()) != RC_OK)
{
return result;
}
}
if ((result = pReader->EndGroup()) != RC_OK)
{
return result;
}
mAtlasEntities.insert({ currEntryName, currBounds });
_createSubTexture(currEntryName, currBounds);
}
if ((result = pReader->EndGroup()) != RC_OK)
{
return result;
}
return RC_OK;
}
ITexture2D* CTextureAtlas::GetTexture() const
{
return mpResourceManager->GetResource<ITexture2D>(mTextureResourceHandle);
}
TResult<TRectI32> CTextureAtlas::GetTextureRect(const std::string& textureName) const
{
if (mAtlasEntities.find(textureName) == mAtlasEntities.cend())
{
return Wrench::TErrValue<E_RESULT_CODE>(RC_FAIL);
}
return Wrench::TOkValue<TRectI32>(mAtlasEntities.at(textureName));
}
TResult<TRectF32> CTextureAtlas::GetNormalizedTextureRect(const std::string& textureName) const
{
if (mAtlasEntities.find(textureName) == mAtlasEntities.cend())
{
return Wrench::TErrValue<E_RESULT_CODE>(RC_FAIL);
}
TRectI32 nonNormalizedRect = mAtlasEntities.at(textureName);
F32 invWidth = 1.0f / mWidth;
F32 invHeight = 1.0f / mHeight;
return Wrench::TOkValue<TRectF32>({ nonNormalizedRect.x * invWidth,
nonNormalizedRect.y * invHeight,
nonNormalizedRect.width * invWidth,
nonNormalizedRect.height * invHeight });
}
std::vector<std::string> CTextureAtlas::GetTexturesIdentifiersList() const
{
std::vector<std::string> output;
for (auto&& currAtlasEntity : mAtlasEntities)
{
output.push_back(currAtlasEntity.first);
}
return std::move(output);
}
void CTextureAtlas::_updateAtlasSizes(IResource* pTexture)
{
ITexture2D* pTexture2D = dynamic_cast<ITexture2D*>(pTexture);
mWidth = pTexture2D->GetWidth();
mHeight = pTexture2D->GetHeight();
}
TResult<TResourceId> CTextureAtlas::_createSubTexture(const std::string& id, const TRectI32& rect)
{
TAtlasSubTextureParameters subTextureParams;
subTextureParams.mTextureAtlasId = mId;
subTextureParams.mTextureRectInfo = rect;
TResourceId subTextureHandle = mpResourceManager->Create<IAtlasSubTexture>(id, subTextureParams);
if (TResourceId::Invalid == subTextureHandle)
{
return Wrench::TErrValue<E_RESULT_CODE>(RC_FAIL);
}
mpSubTextures.push_back(mpResourceManager->GetResource<IAtlasSubTexture>(subTextureHandle));
return Wrench::TOkValue<TResourceId>(subTextureHandle);
}
const IResourceLoader* CTextureAtlas::_getResourceLoader()
{
return mpResourceManager->GetResourceLoader<ITextureAtlas>();
}
TDE2_API ITextureAtlas* CreateTextureAtlas(IResourceManager* pResourceManager, IGraphicsContext* pGraphicsContext, const std::string& name,
const TTexture2DParameters& params, E_RESULT_CODE& result)
{
return CREATE_IMPL(ITextureAtlas, CTextureAtlas, result, pResourceManager, pGraphicsContext, name, params);
}
TDE2_API ITextureAtlas* CreateTextureAtlas(IResourceManager* pResourceManager, IGraphicsContext* pGraphicsContext, const std::string& name,
E_RESULT_CODE& result)
{
return CREATE_IMPL(ITextureAtlas, CTextureAtlas, result, pResourceManager, pGraphicsContext, name);
}
/*!
\brief CTextureAtlasLoader's definition
*/
CTextureAtlasLoader::CTextureAtlasLoader() :
mIsInitialized(false)
{
}
E_RESULT_CODE CTextureAtlasLoader::Init(IResourceManager* pResourceManager, IGraphicsContext* pGraphicsContext, IFileSystem* pFileSystem)
{
if (mIsInitialized)
{
return RC_FAIL;
}
if (!pResourceManager || !pGraphicsContext || !pFileSystem)
{
return RC_INVALID_ARGS;
}
mpResourceManager = pResourceManager;
mpFileSystem = pFileSystem;
mpGraphicsContext = pGraphicsContext;
mIsInitialized = true;
return RC_OK;
}
E_RESULT_CODE CTextureAtlasLoader::Free()
{
if (!mIsInitialized)
{
return RC_FAIL;
}
mIsInitialized = false;
delete this;
return RC_OK;
}
E_RESULT_CODE CTextureAtlasLoader::LoadResource(IResource* pResource) const
{
if (!pResource)
{
return RC_INVALID_ARGS;
}
if (TResult<TFileEntryId> atlasFileId = mpFileSystem->Open<IYAMLFileReader>(pResource->GetName()))
{
return dynamic_cast<ITextureAtlas*>(pResource)->Load(mpFileSystem->Get<IYAMLFileReader>(atlasFileId.Get()));
}
return RC_FILE_NOT_FOUND;
}
TypeId CTextureAtlasLoader::GetResourceTypeId() const
{
return ITextureAtlas::GetTypeId();
}
TDE2_API IResourceLoader* CreateTextureAtlasLoader(IResourceManager* pResourceManager, IGraphicsContext* pGraphicsContext, IFileSystem* pFileSystem, E_RESULT_CODE& result)
{
return CREATE_IMPL(IResourceLoader, CTextureAtlasLoader, result, pResourceManager, pGraphicsContext, pFileSystem);
}
/*!
\brief CTextureAtlasFactory's definition
*/
CTextureAtlasFactory::CTextureAtlasFactory() :
mIsInitialized(false)
{
}
E_RESULT_CODE CTextureAtlasFactory::Init(IResourceManager* pResourceManager, IGraphicsContext* pGraphicsContext)
{
if (mIsInitialized)
{
return RC_FAIL;
}
if (!pGraphicsContext || !pResourceManager)
{
return RC_INVALID_ARGS;
}
mpResourceManager = pResourceManager;
mpGraphicsContext = pGraphicsContext;
mIsInitialized = true;
return RC_OK;
}
E_RESULT_CODE CTextureAtlasFactory::Free()
{
if (!mIsInitialized)
{
return RC_FAIL;
}
mIsInitialized = false;
delete this;
return RC_OK;
}
IResource* CTextureAtlasFactory::Create(const std::string& name, const TBaseResourceParameters& params) const
{
E_RESULT_CODE result = RC_OK;
return dynamic_cast<IResource*>(CreateTextureAtlas(mpResourceManager, mpGraphicsContext, name,
dynamic_cast<const TTexture2DParameters&>(params),
result));
}
IResource* CTextureAtlasFactory::CreateDefault(const std::string& name, const TBaseResourceParameters& params) const
{
E_RESULT_CODE result = RC_OK;
return dynamic_cast<IResource*>(CreateTextureAtlas(mpResourceManager, mpGraphicsContext, name, result));
}
TypeId CTextureAtlasFactory::GetResourceTypeId() const
{
return ITextureAtlas::GetTypeId();
}
TDE2_API IResourceFactory* CreateTextureAtlasFactory(IResourceManager* pResourceManager, IGraphicsContext* pGraphicsContext, E_RESULT_CODE& result)
{
return CREATE_IMPL(IResourceFactory, CTextureAtlasFactory, result, pResourceManager, pGraphicsContext);
}
} |
/****************************************************************************************
* @author: kzvd4729 created: Jul/12/2020 00:48
* solution_verdict: Wrong answer on test 7 language: GNU C++14
* run_time: 15 ms memory_used: 7600 KB
* problem: https://codeforces.com/contest/1372/problem/F
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<unordered_map>
#include<random>
#include<chrono>
#include<stack>
#include<deque>
#define long long long
using namespace std;
const int N=1e6;
int n,ans[N+2];
int ask(int i)
{
if(ans[i])return ans[i];
cout<<"? "<<i<<" "<<i<<endl;
int x,f;cin>>x>>f;
return ans[i]=x;
}
void print()
{
cout<<"!";
for(int i=1;i<=n;i++)cout<<" "<<ans[i];
cout<<endl;
}
void solve(int lo,int hi,int l,int r)
{
if(lo>hi)return;
if(l==r)
{
for(int i=lo;i<=hi;i++)ans[i]=l;
return;
}
int md=(lo+hi)/2;
int x=ask(md);ans[md]=x;
solve(lo,md-1,l,x);solve(md+1,hi,x,r);
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
cin>>n;solve(1,n,ask(1),ask(n));
print();
return 0;
} |
#pragma once
#include "interface.hpp"
#include "internal/sys.hpp"
#include "pci.hpp"
#include "progress.hpp"
#include <ipmiblob/blob_interface.hpp>
#include <cstdint>
#include <vector>
namespace host_tool
{
class P2aDataHandler : public DataInterface
{
public:
P2aDataHandler(ipmiblob::BlobInterface* blob, const PciAccess* pci,
ProgressInterface* progress,
const internal::Sys* sys = &internal::sys_impl) :
blob(blob),
pci(pci), progress(progress), sys(sys)
{}
bool sendContents(const std::string& input, std::uint16_t session) override;
ipmi_flash::FirmwareFlags::UpdateFlags supportedType() const override
{
return ipmi_flash::FirmwareFlags::UpdateFlags::p2a;
}
private:
ipmiblob::BlobInterface* blob;
const PciAccess* pci;
ProgressInterface* progress;
const internal::Sys* sys;
};
} // namespace host_tool
|
; A288663: Decimal representation of the diagonal from the corner to the origin of the n-th stage of growth of the two-dimensional cellular automaton defined by "Rule 493", based on the 5-celled von Neumann neighborhood.
; 1,2,1,12,3,56,7,240,15,992,31,4032,63,16256,127,65280,255,261632,511,1047552,1023,4192256,2047,16773120,4095,67100672,8191,268419072,16383,1073709056,32767,4294901760,65535,17179738112,131071,68719214592,262143,274877382656,524287,1099510579200,1048575,4398044413952,2097151,17592181850112,4194303,70368735789056,8388607,281474959933440,16777215,1125899873288192,33554431,4503599560261632,67108863,18014398375264256,134217727,72057593769492480,268435455,288230375614840832,536870911,1152921503533105152,1073741823,4611686016279904256,2147483647,18446744069414584320,4294967295,73786976286248271872,8589934591,295147905162172956672,17179869183,1180591620683051565056,34359738367,4722366482800925736960,68719476735,18889465931341141901312,137438953471,75557863725639445512192,274877906943,302231454903107537862656,549755813887,1208925819613529663078400,1099511627775,4835703278456317675569152,2199023255551,19342813113829668748787712,4398046511103,77371252455327471088173056,8796093022207,309485009821327476538736640,17592186044415,1237940039285345090527035392,35184372088831,4951760157141450730852319232,70368744177663,19807040628565943660897632256,140737488355327,79228162514264056118567239680,281474976710655,316912650057056787424222380032,562949953421311,1267650600228228275596796362752
sub $0,1
mov $1,2
lpb $0
sub $0,2
mul $1,2
lpe
gcd $0,$1
mul $1,$0
sub $1,$0
mov $0,$1
|
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gui/containers/guiRolloutCtrl.h"
#include "gui/containers/guiScrollCtrl.h"
//////////////////////////////////////////////////////////////////////////
// GuiRolloutCtrl
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_CONOBJECT(GuiRolloutCtrl);
GuiRolloutCtrl::GuiRolloutCtrl()
{
mBounds.set(0,0,200,20);
mExpanded.set(0,0,200,60);
mCaption = StringTable->EmptyString;
mIsExpanded = true;
mIsAnimating = false;
mCollapsing = false;
mAnimateDestHeight = 40;
mAnimateStep = 1;
mCanSave = false;
mDefaultHeight = 40;
mMargin.set( 2,2 );
mIsContainer = true;
mCanCollapse = true;
// Make sure we receive our ticks.
setProcessTicks();
}
GuiRolloutCtrl::~GuiRolloutCtrl()
{
}
//////////////////////////////////////////////////////////////////////////
// Persistence
//////////////////////////////////////////////////////////////////////////
void GuiRolloutCtrl::initPersistFields()
{
Parent::initPersistFields();
addField("Caption", TypeCaseString, Offset(mCaption, GuiRolloutCtrl));
addField("Margin", TypePoint2I, Offset(mMargin, GuiRolloutCtrl));
addField("DefaultHeight", TypeS32, Offset(mDefaultHeight, GuiRolloutCtrl));
addProtectedField( "Collapsed", TypeBool, Offset( mIsExpanded, GuiRolloutCtrl), &setCollapsed, &defaultProtectedGetFn, "" );
addField("ClickCollapse", TypeBool, Offset(mCanCollapse, GuiRolloutCtrl));
}
//////////////////////////////////////////////////////////////////////////
// Scene Events
//////////////////////////////////////////////////////////////////////////
bool GuiRolloutCtrl::onAdd()
{
if( !Parent::onAdd() )
return false;
mHasTexture = ( mProfile ? mProfile->constructBitmapArray() : false );
if( mHasTexture )
mBitmapBounds = mProfile->mBitmapArrayRects.address();
// Calculate Heights for this control
calculateHeights();
return true;
}
bool GuiRolloutCtrl::onWake()
{
if (! Parent::onWake())
return false;
if( !mIsAnimating && mIsExpanded )
sizeToContents();
return true;
}
void GuiRolloutCtrl::addObject( SimObject *obj )
{
// Call Parent.
Parent::addObject( obj );
sizeToContents();
}
void GuiRolloutCtrl::removeObject( SimObject *obj )
{
// Call Parent.
Parent::removeObject( obj );
// Recalculate our rectangles.
calculateHeights();
}
//////////////////////////////////////////////////////////////////////////
// Mouse Events
//////////////////////////////////////////////////////////////////////////
void GuiRolloutCtrl::onMouseDown( const GuiEvent &event )
{
mouseLock();
}
void GuiRolloutCtrl::onMouseUp( const GuiEvent &event )
{
Point2I localPoint = globalToLocalCoord( event.mousePoint );
if( mCanCollapse && mHeader.pointInRect( localPoint ) && !mIsAnimating && isMouseLocked() )
{
if( !mIsExpanded )
animateTo( mExpanded.extent.y );
else
animateTo( mHeader.extent.y );
}
if( isMouseLocked() )
mouseUnlock();
}
//////////////////////////////////////////////////////////////////////////
// Control Sizing Helpers
//////////////////////////////////////////////////////////////////////////
void GuiRolloutCtrl::calculateHeights()
{
S32 barHeight = 20;
if( mHasTexture && mProfile->mBitmapArrayRects.size() >= NumBitmaps )
{
// Store Header Rectangle
mHeader.set( 0, 0, mBounds.extent.x, mProfile->mBitmapArrayRects[ CollapsedCenter ].extent.y );
// Bottom Bar Max
barHeight = mProfile->mBitmapArrayRects[ BottomLeftHeader ].extent.y
+ mProfile->mBitmapArrayRects[ TopLeftHeader ].extent.y;
}
else
{
mHeader.set( 0, 0, mBounds.extent.x, barHeight );
}
GuiControl *content = dynamic_cast<GuiControl*>( at(0) );
if( content != NULL )
mExpanded.set( 0, 0, mBounds.extent.x , barHeight + content->getHeight() + (mMargin.y * 2) );
else
mExpanded.set( 0, 0, mBounds.extent.x, barHeight + mDefaultHeight );
}
void GuiRolloutCtrl::resize( const Point2I &newPosition, const Point2I &newExtent )
{
Parent::resize( newPosition, newExtent );
// Recalculate Heights and resize ourself appropriately.
calculateHeights();
GuiControl *content = dynamic_cast<GuiControl*>( at(0) );
// Size Content Properly?!
if( content != NULL )
{
mChildRect.set( mMargin.x, mHeader.extent.y + mMargin.y , mBounds.extent.x - (mMargin.x * 2), content->mBounds.extent.y - ( mMargin.y * 2 ) );
content->resize( mChildRect.point, mChildRect.extent );
}
}
void GuiRolloutCtrl::sizeToContents()
{
calculateHeights();
// Set destination height
if( size() > 0 )
instantExpand();
else
instantCollapse();
}
void GuiRolloutCtrl::instantExpand()
{
mAnimateDestHeight = mExpanded.extent.y;
mCollapsing = false;
mIsExpanded = true;
mIsAnimating = false;
resize( mBounds.point + mExpanded.point, mExpanded.extent );
}
void GuiRolloutCtrl::instantCollapse()
{
mAnimateDestHeight = mHeader.extent.y;
mCollapsing = false;
mIsExpanded = false;
mIsAnimating = false;
resize( mBounds.point + mHeader.point, mHeader.extent );
}
void GuiRolloutCtrl::childResized(GuiControl *child)
{
Parent::childResized( child );
calculateHeights();
}
//////////////////////////////////////////////////////////////////////////
// Control Sizing Animation Functions
//////////////////////////////////////////////////////////////////////////
void GuiRolloutCtrl::animateTo( S32 height )
{
// We do nothing if we're already animating
if( mIsAnimating )
return;
bool collapsing = (bool)( mBounds.extent.y > height );
// If we're already at the destination height, bail
if( mBounds.extent.y >= height && !collapsing )
{
mIsExpanded = true;
return;
}
// If we're already at the destination height, bail
if( mBounds.extent.y <= height && collapsing )
{
mIsExpanded = false;
return;
}
// Set destination height
mAnimateDestHeight = height;
// Set Animation Mode
mCollapsing = collapsing;
// Set Animation Step (Increment)
if( collapsing )
mAnimateStep = (S32)mFloor( (F32)( mBounds.extent.y - height ) / 2.0f );
else
mAnimateStep = (S32)mFloor( (F32)( height - mBounds.extent.y ) / 2.0f );
// Start our animation
mIsAnimating = true;
}
void GuiRolloutCtrl::processTick()
{
// We do nothing here if we're NOT animating
if( !mIsAnimating )
return;
// Sanity check to fix non collapsing panels.
if( mAnimateStep == 0 )
mAnimateStep = 1;
// We're collapsing ourself down (Hiding our contents)
if( mCollapsing )
{
if( mBounds.extent.y < mAnimateDestHeight )
mBounds.extent.y = mAnimateDestHeight;
else if( ( mBounds.extent.y - mAnimateStep ) < mAnimateDestHeight )
mBounds.extent.y = mAnimateDestHeight;
if( mBounds.extent.y == mAnimateDestHeight )
mIsAnimating = false;
else
mBounds.extent.y -= mAnimateStep;
if( !mIsAnimating )
mIsExpanded = false;
}
else // We're expanding ourself (Showing our contents)
{
if( mBounds.extent.y > mAnimateDestHeight )
mBounds.extent.y = mAnimateDestHeight;
else if( ( mBounds.extent.y + mAnimateStep ) > mAnimateDestHeight )
mBounds.extent.y = mAnimateDestHeight;
if( mBounds.extent.y == mAnimateDestHeight )
mIsAnimating = false;
else
mBounds.extent.y += mAnimateStep;
if( !mIsAnimating )
mIsExpanded = true;
}
if( !mIsAnimating )
{
if( mCollapsing && isMethod("onCollapsed") )
Con::executef( this, 2, "onCollapsed" );
else if( !mCollapsing && isMethod("onExpanded") )
Con::executef( this, 2, "onExpanded" );
calculateHeights();
}
GuiControl* parent = getParent();
if( parent )
{
parent->childResized( this );
// if our parent's parent is a scroll control, scrollvisible.
GuiScrollCtrl* scroll = dynamic_cast<GuiScrollCtrl*>(parent->getParent());
if(scroll)
{
scroll->scrollRectVisible(mBounds);
}
}
}
//////////////////////////////////////////////////////////////////////////
// Control Rendering
//////////////////////////////////////////////////////////////////////////
void GuiRolloutCtrl::onRender(Point2I offset, const RectI &updateRect)
{
if( !mProfile || mProfile->mFont.isNull() )
return;
// Calculate actual world bounds for rendering
RectI worldBounds( offset, mBounds.extent );
if( mProfile->mBitmapArrayRects.size() >= NumBitmaps )
{
dglClearBitmapModulation();
// Draw Rollout From Skin
if( !mIsExpanded )
renderFixedBitmapBordersFilled( worldBounds, 1, mProfile );
else// Draw Border
renderSizableBitmapBordersFilledIndex( worldBounds, TopLeftHeader, mProfile );
// Draw Caption ( Vertically Centered )
ColorI currColor;
dglGetBitmapModulation( &currColor );
Point2I textPosition = mHeader.point + offset + mProfile->mTextOffset;
dglSetBitmapModulation( mProfile->mFontColor );
renderJustifiedText( textPosition, mHeader.extent, mCaption );
dglSetBitmapModulation( currColor );
// If we're collapsed we contain the first child as our content
// thus we don't render it when collapsed. but to support modified
// rollouts with custom header buttons etc we still render our other
// children. -JDD
GuiControl *pChild = dynamic_cast<GuiControl*>( at(0) );
if(pChild)
{
if( !mIsExpanded && pChild->isVisible() )
pChild->setVisible( false );
else if( mIsExpanded && !pChild->isVisible())
pChild->setVisible( true );
}
renderChildControls(offset, updateRect);
}
}
//////////////////////////////////////////////////////////////////////////
// Console
//////////////////////////////////////////////////////////////////////////
ConsoleMethod( GuiRolloutCtrl, isExpanded, bool, 2, 2, "() @return Returns true if object is expanded, false otherwise")
{
return object->isExpanded();
}
ConsoleMethod( GuiRolloutCtrl, collapse, void, 2, 2, "() Collapses control.\n @return No return value.")
{
object->collapse();
}
ConsoleMethod( GuiRolloutCtrl, expand, void, 2, 2, "() Expands control\n @return No return value.")
{
object->expand();
}
ConsoleMethod( GuiRolloutCtrl, instantCollapse, void, 2, 2, "() Collapses control without animation.\n @return No return value.")
{
object->instantCollapse();
}
ConsoleMethod( GuiRolloutCtrl, instantExpand, void, 2, 2, "() Expands control without animation.\n @return No return value.")
{
object->instantExpand();
}
ConsoleMethod( GuiRolloutCtrl, sizeToContents, void, 2, 2, "() Resizes control to fit its contents\n @return No return value.")
{
object->sizeToContents();
}
|
; (proc.asm)
; This program shows how to use the PROC directive with
; different calling conventions.
INCLUDE Irvine32.inc
.code
Example1 PROTO C,
parm1:DWORD, parm2:DWORD
Example2 PROTO STDCALL,
parm1:DWORD, parm2:DWORD
Example3 PROTO PASCAL,
parm1:DWORD, parm2:DWORD
main PROC
INVOKE Example1, 2, 3
INVOKE Example2, 2, 3
INVOKE Example3, 2, 3
exit
main ENDP
Example1 PROC C,
parm1:DWORD, parm2:DWORD
mov eax,parm1
mov ebx,parm2
call DumpRegs
ret
Example1 ENDP
Example2 PROC STDCALL,
parm1:DWORD, parm2:DWORD
mov eax,parm1
mov ebx,parm2
call DumpRegs
ret
Example2 ENDP
Example3 PROC PASCAL,
parm1:DWORD, parm2:DWORD
mov eax,parm1
mov ebx,parm2
call DumpRegs
ret
Example3 ENDP
END main |
; $Id: deps.asm $
;; @file
; Solaris kernel module dependency
;
;
; Copyright (C) 2012 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
%include "iprt/solaris/kmoddeps.mac"
kmoddeps_header ; ELF header, section table and shared string table
kmoddeps_dynstr_start ; ELF .dynstr section
kmoddeps_dynstr_string str_misc_ctf, "misc/ctf"
kmoddeps_dynstr_string str_drv_vboxguest, "drv/vboxguest"
kmoddeps_dynstr_end
kmoddeps_dynamic_start ; ELF .dynamic section
kmoddeps_dynamic_needed str_misc_ctf
kmoddeps_dynamic_needed str_drv_vboxguest
kmoddeps_dynamic_end
|
; A158628: a(n) = 44*n^2 - 1.
; 43,175,395,703,1099,1583,2155,2815,3563,4399,5323,6335,7435,8623,9899,11263,12715,14255,15883,17599,19403,21295,23275,25343,27499,29743,32075,34495,37003,39599,42283,45055,47915,50863,53899,57023,60235,63535,66923,70399,73963,77615,81355,85183,89099,93103,97195,101375,105643,109999,114443,118975,123595,128303,133099,137983,142955,148015,153163,158399,163723,169135,174635,180223,185899,191663,197515,203455,209483,215599,221803,228095,234475,240943,247499,254143,260875,267695,274603,281599,288683,295855,303115,310463,317899,325423,333035,340735,348523,356399,364363,372415,380555,388783,397099,405503,413995,422575,431243,439999,448843,457775,466795,475903,485099,494383,503755,513215,522763,532399,542123,551935,561835,571823,581899,592063,602315,612655,623083,633599,644203,654895,665675,676543,687499,698543,709675,720895,732203,743599,755083,766655,778315,790063,801899,813823,825835,837935,850123,862399,874763,887215,899755,912383,925099,937903,950795,963775,976843,989999,1003243,1016575,1029995,1043503,1057099,1070783,1084555,1098415,1112363,1126399,1140523,1154735,1169035,1183423,1197899,1212463,1227115,1241855,1256683,1271599,1286603,1301695,1316875,1332143,1347499,1362943,1378475,1394095,1409803,1425599,1441483,1457455,1473515,1489663,1505899,1522223,1538635,1555135,1571723,1588399,1605163,1622015,1638955,1655983,1673099,1690303,1707595,1724975,1742443,1759999,1777643,1795375,1813195,1831103,1849099,1867183,1885355,1903615,1921963,1940399,1958923,1977535,1996235,2015023,2033899,2052863,2071915,2091055,2110283,2129599,2149003,2168495,2188075,2207743,2227499,2247343,2267275,2287295,2307403,2327599,2347883,2368255,2388715,2409263,2429899,2450623,2471435,2492335,2513323,2534399,2555563,2576815,2598155,2619583,2641099,2662703,2684395,2706175,2728043,2749999
mov $1,2
add $1,$0
mul $1,$0
mul $1,44
add $1,43
|
; A179571: Number of permutations of 1..n+4 with the number moved left exceeding the number moved right by n.
; 31,66,134,267,529,1048,2080,4137,8243,16446,32842,65623,131173,262260,524420,1048725,2097319,4194490,8388814,16777443,33554681,67109136,134218024,268435777,536871259,1073742198,2147484050,4294967727,8589935053,17179869676,34359738892,68719477293,137438954063,274877907570,549755814550,1099511628475,2199023256289,4398046511880,8796093023024,17592186045273,35184372089731,70368744178606,140737488356314,281474976711687,562949953422389,1125899906843748,2251799813686420,4503599627371717,9007199254742263
add $0,2
lpb $0
add $1,$0
sub $0,1
add $2,4
mul $2,2
lpe
add $1,4
add $1,$2
|
SYS_EXIT equ 1
SYS_WRITE equ 4
STDIN equ 0
STDOUT equ 1
section .data
msg_1 db 'Hello, programmers!', 0xA, 0xD
len_1 equ $ - msg_1
msg_2 db 'Welcome to the world of', 0x20
len_2 equ $ - msg_2
msg_3 db 'Linux assembly programming!', 0xA, 0xD
len_3 equ $ - msg_3
section .text
global _start
_start:
mov ecx, msg_1
mov edx, len_1
call _print
mov ecx, msg_2
mov edx, len_2
call _print
mov ecx, msg_3
mov edx, len_3
call _print
mov eax, SYS_EXIT
int 80h
_print:
mov eax, SYS_WRITE
mov ebx, STDOUT
int 80h
ret |
; A131133: a(0)=1; for n > 0, a(n) = (1/n + 1/a(n-1))*lcm(n, a(n-1)).
; Submitted by Simon Strandgaard
; 1,2,2,5,9,14,10,17,25,34,22,3,5,18,16,31,47,64,41,60,4,25,47,70,47,72,49,76,26,55,17,48,5,38,36,71,107,144,91,10,5,46,44,87,131,176,111,158,103,152,101,152,51,104,79,134,95,8,33,92,38,99,161,32,3,68,67,2,35,104,87,158,115,188,131,206,141,218,148,227,307,388,235,318,67,152,119,206,147,236,163,254,173,266,180,55,151,248,173,272
mov $2,1
mov $3,1
lpb $0
sub $0,1
gcd $1,$3
add $2,$3
div $2,$1
mov $1,$2
add $3,1
lpe
mov $0,$2
|
/*
Author: Mamnuya Rinki
Summary: C++ notes program for quotes, affirmations, actions, and journal entries.
//USAGE
//g++ -std=c++17 notes.cpp -c
//g++ -std=c++17 notes.cpp -o notes
//./notes outputfile and (optional field) "default" and (optional field) inputfile
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#include <regex>
using namespace std;
vector<string> quotes;
vector<string> affirmation;
vector<string> action;
vector<string> journal;
bool inputExists=false;
void defaultNotes();
void checkUserPurpose(string outpoint);
void inputParse(string inpoint);
void quitting(string out, string userInput);
void cleanInput(string reusedInput);
int main(int argc, char* argv[])
{
if (argc < 2 || argc > 4){
cerr << "Usage: " << argv[0] << " [output file]" << " [(optional string) \"default\"]" << " [(optional input file)]"<<"\n";
exit(1);
}
//ios::app allows file appending instead of overwriting
ofstream output {argv[1], ios::app};
string output1=argv[1];
//throws an error if no output file provided and exits the program
if(!output.is_open()){
cerr << "could not open output file: " << argv[1] << endl;
exit(1);
}
cout<<"Welcome to Selfish Notes"<<endl;
cout<<"Enter \"quit\" at any keyboard prompt to end your session."<<endl;
cout<<""<<endl;
ifstream input(argv[0]); //initial default value for input file
if (argc==3){
string input1;
if(strcmp(argv[2], "default") == 0){
cout << "Adding default Selfish Notes!" << endl;
cout << " " << endl;
defaultNotes();
checkUserPurpose(output1);
}
else{
//Command line prompt ./notes output input
input1=argv[2];
if(!input.is_open()){
cerr << "could not open input file: " << input1 << endl;
exit(1);
}
inputExists=true;
//Adjust old generated output files
//to incorporate input file syntax
cleanInput(input1);
cout << "Adding input file Selfish Notes!" << endl;
cout << " " << endl;
inputParse(input1);
checkUserPurpose(output1);
}
}
else if (argc==4){
//Command line prompt ./notes output default input
// or ./notes output input default
//call input file parser
string input1;
if (strcmp(argv[2], "default") == 0){
input1=argv[3];
}
else if (strcmp(argv[3], "default") == 0){
input1 =argv[2];
}
if(!input.is_open()){
cerr << "could not open input file: " << input1 << endl;
exit(1);
}
inputExists=true;
//Adjust old generated output files
//to incorporate input file syntax
cleanInput(input1);
cout << "Adding default Selfish Notes!" << endl;
defaultNotes();
cout << "Adding input file Selfish Notes!" << endl;
cout << " " << endl;
inputParse(input1);
checkUserPurpose(output1);
}
else{
checkUserPurpose(output1);
}
if (inputExists){
input.close();
}
output.close();
}
/*
When an old output file is used as a new input file,
replaces old output file syntax with input file syntax accordingly
*/
void cleanInput(string reusedInput){
//open and read the input file
ifstream oldFile {reusedInput};
string currLine;
bool cleaningQuotes=false;
bool cleaningAffirmations=false;
bool cleaningActions=false;
bool cleaningJournalEntries=false;
vector<string> replacement;
while(getline(oldFile, currLine)){
//implement <start TYPE> and <end TYPE> tags
if(currLine.find("--") != string::npos){
if (currLine.find("--QUOTE") != string::npos){
if (cleaningJournalEntries==true){
//add journal entries tag and reset boolean
//if there are more quotes and values after first journal entries section
replacement.push_back("<end journal entries>");
cleaningJournalEntries=false;
}
cleaningQuotes=true;
replacement.push_back("<start quotes>");
}
else if(currLine.find("--AFFIRM") != string::npos ){
cleaningAffirmations=true;
replacement.push_back("<end quotes>");
replacement.push_back("<start affirmations>");
}
else if(currLine.find("--ACT") != string::npos ){
cleaningActions=true;
replacement.push_back("<end affirmations>");
replacement.push_back("<start actions>");
}
else if(currLine.find("--JOURNAL") != string::npos ){
cleaningJournalEntries=true;
replacement.push_back("<end actions>");
replacement.push_back("<start journal entries>");
//if reaching the end of quotes, reset all cleaning booleans
if (cleaningQuotes==true){
cleaningQuotes=false;
cleaningAffirmations=false;
cleaningActions=false;
}
}
}
else if(currLine ==""){
//add blank lines to vector of new lines
replacement.push_back(currLine);
}
else{
if(currLine.find ("(") && currLine.find (")") && !currLine.find ("--")){
//add line from after (#) until end of line, into the vector of new lines
replacement.push_back(currLine.substr(currLine.find(") ") +2));
}
else{
replacement.push_back(currLine);
}
}
}
//open and overwrite the input file
//ios::app allows file overwriting instead of appending
ofstream cleaned {reusedInput, ios::trunc};
for (int i=0; i<replacement.size();i++){
cleaned<<replacement.at(i)<<"\n";
}
cleaned.close();
}
/*
Parses input file contained in blocks of <start [TYPE]> <end [TYPE]>
*/
void inputParse(string inpoint){
ifstream input(inpoint);
string currLine;
bool parsingQuotes=false;
bool parsingAffirmations=false;
bool parsingActions=false;
bool parsingJournalEntries=false;
while (getline(input, currLine)){
//skips blank lines
if (currLine == "")
{
continue;
}
//parse the input file through it's contained blocks
//uses incomplete .find strings to match atleast half
//of the desired input fields
//ie. finding "act" instead of "action" allows flexibility
//for act, actions, action, acts, etc
//parsing quotes
if(currLine.find("<start quot") != string::npos){
parsingQuotes=true;
continue;
}
else if (currLine.find("<end quot") != string::npos){
parsingQuotes=false;
continue;
}
if (parsingQuotes==true){
quotes.push_back(currLine);
}
//parsing affirmations
if(currLine.find("<start affirm") != string::npos){
parsingAffirmations=true;
continue;
}
else if (currLine.find("<end affirm") != string::npos){
parsingAffirmations=false;
continue;
}
if (parsingAffirmations==true){
affirmation.push_back(currLine);
}
//parsing actions
if(currLine.find("<start act") != string::npos){
parsingActions=true;
continue;
}
else if (currLine.find("<end act") != string::npos){
parsingActions=false;
continue;
}
if (parsingActions==true){
action.push_back(currLine);
}
//parsing journal entries
if(currLine.find("<start journal") != string::npos){
parsingJournalEntries=true;
continue;
}
else if (currLine.find("<end journal") != string::npos){
parsingJournalEntries=false;
continue;
}
if (parsingJournalEntries==true){
journal.push_back(currLine);
}
}
}
/*
Add default selfish notes if "default" is command line argument
*/
void defaultNotes(){
quotes.push_back("\"This time in your life is asking for your self compassion.\" -Morgan Love " );
quotes.push_back("\"You could be the world's best garbage man, the world's best model; it don't matter what you do if you're the best.\" -Muhammad Ali" );
quotes.push_back("\"It always seems impossible until it's done.\" -Nelson Mandela");
quotes.push_back("\"Find people who will make you better.\" -Michelle Obama");
quotes.push_back("\"Let go of what has passed.\" -Imam Ali");
quotes.push_back("\"The best way to predict the future is to invent it.\" -Alan Kay " );
quotes.push_back("\"Richness is not having many belongings, but richness is contentment of the soul.\" -Prophet Muhammad SAS (PBUH)" );
quotes.push_back("\"I alone cannot change the world, but I can cast a stone across the water to create many ripples.\" -Mother Teresa");
quotes.push_back("\"Every moment is a fresh beginning.\" -T.S. Eliot");
quotes.push_back("\"Happiness depends upon ourselves.\" -Aristotle");
quotes.push_back("\"Normality is a paved road: it's comfortable to walk but no flowers grow.\" -Vincent Van Gogh " );
quotes.push_back("\"To get what you love, you must first be patient with what you hate.\" -Imam Al-Ghazali" );
quotes.push_back("\"I can't change the direction of the wind, but I can adjust my sails to always reach my destination.\" -Jimmy Dean");
quotes.push_back("\"Be patient; patience is a pillar of faith.\" -Umar Ibn Al-Khattab");
quotes.push_back("\"Healing takes courage, and we all have courage, even if we have to dig a little to find it.\" -Tori Amos");
quotes.push_back("\"Trust yourself, you know more than you think you do.\" -Benjamin Spock " );
quotes.push_back("\"Work hard in silence, let your success be your noise.\" -Frank Ocean" );
quotes.push_back("\"With every hardship there is ease.\" -Quran 94:6");
quotes.push_back("\"Be in the company of those who boost your spirituality and motivate you to do good than those who make you feel low and unworthy.\" -Mufti Menk");
affirmation.push_back("I am growing.");
affirmation.push_back("I am safe.");
affirmation.push_back("I let go of all that no longer serves me.");
affirmation.push_back("I radiate positive energy.");
affirmation.push_back("I deserve to be surrounded by people who love and respect me.");
affirmation.push_back("My mind and my heart will remain open today.");
affirmation.push_back("I forgive myself for not being perfect.");
affirmation.push_back("I deserve and choose to be happy.");
affirmation.push_back("Every breath I inhale calms me.");
affirmation.push_back("I'm proud of myself.");
affirmation.push_back("I alone hold the truth of who I am.");
affirmation.push_back("I have come farther that I would have ever thought possible, and I'm learning along the way.");
affirmation.push_back("I invite abundance and generous hearts.");
affirmation.push_back("I practice gratitude for all that I have, and all that is yet to come.");
affirmation.push_back("My times of rest are productive.");
affirmation.push_back("When I speak my needs, I receive them abundantly.");
affirmation.push_back("Today, I will hold compassion for myself.");
affirmation.push_back("I gently and easily return to the present moment.");
affirmation.push_back("I am defined on my own terms.");
action.push_back("Stay hydrated. ");
action.push_back("Let people know when you need a break.");
action.push_back("Ask for help as needed, you don't need to do this alone. ");
action.push_back("Be lenient with responding to others, if you decide to do so. ");
action.push_back("Congratulate yourself for completed tasks. ");
action.push_back("Take a deep breath.");
action.push_back("Give someone a hug.");
action.push_back("Go on a short walk. ");
action.push_back("Set intentions.");
action.push_back("Laugh and chat with a loved one.");
action.push_back("Watch a show.");
action.push_back("Listen to your favorite podcast.");
action.push_back("Cleanse your space.");
action.push_back("Have a snack.");
action.push_back("Meditate for five minutes.");
action.push_back("Start a hobby.");
action.push_back("Read a book or article.");
action.push_back("Exercise or stretch.");
action.push_back("Make your bed.");
}
/*
Checks if user would like to add, read, edit, delete or quit their selfish notes.
*/
void checkUserPurpose(string outpoint){
//direct instrutions to adding to file
ofstream output {outpoint, ios::app};
//ios::app allows file appending instead of overwriting
cout<<""<<endl;
cout << "Would you like to add, read, edit, or delete output in your Selfish Notes?" << endl;
cout << "Enter \"add\",\"read\", \"edit\", or \"delete\" on your keyboard." << endl;
string purpose;
cin >> purpose;
//Checks if user is adding
if (purpose == ("add")){
//add methods for adding
cout<<""<<endl;
cout << "Would you like to add a quote, affirmation, action, or journal entry?" << endl;
cout << "Enter \"quote\", \"affirm\", \"act\", OR \"journal\" on your keyboard." << endl;
cin >> purpose;
//inputs the user's quote, affirmation, action, or journal entry
//based on user input
if (purpose == ("quote")){
//add quote
cout << "Enter your new quote: " << endl;
string input;
cin >> input;
quotes.push_back(input);
}
else if (purpose == ("affirm")){
//add affirmation
cout << "Enter your new affirmation: " << endl;
string input;
cin >> input;
affirmation.push_back(input);
}
else if (purpose == ("act")){
//add action
cout << "Enter your new action: " << endl;
string input;
cin >> input;
action.push_back(input);
}
else if (purpose == ("journal")){
//add journal entry
cout << "Enter your new journal entry: " << endl;
string input;
cin >> input;
journal.push_back(input);
}
cout<<""<<endl;
checkUserPurpose(outpoint);
return;
}
//Checks if user is reading
else if (purpose == ("read")){
cout<<""<<endl;
cout<<"\n"<<"--QUOTES--"<<"\n";
//quotes sent to output file
if (!quotes.empty()){
for (int i=0; i<quotes.size();i++){
cout<<"("<<i+1<<") "<<quotes.at(i)<<"\n";
}
}
cout<<""<<endl;
cout<<"\n"<<"--AFFIRMATIONS--"<<"\n";
//affirmations sent to output file
if (!affirmation.empty()){
for (int i=0; i<affirmation.size();i++){
cout<<"("<<i+1<<") "<<affirmation.at(i)<<"\n";
}
}
cout<<""<<endl;
cout<<"\n"<<"--ACTIONS--"<<"\n";
//actions sent to output file
if (!action.empty()){
for (int i=0; i<action.size();i++){
cout<<"("<<i+1<<") "<<action.at(i)<<"\n";
}
}
cout<<""<<endl;
cout<<"\n"<<"--JOURNAL ENTRIES--"<<"\n";
//journal entries sent to output file
if (!journal.empty()){
for (int i=0; i<journal.size();i++){
cout<<"("<<i+1<<") "<<journal.at(i)<<"\n";
}
}
output<<""<<endl;
checkUserPurpose(outpoint);
}
//Checks if user is editing
else if (purpose == ("edit")){
cout<<"Which category's entry would you like to edit?"<<endl;
cout<<"Enter \"quote\", \"affirm\", \"act\", OR \"journal\" on your keyboard." << endl;
vector<string> designatedVector;
string entry;
cin >> entry;
bool editQuotes=false;
bool editAffirmations=false;
bool editActions=false;
bool editJournalEntries=false;
if(entry==("quote")){
designatedVector=quotes;
editQuotes=true;
}
else if(entry==("affirm")){
designatedVector=affirmation;
editAffirmations=true;
}
else if(entry==("act")){
designatedVector=action;
editActions=true;
}
else if(entry==("journal")){
designatedVector=journal;
editJournalEntries=true;
}
else if(entry==("quit")){
quitting(outpoint,entry);
return; //exits program
}
else{
//recursive call if user input isn't valid
cout<<"Sorry, I didn't understand that."<<endl;
checkUserPurpose(outpoint);
}
if (designatedVector.empty()){
cout<<"Sorry, we can't edit an empty entry."<<endl;
checkUserPurpose(outpoint);
}
cout<<"Enter the number of the entry you would like to change."<<endl;
cin>>entry;
//check that user put in an entry of only digits and a valid index
if(entry.find_first_not_of("0123456789") == std::string::npos
&& stoi(entry)-1>=0 && stoi(entry)-1<designatedVector.size()){
int indexOfEdit=stoi(entry)-1;
cout<<"Let's get that changed for you."<<endl;
cout<<""<<endl;
cout<<"The entry was previously: "<<designatedVector.at(indexOfEdit)<<endl;
cout<<""<<endl;
cout<<"What would you like the entry to be replaced with?"<<endl;
cout <<"Enter the desired entry."<<endl;
cin>>entry;
//replace the value that must be edited
designatedVector.at(indexOfEdit)= entry; //insertion/replacement
cout<<"Thank you, you're all good!"<<endl;
//reset the designatedVector to it's corresponding category
if(editQuotes==true){
quotes=designatedVector;
}
else if(editAffirmations==true){
affirmation=designatedVector;
}
else if(editActions==true){
action=designatedVector;
}
else if(editJournalEntries==true){
journal=designatedVector;
}
checkUserPurpose(outpoint);
}
else if(entry==("quit")){
quitting(outpoint,entry);
return; //exits program
}
else{
cout<<"Sorry, no entry exists with this number."<<endl;
checkUserPurpose(outpoint);
}
}
//Checks if user is deleting
else if (purpose == ("delete")){
cout<<"Which category's entry would you like to delete?"<<endl;
cout<<"Enter \"quote\", \"affirm\", \"act\", OR \"journal\" on your keyboard." << endl;
vector<string> designatedVector;
string entry;
cin >> entry;
bool deleteQuotes=false;
bool deleteAffirmations=false;
bool deleteActions=false;
bool deleteJournalEntries=false;
if(entry==("quote")){
designatedVector=quotes;
deleteQuotes=true;
}
else if(entry==("affirm")){
designatedVector=affirmation;
deleteAffirmations=true;
}
else if(entry==("act")){
designatedVector=action;
deleteActions=true;
}
else if(entry==("journal")){
designatedVector=journal;
deleteJournalEntries=true;
}
else if(entry==("quit")){
quitting(outpoint,entry);
return; //exits program
}
else{
//recursive call if user input isn't valid
cout<<"Sorry, I didn't understand that."<<endl;
checkUserPurpose(outpoint);
}
if (designatedVector.empty()){
cout<<"Sorry, we can't delete an empty entry."<<endl;
checkUserPurpose(outpoint);
}
cout<<"Enter the number of the entry you would like to delete."<<endl;
cin>>entry;
//check that user put in an entry of only digits and a valid index
if(entry.find_first_not_of("0123456789") == std::string::npos
&& stoi(entry)-1>=0 && stoi(entry)-1<designatedVector.size()){
int indexOfEdit=stoi(entry)-1;
cout<<"Let's get that deleted for you."<<endl;
designatedVector.erase (designatedVector.begin()+ indexOfEdit);
cout<<"The entry has successfully deleted. Take a deep breath to welcome a fresh start."<<endl;
//reset the designatedVector to it's corresponding category
if(deleteQuotes==true){
quotes=designatedVector;
}
else if(deleteAffirmations==true){
affirmation=designatedVector;
}
else if(deleteActions==true){
action=designatedVector;
}
else if(deleteJournalEntries==true){
journal=designatedVector;
}
checkUserPurpose(outpoint);
}
else if(entry==("quit")){
quitting(outpoint,entry);
}
else{
cout<<"Sorry, no entry exists with this number."<<endl;
checkUserPurpose(outpoint);
}
}
else if (purpose==("quit")){
quitting(outpoint,purpose);
return; //exits program
}
else{
//recursive call if user input isn't valid
cout<<"Sorry, I didn't understand that."<<endl;
checkUserPurpose(outpoint);
}
}
void quitting(string out, string userInput){
ofstream output {out, ios::app};
if(userInput==("quit")){
cout<<""<<endl;
cout<<"You should see your Selfish Notes in your output file."<<endl;
cout<<"Bye for now, hope to see you soon! Take care of yourself."<<endl;
output<<""<<endl;
output<<"\n"<<"--QUOTES--"<<"\n";
//quotes sent to output file
if (!quotes.empty()){
for (int i=0; i<quotes.size();i++){
output<<"("<<i+1<<") "<<quotes.at(i)<<"\n";
}
}
output<<""<<endl;
output<<"\n"<<"--AFFIRMATIONS--"<<"\n";
//affirmations sent to output file
if (!affirmation.empty()){
for (int i=0; i<affirmation.size();i++){
output<<"("<<i+1<<") "<<affirmation.at(i)<<"\n";
}
}
output<<""<<endl;
output<<"\n"<<"--ACTIONS--"<<"\n";
//actions sent to output file
if (!action.empty()){
for (int i=0; i<action.size();i++){
output<<"("<<i+1<<") "<<action.at(i)<<"\n";
}
}
output<<""<<endl;
output<<"\n"<<"--JOURNAL ENTRIES--"<<"\n";
//journal entries sent to output file
if (!journal.empty()){
for (int i=0; i<journal.size();i++){
output<<"("<<i+1<<") "<<journal.at(i)<<"\n";
}
}
output<<""<<endl;
}
}
|
//////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#ifndef NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_VMX_SPU_GSL_SF_BESSEL_K1_HPP_INCLUDED
#define NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_VMX_SPU_GSL_SF_BESSEL_K1_HPP_INCLUDED
#include <nt2/toolbox/gsl_specfun/function/simd/vmx/common/gsl_sf_bessel_K1.hpp>
#endif
|
; A053738: If k is in sequence then 2*k and 2*k+1 are not (and 1 is in the sequence); numbers with an odd number of digits in binary.
; 1,4,5,6,7,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270
mov $2,1
lpb $0
sub $0,$2
mul $2,4
lpe
add $0,$2
|
Sound46_RingSpill_Header:
smpsHeaderStartSong 2
smpsHeaderVoice Sound_Ring_Voices
smpsHeaderTempoSFX $01
smpsHeaderChanSFX $02
smpsHeaderSFXChannel cFM4, Sound46_RingSpill_FM4, $00, $05
smpsHeaderSFXChannel cFM5, Sound46_RingSpill_FM5, $00, $08
; FM4 Data
Sound46_RingSpill_FM4:
smpsSetvoice $00
dc.b nA5, $02, $05, $05, $05, $05, $05, $05, $3A
smpsStop
; FM5 Data
Sound46_RingSpill_FM5:
smpsSetvoice $00
dc.b nRst, $02, nG5, $02, $05, $15, $02, $05, $32
smpsStop
|
; A025923: Expansion of 1/((1-x^9)*(1-x^10)*(1-x^11)).
; 1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,2,1,1,0,0,0,0,1,1,2,2,2,1,1,0,0,1,1,2,2,3,2,2,1,1,1,1,2,2,3,3,3,2,2,2,2,2,2,3,3,4,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4
mov $3,$0
mov $5,2
lpb $5
mov $0,$3
sub $5,1
add $0,$5
trn $0,1
seq $0,29132 ; Expansion of 1/((1-x)(1-x^9)(1-x^10)(1-x^11)).
mov $2,$5
mul $2,$0
add $1,$2
mov $4,$0
lpe
min $3,1
mul $3,$4
sub $1,$3
mov $0,$1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0xe93b, %rsi
lea addresses_WT_ht+0x10fef, %rdi
nop
nop
nop
nop
nop
cmp %rbx, %rbx
mov $37, %rcx
rep movsw
nop
nop
xor $23968, %r9
lea addresses_A_ht+0x125ba, %r14
clflush (%r14)
nop
nop
nop
xor %r12, %r12
mov $0x6162636465666768, %rcx
movq %rcx, %xmm6
and $0xffffffffffffffc0, %r14
movaps %xmm6, (%r14)
nop
nop
inc %r12
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r14
push %r15
push %rbp
push %rcx
push %rsi
// Store
lea addresses_UC+0x1afb0, %r13
nop
nop
nop
nop
nop
cmp %r10, %r10
mov $0x5152535455565758, %rsi
movq %rsi, %xmm0
movups %xmm0, (%r13)
nop
nop
sub $62713, %rsi
// Store
lea addresses_PSE+0xcce3, %rcx
nop
nop
nop
dec %rbp
movw $0x5152, (%rcx)
dec %r15
// Faulty Load
lea addresses_UC+0x413b, %rsi
nop
nop
nop
add %r13, %r13
movb (%rsi), %r14b
lea oracles, %rcx
and $0xff, %r14
shlq $12, %r14
mov (%rcx,%r14,1), %r14
pop %rsi
pop %rcx
pop %rbp
pop %r15
pop %r14
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 16, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': False}}
{'00': 17484}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
_init: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
char *argv[] = { "sh", 0 };
int
main(void)
{
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
7: ff 71 fc pushl -0x4(%ecx)
a: 55 push %ebp
b: 89 e5 mov %esp,%ebp
d: 53 push %ebx
e: 51 push %ecx
int pid, wpid;
if(open("console", O_RDWR) < 0){
f: 83 ec 08 sub $0x8,%esp
12: 6a 02 push $0x2
14: 68 e8 07 00 00 push $0x7e8
19: e8 64 03 00 00 call 382 <open>
1e: 83 c4 10 add $0x10,%esp
21: 85 c0 test %eax,%eax
23: 0f 88 9f 00 00 00 js c8 <main+0xc8>
mknod("console", 1, 1);
open("console", O_RDWR);
}
dup(0); // stdout
29: 83 ec 0c sub $0xc,%esp
2c: 6a 00 push $0x0
2e: e8 87 03 00 00 call 3ba <dup>
dup(0); // stderr
33: c7 04 24 00 00 00 00 movl $0x0,(%esp)
3a: e8 7b 03 00 00 call 3ba <dup>
3f: 83 c4 10 add $0x10,%esp
42: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
for(;;){
printf(1, "init: starting sh\nHamed,Mehrab,Ali\n");
48: 83 ec 08 sub $0x8,%esp
4b: 68 28 08 00 00 push $0x828
50: 6a 01 push $0x1
52: e8 39 04 00 00 call 490 <printf>
pid = fork();
57: e8 de 02 00 00 call 33a <fork>
if(pid < 0){
5c: 83 c4 10 add $0x10,%esp
5f: 85 c0 test %eax,%eax
pid = fork();
61: 89 c3 mov %eax,%ebx
if(pid < 0){
63: 78 2c js 91 <main+0x91>
printf(1, "init: fork failed\n");
exit();
}
if(pid == 0){
65: 74 3d je a4 <main+0xa4>
67: 89 f6 mov %esi,%esi
69: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
exec("sh", argv);
printf(1, "init: exec sh failed\n");
exit();
}
while((wpid=wait()) >= 0 && wpid != pid)
70: e8 d5 02 00 00 call 34a <wait>
75: 85 c0 test %eax,%eax
77: 78 cf js 48 <main+0x48>
79: 39 c3 cmp %eax,%ebx
7b: 74 cb je 48 <main+0x48>
printf(1, "zombie!\n");
7d: 83 ec 08 sub $0x8,%esp
80: 68 1c 08 00 00 push $0x81c
85: 6a 01 push $0x1
87: e8 04 04 00 00 call 490 <printf>
8c: 83 c4 10 add $0x10,%esp
8f: eb df jmp 70 <main+0x70>
printf(1, "init: fork failed\n");
91: 53 push %ebx
92: 53 push %ebx
93: 68 f0 07 00 00 push $0x7f0
98: 6a 01 push $0x1
9a: e8 f1 03 00 00 call 490 <printf>
exit();
9f: e8 9e 02 00 00 call 342 <exit>
exec("sh", argv);
a4: 50 push %eax
a5: 50 push %eax
a6: 68 fc 0a 00 00 push $0xafc
ab: 68 03 08 00 00 push $0x803
b0: e8 c5 02 00 00 call 37a <exec>
printf(1, "init: exec sh failed\n");
b5: 5a pop %edx
b6: 59 pop %ecx
b7: 68 06 08 00 00 push $0x806
bc: 6a 01 push $0x1
be: e8 cd 03 00 00 call 490 <printf>
exit();
c3: e8 7a 02 00 00 call 342 <exit>
mknod("console", 1, 1);
c8: 50 push %eax
c9: 6a 01 push $0x1
cb: 6a 01 push $0x1
cd: 68 e8 07 00 00 push $0x7e8
d2: e8 b3 02 00 00 call 38a <mknod>
open("console", O_RDWR);
d7: 58 pop %eax
d8: 5a pop %edx
d9: 6a 02 push $0x2
db: 68 e8 07 00 00 push $0x7e8
e0: e8 9d 02 00 00 call 382 <open>
e5: 83 c4 10 add $0x10,%esp
e8: e9 3c ff ff ff jmp 29 <main+0x29>
ed: 66 90 xchg %ax,%ax
ef: 90 nop
000000f0 <strcpy>:
f0: 55 push %ebp
f1: 89 e5 mov %esp,%ebp
f3: 53 push %ebx
f4: 8b 45 08 mov 0x8(%ebp),%eax
f7: 8b 4d 0c mov 0xc(%ebp),%ecx
fa: 89 c2 mov %eax,%edx
fc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
100: 83 c1 01 add $0x1,%ecx
103: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
107: 83 c2 01 add $0x1,%edx
10a: 84 db test %bl,%bl
10c: 88 5a ff mov %bl,-0x1(%edx)
10f: 75 ef jne 100 <strcpy+0x10>
111: 5b pop %ebx
112: 5d pop %ebp
113: c3 ret
114: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
11a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000120 <strcmp>:
120: 55 push %ebp
121: 89 e5 mov %esp,%ebp
123: 53 push %ebx
124: 8b 55 08 mov 0x8(%ebp),%edx
127: 8b 4d 0c mov 0xc(%ebp),%ecx
12a: 0f b6 02 movzbl (%edx),%eax
12d: 0f b6 19 movzbl (%ecx),%ebx
130: 84 c0 test %al,%al
132: 75 1c jne 150 <strcmp+0x30>
134: eb 2a jmp 160 <strcmp+0x40>
136: 8d 76 00 lea 0x0(%esi),%esi
139: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
140: 83 c2 01 add $0x1,%edx
143: 0f b6 02 movzbl (%edx),%eax
146: 83 c1 01 add $0x1,%ecx
149: 0f b6 19 movzbl (%ecx),%ebx
14c: 84 c0 test %al,%al
14e: 74 10 je 160 <strcmp+0x40>
150: 38 d8 cmp %bl,%al
152: 74 ec je 140 <strcmp+0x20>
154: 29 d8 sub %ebx,%eax
156: 5b pop %ebx
157: 5d pop %ebp
158: c3 ret
159: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
160: 31 c0 xor %eax,%eax
162: 29 d8 sub %ebx,%eax
164: 5b pop %ebx
165: 5d pop %ebp
166: c3 ret
167: 89 f6 mov %esi,%esi
169: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000170 <strlen>:
170: 55 push %ebp
171: 89 e5 mov %esp,%ebp
173: 8b 4d 08 mov 0x8(%ebp),%ecx
176: 80 39 00 cmpb $0x0,(%ecx)
179: 74 15 je 190 <strlen+0x20>
17b: 31 d2 xor %edx,%edx
17d: 8d 76 00 lea 0x0(%esi),%esi
180: 83 c2 01 add $0x1,%edx
183: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
187: 89 d0 mov %edx,%eax
189: 75 f5 jne 180 <strlen+0x10>
18b: 5d pop %ebp
18c: c3 ret
18d: 8d 76 00 lea 0x0(%esi),%esi
190: 31 c0 xor %eax,%eax
192: 5d pop %ebp
193: c3 ret
194: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
19a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
000001a0 <memset>:
1a0: 55 push %ebp
1a1: 89 e5 mov %esp,%ebp
1a3: 57 push %edi
1a4: 8b 55 08 mov 0x8(%ebp),%edx
1a7: 8b 4d 10 mov 0x10(%ebp),%ecx
1aa: 8b 45 0c mov 0xc(%ebp),%eax
1ad: 89 d7 mov %edx,%edi
1af: fc cld
1b0: f3 aa rep stos %al,%es:(%edi)
1b2: 89 d0 mov %edx,%eax
1b4: 5f pop %edi
1b5: 5d pop %ebp
1b6: c3 ret
1b7: 89 f6 mov %esi,%esi
1b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000001c0 <strchr>:
1c0: 55 push %ebp
1c1: 89 e5 mov %esp,%ebp
1c3: 53 push %ebx
1c4: 8b 45 08 mov 0x8(%ebp),%eax
1c7: 8b 5d 0c mov 0xc(%ebp),%ebx
1ca: 0f b6 10 movzbl (%eax),%edx
1cd: 84 d2 test %dl,%dl
1cf: 74 1d je 1ee <strchr+0x2e>
1d1: 38 d3 cmp %dl,%bl
1d3: 89 d9 mov %ebx,%ecx
1d5: 75 0d jne 1e4 <strchr+0x24>
1d7: eb 17 jmp 1f0 <strchr+0x30>
1d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
1e0: 38 ca cmp %cl,%dl
1e2: 74 0c je 1f0 <strchr+0x30>
1e4: 83 c0 01 add $0x1,%eax
1e7: 0f b6 10 movzbl (%eax),%edx
1ea: 84 d2 test %dl,%dl
1ec: 75 f2 jne 1e0 <strchr+0x20>
1ee: 31 c0 xor %eax,%eax
1f0: 5b pop %ebx
1f1: 5d pop %ebp
1f2: c3 ret
1f3: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
1f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000200 <gets>:
200: 55 push %ebp
201: 89 e5 mov %esp,%ebp
203: 57 push %edi
204: 56 push %esi
205: 53 push %ebx
206: 31 f6 xor %esi,%esi
208: 89 f3 mov %esi,%ebx
20a: 83 ec 1c sub $0x1c,%esp
20d: 8b 7d 08 mov 0x8(%ebp),%edi
210: eb 2f jmp 241 <gets+0x41>
212: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
218: 8d 45 e7 lea -0x19(%ebp),%eax
21b: 83 ec 04 sub $0x4,%esp
21e: 6a 01 push $0x1
220: 50 push %eax
221: 6a 00 push $0x0
223: e8 32 01 00 00 call 35a <read>
228: 83 c4 10 add $0x10,%esp
22b: 85 c0 test %eax,%eax
22d: 7e 1c jle 24b <gets+0x4b>
22f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
233: 83 c7 01 add $0x1,%edi
236: 88 47 ff mov %al,-0x1(%edi)
239: 3c 0a cmp $0xa,%al
23b: 74 23 je 260 <gets+0x60>
23d: 3c 0d cmp $0xd,%al
23f: 74 1f je 260 <gets+0x60>
241: 83 c3 01 add $0x1,%ebx
244: 3b 5d 0c cmp 0xc(%ebp),%ebx
247: 89 fe mov %edi,%esi
249: 7c cd jl 218 <gets+0x18>
24b: 89 f3 mov %esi,%ebx
24d: 8b 45 08 mov 0x8(%ebp),%eax
250: c6 03 00 movb $0x0,(%ebx)
253: 8d 65 f4 lea -0xc(%ebp),%esp
256: 5b pop %ebx
257: 5e pop %esi
258: 5f pop %edi
259: 5d pop %ebp
25a: c3 ret
25b: 90 nop
25c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
260: 8b 75 08 mov 0x8(%ebp),%esi
263: 8b 45 08 mov 0x8(%ebp),%eax
266: 01 de add %ebx,%esi
268: 89 f3 mov %esi,%ebx
26a: c6 03 00 movb $0x0,(%ebx)
26d: 8d 65 f4 lea -0xc(%ebp),%esp
270: 5b pop %ebx
271: 5e pop %esi
272: 5f pop %edi
273: 5d pop %ebp
274: c3 ret
275: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
279: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000280 <stat>:
280: 55 push %ebp
281: 89 e5 mov %esp,%ebp
283: 56 push %esi
284: 53 push %ebx
285: 83 ec 08 sub $0x8,%esp
288: 6a 00 push $0x0
28a: ff 75 08 pushl 0x8(%ebp)
28d: e8 f0 00 00 00 call 382 <open>
292: 83 c4 10 add $0x10,%esp
295: 85 c0 test %eax,%eax
297: 78 27 js 2c0 <stat+0x40>
299: 83 ec 08 sub $0x8,%esp
29c: ff 75 0c pushl 0xc(%ebp)
29f: 89 c3 mov %eax,%ebx
2a1: 50 push %eax
2a2: e8 f3 00 00 00 call 39a <fstat>
2a7: 89 1c 24 mov %ebx,(%esp)
2aa: 89 c6 mov %eax,%esi
2ac: e8 b9 00 00 00 call 36a <close>
2b1: 83 c4 10 add $0x10,%esp
2b4: 8d 65 f8 lea -0x8(%ebp),%esp
2b7: 89 f0 mov %esi,%eax
2b9: 5b pop %ebx
2ba: 5e pop %esi
2bb: 5d pop %ebp
2bc: c3 ret
2bd: 8d 76 00 lea 0x0(%esi),%esi
2c0: be ff ff ff ff mov $0xffffffff,%esi
2c5: eb ed jmp 2b4 <stat+0x34>
2c7: 89 f6 mov %esi,%esi
2c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000002d0 <atoi>:
2d0: 55 push %ebp
2d1: 89 e5 mov %esp,%ebp
2d3: 53 push %ebx
2d4: 8b 4d 08 mov 0x8(%ebp),%ecx
2d7: 0f be 11 movsbl (%ecx),%edx
2da: 8d 42 d0 lea -0x30(%edx),%eax
2dd: 3c 09 cmp $0x9,%al
2df: b8 00 00 00 00 mov $0x0,%eax
2e4: 77 1f ja 305 <atoi+0x35>
2e6: 8d 76 00 lea 0x0(%esi),%esi
2e9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
2f0: 8d 04 80 lea (%eax,%eax,4),%eax
2f3: 83 c1 01 add $0x1,%ecx
2f6: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
2fa: 0f be 11 movsbl (%ecx),%edx
2fd: 8d 5a d0 lea -0x30(%edx),%ebx
300: 80 fb 09 cmp $0x9,%bl
303: 76 eb jbe 2f0 <atoi+0x20>
305: 5b pop %ebx
306: 5d pop %ebp
307: c3 ret
308: 90 nop
309: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000310 <memmove>:
310: 55 push %ebp
311: 89 e5 mov %esp,%ebp
313: 56 push %esi
314: 53 push %ebx
315: 8b 5d 10 mov 0x10(%ebp),%ebx
318: 8b 45 08 mov 0x8(%ebp),%eax
31b: 8b 75 0c mov 0xc(%ebp),%esi
31e: 85 db test %ebx,%ebx
320: 7e 14 jle 336 <memmove+0x26>
322: 31 d2 xor %edx,%edx
324: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
328: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
32c: 88 0c 10 mov %cl,(%eax,%edx,1)
32f: 83 c2 01 add $0x1,%edx
332: 39 d3 cmp %edx,%ebx
334: 75 f2 jne 328 <memmove+0x18>
336: 5b pop %ebx
337: 5e pop %esi
338: 5d pop %ebp
339: c3 ret
0000033a <fork>:
33a: b8 01 00 00 00 mov $0x1,%eax
33f: cd 40 int $0x40
341: c3 ret
00000342 <exit>:
342: b8 02 00 00 00 mov $0x2,%eax
347: cd 40 int $0x40
349: c3 ret
0000034a <wait>:
34a: b8 03 00 00 00 mov $0x3,%eax
34f: cd 40 int $0x40
351: c3 ret
00000352 <pipe>:
352: b8 04 00 00 00 mov $0x4,%eax
357: cd 40 int $0x40
359: c3 ret
0000035a <read>:
35a: b8 05 00 00 00 mov $0x5,%eax
35f: cd 40 int $0x40
361: c3 ret
00000362 <write>:
362: b8 10 00 00 00 mov $0x10,%eax
367: cd 40 int $0x40
369: c3 ret
0000036a <close>:
36a: b8 15 00 00 00 mov $0x15,%eax
36f: cd 40 int $0x40
371: c3 ret
00000372 <kill>:
372: b8 06 00 00 00 mov $0x6,%eax
377: cd 40 int $0x40
379: c3 ret
0000037a <exec>:
37a: b8 07 00 00 00 mov $0x7,%eax
37f: cd 40 int $0x40
381: c3 ret
00000382 <open>:
382: b8 0f 00 00 00 mov $0xf,%eax
387: cd 40 int $0x40
389: c3 ret
0000038a <mknod>:
38a: b8 11 00 00 00 mov $0x11,%eax
38f: cd 40 int $0x40
391: c3 ret
00000392 <unlink>:
392: b8 12 00 00 00 mov $0x12,%eax
397: cd 40 int $0x40
399: c3 ret
0000039a <fstat>:
39a: b8 08 00 00 00 mov $0x8,%eax
39f: cd 40 int $0x40
3a1: c3 ret
000003a2 <link>:
3a2: b8 13 00 00 00 mov $0x13,%eax
3a7: cd 40 int $0x40
3a9: c3 ret
000003aa <mkdir>:
3aa: b8 14 00 00 00 mov $0x14,%eax
3af: cd 40 int $0x40
3b1: c3 ret
000003b2 <chdir>:
3b2: b8 09 00 00 00 mov $0x9,%eax
3b7: cd 40 int $0x40
3b9: c3 ret
000003ba <dup>:
3ba: b8 0a 00 00 00 mov $0xa,%eax
3bf: cd 40 int $0x40
3c1: c3 ret
000003c2 <getpid>:
3c2: b8 0b 00 00 00 mov $0xb,%eax
3c7: cd 40 int $0x40
3c9: c3 ret
000003ca <sbrk>:
3ca: b8 0c 00 00 00 mov $0xc,%eax
3cf: cd 40 int $0x40
3d1: c3 ret
000003d2 <sleep>:
3d2: b8 0d 00 00 00 mov $0xd,%eax
3d7: cd 40 int $0x40
3d9: c3 ret
000003da <uptime>:
3da: b8 0e 00 00 00 mov $0xe,%eax
3df: cd 40 int $0x40
3e1: c3 ret
3e2: 66 90 xchg %ax,%ax
3e4: 66 90 xchg %ax,%ax
3e6: 66 90 xchg %ax,%ax
3e8: 66 90 xchg %ax,%ax
3ea: 66 90 xchg %ax,%ax
3ec: 66 90 xchg %ax,%ax
3ee: 66 90 xchg %ax,%ax
000003f0 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
3f0: 55 push %ebp
3f1: 89 e5 mov %esp,%ebp
3f3: 57 push %edi
3f4: 56 push %esi
3f5: 53 push %ebx
3f6: 83 ec 3c sub $0x3c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
3f9: 85 d2 test %edx,%edx
{
3fb: 89 45 c0 mov %eax,-0x40(%ebp)
neg = 1;
x = -xx;
3fe: 89 d0 mov %edx,%eax
if(sgn && xx < 0){
400: 79 76 jns 478 <printint+0x88>
402: f6 45 08 01 testb $0x1,0x8(%ebp)
406: 74 70 je 478 <printint+0x88>
x = -xx;
408: f7 d8 neg %eax
neg = 1;
40a: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
} else {
x = xx;
}
i = 0;
411: 31 f6 xor %esi,%esi
413: 8d 5d d7 lea -0x29(%ebp),%ebx
416: eb 0a jmp 422 <printint+0x32>
418: 90 nop
419: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
do{
buf[i++] = digits[x % base];
420: 89 fe mov %edi,%esi
422: 31 d2 xor %edx,%edx
424: 8d 7e 01 lea 0x1(%esi),%edi
427: f7 f1 div %ecx
429: 0f b6 92 54 08 00 00 movzbl 0x854(%edx),%edx
}while((x /= base) != 0);
430: 85 c0 test %eax,%eax
buf[i++] = digits[x % base];
432: 88 14 3b mov %dl,(%ebx,%edi,1)
}while((x /= base) != 0);
435: 75 e9 jne 420 <printint+0x30>
if(neg)
437: 8b 45 c4 mov -0x3c(%ebp),%eax
43a: 85 c0 test %eax,%eax
43c: 74 08 je 446 <printint+0x56>
buf[i++] = '-';
43e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1)
443: 8d 7e 02 lea 0x2(%esi),%edi
446: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi
44a: 8b 7d c0 mov -0x40(%ebp),%edi
44d: 8d 76 00 lea 0x0(%esi),%esi
450: 0f b6 06 movzbl (%esi),%eax
write(fd, &c, 1);
453: 83 ec 04 sub $0x4,%esp
456: 83 ee 01 sub $0x1,%esi
459: 6a 01 push $0x1
45b: 53 push %ebx
45c: 57 push %edi
45d: 88 45 d7 mov %al,-0x29(%ebp)
460: e8 fd fe ff ff call 362 <write>
while(--i >= 0)
465: 83 c4 10 add $0x10,%esp
468: 39 de cmp %ebx,%esi
46a: 75 e4 jne 450 <printint+0x60>
putc(fd, buf[i]);
}
46c: 8d 65 f4 lea -0xc(%ebp),%esp
46f: 5b pop %ebx
470: 5e pop %esi
471: 5f pop %edi
472: 5d pop %ebp
473: c3 ret
474: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
478: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
47f: eb 90 jmp 411 <printint+0x21>
481: eb 0d jmp 490 <printf>
483: 90 nop
484: 90 nop
485: 90 nop
486: 90 nop
487: 90 nop
488: 90 nop
489: 90 nop
48a: 90 nop
48b: 90 nop
48c: 90 nop
48d: 90 nop
48e: 90 nop
48f: 90 nop
00000490 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
490: 55 push %ebp
491: 89 e5 mov %esp,%ebp
493: 57 push %edi
494: 56 push %esi
495: 53 push %ebx
496: 83 ec 2c sub $0x2c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
499: 8b 75 0c mov 0xc(%ebp),%esi
49c: 0f b6 1e movzbl (%esi),%ebx
49f: 84 db test %bl,%bl
4a1: 0f 84 b3 00 00 00 je 55a <printf+0xca>
ap = (uint*)(void*)&fmt + 1;
4a7: 8d 45 10 lea 0x10(%ebp),%eax
4aa: 83 c6 01 add $0x1,%esi
state = 0;
4ad: 31 ff xor %edi,%edi
ap = (uint*)(void*)&fmt + 1;
4af: 89 45 d4 mov %eax,-0x2c(%ebp)
4b2: eb 2f jmp 4e3 <printf+0x53>
4b4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
4b8: 83 f8 25 cmp $0x25,%eax
4bb: 0f 84 a7 00 00 00 je 568 <printf+0xd8>
write(fd, &c, 1);
4c1: 8d 45 e2 lea -0x1e(%ebp),%eax
4c4: 83 ec 04 sub $0x4,%esp
4c7: 88 5d e2 mov %bl,-0x1e(%ebp)
4ca: 6a 01 push $0x1
4cc: 50 push %eax
4cd: ff 75 08 pushl 0x8(%ebp)
4d0: e8 8d fe ff ff call 362 <write>
4d5: 83 c4 10 add $0x10,%esp
4d8: 83 c6 01 add $0x1,%esi
for(i = 0; fmt[i]; i++){
4db: 0f b6 5e ff movzbl -0x1(%esi),%ebx
4df: 84 db test %bl,%bl
4e1: 74 77 je 55a <printf+0xca>
if(state == 0){
4e3: 85 ff test %edi,%edi
c = fmt[i] & 0xff;
4e5: 0f be cb movsbl %bl,%ecx
4e8: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
4eb: 74 cb je 4b8 <printf+0x28>
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
4ed: 83 ff 25 cmp $0x25,%edi
4f0: 75 e6 jne 4d8 <printf+0x48>
if(c == 'd'){
4f2: 83 f8 64 cmp $0x64,%eax
4f5: 0f 84 05 01 00 00 je 600 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
4fb: 81 e1 f7 00 00 00 and $0xf7,%ecx
501: 83 f9 70 cmp $0x70,%ecx
504: 74 72 je 578 <printf+0xe8>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
506: 83 f8 73 cmp $0x73,%eax
509: 0f 84 99 00 00 00 je 5a8 <printf+0x118>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
50f: 83 f8 63 cmp $0x63,%eax
512: 0f 84 08 01 00 00 je 620 <printf+0x190>
putc(fd, *ap);
ap++;
} else if(c == '%'){
518: 83 f8 25 cmp $0x25,%eax
51b: 0f 84 ef 00 00 00 je 610 <printf+0x180>
write(fd, &c, 1);
521: 8d 45 e7 lea -0x19(%ebp),%eax
524: 83 ec 04 sub $0x4,%esp
527: c6 45 e7 25 movb $0x25,-0x19(%ebp)
52b: 6a 01 push $0x1
52d: 50 push %eax
52e: ff 75 08 pushl 0x8(%ebp)
531: e8 2c fe ff ff call 362 <write>
536: 83 c4 0c add $0xc,%esp
539: 8d 45 e6 lea -0x1a(%ebp),%eax
53c: 88 5d e6 mov %bl,-0x1a(%ebp)
53f: 6a 01 push $0x1
541: 50 push %eax
542: ff 75 08 pushl 0x8(%ebp)
545: 83 c6 01 add $0x1,%esi
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
548: 31 ff xor %edi,%edi
write(fd, &c, 1);
54a: e8 13 fe ff ff call 362 <write>
for(i = 0; fmt[i]; i++){
54f: 0f b6 5e ff movzbl -0x1(%esi),%ebx
write(fd, &c, 1);
553: 83 c4 10 add $0x10,%esp
for(i = 0; fmt[i]; i++){
556: 84 db test %bl,%bl
558: 75 89 jne 4e3 <printf+0x53>
}
}
}
55a: 8d 65 f4 lea -0xc(%ebp),%esp
55d: 5b pop %ebx
55e: 5e pop %esi
55f: 5f pop %edi
560: 5d pop %ebp
561: c3 ret
562: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
state = '%';
568: bf 25 00 00 00 mov $0x25,%edi
56d: e9 66 ff ff ff jmp 4d8 <printf+0x48>
572: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printint(fd, *ap, 16, 0);
578: 83 ec 0c sub $0xc,%esp
57b: b9 10 00 00 00 mov $0x10,%ecx
580: 6a 00 push $0x0
582: 8b 7d d4 mov -0x2c(%ebp),%edi
585: 8b 45 08 mov 0x8(%ebp),%eax
588: 8b 17 mov (%edi),%edx
58a: e8 61 fe ff ff call 3f0 <printint>
ap++;
58f: 89 f8 mov %edi,%eax
591: 83 c4 10 add $0x10,%esp
state = 0;
594: 31 ff xor %edi,%edi
ap++;
596: 83 c0 04 add $0x4,%eax
599: 89 45 d4 mov %eax,-0x2c(%ebp)
59c: e9 37 ff ff ff jmp 4d8 <printf+0x48>
5a1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
s = (char*)*ap;
5a8: 8b 45 d4 mov -0x2c(%ebp),%eax
5ab: 8b 08 mov (%eax),%ecx
ap++;
5ad: 83 c0 04 add $0x4,%eax
5b0: 89 45 d4 mov %eax,-0x2c(%ebp)
if(s == 0)
5b3: 85 c9 test %ecx,%ecx
5b5: 0f 84 8e 00 00 00 je 649 <printf+0x1b9>
while(*s != 0){
5bb: 0f b6 01 movzbl (%ecx),%eax
state = 0;
5be: 31 ff xor %edi,%edi
s = (char*)*ap;
5c0: 89 cb mov %ecx,%ebx
while(*s != 0){
5c2: 84 c0 test %al,%al
5c4: 0f 84 0e ff ff ff je 4d8 <printf+0x48>
5ca: 89 75 d0 mov %esi,-0x30(%ebp)
5cd: 89 de mov %ebx,%esi
5cf: 8b 5d 08 mov 0x8(%ebp),%ebx
5d2: 8d 7d e3 lea -0x1d(%ebp),%edi
5d5: 8d 76 00 lea 0x0(%esi),%esi
write(fd, &c, 1);
5d8: 83 ec 04 sub $0x4,%esp
s++;
5db: 83 c6 01 add $0x1,%esi
5de: 88 45 e3 mov %al,-0x1d(%ebp)
write(fd, &c, 1);
5e1: 6a 01 push $0x1
5e3: 57 push %edi
5e4: 53 push %ebx
5e5: e8 78 fd ff ff call 362 <write>
while(*s != 0){
5ea: 0f b6 06 movzbl (%esi),%eax
5ed: 83 c4 10 add $0x10,%esp
5f0: 84 c0 test %al,%al
5f2: 75 e4 jne 5d8 <printf+0x148>
5f4: 8b 75 d0 mov -0x30(%ebp),%esi
state = 0;
5f7: 31 ff xor %edi,%edi
5f9: e9 da fe ff ff jmp 4d8 <printf+0x48>
5fe: 66 90 xchg %ax,%ax
printint(fd, *ap, 10, 1);
600: 83 ec 0c sub $0xc,%esp
603: b9 0a 00 00 00 mov $0xa,%ecx
608: 6a 01 push $0x1
60a: e9 73 ff ff ff jmp 582 <printf+0xf2>
60f: 90 nop
write(fd, &c, 1);
610: 83 ec 04 sub $0x4,%esp
613: 88 5d e5 mov %bl,-0x1b(%ebp)
616: 8d 45 e5 lea -0x1b(%ebp),%eax
619: 6a 01 push $0x1
61b: e9 21 ff ff ff jmp 541 <printf+0xb1>
putc(fd, *ap);
620: 8b 7d d4 mov -0x2c(%ebp),%edi
write(fd, &c, 1);
623: 83 ec 04 sub $0x4,%esp
putc(fd, *ap);
626: 8b 07 mov (%edi),%eax
write(fd, &c, 1);
628: 6a 01 push $0x1
ap++;
62a: 83 c7 04 add $0x4,%edi
putc(fd, *ap);
62d: 88 45 e4 mov %al,-0x1c(%ebp)
write(fd, &c, 1);
630: 8d 45 e4 lea -0x1c(%ebp),%eax
633: 50 push %eax
634: ff 75 08 pushl 0x8(%ebp)
637: e8 26 fd ff ff call 362 <write>
ap++;
63c: 89 7d d4 mov %edi,-0x2c(%ebp)
63f: 83 c4 10 add $0x10,%esp
state = 0;
642: 31 ff xor %edi,%edi
644: e9 8f fe ff ff jmp 4d8 <printf+0x48>
s = "(null)";
649: bb 4c 08 00 00 mov $0x84c,%ebx
while(*s != 0){
64e: b8 28 00 00 00 mov $0x28,%eax
653: e9 72 ff ff ff jmp 5ca <printf+0x13a>
658: 66 90 xchg %ax,%ax
65a: 66 90 xchg %ax,%ax
65c: 66 90 xchg %ax,%ax
65e: 66 90 xchg %ax,%ax
00000660 <free>:
660: 55 push %ebp
661: a1 04 0b 00 00 mov 0xb04,%eax
666: 89 e5 mov %esp,%ebp
668: 57 push %edi
669: 56 push %esi
66a: 53 push %ebx
66b: 8b 5d 08 mov 0x8(%ebp),%ebx
66e: 8d 4b f8 lea -0x8(%ebx),%ecx
671: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
678: 39 c8 cmp %ecx,%eax
67a: 8b 10 mov (%eax),%edx
67c: 73 32 jae 6b0 <free+0x50>
67e: 39 d1 cmp %edx,%ecx
680: 72 04 jb 686 <free+0x26>
682: 39 d0 cmp %edx,%eax
684: 72 32 jb 6b8 <free+0x58>
686: 8b 73 fc mov -0x4(%ebx),%esi
689: 8d 3c f1 lea (%ecx,%esi,8),%edi
68c: 39 fa cmp %edi,%edx
68e: 74 30 je 6c0 <free+0x60>
690: 89 53 f8 mov %edx,-0x8(%ebx)
693: 8b 50 04 mov 0x4(%eax),%edx
696: 8d 34 d0 lea (%eax,%edx,8),%esi
699: 39 f1 cmp %esi,%ecx
69b: 74 3a je 6d7 <free+0x77>
69d: 89 08 mov %ecx,(%eax)
69f: a3 04 0b 00 00 mov %eax,0xb04
6a4: 5b pop %ebx
6a5: 5e pop %esi
6a6: 5f pop %edi
6a7: 5d pop %ebp
6a8: c3 ret
6a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
6b0: 39 d0 cmp %edx,%eax
6b2: 72 04 jb 6b8 <free+0x58>
6b4: 39 d1 cmp %edx,%ecx
6b6: 72 ce jb 686 <free+0x26>
6b8: 89 d0 mov %edx,%eax
6ba: eb bc jmp 678 <free+0x18>
6bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
6c0: 03 72 04 add 0x4(%edx),%esi
6c3: 89 73 fc mov %esi,-0x4(%ebx)
6c6: 8b 10 mov (%eax),%edx
6c8: 8b 12 mov (%edx),%edx
6ca: 89 53 f8 mov %edx,-0x8(%ebx)
6cd: 8b 50 04 mov 0x4(%eax),%edx
6d0: 8d 34 d0 lea (%eax,%edx,8),%esi
6d3: 39 f1 cmp %esi,%ecx
6d5: 75 c6 jne 69d <free+0x3d>
6d7: 03 53 fc add -0x4(%ebx),%edx
6da: a3 04 0b 00 00 mov %eax,0xb04
6df: 89 50 04 mov %edx,0x4(%eax)
6e2: 8b 53 f8 mov -0x8(%ebx),%edx
6e5: 89 10 mov %edx,(%eax)
6e7: 5b pop %ebx
6e8: 5e pop %esi
6e9: 5f pop %edi
6ea: 5d pop %ebp
6eb: c3 ret
6ec: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
000006f0 <malloc>:
6f0: 55 push %ebp
6f1: 89 e5 mov %esp,%ebp
6f3: 57 push %edi
6f4: 56 push %esi
6f5: 53 push %ebx
6f6: 83 ec 0c sub $0xc,%esp
6f9: 8b 45 08 mov 0x8(%ebp),%eax
6fc: 8b 15 04 0b 00 00 mov 0xb04,%edx
702: 8d 78 07 lea 0x7(%eax),%edi
705: c1 ef 03 shr $0x3,%edi
708: 83 c7 01 add $0x1,%edi
70b: 85 d2 test %edx,%edx
70d: 0f 84 9d 00 00 00 je 7b0 <malloc+0xc0>
713: 8b 02 mov (%edx),%eax
715: 8b 48 04 mov 0x4(%eax),%ecx
718: 39 cf cmp %ecx,%edi
71a: 76 6c jbe 788 <malloc+0x98>
71c: 81 ff 00 10 00 00 cmp $0x1000,%edi
722: bb 00 10 00 00 mov $0x1000,%ebx
727: 0f 43 df cmovae %edi,%ebx
72a: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi
731: eb 0e jmp 741 <malloc+0x51>
733: 90 nop
734: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
738: 8b 02 mov (%edx),%eax
73a: 8b 48 04 mov 0x4(%eax),%ecx
73d: 39 f9 cmp %edi,%ecx
73f: 73 47 jae 788 <malloc+0x98>
741: 39 05 04 0b 00 00 cmp %eax,0xb04
747: 89 c2 mov %eax,%edx
749: 75 ed jne 738 <malloc+0x48>
74b: 83 ec 0c sub $0xc,%esp
74e: 56 push %esi
74f: e8 76 fc ff ff call 3ca <sbrk>
754: 83 c4 10 add $0x10,%esp
757: 83 f8 ff cmp $0xffffffff,%eax
75a: 74 1c je 778 <malloc+0x88>
75c: 89 58 04 mov %ebx,0x4(%eax)
75f: 83 ec 0c sub $0xc,%esp
762: 83 c0 08 add $0x8,%eax
765: 50 push %eax
766: e8 f5 fe ff ff call 660 <free>
76b: 8b 15 04 0b 00 00 mov 0xb04,%edx
771: 83 c4 10 add $0x10,%esp
774: 85 d2 test %edx,%edx
776: 75 c0 jne 738 <malloc+0x48>
778: 8d 65 f4 lea -0xc(%ebp),%esp
77b: 31 c0 xor %eax,%eax
77d: 5b pop %ebx
77e: 5e pop %esi
77f: 5f pop %edi
780: 5d pop %ebp
781: c3 ret
782: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
788: 39 cf cmp %ecx,%edi
78a: 74 54 je 7e0 <malloc+0xf0>
78c: 29 f9 sub %edi,%ecx
78e: 89 48 04 mov %ecx,0x4(%eax)
791: 8d 04 c8 lea (%eax,%ecx,8),%eax
794: 89 78 04 mov %edi,0x4(%eax)
797: 89 15 04 0b 00 00 mov %edx,0xb04
79d: 8d 65 f4 lea -0xc(%ebp),%esp
7a0: 83 c0 08 add $0x8,%eax
7a3: 5b pop %ebx
7a4: 5e pop %esi
7a5: 5f pop %edi
7a6: 5d pop %ebp
7a7: c3 ret
7a8: 90 nop
7a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
7b0: c7 05 04 0b 00 00 08 movl $0xb08,0xb04
7b7: 0b 00 00
7ba: c7 05 08 0b 00 00 08 movl $0xb08,0xb08
7c1: 0b 00 00
7c4: b8 08 0b 00 00 mov $0xb08,%eax
7c9: c7 05 0c 0b 00 00 00 movl $0x0,0xb0c
7d0: 00 00 00
7d3: e9 44 ff ff ff jmp 71c <malloc+0x2c>
7d8: 90 nop
7d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
7e0: 8b 08 mov (%eax),%ecx
7e2: 89 0a mov %ecx,(%edx)
7e4: eb b1 jmp 797 <malloc+0xa7>
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r15
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0x1442b, %rsi
lea addresses_UC_ht+0x2357, %rdi
nop
add $45757, %rdx
mov $125, %rcx
rep movsw
nop
nop
nop
nop
nop
dec %r15
lea addresses_A_ht+0x19d3b, %rsi
lea addresses_WC_ht+0x227, %rdi
nop
nop
nop
sub $47805, %r11
mov $94, %rcx
rep movsq
nop
nop
nop
xor %r11, %r11
lea addresses_UC_ht+0x1edbb, %rsi
nop
cmp %rbx, %rbx
movb (%rsi), %dl
nop
nop
nop
nop
sub $9728, %r11
lea addresses_WT_ht+0x838d, %rcx
nop
nop
xor %r15, %r15
mov $0x6162636465666768, %rdx
movq %rdx, %xmm6
movups %xmm6, (%rcx)
nop
nop
nop
nop
nop
and %rbx, %rbx
lea addresses_D_ht+0xdda7, %rdi
nop
nop
nop
nop
nop
sub $52140, %r11
movups (%rdi), %xmm0
vpextrq $0, %xmm0, %rsi
nop
nop
nop
and $32013, %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r15
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %rdi
push %rsi
// Faulty Load
lea addresses_UC+0x151e7, %r11
nop
nop
nop
cmp %rsi, %rsi
vmovups (%r11), %ymm6
vextracti128 $1, %ymm6, %xmm6
vpextrq $1, %xmm6, %rdi
lea oracles, %r11
and $0xff, %rdi
shlq $12, %rdi
mov (%r11,%rdi,1), %rdi
pop %rsi
pop %rdi
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_UC', 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_UC', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}}
{'dst': {'same': False, 'congruent': 5, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_UC_ht', 'congruent': 2}}
{'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WT_ht', 'congruent': 1}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D_ht', 'congruent': 6}}
{'37': 21829}
37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37
*/
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
%>
<%docstring>writev(fd, iovec, count) -> str
Invokes the syscall writev.
See 'man 2 writev' for more information.
Arguments:
fd(int): fd
iovec(iovec*): iovec
count(int): count
Returns:
ssize_t
</%docstring>
<%page args="fd=0, iovec=0, count=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = []
can_pushstr_array = []
argument_names = ['fd', 'iovec', 'count']
argument_values = [fd, iovec, count]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%r' % (name, arg))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, str):
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_writev']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* writev(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)} |
// Copyright (c) 2014 Grant Mercer
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <hpx/hpx_init.hpp>
#include <hpx/hpx.hpp>
#include <hpx/include/parallel_adjacent_find.hpp>
#include <hpx/util/lightweight_test.hpp>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include "test_utils.hpp"
//////////////////////////////////////////////////////////////////////////////
unsigned int seed = std::random_device{}();
std::mt19937 gen(seed);
template <typename ExPolicy, typename IteratorTag>
void test_adjacent_find_bad_alloc(ExPolicy policy, IteratorTag)
{
static_assert(
hpx::parallel::execution::is_execution_policy<ExPolicy>::value,
"hpx::parallel::execution::is_execution_policy<ExPolicy>::value");
typedef std::vector<std::size_t>::iterator base_iterator;
typedef test::decorated_iterator<base_iterator, IteratorTag>
decorated_iterator;
std::vector<std::size_t> c(10007);
std::iota(std::begin(c), std::end(c), gen()+1);
bool caught_bad_alloc = false;
try {
hpx::parallel::adjacent_find(policy,
decorated_iterator(
std::begin(c), [](){ throw std::bad_alloc(); }),
decorated_iterator(std::end(c)),
std::greater<std::size_t>());
HPX_TEST(false);
}
catch(std::bad_alloc const&) {
caught_bad_alloc = true;
}
catch(...) {
HPX_TEST(false);
}
HPX_TEST(caught_bad_alloc);
}
template <typename ExPolicy, typename IteratorTag>
void test_adjacent_find_bad_alloc_async(ExPolicy p, IteratorTag)
{
typedef std::vector<std::size_t>::iterator base_iterator;
typedef test::decorated_iterator<base_iterator, IteratorTag>
decorated_iterator;
std::vector<std::size_t> c(10007);
std::iota(std::begin(c), std::end(c), gen()+1);
bool returned_from_algorithm = false;
bool caught_bad_alloc = false;
try {
hpx::future<decorated_iterator> f =
hpx::parallel::adjacent_find(p,
decorated_iterator(
std::begin(c), [](){ throw std::bad_alloc(); }),
decorated_iterator(std::end(c)),
std::greater<std::size_t>());
returned_from_algorithm = true;
f.get();
HPX_TEST(false);
}
catch (std::bad_alloc const&) {
caught_bad_alloc = true;
}
catch (...) {
HPX_TEST(false);
}
HPX_TEST(caught_bad_alloc);
HPX_TEST(returned_from_algorithm);
}
template <typename IteratorTag>
void test_adjacent_find_bad_alloc()
{
using namespace hpx::parallel;
// If the execution policy object is of type vector_execution_policy,
// std::terminate shall be called. therefore we do not test exceptions
// with a vector execution policy
test_adjacent_find_bad_alloc(execution::seq, IteratorTag());
test_adjacent_find_bad_alloc(execution::par, IteratorTag());
test_adjacent_find_bad_alloc_async(execution::seq(execution::task), IteratorTag());
test_adjacent_find_bad_alloc_async(execution::par(execution::task), IteratorTag());
}
void adjacent_find_bad_alloc_test()
{
test_adjacent_find_bad_alloc<std::random_access_iterator_tag>();
test_adjacent_find_bad_alloc<std::forward_iterator_tag>();
}
int hpx_main(boost::program_options::variables_map& vm)
{
if (vm.count("seed"))
seed = vm["seed"].as<unsigned int>();
std::cout << "using seed: " << seed << std::endl;
gen.seed(seed);
adjacent_find_bad_alloc_test();
return hpx::finalize();
}
int main(int argc, char* argv[])
{
// add command line option which controls the random number generator seed
using namespace boost::program_options;
options_description desc_commandline(
"Usage: " HPX_APPLICATION_STRING " [options]");
desc_commandline.add_options()
("seed,s", value<unsigned int>(),
"the random number generator seed to use for this run")
;
// By default this test should run on all available cores
std::vector<std::string> const cfg = {
"hpx.os_threads=all"
};
// Initialize and run HPX
HPX_TEST_EQ_MSG(hpx::init(desc_commandline, argc, argv, cfg), 0,
"HPX main exited with non-zero status");
return hpx::util::report_errors();
}
|
// Copyright (c) 2014-2015 The Dash Developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2020 The Verizon Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "db.h"
#include "init.h"
#include "main.h"
#include "masternode-budget.h"
#include "masternode-payments.h"
#include "masternodeconfig.h"
#include "masternodeman.h"
#include "rpcserver.h"
#include "utilmoneystr.h"
#include <fstream>
using namespace json_spirit;
using namespace std;
void budgetToJSON(CBudgetProposal* pbudgetProposal, Object& bObj)
{
CTxDestination address1;
ExtractDestination(pbudgetProposal->GetPayee(), address1);
CBitcoinAddress address2(address1);
bObj.push_back(Pair("Name", pbudgetProposal->GetName()));
bObj.push_back(Pair("URL", pbudgetProposal->GetURL()));
bObj.push_back(Pair("Hash", pbudgetProposal->GetHash().ToString()));
bObj.push_back(Pair("FeeHash", pbudgetProposal->nFeeTXHash.ToString()));
bObj.push_back(Pair("BlockStart", (int64_t)pbudgetProposal->GetBlockStart()));
bObj.push_back(Pair("BlockEnd", (int64_t)pbudgetProposal->GetBlockEnd()));
bObj.push_back(Pair("TotalPaymentCount", (int64_t)pbudgetProposal->GetTotalPaymentCount()));
bObj.push_back(Pair("RemainingPaymentCount", (int64_t)pbudgetProposal->GetRemainingPaymentCount()));
bObj.push_back(Pair("PaymentAddress", address2.ToString()));
bObj.push_back(Pair("Ratio", pbudgetProposal->GetRatio()));
bObj.push_back(Pair("Yeas", (int64_t)pbudgetProposal->GetYeas()));
bObj.push_back(Pair("Nays", (int64_t)pbudgetProposal->GetNays()));
bObj.push_back(Pair("Abstains", (int64_t)pbudgetProposal->GetAbstains()));
bObj.push_back(Pair("TotalPayment", ValueFromAmount(pbudgetProposal->GetAmount() * pbudgetProposal->GetTotalPaymentCount())));
bObj.push_back(Pair("MonthlyPayment", ValueFromAmount(pbudgetProposal->GetAmount())));
bObj.push_back(Pair("IsEstablished", pbudgetProposal->IsEstablished()));
std::string strError = "";
bObj.push_back(Pair("IsValid", pbudgetProposal->IsValid(strError)));
bObj.push_back(Pair("IsValidReason", strError.c_str()));
bObj.push_back(Pair("fValid", pbudgetProposal->fValid));
}
// This command is retained for backwards compatibility, but is depreciated.
// Future removal of this command is planned to keep things clean.
Value mnbudget(const Array& params, bool fHelp)
{
string strCommand;
if (params.size() >= 1)
strCommand = params[0].get_str();
if (fHelp ||
(strCommand != "vote-alias" && strCommand != "vote-many" && strCommand != "prepare" && strCommand != "submit" && strCommand != "vote" && strCommand != "getvotes" && strCommand != "getinfo" && strCommand != "show" && strCommand != "projection" && strCommand != "check" && strCommand != "nextblock"))
throw runtime_error(
"mnbudget \"command\"... ( \"passphrase\" )\n"
"\nVote or show current budgets\n"
"This command is depreciated, please see individual command documentation for future reference\n\n"
"\nAvailable commands:\n"
" prepare - Prepare proposal for network by signing and creating tx\n"
" submit - Submit proposal for network\n"
" vote-many - Vote on a Verizon initiative\n"
" vote-alias - Vote on a Verizon initiative\n"
" vote - Vote on a Verizon initiative/budget\n"
" getvotes - Show current masternode budgets\n"
" getinfo - Show current masternode budgets\n"
" show - Show all budgets\n"
" projection - Show the projection of which proposals will be paid the next cycle\n"
" check - Scan proposals and remove invalid\n"
" nextblock - Get next superblock for budget system\n");
if (strCommand == "nextblock") {
Array newParams(params.size() - 1);
std::copy(params.begin() + 1, params.end(), newParams.begin());
return getnextsuperblock(newParams, fHelp);
}
if (strCommand == "prepare") {
Array newParams(params.size() - 1);
std::copy(params.begin() + 1, params.end(), newParams.begin());
return preparebudget(newParams, fHelp);
}
if (strCommand == "submit") {
Array newParams(params.size() - 1);
std::copy(params.begin() + 1, params.end(), newParams.begin());
return submitbudget(newParams, fHelp);
}
if (strCommand == "vote" || strCommand == "vote-many" || strCommand == "vote-alias") {
if (strCommand == "vote-alias")
throw runtime_error(
"vote-alias is not supported with this command\n"
"Please use mnbudgetvote instead.\n"
);
return mnbudgetvote(params, fHelp);
}
if (strCommand == "projection") {
Array newParams(params.size() - 1);
std::copy(params.begin() + 1, params.end(), newParams.begin());
return getbudgetprojection(newParams, fHelp);
}
if (strCommand == "show" || strCommand == "getinfo") {
Array newParams(params.size() - 1);
std::copy(params.begin() + 1, params.end(), newParams.begin());
return getbudgetinfo(newParams, fHelp);
}
if (strCommand == "getvotes") {
Array newParams(params.size() - 1);
std::copy(params.begin() + 1, params.end(), newParams.begin());
return getbudgetvotes(newParams, fHelp);
}
if (strCommand == "check") {
Array newParams(params.size() - 1);
std::copy(params.begin() + 1, params.end(), newParams.begin());
return checkbudgets(newParams, fHelp);
}
return Value::null;
}
Value preparebudget(const Array& params, bool fHelp)
{
int nBlockMin = 0;
CBlockIndex* pindexPrev = chainActive.Tip();
if (fHelp || params.size() != 6)
throw runtime_error(
"preparebudget \"proposal-name\" \"url\" payment-count block-start \"vrz-address\" monthy-payment\n"
"\nPrepare proposal for network by signing and creating tx\n"
"\nArguments:\n"
"1. \"proposal-name\": (string, required) Desired proposal name (20 character limit)\n"
"2. \"url\": (string, required) URL of proposal details (64 character limit)\n"
"3. payment-count: (numeric, required) Total number of monthly payments\n"
"4. block-start: (numeric, required) Starting super block height\n"
"5. \"vrz-address\": (string, required) Verizon address to send payments to\n"
"6. monthly-payment: (numeric, required) Monthly payment amount\n"
"\nResult:\n"
"\"xxxx\" (string) proposal fee hash (if successful) or error message (if failed)\n"
"\nExamples:\n" +
HelpExampleCli("preparebudget", "\"test-proposal\" \"https://forum.vrz.io/t/test-proposal\" 2 820800 \"SPrYJL948mo27BewWx2DhFXvH9DdC9V61p\" 500") +
HelpExampleRpc("preparebudget", "\"test-proposal\" \"https://forum.vrz.io/t/test-proposal\" 2 820800 \"SPrYJL948mo27BewWx2DhFXvH9DdC9V61p\" 500"));
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
std::string strProposalName = SanitizeString(params[0].get_str());
if (strProposalName.size() > 20)
throw runtime_error("Invalid proposal name, limit of 20 characters.");
std::string strURL = SanitizeString(params[1].get_str());
if (strURL.size() > 64)
throw runtime_error("Invalid url, limit of 64 characters.");
int nPaymentCount = params[2].get_int();
if (nPaymentCount < 1)
throw runtime_error("Invalid payment count, must be more than zero.");
//set block min
if (pindexPrev != NULL) nBlockMin = pindexPrev->nHeight - GetBudgetPaymentCycleBlocks() * (nPaymentCount + 1);
int nBlockStart = params[3].get_int();
if (nBlockStart % GetBudgetPaymentCycleBlocks() != 0) {
int nNext = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks();
throw runtime_error(strprintf("Invalid block start - must be a budget cycle block. Next valid block: %d", nNext));
}
int nBlockEnd = nBlockStart + GetBudgetPaymentCycleBlocks() * nPaymentCount;
if (nBlockStart < nBlockMin)
throw runtime_error("Invalid block start, must be more than current height.");
if (nBlockEnd < pindexPrev->nHeight)
throw runtime_error("Invalid ending block, starting block + (payment_cycle*payments) must be more than current height.");
CBitcoinAddress address(params[4].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Verizon address");
// Parse Verizon address
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(params[5]);
//*************************************************************************
// create transaction 15 minutes into the future, to allow for confirmation time
CBudgetProposalBroadcast budgetProposalBroadcast(strProposalName, strURL, nPaymentCount, scriptPubKey, nAmount, nBlockStart, 0);
std::string strError = "";
if (!budgetProposalBroadcast.IsValid(strError, false))
throw runtime_error("Proposal is not valid - " + budgetProposalBroadcast.GetHash().ToString() + " - " + strError);
bool useIX = false; //true;
// if (params.size() > 7) {
// if(params[7].get_str() != "false" && params[7].get_str() != "true")
// return "Invalid use_ix, must be true or false";
// useIX = params[7].get_str() == "true" ? true : false;
// }
CWalletTx wtx;
if (!pwalletMain->GetBudgetSystemCollateralTX(wtx, budgetProposalBroadcast.GetHash(), useIX)) {
throw runtime_error("Error making collateral transaction for proposal. Please check your wallet balance.");
}
// make our change address
CReserveKey reservekey(pwalletMain);
//send the tx to the network
pwalletMain->CommitTransaction(wtx, reservekey, useIX ? "ix" : "tx");
return wtx.GetHash().ToString();
}
Value submitbudget(const Array& params, bool fHelp)
{
int nBlockMin = 0;
CBlockIndex* pindexPrev = chainActive.Tip();
if (fHelp || params.size() != 7)
throw runtime_error(
"submitbudget \"proposal-name\" \"url\" payment-count block-start \"vrz-address\" monthy-payment \"fee-tx\"\n"
"\nSubmit proposal to the network\n"
"\nArguments:\n"
"1. \"proposal-name\": (string, required) Desired proposal name (20 character limit)\n"
"2. \"url\": (string, required) URL of proposal details (64 character limit)\n"
"3. payment-count: (numeric, required) Total number of monthly payments\n"
"4. block-start: (numeric, required) Starting super block height\n"
"5. \"vrz-address\": (string, required) Verizon address to send payments to\n"
"6. monthly-payment: (numeric, required) Monthly payment amount\n"
"7. \"fee-tx\": (string, required) Transaction hash from preparebudget command\n"
"\nResult:\n"
"\"xxxx\" (string) proposal hash (if successful) or error message (if failed)\n"
"\nExamples:\n" +
HelpExampleCli("submitbudget", "\"test-proposal\" \"https://forum.vrz.io/t/test-proposal\" 2 820800 \"SPrYJL948mo27BewWx2DhFXvH9DdC9V61p\" 500") +
HelpExampleRpc("submitbudget", "\"test-proposal\" \"https://forum.vrz.io/t/test-proposal\" 2 820800 \"SPrYJL948mo27BewWx2DhFXvH9DdC9V61p\" 500"));
// Check these inputs the same way we check the vote commands:
// **********************************************************
std::string strProposalName = SanitizeString(params[0].get_str());
if (strProposalName.size() > 20)
throw runtime_error("Invalid proposal name, limit of 20 characters.");
std::string strURL = SanitizeString(params[1].get_str());
if (strURL.size() > 64)
throw runtime_error("Invalid url, limit of 64 characters.");
int nPaymentCount = params[2].get_int();
if (nPaymentCount < 1)
throw runtime_error("Invalid payment count, must be more than zero.");
//set block min
if (pindexPrev != NULL) nBlockMin = pindexPrev->nHeight - GetBudgetPaymentCycleBlocks() * (nPaymentCount + 1);
int nBlockStart = params[3].get_int();
if (nBlockStart % GetBudgetPaymentCycleBlocks() != 0) {
int nNext = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks();
throw runtime_error(strprintf("Invalid block start - must be a budget cycle block. Next valid block: %d", nNext));
}
int nBlockEnd = nBlockStart + (GetBudgetPaymentCycleBlocks() * nPaymentCount);
if (nBlockStart < nBlockMin)
throw runtime_error("Invalid block start, must be more than current height.");
if (nBlockEnd < pindexPrev->nHeight)
throw runtime_error("Invalid ending block, starting block + (payment_cycle*payments) must be more than current height.");
CBitcoinAddress address(params[4].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Verizon address");
// Parse Verizon address
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(params[5]);
uint256 hash = ParseHashV(params[6], "parameter 1");
//create the proposal incase we're the first to make it
CBudgetProposalBroadcast budgetProposalBroadcast(strProposalName, strURL, nPaymentCount, scriptPubKey, nAmount, nBlockStart, hash);
std::string strError = "";
int nConf = 0;
if (!IsBudgetCollateralValid(hash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)) {
throw runtime_error("Proposal FeeTX is not valid - " + hash.ToString() + " - " + strError);
}
if (!masternodeSync.IsBlockchainSynced()) {
throw runtime_error("Must wait for client to sync with masternode network. Try again in a minute or so.");
}
// if(!budgetProposalBroadcast.IsValid(strError)){
// return "Proposal is not valid - " + budgetProposalBroadcast.GetHash().ToString() + " - " + strError;
// }
budget.mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast));
budgetProposalBroadcast.Relay();
if(budget.AddProposal(budgetProposalBroadcast)) {
return budgetProposalBroadcast.GetHash().ToString();
}
throw runtime_error("Invalid proposal, see debug.log for details.");
}
Value mnbudgetvote(const Array& params, bool fHelp)
{
std::string strCommand;
if (params.size() >= 1) {
strCommand = params[0].get_str();
// Backwards compatibility with legacy `mnbudget` command
if (strCommand == "vote") strCommand = "local";
if (strCommand == "vote-many") strCommand = "many";
if (strCommand == "vote-alias") strCommand = "alias";
}
if (fHelp || (params.size() == 3 && (strCommand != "local" && strCommand != "many")) || (params.size() == 4 && strCommand != "alias") ||
params.size() > 4 || params.size() < 3)
throw runtime_error(
"mnbudgetvote \"local|many|alias\" \"votehash\" \"yes|no\" ( \"alias\" )\n"
"\nVote on a budget proposal\n"
"\nArguments:\n"
"1. \"mode\" (string, required) The voting mode. 'local' for voting directly from a masternode, 'many' for voting with a MN controller and casting the same vote for each MN, 'alias' for voting with a MN controller and casting a vote for a single MN\n"
"2. \"votehash\" (string, required) The vote hash for the proposal\n"
"3. \"votecast\" (string, required) Your vote. 'yes' to vote for the proposal, 'no' to vote against\n"
"4. \"alias\" (string, required for 'alias' mode) The MN alias to cast a vote for.\n"
"\nResult:\n"
"{\n"
" \"overall\": \"xxxx\", (string) The overall status message for the vote cast\n"
" \"detail\": [\n"
" {\n"
" \"node\": \"xxxx\", (string) 'local' or the MN alias\n"
" \"result\": \"xxxx\", (string) Either 'Success' or 'Failed'\n"
" \"error\": \"xxxx\", (string) Error message, if vote failed\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("mnbudgetvote", "\"local\" \"ed2f83cedee59a91406f5f47ec4d60bf5a7f9ee6293913c82976bd2d3a658041\" \"yes\"") +
HelpExampleRpc("mnbudgetvote", "\"local\" \"ed2f83cedee59a91406f5f47ec4d60bf5a7f9ee6293913c82976bd2d3a658041\" \"yes\""));
uint256 hash = ParseHashV(params[1], "parameter 1");
std::string strVote = params[2].get_str();
if (strVote != "yes" && strVote != "no") return "You can only vote 'yes' or 'no'";
int nVote = VOTE_ABSTAIN;
if (strVote == "yes") nVote = VOTE_YES;
if (strVote == "no") nVote = VOTE_NO;
int success = 0;
int failed = 0;
Array resultsObj;
if (strCommand == "local") {
CPubKey pubKeyMasternode;
CKey keyMasternode;
std::string errorMessage;
Object statusObj;
while (true) {
if (!privateSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) {
failed++;
statusObj.push_back(Pair("node", "local"));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage));
resultsObj.push_back(statusObj);
break;
}
CMasternode* pmn = mnodeman.Find(activeMasternode.vin);
if (pmn == NULL) {
failed++;
statusObj.push_back(Pair("node", "local"));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "Failure to find masternode in list : " + activeMasternode.vin.ToString()));
resultsObj.push_back(statusObj);
break;
}
CBudgetVote vote(activeMasternode.vin, hash, nVote);
if (!vote.Sign(keyMasternode, pubKeyMasternode)) {
failed++;
statusObj.push_back(Pair("node", "local"));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "Failure to sign."));
resultsObj.push_back(statusObj);
break;
}
std::string strError = "";
if (budget.UpdateProposal(vote, NULL, strError)) {
success++;
budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote));
vote.Relay();
statusObj.push_back(Pair("node", "local"));
statusObj.push_back(Pair("result", "success"));
statusObj.push_back(Pair("error", ""));
} else {
failed++;
statusObj.push_back(Pair("node", "local"));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "Error voting : " + strError));
}
resultsObj.push_back(statusObj);
break;
}
Object returnObj;
returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed)));
returnObj.push_back(Pair("detail", resultsObj));
return returnObj;
}
if (strCommand == "many") {
BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) {
std::string errorMessage;
std::vector<unsigned char> vchMasterNodeSignature;
std::string strMasterNodeSignMessage;
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
CPubKey pubKeyMasternode;
CKey keyMasternode;
Object statusObj;
if (!privateSendSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)) {
failed++;
statusObj.push_back(Pair("node", mne.getAlias()));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage));
resultsObj.push_back(statusObj);
continue;
}
CMasternode* pmn = mnodeman.Find(pubKeyMasternode);
if (pmn == NULL) {
failed++;
statusObj.push_back(Pair("node", mne.getAlias()));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "Can't find masternode by pubkey"));
resultsObj.push_back(statusObj);
continue;
}
CBudgetVote vote(pmn->vin, hash, nVote);
if (!vote.Sign(keyMasternode, pubKeyMasternode)) {
failed++;
statusObj.push_back(Pair("node", mne.getAlias()));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "Failure to sign."));
resultsObj.push_back(statusObj);
continue;
}
std::string strError = "";
if (budget.UpdateProposal(vote, NULL, strError)) {
budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote));
vote.Relay();
success++;
statusObj.push_back(Pair("node", mne.getAlias()));
statusObj.push_back(Pair("result", "success"));
statusObj.push_back(Pair("error", ""));
} else {
failed++;
statusObj.push_back(Pair("node", mne.getAlias()));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", strError.c_str()));
}
resultsObj.push_back(statusObj);
}
Object returnObj;
returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed)));
returnObj.push_back(Pair("detail", resultsObj));
return returnObj;
}
if (strCommand == "alias") {
std::string strAlias = params[3].get_str();
std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries;
mnEntries = masternodeConfig.getEntries();
BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) {
if( strAlias != mne.getAlias()) continue;
std::string errorMessage;
std::vector<unsigned char> vchMasterNodeSignature;
std::string strMasterNodeSignMessage;
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
CPubKey pubKeyMasternode;
CKey keyMasternode;
Object statusObj;
if(!privateSendSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)){
failed++;
statusObj.push_back(Pair("node", mne.getAlias()));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage));
resultsObj.push_back(statusObj);
continue;
}
CMasternode* pmn = mnodeman.Find(pubKeyMasternode);
if(pmn == NULL)
{
failed++;
statusObj.push_back(Pair("node", mne.getAlias()));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "Can't find masternode by pubkey"));
resultsObj.push_back(statusObj);
continue;
}
CBudgetVote vote(pmn->vin, hash, nVote);
if(!vote.Sign(keyMasternode, pubKeyMasternode)){
failed++;
statusObj.push_back(Pair("node", mne.getAlias()));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "Failure to sign."));
resultsObj.push_back(statusObj);
continue;
}
std::string strError = "";
if(budget.UpdateProposal(vote, NULL, strError)) {
budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote));
vote.Relay();
success++;
statusObj.push_back(Pair("node", mne.getAlias()));
statusObj.push_back(Pair("result", "success"));
statusObj.push_back(Pair("error", ""));
} else {
failed++;
statusObj.push_back(Pair("node", mne.getAlias()));
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", strError.c_str()));
}
resultsObj.push_back(statusObj);
}
Object returnObj;
returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed)));
returnObj.push_back(Pair("detail", resultsObj));
return returnObj;
}
return Value::null;
}
Value getbudgetvotes(const Array& params, bool fHelp)
{
if (params.size() != 1)
throw runtime_error(
"getbudgetvotes \"proposal-name\"\n"
"\nPrint vote information for a budget proposal\n"
"\nArguments:\n"
"1. \"proposal-name\": (string, required) Name of the proposal\n"
"\nResult:\n"
"[\n"
" {\n"
" \"mnId\": \"xxxx\", (string) Hash of the masternode's collateral transaction\n"
" \"nHash\": \"xxxx\", (string) Hash of the vote\n"
" \"Vote\": \"YES|NO\", (string) Vote cast ('YES' or 'NO')\n"
" \"nTime\": xxxx, (numeric) Time in seconds since epoch the vote was cast\n"
" \"fValid\": true|false, (boolean) 'true' if the vote is valid, 'false' otherwise\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getbudgetvotes", "\"test-proposal\"") + HelpExampleRpc("getbudgetvotes", "\"test-proposal\""));
std::string strProposalName = SanitizeString(params[0].get_str());
Array ret;
CBudgetProposal* pbudgetProposal = budget.FindProposal(strProposalName);
if (pbudgetProposal == NULL) throw runtime_error("Unknown proposal name");
std::map<uint256, CBudgetVote>::iterator it = pbudgetProposal->mapVotes.begin();
while (it != pbudgetProposal->mapVotes.end()) {
Object bObj;
bObj.push_back(Pair("mnId", (*it).second.vin.prevout.hash.ToString()));
bObj.push_back(Pair("nHash", (*it).first.ToString().c_str()));
bObj.push_back(Pair("Vote", (*it).second.GetVoteString()));
bObj.push_back(Pair("nTime", (int64_t)(*it).second.nTime));
bObj.push_back(Pair("fValid", (*it).second.fValid));
ret.push_back(bObj);
it++;
}
return ret;
}
Value getnextsuperblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getnextsuperblock\n"
"\nPrint the next super block height\n"
"\nResult:\n"
"n (numeric) Block height of the next super block\n"
"\nExamples:\n" +
HelpExampleCli("getnextsuperblock", "") + HelpExampleRpc("getnextsuperblock", ""));
CBlockIndex* pindexPrev = chainActive.Tip();
if (!pindexPrev) return "unknown";
int nNext = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks();
return nNext;
}
Value getbudgetprojection(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbudgetprojection\n"
"\nShow the projection of which proposals will be paid the next cycle\n"
"\nResult:\n"
"[\n"
" {\n"
" \"Name\": \"xxxx\", (string) Proposal Name\n"
" \"URL\": \"xxxx\", (string) Proposal URL\n"
" \"Hash\": \"xxxx\", (string) Proposal vote hash\n"
" \"FeeHash\": \"xxxx\", (string) Proposal fee hash\n"
" \"BlockStart\": n, (numeric) Proposal starting block\n"
" \"BlockEnd\": n, (numeric) Proposal ending block\n"
" \"TotalPaymentCount\": n, (numeric) Number of payments\n"
" \"RemainingPaymentCount\": n, (numeric) Number of remaining payments\n"
" \"PaymentAddress\": \"xxxx\", (string) Verizon address of payment\n"
" \"Ratio\": x.xxx, (numeric) Ratio of yeas vs nays\n"
" \"Yeas\": n, (numeric) Number of yea votes\n"
" \"Nays\": n, (numeric) Number of nay votes\n"
" \"Abstains\": n, (numeric) Number of abstains\n"
" \"TotalPayment\": xxx.xxx, (numeric) Total payment amount\n"
" \"MonthlyPayment\": xxx.xxx, (numeric) Monthly payment amount\n"
" \"IsEstablished\": true|false, (boolean) Established (true) or (false)\n"
" \"IsValid\": true|false, (boolean) Valid (true) or Invalid (false)\n"
" \"IsValidReason\": \"xxxx\", (string) Error message, if any\n"
" \"fValid\": true|false, (boolean) Valid (true) or Invalid (false)\n"
" \"Alloted\": xxx.xxx, (numeric) Amount alloted in current period\n"
" \"TotalBudgetAlloted\": xxx.xxx (numeric) Total alloted\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getbudgetprojection", "") + HelpExampleRpc("getbudgetprojection", ""));
Array ret;
Object resultObj;
CAmount nTotalAllotted = 0;
std::vector<CBudgetProposal*> winningProps = budget.GetBudget();
BOOST_FOREACH (CBudgetProposal* pbudgetProposal, winningProps) {
nTotalAllotted += pbudgetProposal->GetAllotted();
CTxDestination address1;
ExtractDestination(pbudgetProposal->GetPayee(), address1);
CBitcoinAddress address2(address1);
Object bObj;
budgetToJSON(pbudgetProposal, bObj);
bObj.push_back(Pair("Alloted", ValueFromAmount(pbudgetProposal->GetAllotted())));
bObj.push_back(Pair("TotalBudgetAlloted", ValueFromAmount(nTotalAllotted)));
ret.push_back(bObj);
}
return ret;
}
Value getbudgetinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getbudgetinfo ( \"proposal\" )\n"
"\nShow current masternode budgets\n"
"\nArguments:\n"
"1. \"proposal\" (string, optional) Proposal name\n"
"\nResult:\n"
"[\n"
" {\n"
" \"Name\": \"xxxx\", (string) Proposal Name\n"
" \"URL\": \"xxxx\", (string) Proposal URL\n"
" \"Hash\": \"xxxx\", (string) Proposal vote hash\n"
" \"FeeHash\": \"xxxx\", (string) Proposal fee hash\n"
" \"BlockStart\": n, (numeric) Proposal starting block\n"
" \"BlockEnd\": n, (numeric) Proposal ending block\n"
" \"TotalPaymentCount\": n, (numeric) Number of payments\n"
" \"RemainingPaymentCount\": n, (numeric) Number of remaining payments\n"
" \"PaymentAddress\": \"xxxx\", (string) Verizon address of payment\n"
" \"Ratio\": x.xxx, (numeric) Ratio of yeas vs nays\n"
" \"Yeas\": n, (numeric) Number of yea votes\n"
" \"Nays\": n, (numeric) Number of nay votes\n"
" \"Abstains\": n, (numeric) Number of abstains\n"
" \"TotalPayment\": xxx.xxx, (numeric) Total payment amount\n"
" \"MonthlyPayment\": xxx.xxx, (numeric) Monthly payment amount\n"
" \"IsEstablished\": true|false, (boolean) Established (true) or (false)\n"
" \"IsValid\": true|false, (boolean) Valid (true) or Invalid (false)\n"
" \"IsValidReason\": \"xxxx\", (string) Error message, if any\n"
" \"fValid\": true|false, (boolean) Valid (true) or Invalid (false)\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getbudgetprojection", "") + HelpExampleRpc("getbudgetprojection", ""));
Array ret;
std::string strShow = "valid";
if (params.size() == 1) {
std::string strProposalName = SanitizeString(params[0].get_str());
CBudgetProposal* pbudgetProposal = budget.FindProposal(strProposalName);
if (pbudgetProposal == NULL) throw runtime_error("Unknown proposal name");
Object bObj;
budgetToJSON(pbudgetProposal, bObj);
ret.push_back(bObj);
return ret;
}
std::vector<CBudgetProposal*> winningProps = budget.GetAllProposals();
BOOST_FOREACH (CBudgetProposal* pbudgetProposal, winningProps) {
if (strShow == "valid" && !pbudgetProposal->fValid) continue;
Object bObj;
budgetToJSON(pbudgetProposal, bObj);
ret.push_back(bObj);
}
return ret;
}
Value mnbudgetrawvote(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 6)
throw runtime_error(
"mnbudgetrawvote \"masternode-tx-hash\" masternode-tx-index \"proposal-hash\" yes|no time \"vote-sig\"\n"
"\nCompile and relay a proposal vote with provided external signature instead of signing vote internally\n"
"\nArguments:\n"
"1. \"masternode-tx-hash\" (string, required) Transaction hash for the masternode\n"
"2. masternode-tx-index (numeric, required) Output index for the masternode\n"
"3. \"proposal-hash\" (string, required) Proposal vote hash\n"
"4. yes|no (boolean, required) Vote to cast\n"
"5. time (numeric, required) Time since epoch in seconds\n"
"6. \"vote-sig\" (string, required) External signature\n"
"\nResult:\n"
"\"status\" (string) Vote status or error message\n"
"\nExamples:\n" +
HelpExampleCli("mnbudgetrawvote", "") + HelpExampleRpc("mnbudgetrawvote", ""));
uint256 hashMnTx = ParseHashV(params[0], "mn tx hash");
int nMnTxIndex = params[1].get_int();
CTxIn vin = CTxIn(hashMnTx, nMnTxIndex);
uint256 hashProposal = ParseHashV(params[2], "Proposal hash");
std::string strVote = params[3].get_str();
if (strVote != "yes" && strVote != "no") return "You can only vote 'yes' or 'no'";
int nVote = VOTE_ABSTAIN;
if (strVote == "yes") nVote = VOTE_YES;
if (strVote == "no") nVote = VOTE_NO;
int64_t nTime = params[4].get_int64();
std::string strSig = params[5].get_str();
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSig.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CMasternode* pmn = mnodeman.Find(vin);
if (pmn == NULL) {
return "Failure to find masternode in list : " + vin.ToString();
}
CBudgetVote vote(vin, hashProposal, nVote);
vote.nTime = nTime;
vote.vchSig = vchSig;
if (!vote.SignatureValid(true)) {
return "Failure to verify signature.";
}
std::string strError = "";
if (budget.UpdateProposal(vote, NULL, strError)) {
budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote));
vote.Relay();
return "Voted successfully";
} else {
return "Error voting : " + strError;
}
}
Value mnfinalbudget(const Array& params, bool fHelp)
{
string strCommand;
if (params.size() >= 1)
strCommand = params[0].get_str();
if (fHelp ||
(strCommand != "suggest" && strCommand != "vote-many" && strCommand != "vote" && strCommand != "show" && strCommand != "getvotes"))
throw runtime_error(
"mnfinalbudget \"command\"... ( \"passphrase\" )\n"
"Vote or show current budgets\n"
"\nAvailable commands:\n"
" vote-many - Vote on a finalized budget\n"
" vote - Vote on a finalized budget\n"
" show - Show existing finalized budgets\n"
" getvotes - Get vote information for each finalized budget\n");
if (strCommand == "vote-many") {
if (params.size() != 2)
throw runtime_error("Correct usage is 'mnfinalbudget vote-many BUDGET_HASH'");
std::string strHash = params[1].get_str();
uint256 hash(strHash);
int success = 0;
int failed = 0;
Object resultsObj;
BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) {
std::string errorMessage;
std::vector<unsigned char> vchMasterNodeSignature;
std::string strMasterNodeSignMessage;
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
CPubKey pubKeyMasternode;
CKey keyMasternode;
Object statusObj;
if (!privateSendSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)) {
failed++;
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("errorMessage", "Masternode signing error, could not set key correctly: " + errorMessage));
resultsObj.push_back(Pair(mne.getAlias(), statusObj));
continue;
}
CMasternode* pmn = mnodeman.Find(pubKeyMasternode);
if (pmn == NULL) {
failed++;
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("errorMessage", "Can't find masternode by pubkey"));
resultsObj.push_back(Pair(mne.getAlias(), statusObj));
continue;
}
CFinalizedBudgetVote vote(pmn->vin, hash);
if (!vote.Sign(keyMasternode, pubKeyMasternode)) {
failed++;
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("errorMessage", "Failure to sign."));
resultsObj.push_back(Pair(mne.getAlias(), statusObj));
continue;
}
std::string strError = "";
if (budget.UpdateFinalizedBudget(vote, NULL, strError)) {
budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote));
vote.Relay();
success++;
statusObj.push_back(Pair("result", "success"));
} else {
failed++;
statusObj.push_back(Pair("result", strError.c_str()));
}
resultsObj.push_back(Pair(mne.getAlias(), statusObj));
}
Object returnObj;
returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed)));
returnObj.push_back(Pair("detail", resultsObj));
return returnObj;
}
if (strCommand == "vote") {
if (params.size() != 2)
throw runtime_error("Correct usage is 'mnfinalbudget vote BUDGET_HASH'");
std::string strHash = params[1].get_str();
uint256 hash(strHash);
CPubKey pubKeyMasternode;
CKey keyMasternode;
std::string errorMessage;
if (!privateSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode))
return "Error upon calling SetKey";
CMasternode* pmn = mnodeman.Find(activeMasternode.vin);
if (pmn == NULL) {
return "Failure to find masternode in list : " + activeMasternode.vin.ToString();
}
CFinalizedBudgetVote vote(activeMasternode.vin, hash);
if (!vote.Sign(keyMasternode, pubKeyMasternode)) {
return "Failure to sign.";
}
std::string strError = "";
if (budget.UpdateFinalizedBudget(vote, NULL, strError)) {
budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote));
vote.Relay();
return "success";
} else {
return "Error voting : " + strError;
}
}
if (strCommand == "show") {
Object resultObj;
std::vector<CFinalizedBudget*> winningFbs = budget.GetFinalizedBudgets();
BOOST_FOREACH (CFinalizedBudget* finalizedBudget, winningFbs) {
Object bObj;
bObj.push_back(Pair("FeeTX", finalizedBudget->nFeeTXHash.ToString()));
bObj.push_back(Pair("Hash", finalizedBudget->GetHash().ToString()));
bObj.push_back(Pair("BlockStart", (int64_t)finalizedBudget->GetBlockStart()));
bObj.push_back(Pair("BlockEnd", (int64_t)finalizedBudget->GetBlockEnd()));
bObj.push_back(Pair("Proposals", finalizedBudget->GetProposals()));
bObj.push_back(Pair("VoteCount", (int64_t)finalizedBudget->GetVoteCount()));
bObj.push_back(Pair("Status", finalizedBudget->GetStatus()));
std::string strError = "";
bObj.push_back(Pair("IsValid", finalizedBudget->IsValid(strError)));
bObj.push_back(Pair("IsValidReason", strError.c_str()));
resultObj.push_back(Pair(finalizedBudget->GetName(), bObj));
}
return resultObj;
}
if (strCommand == "getvotes") {
if (params.size() != 2)
throw runtime_error("Correct usage is 'mnbudget getvotes budget-hash'");
std::string strHash = params[1].get_str();
uint256 hash(strHash);
Object obj;
CFinalizedBudget* pfinalBudget = budget.FindFinalizedBudget(hash);
if (pfinalBudget == NULL) return "Unknown budget hash";
std::map<uint256, CFinalizedBudgetVote>::iterator it = pfinalBudget->mapVotes.begin();
while (it != pfinalBudget->mapVotes.end()) {
Object bObj;
bObj.push_back(Pair("nHash", (*it).first.ToString().c_str()));
bObj.push_back(Pair("nTime", (int64_t)(*it).second.nTime));
bObj.push_back(Pair("fValid", (*it).second.fValid));
obj.push_back(Pair((*it).second.vin.prevout.ToStringShort(), bObj));
it++;
}
return obj;
}
return Value::null;
}
Value checkbudgets(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"checkbudgets\n"
"\nInitiates a buddget check cycle manually\n"
"\nExamples:\n" +
HelpExampleCli("checkbudgets", "") + HelpExampleRpc("checkbudgets", ""));
budget.CheckAndRemove();
return Value::null;
}
|
; ----------------------------------------------------------------
; Z88DK INTERFACE LIBRARY FOR THE BIFROST*2 ENGINE
;
; See "bifrost2.h" for further details
; ----------------------------------------------------------------
SECTION code_clib
SECTION code_bifrost2
PUBLIC asm_BIFROST2_stop
defc asm_BIFROST2_stop = 51634
|
;******************************************************************************
;
; (c) 2010 by BECK IPC GmbH
; http://www.beck-ipc.com
;
;******************************************************************************
;
; Module: rtxdyn00.asm
; Function: Dynamic linking of RTX API Function
;
;
;******************************************************************************
;
; $Header$
;
;******************************************************************************
INCLUDE rtxDLapi.def
_TEXT SEGMENT BYTE PUBLIC 'CODE'
ASSUME CS:_TEXT, DS:NOTHING, ES:NOTHING, SS:NOTHING
;******************************************************************************
; Prototypes
;******************************************************************************
PUBLIC _RTX_Get_TimeDate_us
;******************************************************************************
; RTX_Get_TimeDate_us()
;******************************************************************************
_RTX_Get_TimeDate_us PROC FAR
LINKER_PATCH ; Will be replaced by dynamic linking code
MOV AX, IDX_RTX_Get_TimeDate_us ; AH = 0, AL = Function number
INT RTX_SWI
; IP-Register will be adjusted on return from software interrupt so that the
; new code is executed immediately.
_RTX_Get_TimeDate_us ENDP
_TEXT ENDS
END
; End of file
|
; A188038: a(n) = [nr]-[kr]-[nr-kr], where r=sqrt(2), k=2, [ ]=floor.
; 1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1
mov $1,$0
lpb $1
mov $2,$1
sub $1,2
seq $2,188044 ; a(n) = [n*r] - [k*r] - [n*r-k*r], where r=sqrt(2), k=4, [ ]=floor.
add $0,$2
add $0,1
lpe
add $0,1
mod $0,2
|
; A041481: Denominators of continued fraction convergents to sqrt(257).
; Submitted by Jamie Morken(s2)
; 1,32,1025,32832,1051649,33685600,1078990849,34561392768,1107043559425,35459955294368,1135825612979201,36381879570628800,1165355971873100801,37327772979509854432,1195654091316188442625,38298258695097540018432,1226739932334437469032449,39293976093397096549056800,1258633974921041527038850049,40315581173566725961792258368,1291357231529056272304391117825,41363746990103367439702308028768,1324931260914836814342778248038401,42439164096264881426408606245257600,1359378182341391042459418178096281601
mov $3,1
lpb $0
sub $0,1
mov $2,$3
mul $3,32
add $3,$1
mov $1,$2
lpe
mov $0,$3
|
;
; ANSI Video handling for the Jupiter ACE
;
; Stefano Bodrato - Feb. 2001
;
;
; set it up with:
; .text_cols = max columns
; .text_rows = max rows
;
; Display a char in location (ansi_ROW),(ansi_COLUMN)
; A=char to display
;
;
; $Id: f_ansi_char.asm,v 1.2 2016/11/17 09:39:03 stefano Exp $
;
SECTION code_clib
PUBLIC ansi_CHAR
PUBLIC text_cols
PUBLIC text_rows
EXTERN ansi_ROW
EXTERN ansi_COLUMN
EXTERN bee_attr
EXTERN INVRS
;.text_cols defb 80
EXTERN ansicolumns
.text_cols defb ansicolumns
defb 0
.text_rows defb 25
.ansi_CHAR
.setout
ld hl,INVRS
or (HL)
push af
ld hl,$F000
ld a,(ansi_ROW)
and a
jr z,r_zero
ld b,a
ld de,(text_cols)
.r_loop
add hl,de
djnz r_loop
.r_zero
ld a,(ansi_COLUMN)
ld d,0
ld e,a
add hl,de
pop af
ld (hl),a
ld a,64
out (8),a
ld de,$800
add hl,de
ld a,(bee_attr)
ld (hl),a
xor a
out (8),a
ret
|
#include "JSystem/J3D/J3DDrawBuffer.h"
#include "JSystem/J3D/J3DSys.h"
#include "JSystem/JUT/JUTException.h"
#include "Sys/DrawBuffers.h"
#include "types.h"
/*
Generated from dpostproc
.section .rodata # 0x804732E0 - 0x8049E220
.global lbl_8049BAD8
lbl_8049BAD8:
.4byte 0x73797344
.4byte 0x72617742
.4byte 0x75666665
.4byte 0x722E6370
.4byte 0x70000000
.global lbl_8049BAEC
lbl_8049BAEC:
.asciz "P2Assert"
.skip 3
.global lbl_8049BAF8
lbl_8049BAF8:
.4byte 0x44726177
.4byte 0x42756666
.4byte 0x65720000
.4byte 0x00000000
.section .data, "wa" # 0x8049E220 - 0x804EFC20
.global __vt__Q23Sys11DrawBuffers
__vt__Q23Sys11DrawBuffers:
.4byte 0
.4byte 0
.4byte __dt__Q23Sys11DrawBuffersFv
.4byte getChildCount__5CNodeFv
.global __vt__Q23Sys10DrawBuffer
__vt__Q23Sys10DrawBuffer:
.4byte 0
.4byte 0
.4byte __dt__Q23Sys10DrawBufferFv
.4byte getChildCount__5CNodeFv
*/
namespace Sys {
/*
* --INFO--
* Address: 80455700
* Size: 00005C
*/
DrawBuffer::DrawBuffer()
: CNode()
{
_18.byteView[0] = 0;
_18.byteView[1] = 0;
_18.byteView[0] = 0;
_18.byteView[1] = 0;
_1C = nullptr;
_20 = -1;
}
/*
* __dt__Q23Sys10DrawBufferFv
* --INFO--
* Address: 8045575C
* Size: 000060
*/
DrawBuffer::~DrawBuffer() { }
/*
* --INFO--
* Address: 804557BC
* Size: 0000DC
*/
void DrawBuffer::create(Sys::DrawBuffer::CreateArg& arg)
{
u32 bufferSize = arg._00;
_18.typeView |= arg._04;
m_name = arg.m_name;
P2ASSERTLINE(42, _1C == nullptr);
_1C = new J3DDrawBuffer(bufferSize);
_1C->_0C = arg._0C;
_1C->_08 = arg._10;
_28 = _1C->_08;
_24 = _1C->_0C;
}
/*
* draw__Q23Sys10DrawBufferFv
* --INFO--
* Address: 80455898
* Size: 000088
*/
void DrawBuffer::draw()
{
P2ASSERTLINE(57, _1C != nullptr);
if ((_18.typeView & 1) != 0) {
j3dSys._50 = 4;
} else {
j3dSys._50 = 3;
}
_1C->draw();
}
/*
* --INFO--
* Address: 80455920
* Size: 000058
*/
void DrawBuffer::frameInit()
{
P2ASSERTLINE(69, _1C != nullptr);
_1C->frameInit();
}
/*
* --INFO--
* Address: 80455978
* Size: 000054
*/
DrawBuffers::DrawBuffers()
: CNode()
{
m_buffers = nullptr;
m_count = 0;
setName("DrawBuffer");
}
/*
* __dt__Q23Sys11DrawBuffersFv
* --INFO--
* Address: 804559CC
* Size: 000060
*/
DrawBuffers::~DrawBuffers() { }
/*
* --INFO--
* Address: 80455A2C
* Size: 000098
*/
void DrawBuffers::allocate(int count)
{
m_buffers = new DrawBuffer[count];
m_count = count;
for (int i = 0; i < m_count; i++) {
get(i)->_20 = i;
}
}
/*
* --INFO--
* Address: 80455AC4
* Size: 00008C
*/
DrawBuffer* DrawBuffers::get(int index)
{
bool check = false;
if (m_buffers != nullptr && 0 <= index && index < m_count) {
check = true;
}
P2ASSERTLINE(148, check);
return &m_buffers[index];
}
/*
* --INFO--
* Address: 80455B50
* Size: 0000E0
*/
void DrawBuffers::frameInitAll()
{
for (int i = 0; i < m_count; i++) {
get(i)->frameInit();
}
}
} // namespace Sys
|
/*
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
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 <iostream>
#include <sstream>
#include <cstdint>
#include <cstring>
#include "lte/gateway/c/core/oai/tasks/nas5g/include/ies/M5GServiceType.h"
#include "lte/gateway/c/core/oai/tasks/nas5g/include/M5GCommonDefs.h"
namespace magma5g {
ServiceTypeMsg::ServiceTypeMsg(){};
ServiceTypeMsg::~ServiceTypeMsg(){};
// Decode ServiceType IE
int ServiceTypeMsg::DecodeServiceTypeMsg(ServiceTypeMsg* svc_type, uint8_t iei,
uint8_t* buffer, uint32_t len) {
int decoded = 0;
svc_type->service_type_value = ((*buffer & 0xf0) >> 4);
MLOG(MDEBUG) << "DecodeServiceTypeMsg__: service_type_value = " << std::hex
<< int(svc_type->service_type_value) << std::endl;
return (decoded);
};
// Encode ServiceType IE
int ServiceTypeMsg::EncodeServiceTypeMsg(ServiceTypeMsg* svc_type, uint8_t iei,
uint8_t* buffer, uint32_t len) {
int encoded = 0;
*buffer = svc_type->service_type_value & 0x0f;
MLOG(MDEBUG) << "DecodeServiceTypeMsg__: service_type_value = " << std::hex
<< int(*buffer) << std::endl;
encoded++;
return (encoded);
};
} // namespace magma5g
|
//
// Created by sylvain on 27/01/17.
//
#include <iostream>
#include <iomanip>
#include "Characters/Character.hh"
Character::Character(std::string const &name)
: ACharacteristics(1, 1, 1, 1), _name(name), _health(100), _armor(0)
{}
Character::~Character()
{}
void Character::displayInfo() const
{
std::cout << std::setw(10) << this->getName() << ":\n";
std::cout << std::setw(10) << this->getHealth() << " hp\n";
std::cout << std::setw(10) << this->getEnergy() << " energy\n";
std::cout << std::setw(10) << this->getArmor() << " armor\n";
std::cout << std::setw(10) << this->getStrength() << " strength\n";
std::cout << std::setw(10) << this->getStamina() << " stamina\n";
std::cout << std::setw(10) << this->getIntelligence() << " intelligence\n";
std::cout << std::setw(10) << this->getAgility() << " agility" << std::endl;
}
Character &Character::setHealth(int health)
{
this->_health = health;
return *this;
}
Character &Character::setEnergy(int energy)
{
this->_energy = energy;
return *this;
}
Character &Character::setArmor(int armor)
{
this->_armor = armor;
return *this;
}
std::string Character::getName() const
{
return this->_name;
}
int Character::getHealth() const
{
return this->_health;
}
int Character::getEnergy() const
{
return this->_energy;
}
int Character::getArmor() const
{
return this->_armor;
}
|
COMMENT @----------------------------------------------------------------------
Copyright (c) GeoWorks 1988 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: OpenLook/Win
FILE: winFieldData.asm
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 3/89 Initial version
DESCRIPTION:
This file contains data for drawing open look fields.
$Id: cwinFieldData.asm,v 1.1 97/04/07 10:53:00 newdeal Exp $
------------------------------------------------------------------------------@
;------------------------------------------------------------------------------
; Constants
;------------------------------------------------------------------------------
;------------------------------------------------------------------------------
; Data
;------------------------------------------------------------------------------
if _FXIP
RegionResourceXIP segment resource
else
Init segment resource
endif
; CHANGE to use same field for all UI's, so we don't get oddball corners
; peaking through in some UI's.
;
fieldRegion label Region
word -1, EOREGREC
word PARAM_3, 0, PARAM_2, EOREGREC
word EOREGREC
if _FXIP
RegionResourceXIP ends
else
Init ends
endif
|
; A312606: Coordination sequence Gal.6.255.1 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; 1,4,8,14,19,23,27,31,36,42,46,50,54,58,64,69,73,77,81,86,92,96,100,104,108,114,119,123,127,131,136,142,146,150,154,158,164,169,173,177,181,186,192,196,200,204,208,214,219,223
mov $2,$0
add $2,1
mov $4,$0
lpb $2
mov $0,$4
sub $2,1
sub $0,$2
mov $5,$0
mov $7,2
lpb $7
mov $0,$5
sub $7,1
add $0,$7
sub $0,1
mul $0,2
cal $0,313753 ; Coordination sequence Gal.6.253.3 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
add $0,6
mov $3,$0
mov $8,$7
lpb $8
mov $6,$3
sub $8,1
lpe
lpe
lpb $5
mov $5,0
sub $6,$3
lpe
mov $3,$6
sub $3,6
add $1,$3
lpe
|
%ifndef NSECS
%assign NSECS 16384
%endif
%assign NSECS ((NSECS+3) & ~3)
%assign n 0
%rep NSECS
%assign gcom (n & ~3) + 2
section .text %+ n progbits exec
start_ %+ n:
nop
jmp start_ %+ gcom
%assign n n+1
%endrep
|
// name=random ; gcc $name.cc -std=c++11 -lstdc++ -o /tmp/$name && /tmp/$name
/**
https://stackoverflow.com/questions/9878965/rand-between-0-and-1
https://stackoverflow.com/questions/31417957/encapsulated-random-number-generator-in-c-11-using-boost
**/
#include <iostream>
#include <iomanip>
#include <random>
int main()
{
std::mt19937_64 rng;
unsigned seed = 0u ;
rng.seed(seed);
std::uniform_real_distribution<double> unif(0, 1);
double a ;
double b ;
bool done ;
unsigned count = 0 ;
do {
a = unif(rng);
b = unif(rng);
std::cout
<< " count " << std::setw(10) << count
<< " a " << std::fixed << std::setw(10) << std::setprecision(4) << a
<< " b " << std::fixed << std::setw(10) << std::setprecision(4) << b
<< std::endl
;
done = a > 0.99 && b > 0.99 ;
count += 1 ;
} while( done == false ) ;
std::cout
<< " result "
<< " count " << count
<< " a " << a
<< " b " << b
<< std::endl
;
return 0;
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r14
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_normal_ht+0x12a1e, %rsi
lea addresses_UC_ht+0x19d6e, %rdi
nop
nop
nop
sub $42737, %r13
mov $87, %rcx
rep movsb
nop
cmp %rdi, %rdi
lea addresses_UC_ht+0xad1e, %rax
nop
cmp %r13, %r13
movups (%rax), %xmm1
vpextrq $0, %xmm1, %r14
nop
nop
nop
nop
nop
add %r13, %r13
lea addresses_normal_ht+0x1e81e, %rax
nop
nop
nop
xor $22945, %rdx
mov $0x6162636465666768, %rcx
movq %rcx, (%rax)
nop
lfence
lea addresses_D_ht+0x1359e, %r13
nop
nop
nop
nop
nop
add %rdx, %rdx
movl $0x61626364, (%r13)
nop
nop
xor %rdi, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r14
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %r8
push %rbx
push %rcx
push %rdx
// Store
lea addresses_WC+0x1d7dd, %rdx
nop
nop
nop
nop
cmp %r11, %r11
mov $0x5152535455565758, %rcx
movq %rcx, %xmm2
vmovups %ymm2, (%rdx)
nop
nop
mfence
// Store
lea addresses_UC+0xc254, %rbx
nop
nop
nop
nop
add $39583, %r13
movb $0x51, (%rbx)
// Exception!!!
nop
nop
mov (0), %r11
nop
nop
nop
nop
and %r11, %r11
// Faulty Load
lea addresses_normal+0x13a1e, %rbx
nop
nop
nop
nop
nop
inc %rcx
movups (%rbx), %xmm2
vpextrq $1, %xmm2, %r13
lea oracles, %rcx
and $0xff, %r13
shlq $12, %r13
mov (%rcx,%r13,1), %r13
pop %rdx
pop %rcx
pop %rbx
pop %r8
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_normal_ht'}, 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_UC_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 6}}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
PROCESSOR 6502
; Convert long int on stack to byte
MAC F_cbyte_long
pla
pla
ENDM
; Convert long int on stack to word
MAC F_cword_long
pla
ENDM
; Convert long int on stack to int
MAC F_cint_long
pla
ENDM
; Convert long int on stack to float
MAC F_cfloat_long ; @pull @push
IF !FPULL
pla
sta FAC + 1
eor #$FF
rol
pla
sta FAC + 2
pla
sta FAC + 3
ELSE
sta FAC + 3
sty FAC + 2
stx FAC + 1
txa
eor #$FF
rol
ENDIF
import I_LTOF
jsr LTOF
pfac
ENDM
IFCONST I_LTOF_IMPORTED
LTOF SUBROUTINE
ldx #$98
stx FAC
lda #$00
sta FACEXTENSION
sta FACSIGN
import I_FPLIB
jmp NORMALIZE_FAC1
ENDIF |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "ApiDispatchers.h"
#include "../host/directio.h"
#include "../host/getset.h"
#include "../host/stream.h"
#include "../host/srvinit.h"
#include "../host/telemetry.hpp"
#include "../host/cmdline.h"
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCP(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_GETCP_MSG* const a = &m->u.consoleMsgL1.GetConsoleCP;
if (a->Output)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleOutputCP);
m->_pApiRoutines->GetConsoleOutputCodePageImpl(a->CodePage);
}
else
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleCP);
m->_pApiRoutines->GetConsoleInputCodePageImpl(a->CodePage);
}
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleMode(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleMode);
CONSOLE_MODE_MSG* const a = &m->u.consoleMsgL1.GetConsoleMode;
std::wstring_view handleType = L"unknown";
TraceLoggingWrite(g_hConhostV2EventTraceProvider,
"API_GetConsoleMode",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE),
TraceLoggingOpcode(WINEVENT_OPCODE_START));
auto tracing = wil::scope_exit([&]() {
Tracing::s_TraceApi(a, handleType);
TraceLoggingWrite(g_hConhostV2EventTraceProvider,
"API_GetConsoleMode",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE),
TraceLoggingOpcode(WINEVENT_OPCODE_STOP));
});
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
if (pObjectHandle->IsInputHandle())
{
handleType = L"input";
InputBuffer* pObj;
RETURN_IF_FAILED(pObjectHandle->GetInputBuffer(GENERIC_READ, &pObj));
m->_pApiRoutines->GetConsoleInputModeImpl(*pObj, a->Mode);
}
else
{
handleType = L"output";
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_READ, &pObj));
m->_pApiRoutines->GetConsoleOutputModeImpl(*pObj, a->Mode);
}
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleMode(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleMode);
CONSOLE_MODE_MSG* const a = &m->u.consoleMsgL1.SetConsoleMode;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
if (pObjectHandle->IsInputHandle())
{
InputBuffer* pObj;
RETURN_IF_FAILED(pObjectHandle->GetInputBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleInputModeImpl(*pObj, a->Mode);
}
else
{
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleOutputModeImpl(*pObj, a->Mode);
}
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetNumberOfInputEvents(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetNumberOfConsoleInputEvents);
CONSOLE_GETNUMBEROFINPUTEVENTS_MSG* const a = &m->u.consoleMsgL1.GetNumberOfConsoleInputEvents;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
InputBuffer* pObj;
RETURN_IF_FAILED(pObjectHandle->GetInputBuffer(GENERIC_READ, &pObj));
return m->_pApiRoutines->GetNumberOfConsoleInputEventsImpl(*pObj, a->ReadyEvents);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleInput(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const pbReplyPending)
{
*pbReplyPending = FALSE;
CONSOLE_GETCONSOLEINPUT_MSG* const a = &m->u.consoleMsgL1.GetConsoleInput;
if (WI_IsFlagSet(a->Flags, CONSOLE_READ_NOREMOVE))
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::PeekConsoleInput, a->Unicode);
}
else
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::ReadConsoleInput, a->Unicode);
}
a->NumRecords = 0;
// If any flags are set that are not within our enum, it's invalid.
if (WI_IsAnyFlagSet(a->Flags, ~CONSOLE_READ_VALID))
{
return E_INVALIDARG;
}
// Make sure we have a valid input buffer.
ConsoleHandleData* const pHandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pHandleData);
InputBuffer* pInputBuffer;
RETURN_IF_FAILED(pHandleData->GetInputBuffer(GENERIC_READ, &pInputBuffer));
// Get output buffer.
PVOID pvBuffer;
ULONG cbBufferSize;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvBuffer, &cbBufferSize));
INPUT_RECORD* const rgRecords = reinterpret_cast<INPUT_RECORD*>(pvBuffer);
size_t const cRecords = cbBufferSize / sizeof(INPUT_RECORD);
bool const fIsPeek = WI_IsFlagSet(a->Flags, CONSOLE_READ_NOREMOVE);
bool const fIsWaitAllowed = WI_IsFlagClear(a->Flags, CONSOLE_READ_NOWAIT);
INPUT_READ_HANDLE_DATA* const pInputReadHandleData = pHandleData->GetClientInput();
std::unique_ptr<IWaitRoutine> waiter;
HRESULT hr;
std::deque<std::unique_ptr<IInputEvent>> outEvents;
size_t const eventsToRead = cRecords;
if (a->Unicode)
{
if (fIsPeek)
{
hr = m->_pApiRoutines->PeekConsoleInputWImpl(*pInputBuffer,
outEvents,
eventsToRead,
*pInputReadHandleData,
waiter);
}
else
{
hr = m->_pApiRoutines->ReadConsoleInputWImpl(*pInputBuffer,
outEvents,
eventsToRead,
*pInputReadHandleData,
waiter);
}
}
else
{
if (fIsPeek)
{
hr = m->_pApiRoutines->PeekConsoleInputAImpl(*pInputBuffer,
outEvents,
eventsToRead,
*pInputReadHandleData,
waiter);
}
else
{
hr = m->_pApiRoutines->ReadConsoleInputAImpl(*pInputBuffer,
outEvents,
eventsToRead,
*pInputReadHandleData,
waiter);
}
}
// We must return the number of records in the message payload (to alert the client)
// as well as in the message headers (below in SetReplyInformation) to alert the driver.
LOG_IF_FAILED(SizeTToULong(outEvents.size(), &a->NumRecords));
size_t cbWritten;
LOG_IF_FAILED(SizeTMult(outEvents.size(), sizeof(INPUT_RECORD), &cbWritten));
if (nullptr != waiter.get())
{
// In some circumstances, the read may have told us to wait because it didn't have data,
// but the client explicitly asked us to return immediate. In that case, we'll convert the
// wait request into a "0 bytes found, OK".
if (fIsWaitAllowed)
{
hr = ConsoleWaitQueue::s_CreateWait(m, waiter.release());
if (SUCCEEDED(hr))
{
*pbReplyPending = TRUE;
hr = CONSOLE_STATUS_WAIT;
}
}
else
{
// If wait isn't allowed and the routine generated a
// waiter, say there was nothing to be
// retrieved right now.
// The waiter will be auto-freed in the smart pointer.
cbWritten = 0;
hr = S_OK;
}
}
else
{
try
{
for (size_t i = 0; i < cRecords; ++i)
{
if (outEvents.empty())
{
break;
}
rgRecords[i] = outEvents.front()->ToInputRecord();
outEvents.pop_front();
}
}
CATCH_RETURN();
}
if (SUCCEEDED(hr))
{
m->SetReplyInformation(cbWritten);
}
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerReadConsole(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const pbReplyPending)
{
*pbReplyPending = FALSE;
CONSOLE_READCONSOLE_MSG* const a = &m->u.consoleMsgL1.ReadConsole;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::ReadConsole, a->Unicode);
a->NumBytes = 0; // we return 0 until proven otherwise.
// Make sure we have a valid input buffer.
ConsoleHandleData* const HandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, HandleData);
InputBuffer* pInputBuffer;
RETURN_IF_FAILED(HandleData->GetInputBuffer(GENERIC_READ, &pInputBuffer));
// Get output parameter buffer.
PVOID pvBuffer;
ULONG cbBufferSize;
// TODO: This is dumb. We should find out how much we need, not guess.
// If the request is not in Unicode mode, we must allocate an output buffer that is twice as big as the actual caller buffer.
RETURN_IF_FAILED(m->GetAugmentedOutputBuffer((a->Unicode != FALSE) ? 1 : 2,
&pvBuffer,
&cbBufferSize));
// TODO: This is also rather strange and will also probably make more sense if we stop guessing that we need 2x buffer to convert.
// This might need to go on the other side of the fence (inside host) because the server doesn't know what we're going to do with initial num bytes.
// (This restriction exists because it's going to copy initial into the final buffer, but we don't know that.)
RETURN_HR_IF(E_INVALIDARG, a->InitialNumBytes > cbBufferSize);
// Retrieve input parameters.
// 1. Exe name making the request
ULONG const cchExeName = a->ExeNameLength;
ULONG cbExeName;
RETURN_IF_FAILED(ULongMult(cchExeName, sizeof(wchar_t), &cbExeName));
wistd::unique_ptr<wchar_t[]> pwsExeName;
if (cchExeName > 0)
{
pwsExeName = wil::make_unique_nothrow<wchar_t[]>(cchExeName);
RETURN_IF_NULL_ALLOC(pwsExeName);
RETURN_IF_FAILED(m->ReadMessageInput(0, pwsExeName.get(), cbExeName));
}
const std::wstring_view exeView(pwsExeName.get(), cchExeName);
// 2. Existing data in the buffer that was passed in.
ULONG const cbInitialData = a->InitialNumBytes;
std::unique_ptr<char[]> pbInitialData;
try
{
if (cbInitialData > 0)
{
pbInitialData = std::make_unique<char[]>(cbInitialData);
// This parameter starts immediately after the exe name so skip by that many bytes.
RETURN_IF_FAILED(m->ReadMessageInput(cbExeName, pbInitialData.get(), cbInitialData));
}
}
CATCH_RETURN();
// ReadConsole needs this to get details associated with an attached process (such as the command history list, telemetry metadata).
HANDLE const hConsoleClient = (HANDLE)m->GetProcessHandle();
// ReadConsole needs this to store context information across "processed reads" e.g. reads on the same handle
// across multiple calls when we are simulating a command prompt input line for the client application.
INPUT_READ_HANDLE_DATA* const pInputReadHandleData = HandleData->GetClientInput();
std::unique_ptr<IWaitRoutine> waiter;
size_t cbWritten;
HRESULT hr;
if (a->Unicode)
{
const std::string_view initialData(pbInitialData.get(), cbInitialData);
const gsl::span<char> outputBuffer(reinterpret_cast<char*>(pvBuffer), cbBufferSize);
hr = m->_pApiRoutines->ReadConsoleWImpl(*pInputBuffer,
outputBuffer,
cbWritten, // We must set the reply length in bytes.
waiter,
initialData,
exeView,
*pInputReadHandleData,
hConsoleClient,
a->CtrlWakeupMask,
a->ControlKeyState);
}
else
{
const std::string_view initialData(pbInitialData.get(), cbInitialData);
const gsl::span<char> outputBuffer(reinterpret_cast<char*>(pvBuffer), cbBufferSize);
hr = m->_pApiRoutines->ReadConsoleAImpl(*pInputBuffer,
outputBuffer,
cbWritten, // We must set the reply length in bytes.
waiter,
initialData,
exeView,
*pInputReadHandleData,
hConsoleClient,
a->CtrlWakeupMask,
a->ControlKeyState);
}
LOG_IF_FAILED(SizeTToULong(cbWritten, &a->NumBytes));
if (nullptr != waiter.get())
{
// If we received a waiter, we need to queue the wait and not reply.
hr = ConsoleWaitQueue::s_CreateWait(m, waiter.release());
if (SUCCEEDED(hr))
{
*pbReplyPending = TRUE;
}
}
else
{
// - This routine is called when a ReadConsole or ReadFile request is about to be completed.
// - It sets the number of bytes written as the information to be written with the completion status and,
// if CTRL+Z processing is enabled and a CTRL+Z is detected, switches the number of bytes read to zero.
if (a->ProcessControlZ != FALSE &&
a->NumBytes > 0 &&
m->State.OutputBuffer != nullptr &&
*(PUCHAR)m->State.OutputBuffer == 0x1a)
{
a->NumBytes = 0;
}
m->SetReplyInformation(a->NumBytes);
}
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsole(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const pbReplyPending)
{
*pbReplyPending = FALSE;
CONSOLE_WRITECONSOLE_MSG* const a = &m->u.consoleMsgL1.WriteConsole;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::WriteConsole, a->Unicode);
// Make sure we have a valid screen buffer.
ConsoleHandleData* HandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, HandleData);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(HandleData->GetScreenBuffer(GENERIC_WRITE, &pScreenInfo));
// Get input parameter buffer
PVOID pvBuffer;
ULONG cbBufferSize;
auto tracing = wil::scope_exit([&]() {
Tracing::s_TraceApi(pvBuffer, a);
});
RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbBufferSize));
std::unique_ptr<IWaitRoutine> waiter;
size_t cbRead;
const auto requiresVtQuirk{ m->GetProcessHandle()->GetShimPolicy().IsVtColorQuirkRequired() };
// We have to hold onto the HR from the call and return it.
// We can't return some other error after the actual API call.
// This is because the write console function is allowed to write part of the string and then return an error.
// It then must report back how far it got before it failed.
HRESULT hr;
if (a->Unicode)
{
const std::wstring_view buffer(reinterpret_cast<wchar_t*>(pvBuffer), cbBufferSize / sizeof(wchar_t));
size_t cchInputRead;
hr = m->_pApiRoutines->WriteConsoleWImpl(*pScreenInfo, buffer, cchInputRead, requiresVtQuirk, waiter);
// We must set the reply length in bytes. Convert back from characters.
LOG_IF_FAILED(SizeTMult(cchInputRead, sizeof(wchar_t), &cbRead));
}
else
{
const std::string_view buffer(reinterpret_cast<char*>(pvBuffer), cbBufferSize);
size_t cchInputRead;
hr = m->_pApiRoutines->WriteConsoleAImpl(*pScreenInfo, buffer, cchInputRead, requiresVtQuirk, waiter);
// Reply length is already in bytes (chars), don't need to convert.
cbRead = cchInputRead;
}
// We must return the byte length of the read data in the message.
LOG_IF_FAILED(SizeTToULong(cbRead, &a->NumBytes));
if (nullptr != waiter.get())
{
// If we received a waiter, we need to queue the wait and not reply.
hr = ConsoleWaitQueue::s_CreateWait(m, waiter.release());
if (SUCCEEDED(hr))
{
*pbReplyPending = TRUE;
}
}
else
{
// If no waiter, fill the response data and return.
m->SetReplyInformation(a->NumBytes);
}
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerFillConsoleOutput(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
PCONSOLE_FILLCONSOLEOUTPUT_MSG const a = &m->u.consoleMsgL2.FillConsoleOutput;
switch (a->ElementType)
{
case CONSOLE_ATTRIBUTE:
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::FillConsoleOutputAttribute);
break;
case CONSOLE_ASCII:
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::FillConsoleOutputCharacter, false);
break;
case CONSOLE_REAL_UNICODE:
case CONSOLE_FALSE_UNICODE:
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::FillConsoleOutputCharacter, true);
break;
}
// Capture length of initial fill.
size_t fill = a->Length;
// Set written length to 0 in case we early return.
a->Length = 0;
// Make sure we have a valid screen buffer.
ConsoleHandleData* HandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, HandleData);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(HandleData->GetScreenBuffer(GENERIC_WRITE, &pScreenInfo));
HRESULT hr;
size_t amountWritten;
switch (a->ElementType)
{
case CONSOLE_ATTRIBUTE:
{
hr = m->_pApiRoutines->FillConsoleOutputAttributeImpl(*pScreenInfo,
a->Element,
fill,
a->WriteCoord,
amountWritten);
break;
}
case CONSOLE_REAL_UNICODE:
case CONSOLE_FALSE_UNICODE:
{
// GH#3126 if the client application is powershell.exe, then we might
// need to enable a compatibility shim.
hr = m->_pApiRoutines->FillConsoleOutputCharacterWImpl(*pScreenInfo,
a->Element,
fill,
a->WriteCoord,
amountWritten,
m->GetProcessHandle()->GetShimPolicy().IsPowershellExe());
break;
}
case CONSOLE_ASCII:
{
hr = m->_pApiRoutines->FillConsoleOutputCharacterAImpl(*pScreenInfo,
static_cast<char>(a->Element),
fill,
a->WriteCoord,
amountWritten);
break;
}
default:
return E_INVALIDARG;
}
LOG_IF_FAILED(SizeTToDWord(amountWritten, &a->Length));
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleActiveScreenBuffer(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleActiveScreenBuffer);
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
m->_pApiRoutines->SetConsoleActiveScreenBufferImpl(*pObj);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerFlushConsoleInputBuffer(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::FlushConsoleInputBuffer);
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
InputBuffer* pObj;
RETURN_IF_FAILED(pObjectHandle->GetInputBuffer(GENERIC_WRITE, &pObj));
m->_pApiRoutines->FlushConsoleInputBuffer(*pObj);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCP(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_SETCP_MSG* const a = &m->u.consoleMsgL2.SetConsoleCP;
if (a->Output)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleOutputCP);
return m->_pApiRoutines->SetConsoleOutputCodePageImpl(a->CodePage);
}
else
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleCP);
return m->_pApiRoutines->SetConsoleInputCodePageImpl(a->CodePage);
}
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCursorInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleCursorInfo);
CONSOLE_GETCURSORINFO_MSG* const a = &m->u.consoleMsgL2.GetConsoleCursorInfo;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
bool visible = false;
m->_pApiRoutines->GetConsoleCursorInfoImpl(*pObj, a->CursorSize, visible);
a->Visible = !!visible;
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCursorInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleCursorInfo);
CONSOLE_SETCURSORINFO_MSG* const a = &m->u.consoleMsgL2.SetConsoleCursorInfo;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleCursorInfoImpl(*pObj, a->CursorSize, a->Visible);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleScreenBufferInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleScreenBufferInfoEx);
CONSOLE_SCREENBUFFERINFO_MSG* const a = &m->u.consoleMsgL2.GetConsoleScreenBufferInfo;
auto tracing = wil::scope_exit([&]() {
Tracing::s_TraceApi(a);
});
CONSOLE_SCREEN_BUFFER_INFOEX ex = { 0 };
ex.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_READ, &pObj));
m->_pApiRoutines->GetConsoleScreenBufferInfoExImpl(*pObj, ex);
a->FullscreenSupported = !!ex.bFullscreenSupported;
size_t const ColorTableSizeInBytes = RTL_NUMBER_OF_V2(ex.ColorTable) * sizeof(*ex.ColorTable);
CopyMemory(a->ColorTable, ex.ColorTable, ColorTableSizeInBytes);
a->CursorPosition = ex.dwCursorPosition;
a->MaximumWindowSize = ex.dwMaximumWindowSize;
a->Size = ex.dwSize;
a->ScrollPosition.X = ex.srWindow.Left;
a->ScrollPosition.Y = ex.srWindow.Top;
a->CurrentWindowSize.X = ex.srWindow.Right - ex.srWindow.Left;
a->CurrentWindowSize.Y = ex.srWindow.Bottom - ex.srWindow.Top;
a->Attributes = ex.wAttributes;
a->PopupAttributes = ex.wPopupAttributes;
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleScreenBufferInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleScreenBufferInfoEx);
CONSOLE_SCREENBUFFERINFO_MSG* const a = &m->u.consoleMsgL2.SetConsoleScreenBufferInfo;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
CONSOLE_SCREEN_BUFFER_INFOEX ex = { 0 };
ex.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
ex.bFullscreenSupported = a->FullscreenSupported;
size_t const ColorTableSizeInBytes = RTL_NUMBER_OF_V2(ex.ColorTable) * sizeof(*ex.ColorTable);
CopyMemory(ex.ColorTable, a->ColorTable, ColorTableSizeInBytes);
ex.dwCursorPosition = a->CursorPosition;
ex.dwMaximumWindowSize = a->MaximumWindowSize;
ex.dwSize = a->Size;
ex.srWindow = { 0 };
ex.srWindow.Left = a->ScrollPosition.X;
ex.srWindow.Top = a->ScrollPosition.Y;
ex.srWindow.Right = ex.srWindow.Left + a->CurrentWindowSize.X;
ex.srWindow.Bottom = ex.srWindow.Top + a->CurrentWindowSize.Y;
ex.wAttributes = a->Attributes;
ex.wPopupAttributes = a->PopupAttributes;
return m->_pApiRoutines->SetConsoleScreenBufferInfoExImpl(*pObj, ex);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleScreenBufferSize(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleScreenBufferSize);
CONSOLE_SETSCREENBUFFERSIZE_MSG* const a = &m->u.consoleMsgL2.SetConsoleScreenBufferSize;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleScreenBufferSizeImpl(*pObj, a->Size);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCursorPosition(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleCursorPosition);
CONSOLE_SETCURSORPOSITION_MSG* const a = &m->u.consoleMsgL2.SetConsoleCursorPosition;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleCursorPositionImpl(*pObj, a->CursorPosition);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetLargestConsoleWindowSize(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetLargestConsoleWindowSize);
CONSOLE_GETLARGESTWINDOWSIZE_MSG* const a = &m->u.consoleMsgL2.GetLargestConsoleWindowSize;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
m->_pApiRoutines->GetLargestConsoleWindowSizeImpl(*pObj, a->Size);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerScrollConsoleScreenBuffer(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_SCROLLSCREENBUFFER_MSG* const a = &m->u.consoleMsgL2.ScrollConsoleScreenBuffer;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::ScrollConsoleScreenBuffer, a->Unicode);
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
if (a->Unicode)
{
// GH#3126 if the client application is cmd.exe, then we might need to
// enable a compatibility shim.
return m->_pApiRoutines->ScrollConsoleScreenBufferWImpl(*pObj,
a->ScrollRectangle,
a->DestinationOrigin,
a->Clip ? std::optional<SMALL_RECT>(a->ClipRectangle) : std::nullopt,
a->Fill.Char.UnicodeChar,
a->Fill.Attributes,
m->GetProcessHandle()->GetShimPolicy().IsCmdExe());
}
else
{
return m->_pApiRoutines->ScrollConsoleScreenBufferAImpl(*pObj,
a->ScrollRectangle,
a->DestinationOrigin,
a->Clip ? std::optional<SMALL_RECT>(a->ClipRectangle) : std::nullopt,
a->Fill.Char.AsciiChar,
a->Fill.Attributes);
}
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleTextAttribute(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleTextAttribute);
CONSOLE_SETTEXTATTRIBUTE_MSG* const a = &m->u.consoleMsgL2.SetConsoleTextAttribute;
auto tracing = wil::scope_exit([&]() {
Tracing::s_TraceApi(a);
});
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
RETURN_HR(m->_pApiRoutines->SetConsoleTextAttributeImpl(*pObj, a->Attributes));
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleWindowInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleWindowInfo);
CONSOLE_SETWINDOWINFO_MSG* const a = &m->u.consoleMsgL2.SetConsoleWindowInfo;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleWindowInfoImpl(*pObj, a->Absolute, a->Window);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerReadConsoleOutputString(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
RETURN_HR_IF(E_ACCESSDENIED, !m->GetProcessHandle()->GetPolicy().CanReadOutputBuffer());
CONSOLE_READCONSOLEOUTPUTSTRING_MSG* const a = &m->u.consoleMsgL2.ReadConsoleOutputString;
switch (a->StringType)
{
case CONSOLE_ATTRIBUTE:
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::ReadConsoleOutputAttribute);
break;
case CONSOLE_ASCII:
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::ReadConsoleOutputCharacter, false);
break;
case CONSOLE_REAL_UNICODE:
case CONSOLE_FALSE_UNICODE:
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::ReadConsoleOutputCharacter, true);
break;
}
a->NumRecords = 0; // Set to 0 records returned in case we have failures.
PVOID pvBuffer;
ULONG cbBuffer;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvBuffer, &cbBuffer));
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_READ, &pScreenInfo));
size_t written;
switch (a->StringType)
{
case CONSOLE_ATTRIBUTE:
{
const gsl::span<WORD> buffer(reinterpret_cast<WORD*>(pvBuffer), cbBuffer / sizeof(WORD));
RETURN_IF_FAILED(m->_pApiRoutines->ReadConsoleOutputAttributeImpl(*pScreenInfo, a->ReadCoord, buffer, written));
break;
}
case CONSOLE_REAL_UNICODE:
case CONSOLE_FALSE_UNICODE:
{
const gsl::span<wchar_t> buffer(reinterpret_cast<wchar_t*>(pvBuffer), cbBuffer / sizeof(wchar_t));
RETURN_IF_FAILED(m->_pApiRoutines->ReadConsoleOutputCharacterWImpl(*pScreenInfo, a->ReadCoord, buffer, written));
break;
}
case CONSOLE_ASCII:
{
const gsl::span<char> buffer(reinterpret_cast<char*>(pvBuffer), cbBuffer);
RETURN_IF_FAILED(m->_pApiRoutines->ReadConsoleOutputCharacterAImpl(*pScreenInfo, a->ReadCoord, buffer, written));
break;
}
default:
return E_INVALIDARG;
}
// Report count of records now in the buffer (varies based on type)
RETURN_IF_FAILED(SizeTToULong(written, &a->NumRecords));
m->SetReplyInformation(cbBuffer); // Set the reply buffer size to what we were originally told the buffer size was (on the way in)
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsoleInput(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
PCONSOLE_WRITECONSOLEINPUT_MSG const a = &m->u.consoleMsgL2.WriteConsoleInput;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::WriteConsoleInput, a->Unicode);
a->NumRecords = 0;
RETURN_HR_IF(E_ACCESSDENIED, !m->GetProcessHandle()->GetPolicy().CanWriteInputBuffer());
PVOID pvBuffer;
ULONG cbSize;
RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbSize));
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
InputBuffer* pInputBuffer;
RETURN_IF_FAILED(pObjectHandle->GetInputBuffer(GENERIC_WRITE, &pInputBuffer));
size_t written;
gsl::span<const INPUT_RECORD> buffer(reinterpret_cast<INPUT_RECORD*>(pvBuffer), cbSize / sizeof(INPUT_RECORD));
if (!a->Unicode)
{
RETURN_IF_FAILED(m->_pApiRoutines->WriteConsoleInputAImpl(*pInputBuffer, buffer, written, !!a->Append));
}
else
{
RETURN_IF_FAILED(m->_pApiRoutines->WriteConsoleInputWImpl(*pInputBuffer, buffer, written, !!a->Append));
}
RETURN_IF_FAILED(SizeTToULong(written, &a->NumRecords));
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsoleOutput(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
PCONSOLE_WRITECONSOLEOUTPUT_MSG const a = &m->u.consoleMsgL2.WriteConsoleOutput;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::WriteConsoleOutput, a->Unicode);
// Backup originalRegion and set the written area to a 0 size rectangle in case of failures.
const auto originalRegion = Microsoft::Console::Types::Viewport::FromInclusive(a->CharRegion);
auto writtenRegion = Microsoft::Console::Types::Viewport::FromDimensions(originalRegion.Origin(), { 0, 0 });
a->CharRegion = writtenRegion.ToInclusive();
// Get input parameter buffer
PVOID pvBuffer;
ULONG cbSize;
RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbSize));
// Make sure we have a valid screen buffer.
ConsoleHandleData* HandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, HandleData);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(HandleData->GetScreenBuffer(GENERIC_WRITE, &pScreenInfo));
// Validate parameters
size_t regionArea;
RETURN_IF_FAILED(SizeTMult(originalRegion.Dimensions().X, originalRegion.Dimensions().Y, ®ionArea));
size_t regionBytes;
RETURN_IF_FAILED(SizeTMult(regionArea, sizeof(CHAR_INFO), ®ionBytes));
RETURN_HR_IF(E_INVALIDARG, cbSize < regionBytes); // If given fewer bytes on input than we need to do this write, it's invalid.
const gsl::span<CHAR_INFO> buffer(reinterpret_cast<CHAR_INFO*>(pvBuffer), cbSize / sizeof(CHAR_INFO));
if (!a->Unicode)
{
RETURN_IF_FAILED(m->_pApiRoutines->WriteConsoleOutputAImpl(*pScreenInfo, buffer, originalRegion, writtenRegion));
}
else
{
RETURN_IF_FAILED(m->_pApiRoutines->WriteConsoleOutputWImpl(*pScreenInfo, buffer, originalRegion, writtenRegion));
}
// Update the written region if we were successful
a->CharRegion = writtenRegion.ToInclusive();
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerWriteConsoleOutputString(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
PCONSOLE_WRITECONSOLEOUTPUTSTRING_MSG const a = &m->u.consoleMsgL2.WriteConsoleOutputString;
auto tracing = wil::scope_exit([&]() {
Tracing::s_TraceApi(a);
});
switch (a->StringType)
{
case CONSOLE_ATTRIBUTE:
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::WriteConsoleOutputAttribute);
break;
case CONSOLE_ASCII:
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::WriteConsoleOutputCharacter, false);
break;
case CONSOLE_REAL_UNICODE:
case CONSOLE_FALSE_UNICODE:
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::WriteConsoleOutputCharacter, true);
break;
}
// Set written records to 0 in case we early return.
a->NumRecords = 0;
// Make sure we have a valid screen buffer.
ConsoleHandleData* HandleData = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, HandleData);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(HandleData->GetScreenBuffer(GENERIC_WRITE, &pScreenInfo));
// Get input parameter buffer
PVOID pvBuffer;
ULONG cbBufferSize;
RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbBufferSize));
HRESULT hr;
size_t used;
switch (a->StringType)
{
case CONSOLE_ASCII:
{
const std::string_view text(reinterpret_cast<char*>(pvBuffer), cbBufferSize);
hr = m->_pApiRoutines->WriteConsoleOutputCharacterAImpl(*pScreenInfo,
text,
a->WriteCoord,
used);
break;
}
case CONSOLE_REAL_UNICODE:
case CONSOLE_FALSE_UNICODE:
{
const std::wstring_view text(reinterpret_cast<wchar_t*>(pvBuffer), cbBufferSize / sizeof(wchar_t));
hr = m->_pApiRoutines->WriteConsoleOutputCharacterWImpl(*pScreenInfo,
text,
a->WriteCoord,
used);
break;
}
case CONSOLE_ATTRIBUTE:
{
const gsl::span<const WORD> text(reinterpret_cast<WORD*>(pvBuffer), cbBufferSize / sizeof(WORD));
hr = m->_pApiRoutines->WriteConsoleOutputAttributeImpl(*pScreenInfo,
text,
a->WriteCoord,
used);
break;
}
default:
return E_INVALIDARG;
}
// We need to return how many records were consumed off of the string
LOG_IF_FAILED(SizeTToULong(used, &a->NumRecords));
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerReadConsoleOutput(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
RETURN_HR_IF(E_ACCESSDENIED, !m->GetProcessHandle()->GetPolicy().CanReadOutputBuffer());
CONSOLE_READCONSOLEOUTPUT_MSG* const a = &m->u.consoleMsgL2.ReadConsoleOutput;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::ReadConsoleOutput, a->Unicode);
// Backup data region passed and set it to a zero size region in case we exit early for failures.
const auto originalRegion = Microsoft::Console::Types::Viewport::FromInclusive(a->CharRegion);
const auto zeroRegion = Microsoft::Console::Types::Viewport::FromDimensions(originalRegion.Origin(), { 0, 0 });
a->CharRegion = zeroRegion.ToInclusive();
PVOID pvBuffer;
ULONG cbBuffer;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvBuffer, &cbBuffer));
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pScreenInfo;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_READ, &pScreenInfo));
// Validate parameters
size_t regionArea;
RETURN_IF_FAILED(SizeTMult(originalRegion.Dimensions().X, originalRegion.Dimensions().Y, ®ionArea));
size_t regionBytes;
RETURN_IF_FAILED(SizeTMult(regionArea, sizeof(CHAR_INFO), ®ionBytes));
RETURN_HR_IF(E_INVALIDARG, regionArea > 0 && ((regionArea > ULONG_MAX / sizeof(CHAR_INFO)) || (cbBuffer < regionBytes)));
gsl::span<CHAR_INFO> buffer(reinterpret_cast<CHAR_INFO*>(pvBuffer), cbBuffer / sizeof(CHAR_INFO));
auto finalRegion = Microsoft::Console::Types::Viewport::Empty(); // the actual region read out of the buffer
if (!a->Unicode)
{
RETURN_IF_FAILED(m->_pApiRoutines->ReadConsoleOutputAImpl(*pScreenInfo,
buffer,
originalRegion,
finalRegion));
}
else
{
RETURN_IF_FAILED(m->_pApiRoutines->ReadConsoleOutputWImpl(*pScreenInfo,
buffer,
originalRegion,
finalRegion));
}
a->CharRegion = finalRegion.ToInclusive();
// We have to reply back with the entire buffer length. The client side in kernelbase will trim out
// the correct region of the buffer for return to the original caller.
m->SetReplyInformation(cbBuffer);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleTitle(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
PCONSOLE_GETTITLE_MSG const a = &m->u.consoleMsgL2.GetConsoleTitle;
Telemetry::Instance().LogApiCall(a->Original ? Telemetry::ApiCall::GetConsoleOriginalTitle : Telemetry::ApiCall::GetConsoleTitle, a->Unicode);
PVOID pvBuffer;
ULONG cbBuffer;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvBuffer, &cbBuffer));
HRESULT hr = S_OK;
if (a->Unicode)
{
gsl::span<wchar_t> buffer(reinterpret_cast<wchar_t*>(pvBuffer), cbBuffer / sizeof(wchar_t));
size_t written;
size_t needed;
if (a->Original)
{
// This API traditionally doesn't return an HRESULT. Log and discard.
LOG_IF_FAILED(m->_pApiRoutines->GetConsoleOriginalTitleWImpl(buffer, written, needed));
}
else
{
// This API traditionally doesn't return an HRESULT. Log and discard.
LOG_IF_FAILED(m->_pApiRoutines->GetConsoleTitleWImpl(buffer, written, needed));
}
// We must return the needed length of the title string in the TitleLength.
LOG_IF_FAILED(SizeTToULong(needed, &a->TitleLength));
// We must return the actually written length of the title string in the reply.
m->SetReplyInformation(written * sizeof(wchar_t));
}
else
{
gsl::span<char> buffer(reinterpret_cast<char*>(pvBuffer), cbBuffer);
size_t written;
size_t needed;
if (a->Original)
{
hr = m->_pApiRoutines->GetConsoleOriginalTitleAImpl(buffer, written, needed);
}
else
{
hr = m->_pApiRoutines->GetConsoleTitleAImpl(buffer, written, needed);
}
// We must return the needed length of the title string in the TitleLength.
LOG_IF_FAILED(SizeTToULong(needed, &a->TitleLength));
// We must return the actually written length of the title string in the reply.
m->SetReplyInformation(written * sizeof(char));
}
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleTitle(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_SETTITLE_MSG* const a = &m->u.consoleMsgL2.SetConsoleTitle;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleTitle, a->Unicode);
PVOID pvBuffer;
ULONG cbOriginalLength;
RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbOriginalLength));
if (a->Unicode)
{
const std::wstring_view title(reinterpret_cast<wchar_t*>(pvBuffer), cbOriginalLength / sizeof(wchar_t));
return m->_pApiRoutines->SetConsoleTitleWImpl(title);
}
else
{
const std::string_view title(reinterpret_cast<char*>(pvBuffer), cbOriginalLength);
return m->_pApiRoutines->SetConsoleTitleAImpl(title);
}
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleMouseInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetNumberOfConsoleMouseButtons);
CONSOLE_GETMOUSEINFO_MSG* const a = &m->u.consoleMsgL3.GetConsoleMouseInfo;
m->_pApiRoutines->GetNumberOfConsoleMouseButtonsImpl(a->NumButtons);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleFontSize(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleFontSize);
CONSOLE_GETFONTSIZE_MSG* const a = &m->u.consoleMsgL3.GetConsoleFontSize;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_READ, &pObj));
return m->_pApiRoutines->GetConsoleFontSizeImpl(*pObj, a->FontIndex, a->FontSize);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCurrentFont(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetCurrentConsoleFontEx);
CONSOLE_CURRENTFONT_MSG* const a = &m->u.consoleMsgL3.GetCurrentConsoleFont;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_READ, &pObj));
CONSOLE_FONT_INFOEX FontInfo = { 0 };
FontInfo.cbSize = sizeof(FontInfo);
RETURN_IF_FAILED(m->_pApiRoutines->GetCurrentConsoleFontExImpl(*pObj, a->MaximumWindow, FontInfo));
CopyMemory(a->FaceName, FontInfo.FaceName, RTL_NUMBER_OF_V2(a->FaceName) * sizeof(a->FaceName[0]));
a->FontFamily = FontInfo.FontFamily;
a->FontIndex = FontInfo.nFont;
a->FontSize = FontInfo.dwFontSize;
a->FontWeight = FontInfo.FontWeight;
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleDisplayMode(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleDisplayMode);
CONSOLE_SETDISPLAYMODE_MSG* const a = &m->u.consoleMsgL3.SetConsoleDisplayMode;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
return m->_pApiRoutines->SetConsoleDisplayModeImpl(*pObj, a->dwFlags, a->ScreenBufferDimensions);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleDisplayMode(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleDisplayMode);
CONSOLE_GETDISPLAYMODE_MSG* const a = &m->u.consoleMsgL3.GetConsoleDisplayMode;
// Historically this has never checked the handles. It just returns global state.
m->_pApiRoutines->GetConsoleDisplayModeImpl(a->ModeFlags);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerAddConsoleAlias(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_ADDALIAS_MSG* const a = &m->u.consoleMsgL3.AddConsoleAliasW;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::AddConsoleAlias, a->Unicode);
// Read the input buffer and validate the strings.
PVOID pvBuffer;
ULONG cbBufferSize;
RETURN_IF_FAILED(m->GetInputBuffer(&pvBuffer, &cbBufferSize));
PVOID pvInputTarget;
ULONG const cbInputTarget = a->TargetLength;
PVOID pvInputExeName;
ULONG const cbInputExeName = a->ExeLength;
PVOID pvInputSource;
ULONG const cbInputSource = a->SourceLength;
// clang-format off
RETURN_HR_IF(E_INVALIDARG, !IsValidStringBuffer(a->Unicode,
pvBuffer,
cbBufferSize,
3,
cbInputExeName,
&pvInputExeName,
cbInputSource,
&pvInputSource,
cbInputTarget,
&pvInputTarget));
// clang-format on
if (a->Unicode)
{
const std::wstring_view inputSource(reinterpret_cast<wchar_t*>(pvInputSource), cbInputSource / sizeof(wchar_t));
const std::wstring_view inputTarget(reinterpret_cast<wchar_t*>(pvInputTarget), cbInputTarget / sizeof(wchar_t));
const std::wstring_view inputExeName(reinterpret_cast<wchar_t*>(pvInputExeName), cbInputExeName / sizeof(wchar_t));
return m->_pApiRoutines->AddConsoleAliasWImpl(inputSource, inputTarget, inputExeName);
}
else
{
const std::string_view inputSource(reinterpret_cast<char*>(pvInputSource), cbInputSource);
const std::string_view inputTarget(reinterpret_cast<char*>(pvInputTarget), cbInputTarget);
const std::string_view inputExeName(reinterpret_cast<char*>(pvInputExeName), cbInputExeName);
return m->_pApiRoutines->AddConsoleAliasAImpl(inputSource, inputTarget, inputExeName);
}
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleAlias(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_GETALIAS_MSG* const a = &m->u.consoleMsgL3.GetConsoleAliasW;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleAlias, a->Unicode);
PVOID pvInputBuffer;
ULONG cbInputBufferSize;
RETURN_IF_FAILED(m->GetInputBuffer(&pvInputBuffer, &cbInputBufferSize));
PVOID pvInputExe;
ULONG const cbInputExe = a->ExeLength;
PVOID pvInputSource;
ULONG const cbInputSource = a->SourceLength;
// clang-format off
RETURN_HR_IF(E_INVALIDARG, !IsValidStringBuffer(a->Unicode,
pvInputBuffer,
cbInputBufferSize,
2,
cbInputExe,
&pvInputExe,
cbInputSource,
&pvInputSource));
// clang-format on
PVOID pvOutputBuffer;
ULONG cbOutputBufferSize;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvOutputBuffer, &cbOutputBufferSize));
HRESULT hr;
size_t cbWritten;
if (a->Unicode)
{
const std::wstring_view inputSource(reinterpret_cast<wchar_t*>(pvInputSource), cbInputSource / sizeof(wchar_t));
const std::wstring_view inputExeName(reinterpret_cast<wchar_t*>(pvInputExe), cbInputExe / sizeof(wchar_t));
gsl::span<wchar_t> outputBuffer(reinterpret_cast<wchar_t*>(pvOutputBuffer), cbOutputBufferSize / sizeof(wchar_t));
size_t cchWritten;
hr = m->_pApiRoutines->GetConsoleAliasWImpl(inputSource, outputBuffer, cchWritten, inputExeName);
// We must set the reply length in bytes. Convert back from characters.
RETURN_IF_FAILED(SizeTMult(cchWritten, sizeof(wchar_t), &cbWritten));
}
else
{
const std::string_view inputSource(reinterpret_cast<char*>(pvInputSource), cbInputSource);
const std::string_view inputExeName(reinterpret_cast<char*>(pvInputExe), cbInputExe);
gsl::span<char> outputBuffer(reinterpret_cast<char*>(pvOutputBuffer), cbOutputBufferSize);
size_t cchWritten;
hr = m->_pApiRoutines->GetConsoleAliasAImpl(inputSource, outputBuffer, cchWritten, inputExeName);
cbWritten = cchWritten;
}
// We must return the byte length of the written data in the message
RETURN_IF_FAILED(SizeTToUShort(cbWritten, &a->TargetLength));
m->SetReplyInformation(a->TargetLength);
// See conlibk.lib. For any "buffer too small condition", we must send the exact status code
// NTSTATUS = STATUS_BUFFER_TOO_SMALL. If we send Win32 or HRESULT equivalents, the client library
// will zero out our DWORD return value set in a->TargetLength on our behalf.
if (ERROR_INSUFFICIENT_BUFFER == hr ||
HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) == hr)
{
hr = STATUS_BUFFER_TOO_SMALL;
}
return hr;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleAliasesLength(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
PCONSOLE_GETALIASESLENGTH_MSG const a = &m->u.consoleMsgL3.GetConsoleAliasesLengthW;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleAliasesLength, a->Unicode);
ULONG cbExeNameLength;
PVOID pvExeName;
RETURN_IF_FAILED(m->GetInputBuffer(&pvExeName, &cbExeNameLength));
size_t cbAliasesLength;
if (a->Unicode)
{
const std::wstring_view inputExeName(reinterpret_cast<wchar_t*>(pvExeName), cbExeNameLength / sizeof(wchar_t));
size_t cchAliasesLength;
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleAliasesLengthWImpl(inputExeName, cchAliasesLength));
RETURN_IF_FAILED(SizeTMult(cchAliasesLength, sizeof(wchar_t), &cbAliasesLength));
}
else
{
const std::string_view inputExeName(reinterpret_cast<char*>(pvExeName), cbExeNameLength);
size_t cchAliasesLength;
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleAliasesLengthAImpl(inputExeName, cchAliasesLength));
cbAliasesLength = cchAliasesLength;
}
RETURN_IF_FAILED(SizeTToULong(cbAliasesLength, &a->AliasesLength));
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleAliasExesLength(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
PCONSOLE_GETALIASEXESLENGTH_MSG const a = &m->u.consoleMsgL3.GetConsoleAliasExesLengthW;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleAliasExesLength, a->Unicode);
size_t cbAliasExesLength;
if (a->Unicode)
{
size_t cchAliasExesLength;
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleAliasExesLengthWImpl(cchAliasExesLength));
cbAliasExesLength = cchAliasExesLength * sizeof(wchar_t);
}
else
{
size_t cchAliasExesLength;
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleAliasExesLengthAImpl(cchAliasExesLength));
cbAliasExesLength = cchAliasExesLength;
}
RETURN_IF_FAILED(SizeTToULong(cbAliasExesLength, &a->AliasExesLength));
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleAliases(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_GETALIASES_MSG* const a = &m->u.consoleMsgL3.GetConsoleAliasesW;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleAliases, a->Unicode);
PVOID pvExeName;
ULONG cbExeNameLength;
RETURN_IF_FAILED(m->GetInputBuffer(&pvExeName, &cbExeNameLength));
PVOID pvOutputBuffer;
DWORD cbAliasesBufferLength;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvOutputBuffer, &cbAliasesBufferLength));
size_t cbWritten;
if (a->Unicode)
{
const std::wstring_view inputExeName(reinterpret_cast<wchar_t*>(pvExeName), cbExeNameLength / sizeof(wchar_t));
gsl::span<wchar_t> outputBuffer(reinterpret_cast<wchar_t*>(pvOutputBuffer), cbAliasesBufferLength / sizeof(wchar_t));
size_t cchWritten;
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleAliasesWImpl(inputExeName, outputBuffer, cchWritten));
// We must set the reply length in bytes. Convert back from characters.
RETURN_IF_FAILED(SizeTMult(cchWritten, sizeof(wchar_t), &cbWritten));
}
else
{
const std::string_view inputExeName(reinterpret_cast<char*>(pvExeName), cbExeNameLength);
gsl::span<char> outputBuffer(reinterpret_cast<char*>(pvOutputBuffer), cbAliasesBufferLength);
size_t cchWritten;
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleAliasesAImpl(inputExeName, outputBuffer, cchWritten));
cbWritten = cchWritten;
}
RETURN_IF_FAILED(SizeTToULong(cbWritten, &a->AliasesBufferLength));
m->SetReplyInformation(a->AliasesBufferLength);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleAliasExes(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_GETALIASEXES_MSG* const a = &m->u.consoleMsgL3.GetConsoleAliasExesW;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleAliasExes, a->Unicode);
PVOID pvBuffer;
ULONG cbAliasExesBufferLength;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvBuffer, &cbAliasExesBufferLength));
size_t cbWritten;
if (a->Unicode)
{
gsl::span<wchar_t> outputBuffer(reinterpret_cast<wchar_t*>(pvBuffer), cbAliasExesBufferLength / sizeof(wchar_t));
size_t cchWritten;
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleAliasExesWImpl(outputBuffer, cchWritten));
RETURN_IF_FAILED(SizeTMult(cchWritten, sizeof(wchar_t), &cbWritten));
}
else
{
gsl::span<char> outputBuffer(reinterpret_cast<char*>(pvBuffer), cbAliasExesBufferLength);
size_t cchWritten;
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleAliasExesAImpl(outputBuffer, cchWritten));
cbWritten = cchWritten;
}
// We must return the byte length of the written data in the message
RETURN_IF_FAILED(SizeTToULong(cbWritten, &a->AliasExesBufferLength));
m->SetReplyInformation(a->AliasExesBufferLength);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerExpungeConsoleCommandHistory(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_EXPUNGECOMMANDHISTORY_MSG* const a = &m->u.consoleMsgL3.ExpungeConsoleCommandHistoryW;
PVOID pvExeName;
ULONG cbExeNameLength;
RETURN_IF_FAILED(m->GetInputBuffer(&pvExeName, &cbExeNameLength));
if (a->Unicode)
{
const std::wstring_view inputExeName(reinterpret_cast<wchar_t*>(pvExeName), cbExeNameLength / sizeof(wchar_t));
return m->_pApiRoutines->ExpungeConsoleCommandHistoryWImpl(inputExeName);
}
else
{
const std::string_view inputExeName(reinterpret_cast<char*>(pvExeName), cbExeNameLength);
return m->_pApiRoutines->ExpungeConsoleCommandHistoryAImpl(inputExeName);
}
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleNumberOfCommands(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_SETNUMBEROFCOMMANDS_MSG* const a = &m->u.consoleMsgL3.SetConsoleNumberOfCommandsW;
PVOID pvExeName;
ULONG cbExeNameLength;
RETURN_IF_FAILED(m->GetInputBuffer(&pvExeName, &cbExeNameLength));
size_t const NumberOfCommands = a->NumCommands;
if (a->Unicode)
{
const std::wstring_view inputExeName(reinterpret_cast<wchar_t*>(pvExeName), cbExeNameLength / sizeof(wchar_t));
return m->_pApiRoutines->SetConsoleNumberOfCommandsWImpl(inputExeName, NumberOfCommands);
}
else
{
const std::string_view inputExeName(reinterpret_cast<char*>(pvExeName), cbExeNameLength);
return m->_pApiRoutines->SetConsoleNumberOfCommandsAImpl(inputExeName, NumberOfCommands);
}
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCommandHistoryLength(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
PCONSOLE_GETCOMMANDHISTORYLENGTH_MSG const a = &m->u.consoleMsgL3.GetConsoleCommandHistoryLengthW;
PVOID pvExeName;
ULONG cbExeNameLength;
RETURN_IF_FAILED(m->GetInputBuffer(&pvExeName, &cbExeNameLength));
size_t cbCommandHistoryLength;
if (a->Unicode)
{
size_t cchCommandHistoryLength;
const std::wstring_view inputExeName(reinterpret_cast<wchar_t*>(pvExeName), cbExeNameLength / sizeof(wchar_t));
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleCommandHistoryLengthWImpl(inputExeName, cchCommandHistoryLength));
// We must set the reply length in bytes. Convert back from characters.
RETURN_IF_FAILED(SizeTMult(cchCommandHistoryLength, sizeof(wchar_t), &cbCommandHistoryLength));
}
else
{
size_t cchCommandHistoryLength;
const std::string_view inputExeName(reinterpret_cast<char*>(pvExeName), cbExeNameLength);
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleCommandHistoryLengthAImpl(inputExeName, cchCommandHistoryLength));
cbCommandHistoryLength = cchCommandHistoryLength;
}
// Fit return value into structure memory size
RETURN_IF_FAILED(SizeTToULong(cbCommandHistoryLength, &a->CommandHistoryLength));
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleCommandHistory(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
PCONSOLE_GETCOMMANDHISTORY_MSG const a = &m->u.consoleMsgL3.GetConsoleCommandHistoryW;
PVOID pvExeName;
ULONG cbExeNameLength;
RETURN_IF_FAILED(m->GetInputBuffer(&pvExeName, &cbExeNameLength));
PVOID pvOutputBuffer;
ULONG cbOutputBuffer;
RETURN_IF_FAILED(m->GetOutputBuffer(&pvOutputBuffer, &cbOutputBuffer));
size_t cbWritten;
if (a->Unicode)
{
const std::wstring_view inputExeName(reinterpret_cast<wchar_t*>(pvExeName), cbExeNameLength / sizeof(wchar_t));
gsl::span<wchar_t> outputBuffer(reinterpret_cast<wchar_t*>(pvOutputBuffer), cbOutputBuffer / sizeof(wchar_t));
size_t cchWritten;
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleCommandHistoryWImpl(inputExeName, outputBuffer, cchWritten));
// We must set the reply length in bytes. Convert back from characters.
RETURN_IF_FAILED(SizeTMult(cchWritten, sizeof(wchar_t), &cbWritten));
}
else
{
const std::string_view inputExeName(reinterpret_cast<char*>(pvExeName), cbExeNameLength);
gsl::span<char> outputBuffer(reinterpret_cast<char*>(pvOutputBuffer), cbOutputBuffer);
size_t cchWritten;
RETURN_IF_FAILED(m->_pApiRoutines->GetConsoleCommandHistoryAImpl(inputExeName, outputBuffer, cchWritten));
cbWritten = cchWritten;
}
// Fit return value into structure memory size.
RETURN_IF_FAILED(SizeTToULong(cbWritten, &a->CommandBufferLength));
m->SetReplyInformation(a->CommandBufferLength);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleWindow(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleWindow);
CONSOLE_GETCONSOLEWINDOW_MSG* const a = &m->u.consoleMsgL3.GetConsoleWindow;
m->_pApiRoutines->GetConsoleWindowImpl(a->hwnd);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleSelectionInfo(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleSelectionInfo);
CONSOLE_GETSELECTIONINFO_MSG* const a = &m->u.consoleMsgL3.GetConsoleSelectionInfo;
m->_pApiRoutines->GetConsoleSelectionInfoImpl(a->SelectionInfo);
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerGetConsoleHistory(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_HISTORY_MSG* const a = &m->u.consoleMsgL3.GetConsoleHistory;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::GetConsoleHistoryInfo);
CONSOLE_HISTORY_INFO info;
info.cbSize = sizeof(info);
m->_pApiRoutines->GetConsoleHistoryInfoImpl(info);
a->dwFlags = info.dwFlags;
a->HistoryBufferSize = info.HistoryBufferSize;
a->NumberOfHistoryBuffers = info.NumberOfHistoryBuffers;
return S_OK;
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleHistory(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
CONSOLE_HISTORY_MSG* const a = &m->u.consoleMsgL3.SetConsoleHistory;
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetConsoleHistoryInfo);
CONSOLE_HISTORY_INFO info;
info.cbSize = sizeof(info);
info.dwFlags = a->dwFlags;
info.HistoryBufferSize = a->HistoryBufferSize;
info.NumberOfHistoryBuffers = a->NumberOfHistoryBuffers;
return m->_pApiRoutines->SetConsoleHistoryInfoImpl(info);
}
[[nodiscard]] HRESULT ApiDispatchers::ServerSetConsoleCurrentFont(_Inout_ CONSOLE_API_MSG* const m,
_Inout_ BOOL* const /*pbReplyPending*/)
{
Telemetry::Instance().LogApiCall(Telemetry::ApiCall::SetCurrentConsoleFontEx);
CONSOLE_CURRENTFONT_MSG* const a = &m->u.consoleMsgL3.SetCurrentConsoleFont;
ConsoleHandleData* const pObjectHandle = m->GetObjectHandle();
RETURN_HR_IF_NULL(E_HANDLE, pObjectHandle);
SCREEN_INFORMATION* pObj;
RETURN_IF_FAILED(pObjectHandle->GetScreenBuffer(GENERIC_WRITE, &pObj));
CONSOLE_FONT_INFOEX Info;
Info.cbSize = sizeof(Info);
Info.dwFontSize = a->FontSize;
CopyMemory(Info.FaceName, a->FaceName, RTL_NUMBER_OF_V2(Info.FaceName) * sizeof(Info.FaceName[0]));
Info.FontFamily = a->FontFamily;
Info.FontWeight = a->FontWeight;
return m->_pApiRoutines->SetCurrentConsoleFontExImpl(*pObj, a->MaximumWindow, Info);
}
|
; ***************************************************************************
; ***************************************************************************
;
; aplib.asm
;
; 65C816 decompressor for data stored in Jorgen Ibsen's aPLib format.
;
; Includes support for Emmanuel Marty's enhancements to the aPLib format.
;
; The code is 413 bytes long.
;
; This code is written for the ASAR assembler.
;
; Based off of the NMOS 6502 decompressor, Copyright 2019, John Brandwood:
; https://github.com/emmanuel-marty/apultra/blob/master/asm/6502/aplib_6502.asm
;
; Distributed under the Boost Software License, Version 1.0.
;
; Permission is hereby granted, free of charge, to any person or organization
; obtaining a copy of the software and accompanying documentation covered by
; this license (the "Software") to use, reproduce, display, distribute,
; execute, and transmit the Software, and to prepare derivative works of the
; Software, and to permit third-parties to whom the Software is furnished to
; do so, all subject to the following:
;
; The copyright notices in the Software and this entire statement, including
; the above license grant, this restriction and the following disclaimer,
; must be included in all copies of the Software, in whole or in part, and
; all derivative works of the Software, unless such copies or derivative
; works are solely in the form of machine-executable object code generated by
; a source language processor.
;
; 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
; SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
; FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
; ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; ***************************************************************************
; ***************************************************************************
; ***************************************************************************
; ***************************************************************************
;
; Decompression Macros
;
; Register usage
!scratch = $f0 ; 2-byte. Scratch+1 must remain #$00!
!hilen = $f2 ; 1-byte. Temporary for high byte of length.
!bitbuf = $f3 ; 1-byte.
!offset = $f4 ; 2-byte.
!spbuf = $f6 ; 2-byte.
!tdstptr = $f8 ; 2-byte. Temporary dstptr location.
!srcptr = $fa ; 3-byte.
!dstptr = $fd ; 2-byte.
!dstbank = $7f ; const.
;
; Macro to increment the source pointer to the next page.
; opt: duplication: removes costly jmps.
;
macro APL_GET_SRC()
lda [!srcptr], y ; opt: keep lowbyte in reg.
iny ; inc src addr.
bne +
inc !srcptr+1 ; highbyte in zeropage.
bne +
inc !srcptr+2 ; page in zeropage.
+:
endmacro
;
; Macro for byte & bit handling.
; opt: duplication: removes costly jmps.
;
macro APL_LOAD_BIT()
%APL_GET_SRC() ; Reload an empty bit-buffer
rol ; from the compressed source.
sta !bitbuf
endmacro
;
; Macro for gamma handling.
; opt: duplication: removes costly jmps.
;
macro APL_GET_GAMMA()
lda #$1 ; Get a gamma-coded value.
--: asl !bitbuf
bne ++
tcs ; opt: 2-cycle.
%APL_LOAD_BIT() ; Reload an empty bit-buffer
tsc ; opt: 2-cycle.
++: rol
rol !hilen
asl !bitbuf
bne ++
tcs ; opt: 2-cycle.
%APL_LOAD_BIT() ; Reload an empty bit-buffer
tsc ; opt: 2-cycle.
++: bcs --
endmacro
; ***************************************************************************
; ***************************************************************************
;
; apl_decompress - Decompress data stored in Jorgen Ibsen's aPLib format.
;
; Uses: lots!
;
; As an optimization, the code to handle window offsets > 64768 bytes has
; been removed, since these don't occur with a 16-bit address range.
;
; As an optimization, the code to handle window offsets > 32000 bytes can
; be commented-out, since these don't occur in typical 8-bit computer usage.
;
; Overall opts: reduce register pressure on y & x, use stack ptr, mvn, remove subroutine jumps.
macro APL()
apl_decompress:
; setup init.
sep #$30
phb ; push bank.
lda #!dstbank ; load new bank.
pha
plb
rep #$30
sei ; disable interrupts.
lda #$0000
sta !scratch ; clear scratch.
sta $004200 ; disable nmi.
tsc ; opt: use sp as free reg.
sta !spbuf ; store sp.
sep #$30
; ---.
ldy !srcptr ; Initialize source index.
stz !srcptr ; Opt: set lowbyte to zero.
lda #$80 ; Initialize an empty
sta !bitbuf ; bit-buffer.
;
; 0 bbbbbbbb - One byte from compressed data, i.e. a "literal".
;
.literal: % APL_GET_SRC()
.write_byte: ldx #$00 ; LWM=0.
sta (!dstptr) ; Write the byte directly to the output.
inc !dstptr
bne .next_tag
inc !dstptr+1
.next_tag: asl !bitbuf ; 0 bbbbbbbb
bne .skip0
%APL_LOAD_BIT() ; opt: no jsr.
.skip0: bcc .literal
.skip1: asl !bitbuf ; 1 0 <offset> <length>
bne .skip2
%APL_LOAD_BIT() ; opt: no jsr.
.skip2: bcc .copy_large
asl !bitbuf ; 1 1 0 dddddddn
bne .skip3
%APL_LOAD_BIT() ; opt: no jsr.
.skip3: bcc .copy_normal
; 1 1 1 dddd - Copy 1 byte within 15 bytes (or zero).
.copy_short: lda #$10
.nibble_loop: asl !bitbuf
bne .skip4
tcs ; opt: 2-cycle.
%APL_LOAD_BIT() ; opt: no jsr.
tsc ; opt: 2-cycle.
.skip4: rol
bcc .nibble_loop
beq .write_byte ; Offset=0 means write zero.
sta !scratch ; +1 of scratch must remain zero.
rep #$20
lda !dstptr
sbc !scratch
sta !tdstptr
sep #$20
lda (!tdstptr)
bra .write_byte
.finished: rep #$30 ; Fin.
lda !spbuf ; load sp.
tcs ; restore sp.
lda $80
sta $004200 ; enable
cli ; enable interrupts.
sep #$30
plb ; restore bank.
rep #$30
rtl ; All decompressed!
;
; 1 1 0 dddddddn - Copy 2 or 3 within 128 bytes.
;
.copy_normal: % APL_GET_SRC() ; 1 1 0 dddddddn
lsr
beq .finished ; Offset 0 == EOF.
sta !offset ; Preserve offset.
tdc ; opt: Clear high byte of length.
sta !offset+1 ; clear high byte of offset.
adc #$2 ; +2 length.
jmp .copy_page ; NZ from previous ADC.
;
; 1 0 <offset> <length> - gamma-coded LZSS pair.
;
.copy_large: tdc ; opt: Clear high byte of length
sta !hilen
%APL_GET_GAMMA() ; opt: no jsr, Get length.
cpx #$1 ; CC if LWM==0, CS if LWM==1.
sbc #$2 ; -3 if LWM==0, -2 if LWM==1.
bcs .normal_pair ; CC if LWM==0 && offset==2.
%APL_GET_GAMMA() ; opt: no jsr, Get length.
xba ; non-opt: put together length.
lda !hilen ; load highbyte of length.
xba ; non-opt: put together length.
bra .copy_page ; Use previous Offset.
.normal_pair: tax ; opt: keep for cmp.
stx !offset+1 ; Save bits 8..15 of offset.
% APL_GET_SRC() ; opt: no jsr.
sta !offset ; Save bits 0...7 of offset.
%APL_GET_GAMMA() ; opt: no jsr.
xba ; non-opt: put together length.
lda !hilen ; load highbyte of length.
xba ; non-opt: put together length.
;
cpx #$00 ; If offset < 256.
beq .lt256
cpx #$7D ; If offset >= 32000, length += 1.
bcs .match_plus2
cpx #$05 ; If offset >= 1280, length += 0.
bcs .match_plus1
.copy_page: ; opt: mvn, Calc address of match and store.
dec
sty !scratch ; opt: 2-cycle, store srcptr lowbyte.
rep #$30
tcs ; opt: 2-cycle, store 2 byte length.
lda !dstptr ; load precomputed destptr.
tay ; transfer cur dest.
sec ; non opt: need to keep this.
sbc !offset ; opt: subtract full offset in one go.
tax ; transfer src.
tsc ; opt: 2-cycle, load 2 byte length.
mvn !dstbank, !dstbank ; opt: mvn.
sty !dstptr ; opt: free computation of next dstptr
sep #$30
ldx #$01 ; transfer 1 to x. ; LWM=1.
ldy !scratch ; opt: 2-cycle, load srcptr lowbyte.
jmp .next_tag
.lt256: ldx !offset ; If offset < 128, length += 1.
bmi .copy_page
sec
.match_plus2: adc #$1 ; CS, so ADC #2.
bcs .match_plus256
.match_plus1: adc #$0 ; CS, so ADC #1, or CC if fall
bcc .copy_page ; through from .match_plus2.
.match_plus256: xba ; rare.
inc
xba
bra .copy_page
.end:
endmacro
|
/*
* Copyright (c) 2019, Zuse Institute Berlin.
*
* Licensed under the New BSD License, see LICENSE file for details.
*
*/
#include "rpc_client.h"
#include "paciofs.grpc.pb.h"
#include "posix_io.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <sys/types.h>
#include <unistd.h>
#include <fstream>
#include <sstream>
#include <string>
namespace paciofs {
namespace grpc {
template <typename Service>
RpcClient<Service>::RpcClient(std::string const &target,
std::string const &cert_chain,
std::string const &private_key,
std::string const &root_certs) {
::grpc::SslCredentialsOptions ssl;
bool use_ssl = false;
if (cert_chain.length() > 0) {
ssl.pem_cert_chain = ReadPem(cert_chain);
use_ssl = true;
}
if (private_key.length() > 0) {
ssl.pem_private_key = ReadPem(private_key);
use_ssl = true;
}
if (root_certs.length() > 0) {
ssl.pem_root_certs = ReadPem(root_certs);
use_ssl = true;
}
CreateMetadata();
if (use_ssl) {
stub_ = Service::NewStub(
::grpc::CreateChannel(target, ::grpc::SslCredentials(ssl)));
} else {
stub_ = Service::NewStub(
::grpc::CreateChannel(target, ::grpc::InsecureChannelCredentials()));
}
}
template <typename Service>
std::string RpcClient<Service>::ReadPem(std::string const &path) {
std::ifstream in;
std::stringstream sstr;
in.open(path);
sstr << in.rdbuf();
return sstr.str();
}
template <typename Service>
void RpcClient<Service>::CreateMetadata() {
// TODO stop using the current user and group so all files can belong to us
metadata_user_ = std::to_string(getuid());
metadata_group_ = std::to_string(getgid());
}
template <typename Service>
std::unique_ptr<typename Service::Stub> const &RpcClient<Service>::Stub() {
return stub_;
}
template <typename Service>
void RpcClient<Service>::SetMetadata(::grpc::ClientContext &context) {
// We do not use call credentials because they get dropped automatically if
// the channel is insecure for obvious reasons. So do not put any sensitive
// information here.
context.AddMetadata("x-user", metadata_user_);
context.AddMetadata("x-group", metadata_group_);
}
template class RpcClient<PacioFsService>;
template class RpcClient<paciofs::io::posix::grpc::PosixIoService>;
} // namespace grpc
} // namespace paciofs
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
80
.text@150
lbegin:
ld c, 41
ld b, 02
ld d, 03
lbegin_waitm2:
ldff a, (c)
and a, d
cmp a, b
jrnz lbegin_waitm2
ld a, 08
ldff(c), a
xor a, a
ldff(0f), a
ld a, 02
ldff(ff), a
ei
ld c, 0f
.text@1000
lstatint:
ld a, 48
ldff(41), a
ldff a, (44)
inc a
ldff(45), a
ld a, 01
ldff(43), a
.text@1058
xor a, a
ldff(c), a
nop
nop
nop
nop
nop
nop
ld a, ff
ldff(45), a
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
ldff a, (c)
and a, 03
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
|
// 2003-03-08 Jerry Quinn <jlquinn@optonline.net>
// Copyright (C) 2003 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#include <istream>
#include <streambuf>
#include <testsuite_hooks.h>
#include <testsuite_io.h>
// libstdc++/9561
void test01()
{
using namespace std;
bool test __attribute__((unused)) = true;
__gnu_test::fail_streambuf b;
std::istream strm (&b);
strm.exceptions (std::ios::badbit);
int i = 0;
try
{
i = strm.get();
i = strm.get();
i = strm.get();
}
catch (__gnu_test::underflow_error&)
{
// strm should throw facet_error and not do anything else
VERIFY(strm.bad());
}
catch (...)
{
VERIFY(false);
}
VERIFY(i == 's');
}
int main()
{
test01();
return 0;
}
|
global _start
section .text
_start:
push 0xb
pop eax
cltd
push edx
push 0x6c6c6177
push 0x207c2021
push 0x64336b63
push 0x75685020
push 0x6f686365
mov esi, esp
push edx
push word 0x632d
mov ecx, esp
push edx
push 0x68732f2f
push 0x6e69622f
mov ebx, esp
push edx
push esi
push ecx
push ebx
mov ecx, esp
int 0x80
|
;
; Create a file by the BASIC driver (open then close)
;
; Stefano - 5/7/2006
;
; int creat(far char *name, mode_t mode);
;
; $Id: creat.asm,v 1.2 2015/01/21 08:09:27 stefano Exp $
PUBLIC creat
EXTERN open
EXTERN close
.creat
pop bc
pop hl
push hl
push bc
push bc
push bc
push hl
call open
pop bc
pop bc
pop bc
ld a,h
or l
cp 255 ; -1 => error ?
ret z
push hl
call close
pop hl
ld hl,0
ret
|
// Copyright Nikolay Mladenov 2007.
// 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 FUNCTION_SIGNATURE_20070531_HPP
#define FUNCTION_SIGNATURE_20070531_HPP
#include <boost/python/converter/registrations.hpp>
#include <boost/python/detail/signature.hpp>
#include <boost/python/object/function.hpp>
#include <boost/python/str.hpp>
#include <boost/python/tuple.hpp>
#include <vector>
namespace boost
{
namespace python
{
namespace objects
{
class function_doc_signature_generator
{
static const char* py_type_str(const python::detail::signature_element& s);
static bool arity_cmp(function const* f1, function const* f2);
static bool are_seq_overloads(function const* f1, function const* f2,
bool check_docs);
static std::vector<function const*> flatten(function const* f);
static std::vector<function const*>
split_seq_overloads(const std::vector<function const*>& funcs,
bool split_on_doc_change);
static str raw_function_pretty_signature(function const* f,
size_t n_overloads,
bool cpp_types = false);
static str parameter_string(py_function const& f, size_t n,
object arg_names, bool cpp_types);
static str pretty_signature(function const* f, size_t n_overloads,
bool cpp_types = false);
public:
static list function_doc_signatures(function const* f);
};
} // namespace objects
} // namespace python
} // namespace boost
#endif // FUNCTION_SIGNATURE_20070531_HPP
|
aLine 0
gNew basePtr
gMoveNext basePtr, Root
gNewVPtr maxNext
gNewVPtr rootNext
gMoveNext rootNext, Root
gNewVPtr basePrev
gNew maxPtr, 1085, 800
gNewVPtr maxPrev
gNew currentPtr, 1085, 920
aLine 1
gBeq basePtr, null, 46
aLine 3
gMove maxPtr, basePtr
aLine 4
gMoveNext currentPtr, basePtr
aLine 5
gBeq currentPtr, null, 8
aLine 6
vBge maxPtr, currentPtr, 3
aLine 7
gMove maxPtr, currentPtr
aLine 9
gMoveNext currentPtr, currentPtr
Jmp -8
aLine 12
gMovePrev basePrev, basePtr
gBne basePrev, Root, 3
aLine 13
gMove Rear, maxPtr
aLine 15
gBne maxPtr, basePtr, 3
aLine 16
gMoveNext basePtr, basePtr
aLine 18
gMovePrev maxPrev, maxPtr
gMoveNext maxNext, maxPtr
nMoveRel maxPtr, maxPtr, 0, -164.545
pSetNext maxPrev, maxNext
aLine 19
gBeq maxNext, null, 3
aLine 20
pSetPrev maxNext, maxPrev
aLine 22
pDeleteNext maxPtr
pDeletePrev maxPtr
nMoveRel maxPtr, Root, 95, -164.545
gMoveNext rootNext, Root
pSetNext maxPtr, rootNext
aLine 23
pSetPrev rootNext, maxPtr
aLine 24
pSetNext Root, maxPtr
aLine 25
pSetPrev maxPtr, Root
aStd
Jmp -46
aLine 27
gDelete basePrev
gDelete basePtr
gDelete maxNext
gDelete maxPtr
gDelete maxPrev
gDelete rootNext
gDelete currentPtr
aStd
Halt |
; Chapter 7
; 7.8 Example program, Sum of Squares
; Simple program to compute the of squares from 1 to n
; ***********************************
; Data declarations
section .data
; ------
; Define constants
SUCCESS equ 0
SYS_exit equ 60
; -----
; Define data
n dd 10
sumOfSquares dq 0
; **********************************
section .text
global _start
_start:
; -----
; Compute sum of squares from 1 to n
; Approach:
; for (i=1; i<n; i++)
; sumOfSquares += i^2
mov rbx, 1 ; i
mov ecx, dword[n]
sumLoop:
mov rax, rbx ; get i
mul rax ; i^2
add qword[sumOfSquares], rax
inc rbx
loop sumLoop
; ------
; Done, terminate program
last:
mov rax, SYS_exit ; call code for exit
mov rdi, SUCCESS ; exit with sucess
syscall
|
// cmcstl2 - A concept-enabled C++ standard library
//
// Copyright Casey Carter 2015
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/caseycarter/cmcstl2
//
#ifndef STL2_DETAIL_ALGORITHM_MOVE_BACKWARD_HPP
#define STL2_DETAIL_ALGORITHM_MOVE_BACKWARD_HPP
#include <stl2/iterator.hpp>
#include <stl2/detail/algorithm/results.hpp>
///////////////////////////////////////////////////////////////////////////
// move_backward [alg.move]
//
STL2_OPEN_NAMESPACE {
template<class I1, class I2>
using move_backward_result = __in_out_result<I1, I2>;
struct __move_backward_fn : private __niebloid {
template<BidirectionalIterator I1, Sentinel<I1> S1, BidirectionalIterator I2>
requires IndirectlyMovable<I1, I2>
constexpr move_backward_result<I1, I2>
operator()(I1 first, S1 s, I2 result) const {
auto last = next(first, std::move(s));
auto i = last;
while (i != first) {
*--result = iter_move(--i);
}
return {std::move(last), std::move(result)};
}
template<BidirectionalRange Rng, BidirectionalIterator I>
requires IndirectlyMovable<iterator_t<Rng>, I>
constexpr move_backward_result<safe_iterator_t<Rng>, I>
operator()(Rng&& rng, I result) const {
return (*this)(begin(rng), end(rng), std::move(result));
}
};
inline constexpr __move_backward_fn move_backward {};
} STL2_CLOSE_NAMESPACE
#endif
|
;
;
; ZX Spectrum ZXMMC specific routines
; code by Alessandro Poppi
; ported to z88dk by Stefano Bodrato - Mar 2010
;
; $Id: mmc_read_block.asm,v 1.3 2016-06-10 21:28:03 dom Exp $
;
; Read a 512 byte data block from the MMC card
; extern int __LIB__ mmc_read_block(struct MMC mmc_descriptor, long card_address, unsigned char *address);
;
;-----------------------------------------------------------------------------------------
; READ A SINGLE BLOCK OF DATA subroutine
;
; This routine only works for blocksize = 512 (two INIR sequence).
;
; HL, DE= MSB, LSB of 32bit address in MMC memory
; then, HL = ram buffer address
;
; RETURN code in HL:
; 0 = OK
; 1 = read_block command error
; 2 = no wait_data token from MMC
;
; DESTROYS AF, HL
;-----------------------------------------------------------------------------------------
SECTION code_clib
PUBLIC mmc_read_block
PUBLIC _mmc_read_block
EXTERN mmc_send_command
EXTERN mmc_waitdata_token
EXTERN clock32
EXTERN cs_high
EXTERN __mmc_card_select
INCLUDE "target/zx/def/zxmmc.def"
mmc_read_block:
_mmc_read_block:
ld ix,0
add ix,sp
ld l,(ix+8)
ld h,(ix+9) ; MMC struct
ld a,(hl)
inc hl ; ptr to MMC mask to be used to select port
ld a,(hl)
ld (__mmc_card_select), a
ld l,(ix+2)
ld h,(ix+3) ; RAM ptr
push hl
ld e,(ix+4) ; LSB
ld d,(ix+5) ; .
ld l,(ix+6) ; .
ld h,(ix+7) ; MSB
ld a,MMC_READ_SINGLE_BLOCK ; Command code for block read
call mmc_send_command
and a
jr z,noerror
ld l,a
ld h,0
noerror:
call mmc_waitdata_token
cp $FE
jr z,read_mmc_block ; OK
pop hl
ld hl,2 ; no data token from MMC
ret
read_mmc_block:
pop hl ; HL = INIR write pointer
ld bc,SPI_PORT ; B = 0 = 256 bytes for the first INIR; C = I/O port
inir
nop
inir
nop
nop
in a,(SPI_PORT) ; CRC
nop
nop
in a,(SPI_PORT) ; CRC
call cs_high ; set cs high
call clock32 ; 32 more clock cycles
ld hl,0
ret
|
#include <iostream>
#include <list>
using namespace std;
/*
Application Crash test !
*/
int main()
{
int a = 4;
std::list<int> x[-a];
//result(Application Crash)
}
|
; Q40 SMSQ BEEP emulation 1988 Tony Tebby
section sms
xdef hdop_beep
xdef hdop_bpof
xref hdop_poll
xref hdop_ssss
include 'dev8_keys_sys'
include 'dev8_keys_iod'
include 'dev8_keys_err'
include 'dev8_keys_sss'
include 'dev8_smsq_q40_hdop_data'
hdop_beep
hob.rege reg d1-d3/a0/a1/a2
hob.regx reg d1-d3/a0/a1/a2/a3
movem.l hob.rege,-(sp)
move.l a3,a1 ; save parameter block
bsr.l hob_lloc ; locate linkage and stop beeping
bne.l hob_exit
lea ho_work(a3),a0
move.b (a1)+,d0 ; number of parameters
moveq #0,d1 ; no nibbles
move.l (a1)+,d2 ; mask of bits
bra.s hob_dlend
hob_dloop
moveq #0,d3
move.b (a1)+,d3 ; next byte
ror.l #1,d2 ; any to send?
bcs.s hob_skip ; ... no
ror.l #1,d2 ; how much?
bcs.s hob_byte ; a byte
and.b #$0f,d3 ; ... this much
not.b d1 ; any sent already?
bne.s hob_msnib ; ... no
or.b d3,(a0)+ ; put it in
bra.s hob_dlend
hob_msnib
lsl.b #4,d3
move.b d3,(a0) ; set ms nibble
bra.s hob_dlend
hob_byte
tst.b d1 ; a nibble in already?
beq.s hob_whole ; ... no
ror.w #4,d3 ; ms nibble
or.b d3,(a0)+
rol.w #8,d3 ; ls nibble
move.b d3,(a0)
bra.s hob_dlend
hob_whole
move.b d3,(a0)+ ; whole byte
bra.s hob_dlend
hob_skip
ror.l #1,d2 ; skip bit
hob_dlend
dbra d0,hob_dloop ; next bit.
lea ho_work(a3),a0
moveq #0,d0 ; get pitch 1
move.b (a0)+,d0
subq.b #1,d0
mulu #ho.bpscl,d0
lsr.l #ho.bpssf,d0
add.w #ho.bpoff,d0 ; scaled and offset
move.w d0,ho_bphgh(a3)
move.w d0,d2
moveq #0,d1 ; get pitch 2
move.b (a0)+,d1
subq.b #1,d1
tst.w (a0) ; any interval?
beq.s hob_setl ; ... none
move.b d1,d0
mulu #ho.bpscl,d0
lsr.l #ho.bpssf,d0
add.w #ho.bpoff,d0 ; scaled and offset
hob_setl
move.w d0,ho_bplow(a3)
add.w d0,d2 ; total of pitches
add.w #ho.bpfb,d2
move.l #ho.bpfa,d0
divu d2,d0
add.w #ho.bpfo,d0 ; pitch fudge factor for duration
move.w (a0)+,d3
ror.w #8,d3
mulu d0,d3 ; interval
add.l #$8000,d3 ; rounded
swap d3
move.w d3,ho_bpint(a3) ; keep it
move.w (a0)+,d3 ; length
beq.s hob_snln
ror.w #8,d3
mulu d0,d3
swap d3
addq.w #1,d3
hob_snln
not.w d3 ; length (-ve)
move.b (a0)+,d0 ; step / wrap
move.b d0,d1
ext.w d0
asr.w #4,d0
muls #ho.bpscl,d0
asr.l #ho.bpssf,d0
move.w d0,ho_bpstp(a3) ; step
tst.w ho_bpint(a3) ; cannot have zero interval
bne.s hob_swrap
addq.w #1,ho_bpint(a3)
lsl.w ho_bpstp(a3) ; increase step
bne.s hob_swrap
subq.w #2,ho_bpint(a3) ; ... none, almost infinite interval
hob_swrap
addq.b #1,d1
and.w #$000f,d1 ; 0-15
move.w d1,ho_bpwrp(a3)
st sys_qlbp(a6) ; ... beeping now
move.w d3,ho_bptim(a3) ; set it going
hob_ok
moveq #0,d0
hob_exit
movem.l (sp)+,hob.regx
rts
hdop_bpof
movem.l hob.rege,-(sp)
clr.b sys_qlbp(a6) ; ... not beeping now
pea hob_exit
; locate linkage and kill old beep
hob_lloc
lea sys_poll(a6),a3 ; find kbd poll linkage
lea hdop_poll,a0
holl_look
move.l (a3),d0 ; next link
beq.s holl_bp ; ... all done
move.l d0,a3
cmp.l iod_plad-iod_pllk(a3),a0 ; ours?
bne.s holl_look ; ... no
subq.l #iod_pllk,a3
clr.w ho_bptim(a3) ; ... stop generating beeps
moveq #sss_kill,d0
move.l a4,-(sp)
jsr hdop_ssss ; kill the old beep
move.l (sp)+,a4
moveq #0,d0
rts
holl_bp
moveq #err.ipar,d1
rts
end
|
; A258598: a(n) = 17*3^n.
; 17,51,153,459,1377,4131,12393,37179,111537,334611,1003833,3011499,9034497,27103491,81310473,243931419,731794257,2195382771,6586148313,19758444939,59275334817,177826004451,533478013353,1600434040059,4801302120177,14403906360531
mov $1,3
pow $1,$0
mul $1,17
|
; ────┤ Trabalho de Prática em Organização Computacional │ Agosto 2021 ├────
; Gabriel Victor Cardoso Fernandes - 11878296
; Gabriel Alves Kuabara - 11275043
; Lourenço de Salles Roselino - 11796805
; Caracteres que constroem o Mapa
; boneco - z amarelo
; parede normal - } azul
; parede mortal - { vermelho
; bandeira de chegada - ) rosa
; moedinhas - * amarela
jmp main
; ────────┤ Strings e dados do menu e do mapa ├────────
menu_art : string " Tomb of the Mask Gabriel Alves Kuabara Gabriel Victor Cardoso Fernandes Lourenyo de Salles Roselino }}}}}}}} } } } } } } } } } } } } } }}}} } } } }}}}}}}} Pressione Enter para Jogar "
mapa : string "}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}* ) }}}}}}}}}}}}}}}*}}}}}}}}}}}}}}}}}}}}}}} }}}}}}}}}}}}}}}*}}}}}}}}}}}}}}}}}}}}}}} }}}}}}}}}}}}}*}}}}}}}}}}}******}}}}}} } }}}}}}}}}}}}}*}}}}}}}}}}}*}}{}*}}}} }}}}}}}}}}******************}}}} * * }}}}}}}*} }}}*}}}}}}} *** }} }}}}}}}* *}}}}}} }}* }}}}}}}* }}*}}}}}} * }}}}}}}}}}*}******************** }}}}}}}}}}*}}}}}}}}}}} }}}}}}}}}}}}}}}}}}}}}}}}}}}*}}}*******} }}}*}}}*******} }}}} }}}}}}}}}}}}}}}}}} }}}**********}} }}}} }}}}}}}}}}}}}}}}}} }}}}}}}}}}}}}} }}}}****************}}} }}}}}}****}}}} }}}}*********************}}}}}**********}}}}* **** }}}}}}****}}}}}*}}}{* } }****}}}}} ****}*****}}}{******** }}}}}}}}}} }***}}*}}}}}}}}}}}}}}}*}}}}} }}}}}}}}}} }}}}}}*}}}}}}}}}}}}}}}*}}}}} }}}}}}}}}} }}}}}**}}}}}}}}}}}}}}}*}}}}} }}}}}}}}}} }}}}}*}}}}}}}}}}}}}}}}*}}}}} }}}}}}}}}}***************************** }}}}}}}}}} }}}}}*}}}}}}}}}}}}}}}} }}}} }}}}}}}}}}} }}}}}*}}}}}}}}}}}}}}}} }}}}}{* }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} GET TO THE ) "
; Temos 2 linhas pra printar: menu_art[1080] e menu_art[1120]
mensagem_vitoria: string "Parabens, voce venceu"
mensagem_derrota: string "Tente novamente parca"
cores_sprites : var #5
static cores_sprites + #0, #2816 ; Cor da moeda
static cores_sprites + #1, #1024 ; Cor da parede_normal
static cores_sprites + #2, #2304 ; Cor da parede_mortal
static cores_sprites + #3, #3328 ; Cor da bandeira
static cores_sprites + #4, #0 ; sem cor
; ─────────────────────────────────────────────────────
; ──────────┤ Dados relacionados ao jogador ├──────────
posicao_inicial : var #1
static posicao_inicial, #1067 ; Posicao inicial do boneco
conta_bancaria: var #1 ; guarda quanta moedinhas o jogador tem
static conta_bancaria + #0, #0
posicao_print_moedas: var #1
static posicao_print_moedas, #1196 ; Posicao da tela onde imprimir as moedas
;Variaveis de velocidade
velocidade : var #2
static velocidade + #0, #40 ; velocidade vertical (subindo || descendo)
static velocidade + #1, #1 ; velocidade horizontal (esquerda || direita)
; ─────────────────────────────────────────────────────
; ────────────┤ Dados para delay do clock ├────────────
numero_loops : var #1
static numero_loops, #1
numero_nops_por_loop : var #1
static numero_nops_por_loop, #300000
; ─────────────────────────────────────────────────────
main:
loadn r7, #0 ; Carrega estado inicial do jogo (0 = inicial | 1 = perdeu | 2 = ganhou)
loadn r6, #0
imprime_menu:
loadn r0, #0 ; r0 = print_pos
loadn r1, #menu_art ; r1 = end(menu_art)
call imprime_string ; Printa menu
cmp r6, r7 ; Caso o estado do jogo nao seja o inicial, acabar programa
jeq iniciar_jogo
call delay_clock
halt
iniciar_jogo:
; Inicializa timer pro usuario apertar Enter
loadn r0, #0
loadn r3, #300000
; ────────────┤ Espera até o usuário apertar enter para começar o jogo ├────────────
loop_menu:
loadn r2, #13 ; Caracter do enter
inc r0
cmp r0, r3
jeq main
inchar r1 ; Le teclado
cmp r1, r2
jeq inicia_jogo ; Se apertou Enter, inicia o jogo.
jmp loop_menu ; Se não, fica em loop
inicia_jogo:
loadn r0, #0 ; r0 = print_pos
loadn r1, #mapa ; r1 = end(mapa)
call imprime_string ; Printa o mapa
; ────┤ Daqui pra frente a pos_boneco vai estar sempre em r0 ├────
load r0, posicao_inicial ; r0 = pos_inicial do boneco
loadn r6, #0
call imprime_boneco
; ────────────┤ Leitura da movimentação ├────────────
le_direcao:
loadn r1, #0
loadn r2, #0
inchar r1 ; r1 = dir | direção lida pelo usuario
cmp r1, r2 ; nao leu nada -> loop pra ler denovo
jeq le_direcao
; r1 = direção lida
checa_movimento:
; ────────────┤ Checagem de movimento vertical ├────────────
loadn r3, #0 ; velocidades[0] = #40 -> vertical (subindo || descendo)
; ────────────┤ Checagem subindo ├────────────
loadn r2, #'w'
cmp r1, r2 ; dir == 'w'
loadn r5, #velocidade_decrementando
jeq velocidade_decrementando
; ────────────┤ Checagem descendo ├────────────
loadn r2, #'s'
cmp r1, r2 ; dir == 's'
loadn r5, #velocidade_incrementando
jeq velocidade_incrementando
; ────────────┤ Checagem de movimento horizontal ├────────────
loadn r3, #1 ; velocidades[1] = #1 -> horizontal (esquerda || direita)
; ────────────┤ Checagem direita ├────────────
loadn r2, #'d'
cmp r1, r2 ; dir == 'd'
loadn r5, #velocidade_incrementando
jeq velocidade_incrementando
; ────────────┤ Checagem esquerda ├────────────
loadn r2, #'a' ; velocidades[3] = indo pra esquerda
cmp r1, r2 ; dir == 'a'
loadn r5, #velocidade_decrementando
jeq velocidade_decrementando
jmp le_direcao ; Se não moveu -> Le entrada de novo
; ────────────┤ Fim da leitura de movimentação ├────────────
; ────────────┤ Funções de velocidade ├────────────
; Geram a velocidade de movimentação no r2
; Movimento continuo dá jump pra r5 (evita ifs desnecessarios)
velocidade_incrementando: ; Movimento para direita ou para baixo -> Incrementa pos
nop
loadn r1, #velocidade ; r1 = end(velocidade)
add r1, r1, r3 ; r1 = end(velocidade[i])
loadi r2, r1 ; r2 = velocidade[i]
add r1, r0, r2 ; r1 = prox_pos | prox_pos = pos_atual + velocidade
jmp confere_colisao
velocidade_decrementando: ; Movimento para esquerda ou para cima -> Decrementa pos
nop
loadn r1, #velocidade ; r1 = end(velocidade)
add r1, r1, r3 ; r1 = end(velocidade[i])
loadi r2, r1 ; r2 = velocidade[i]
sub r1, r0, r2 ; r1 = prox_pos | prox_pos = pos_atual - velocidade
; ────────────┤ Logica de Colisao ├────────────
; r0 = pos_atual | r2 = velocidade
confere_colisao:
loadn r6, #mapa ; r6 = end(mapa)
add r6, r6, r1 ; r6 = end(mapa[prox_pos])
loadi r6, r6 ; r6 = mapa[prox_pos] | sprite que vamos comparar
; ────┤ Posicao vazia: continua movendo ├────
loadn r4, #' '
cmp r6, r4
jne posicao_nao_vazia
call movimentar_boneco
; Continua movendo: pula para função de velocidade (que o end tá no r5)
push r5
rts
; ────────────────────────────────────────
posicao_nao_vazia:
; ────┤ Moeda: fica rico ├────
loadn r4, #'*'
cmp r6, r4
jne nao_coletou_moeda
call atualizar_moedas
call movimentar_boneco
; Continua movendo: pula para função de velocidade (que o end tá no r5)
push r5
rts
; ────────────────────────────────────────
nao_coletou_moeda:
; ────┤ Parede normal: pede movimento ├────
loadn r4, #'}'
cmp r6, r4
jne nao_bateu_em_parede_normal
loadn r6, #0
call imprime_boneco
jeq le_direcao
nao_bateu_em_parede_normal:
; ────┤ Parede mortal: perder jogo ├────
loadn r4, #'{'
cmp r6, r4
loadn r7, #1 ; Jogador perdeu
jeq game_over
; ────┤ Bandeira: ganhar jogo ├────
loadn r4, #')'
cmp r6, r4
loadn r7, #2 ; Jogador ganhou
; r7 = estado final (0 = nada | 1 = derrota | 2 = vitoria)
game_over:
loadn r5, #1
loadn r6, #mensagem_derrota
cmp r5, r7 ; estado_final == derrota
jeq game_over_saida
loadn r5, #2
loadn r6, #mensagem_vitoria
cmp r5, r7 ; estado_final == vitoria
game_over_saida: ; Copia string resultado e sai do jogo
call copia_string
jeq imprime_menu
; ────────────┤ Fim logica de Colisao ├────────────
; ────────────┤ Movimentação ├────────────
; r0 = pos_atual | r1 = prox_pos
movimentar_boneco:
push r2
push r3
; ────┤ Apagando o boneco da pos_atual ├────
loadn r2, #' '
outchar r2, r0 ; Apaga boneco do mapa[r0]
; ──────────────────────────────────────────
; ────┤ Atualiza e printa o boneco pra prox_pos ├────
mov r0, r1 ; r0 = prox_pos
loadn r3, #mapa ; r3 = end(mapa)
add r1, r0, r3 ; r1 = end(mapa[prox_pos])
storei r1, r2 ; Apaga o que estiver na proxima posicao
call imprime_boneco
; ───────────────────────────────────────────────────
call delay_clock
pop r3
pop r2
rts
; ────────┤ Fim da Movimentação ├────────
; ────────────┤ Utilidades Gerais ├────────────
; r0 = posicao da tela | r1 = end da string | r2 = cor da string
imprime_string:
push r0
push r1
push r2
push r3
push r4
push r5
push r6
loadn r3, #'\0' ; Criterio de parada do print da string
loadn r6, #cores_sprites
imprime_string_loop:
loadi r4, r1 ; ; r4 = sprite | sprite = string[i]
cmp r4, r3 ; sprite == '\0' -> terminou de printar
jeq imprime_string_fim
loadn r5, #'*'
cmp r4, r5 ; sprite = moeda
loadn r2, #0
jeq imprime_sprite
loadn r5, #'}'
cmp r4, r5 ; sprite = parede_normal
loadn r2, #1
jeq imprime_sprite
loadn r5, #'{'
cmp r4, r5 ; sprite = parede_mortal
loadn r2, #2
jeq imprime_sprite
loadn r5, #')'
cmp r4, r5 ; sprite = bandeira
loadn r2, #3
jeq imprime_sprite
loadn r2, #4
imprime_sprite:
add r2, r2, r6 ; cor_sprite = end(cores_sprites[sprite])
loadi r2, r2 ; cor_sprite = cores_sprites[sprite]
add r4, r2, r4 ; sprite + cor_sprite
outchar r4, r0
inc r0 ; pos++
inc r1 ; i++ (string[i])
jmp imprime_string_loop
imprime_string_fim:
pop r6
pop r5
pop r4
pop r3
pop r2
pop r1
pop r0
rts
; r0 = pos_boneco
imprime_boneco:
push r1
push r2
loadn r1, #'z' ; r1 = boneco
loadn r2, #768 ; Cor do boneco
add r1, r1, r2
outchar r1, r0 ; Printa boneco em mapa[r0]
pop r2
pop r1
rts
atualizar_moedas:
push r0
push r1
push r2
push r3
push r4
load r2, conta_bancaria
inc r2
store conta_bancaria, r2
load r0, posicao_print_moedas
loadn r1, #2858 ; r1 = moeda amarela
outchar r1, r0
inc r0
loadn r1, #100 ; Primeiro digito
div r1, r2, r1
loadn r3, #2864 ; r3 = cor amarelo
add r1, r3, r1 ; r1 = primeiro digito + cor amarelo
outchar r1, r0
inc r0
loadn r4, #10 ; Segundo digito
div r1, r2, r4
mod r1, r1, r4
add r1, r3, r1 ; r1 = segundo digito + cor amarelo
outchar r1, r0
inc r0
loadn r1, #10 ; Terceiro digito
mod r1, r2, r1
add r1, r3, r1 ; r1 = terceiro digito + cor amarelo
outchar r1, r0
pop r4
pop r3
pop r2
pop r1
pop r0
rts
; Escreve uma string dentro de outra a partir da posicao no r6
; r6 = end(string)
copia_string:
loadn r3, #1089 ; Posicao inicial da mensagem de finalizacao
loadn r4, #menu_art ; r4 = end(menu)
add r3, r3, r4 ; r3 = end(menu[pos_mensagem])
loadn r4, #'\0' ; Caractere de parada da string
copia_string_loop:
loadi r5, r6 ; r5 = menu[pos_mensagem]
cmp r5, r4 ; r5 == '\0' -> terminou de printar
jeq copia_string_fim
copia_caractere:
storei r3, r5
inc r3 ; menu_pos++
inc r6 ; string_pos++
jmp copia_string_loop
copia_string_fim:
rts
; Funcao de delay: mantém o clock ocupado para atrasar o jogo
delay_clock:
push r0
push r1
push r2
loadn r0, #1 ; n de loops
loadn r2, #0
delay_loop:
loadn r1, #300000 ; n de nops
dec r0
delay_nop: ; roda (n_loops * n_nops) vezes
nop
dec r1
cmp r1, r2
jne delay_nop
cmp r0, r2
jne delay_loop
pop r2
pop r1
pop r0
rts
|
;;;;;;;;;;;;;;;;
; test branching
;;;;;;;;;;;;;;;;
.org $8000
;;;;;;;;;;;;;;;;
; test JMP (indirect)
;;;;;;;;;;;;;;;;
LDX #$00 ; reset X register
LDA #<ind_skip_1 ; low byte of target address
STA $0250
LDA #>ind_skip_1 ; high byte of target address
STA $0251
JMP ($0250) ; jump to address specified at $0050 ($8012)
LDX #$01 ; set X=1 (this shouldn't execute)
;;; this is offset $8011 in PRG ;;;
ind_skip_1:
NOP ; perform assertions:
; x = 0x0
; test page boundary bug
; we stick a label at the bottom offset from the correct label by $1000 bytes
; so that the low byte is the same but the high byte is different
LDX #$00 ; reset X register
LDA #$EE ; load bogus byte as MSB
STA $0300 ; store after page boundary
LDA #<ind_skip_3 ; fetch lower byte of incorrect label
STA $02FF ; store before page boundary
LDA #>ind_skip_3 ; fetch upper byte of correct label
STA $0200 ; store after wrong page boundary
JMP ($02FF)
ind_skip_2:
LDX #$01 ; this shouldn't execute
ind_skip_3:
LDX #$02 ; this should execute
ind_end:
NOP ; perform assertions:
; x = 0x0
;;;;;;;;;;;;;;;;
; test JMP
;;;;;;;;;;;;;;;;
LDA #$00 ; reset registers
LDX #$00
JMP skip1 ; skip next instruction
LDX #$01 ; set X register (this shouldn't execute)
skip1: LDA #$01 ; a = 1
NOP ; perform assertions:
; a = 0x01
; x = 0x00
;;;;;;;;;;;;;;;;
; test JSR
;;;;;;;;;;;;;;;;
LDX #$05 ; set x
JSR subroutine ; jump to subroutine
INX ; increment X
JMP end_jsr_test
subroutine: INX ; increment X
RTS ; return
LDX #$00 ; reset X (shouldn't execute)
end_jsr_test:
NOP ; perform assertions:
; x = 0x07
;;;;;;;;;;;;;;;;
; test BEQ, BNE
;;;;;;;;;;;;;;;;
LDX #$00 ; reset X
LDY #$00 ; reset Y
LDA #$00 ; set a=0 (sets zero flag)
BNE not_equal ; this should not branch
BEQ equal ; this should branch
equal:
LDX #$01 ; set x=1
JMP equ_part_2 ; skip the not_equal section
not_equal: ; this should not be reached
LDX #$02 ; set x=2 (should not execute)
equ_part_2:
LDA #$01 ; set a=1 (clears zero flag)
BEQ equal_2 ; this should not branch
BNE not_equal_2 ; this should branch
equal_2: ; this shouldn't be reached
LDY #$01 ; set y=1
JMP equ_end ; skip the not_equal_2 section
not_equal_2:
LDY #$02 ; set y=2
equ_end:
NOP ; perform assertions:
; x = 1
; y = 2
;;;;;;;;;;;;;;;;
; test BCC, BCS
;;;;;;;;;;;;;;;;
LDX #$00 ; reset X
LDY #$00 ; reset Y
SEC ; set carry flag
BCC no_carry ; this should not branch
BCS carry ; this should branch
carry:
LDX #$01 ; set x=1
JMP carry_part_2 ; skip the no_carry section
no_carry: ; this should not be reached
LDX #$02 ; set x=2
carry_part_2:
CLC ; clear carry flag
BCS carry_2 ; this should not branch
BCC no_carry_2 ; this should branch
carry_2: ; this should not be reached
LDY #$01 ; set y=1
JMP carry_end ; skip the no_carry_2 section
no_carry_2:
LDY #$02 ; set y=2
carry_end:
NOP ; perform assertions:
; x = 1
; y = 2
;;;;;;;;;;;;;;;;
; test BPL, BMI
;;;;;;;;;;;;;;;;
LDX #$00 ; reset X
LDY #$00 ; reset Y
LDA #$01 ; set a to be positive (clears negative flag)
BMI minus ; this should not branch
BPL plus ; this should branch
plus:
LDX #$01 ; set x=1
JMP sign_part_2 ; skip the minus section
minus: ; this should not be reached
LDX #$02 ; set x=2
sign_part_2:
LDA #$80 ; set a to be negative (sets negative flag)
BPL plus_2 ; this should not branch
BMI minus_2 ; this should branch
plus_2: ; this should not be reached
LDY #$01 ; set y=1
JMP sign_end ; skip the no_carry_2 section
minus_2:
LDY #$02 ; set y=2
sign_end:
NOP ; perform assertions:
; x = 1
; y = 2
; we rely on the test supervisor to set the overflow
; flag here to avoid relying on arithmetic instructions
;;;;;;;;;;;;;;;;
; test BVS, BVC
;;;;;;;;;;;;;;;;
LDX #$00 ; reset X
LDY #$00 ; reset Y
BVC no_overflow ; this should not branch
BVS overflow ; this should branch
overflow:
LDX #$01 ; set x=1
JMP overflow_part_2 ; skip the no_carry section
no_overflow: ; this should not be reached
LDX #$02 ; set x=2
overflow_part_2:
CLV ; clear overflow flag
BVS overflow_2 ; this should not branch
BVC no_overflow_2 ; this should branch
overflow_2: ; this should not be reached
LDY #$01 ; set y=1
JMP overflow_end ; skip the no_overflow_2 section
no_overflow_2:
LDY #$02 ; set y=2
overflow_end:
NOP ; perform assertions:
; x = 1
; y = 2
.org $BFFA
.dw $8000
.dw $8000
.dw $8000
|
; A017115: a(n) = (8*n + 4)^3.
; 64,1728,8000,21952,46656,85184,140608,216000,314432,438976,592704,778688,1000000,1259712,1560896,1906624,2299968,2744000,3241792,3796416,4410944,5088448,5832000,6644672,7529536,8489664,9528128,10648000,11852352,13144256,14526784,16003008,17576000,19248832,21024576,22906304,24897088,27000000,29218112,31554496,34012224,36594368,39304000,42144192,45118016,48228544,51478848,54872000,58411072,62099136,65939264,69934528,74088000,78402752,82881856,87528384,92345408,97336000,102503232,107850176
mul $0,8
add $0,4
pow $0,3
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "Init.h"
#include "bindings/core/v8/ScriptStreamerThread.h"
#include "core/EventNames.h"
#include "core/EventTargetNames.h"
#include "core/EventTypeNames.h"
#include "core/FetchInitiatorTypeNames.h"
#include "core/HTMLNames.h"
#include "core/HTMLTokenizerNames.h"
#include "core/InputTypeNames.h"
#include "core/MathMLNames.h"
#include "core/MediaFeatureNames.h"
#include "core/MediaTypeNames.h"
#include "core/SVGNames.h"
#include "core/XLinkNames.h"
#include "core/XMLNSNames.h"
#include "core/XMLNames.h"
#include "core/css/parser/CSSParserTokenRange.h"
#include "core/dom/Document.h"
#include "core/dom/StyleChangeReason.h"
#include "core/events/EventFactory.h"
#include "core/html/parser/HTMLParserThread.h"
#include "core/workers/WorkerThread.h"
#include "platform/EventTracer.h"
#include "platform/FontFamilyNames.h"
#include "platform/Partitions.h"
#include "platform/PlatformThreadData.h"
#include "wtf/text/StringStatics.h"
namespace blink {
void CoreInitializer::registerEventFactory()
{
static bool isRegistered = false;
if (isRegistered)
return;
isRegistered = true;
Document::registerEventFactory(EventFactory::create());
}
void CoreInitializer::init()
{
ASSERT(!m_isInited);
m_isInited = true;
HTMLNames::init();
SVGNames::init();
XLinkNames::init();
MathMLNames::init();
XMLNSNames::init();
XMLNames::init();
EventNames::init();
EventTargetNames::init();
EventTypeNames::init();
FetchInitiatorTypeNames::init();
FontFamilyNames::init();
HTMLTokenizerNames::init();
InputTypeNames::init();
MediaFeatureNames::init();
MediaTypeNames::init();
CSSParserTokenRange::initStaticEOFToken();
// It would make logical sense to do this in WTF::initialize() but there are
// ordering dependencies, e.g. about "xmlns".
WTF::StringStatics::init();
StyleChangeExtraData::init();
QualifiedName::init();
Partitions::init();
EventTracer::initialize();
registerEventFactory();
// Ensure that the main thread's thread-local data is initialized before
// starting any worker threads.
PlatformThreadData::current();
StringImpl::freezeStaticStrings();
// Creates HTMLParserThread::shared and ScriptStreamerThread::shared, but
// does not start the threads.
HTMLParserThread::init();
ScriptStreamerThread::init();
}
void CoreInitializer::shutdown()
{
// Make sure we stop the HTMLParserThread before Platform::current() is
// cleared.
HTMLParserThread::shutdown();
Partitions::shutdown();
}
} // namespace blink
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
Notification::Notification(const GURL& origin_url,
const GURL& content_url,
const string16& display_source,
const string16& replace_id,
NotificationDelegate* delegate)
: type_(message_center::NOTIFICATION_TYPE_SIMPLE),
origin_url_(origin_url),
is_html_(true),
content_url_(content_url),
display_source_(display_source),
replace_id_(replace_id),
delegate_(delegate) {
}
Notification::Notification(const GURL& origin_url,
const GURL& icon_url,
const string16& title,
const string16& body,
WebKit::WebTextDirection dir,
const string16& display_source,
const string16& replace_id,
NotificationDelegate* delegate)
: type_(message_center::NOTIFICATION_TYPE_SIMPLE),
origin_url_(origin_url),
icon_url_(icon_url),
is_html_(false),
title_(title),
body_(body),
display_source_(display_source),
replace_id_(replace_id),
delegate_(delegate) {
// "Upconvert" the string parameters to a data: URL.
content_url_ = GURL(DesktopNotificationService::CreateDataUrl(
icon_url, title, body, dir));
}
Notification::Notification(message_center::NotificationType type,
const GURL& origin_url,
const GURL& icon_url,
const string16& title,
const string16& body,
WebKit::WebTextDirection dir,
const string16& display_source,
const string16& replace_id,
const DictionaryValue* optional_fields,
NotificationDelegate* delegate)
: type_(type),
origin_url_(origin_url),
icon_url_(icon_url),
is_html_(false),
title_(title),
body_(body),
display_source_(display_source),
replace_id_(replace_id),
optional_fields_(NULL),
delegate_(delegate) {
if (optional_fields)
optional_fields_.reset(optional_fields->DeepCopy());
// "Upconvert" the string parameters to a data: URL. Some balloon views
// require content URL to render anything, so this serves as a backup.
content_url_ = GURL(DesktopNotificationService::CreateDataUrl(
icon_url, title, body, dir));
}
Notification::Notification(const GURL& origin_url,
const gfx::ImageSkia& icon,
const string16& title,
const string16& body,
WebKit::WebTextDirection dir,
const string16& display_source,
const string16& replace_id,
NotificationDelegate* delegate)
: type_(message_center::NOTIFICATION_TYPE_SIMPLE),
origin_url_(origin_url),
icon_(icon),
is_html_(false),
title_(title),
body_(body),
display_source_(display_source),
replace_id_(replace_id),
delegate_(delegate) {
}
Notification::Notification(const Notification& notification)
: type_(notification.type()),
origin_url_(notification.origin_url()),
icon_(notification.icon()),
icon_url_(notification.icon_url()),
is_html_(notification.is_html()),
content_url_(notification.content_url()),
title_(notification.title()),
body_(notification.body()),
display_source_(notification.display_source()),
replace_id_(notification.replace_id()),
delegate_(notification.delegate()) {
if (notification.optional_fields())
optional_fields_.reset(notification.optional_fields()->DeepCopy());
}
Notification::~Notification() {}
Notification& Notification::operator=(const Notification& notification) {
type_ = notification.type();
origin_url_ = notification.origin_url();
icon_ = notification.icon_;
icon_url_ = notification.icon_url();
is_html_ = notification.is_html();
content_url_ = notification.content_url();
title_ = notification.title();
body_ = notification.body();
display_source_ = notification.display_source();
replace_id_ = notification.replace_id();
if (notification.optional_fields())
optional_fields_.reset(notification.optional_fields()->DeepCopy());
else
optional_fields_.reset();
delegate_ = notification.delegate();
return *this;
}
|
DoMysteryGift:
call ClearTileMap
call ClearSprites
call WaitBGMap
call InitMysteryGiftLayout
hlcoord 3, 8
ld de, .String_PressAToLink_BToCancel
call PlaceString
call WaitBGMap
farcall PrepMysteryGiftDataToSend
call MysteryGift_ClearTrainerData
ld a, $2
ld [wca01], a
ld a, $14
ld [wca02], a
ldh a, [rIE]
push af
call Function104a95
ld d, a
xor a
ldh [rIF], a
pop af
ldh [rIE], a
push de
call ClearTileMap
call EnableLCD
call WaitBGMap
ld b, SCGB_DIPLOMA
call GetSGBLayout
call SetPalettes
pop de
hlcoord 2, 8
ld a, d
ld de, .Text_LinkCanceled ; Link has been canceled
cp $10
jp z, .LinkCanceled
cp $6c
jp nz, .CommunicationError
ld a, [wc900]
cp 3
jr z, .skip_checks
call .CheckAlreadyGotFiveGiftsToday
ld hl, .Text_MaxFiveGifts ; Only 5 gifts a day
jp nc, .PrintTextAndExit
call .CheckAlreadyGotAGiftFromThatPerson
ld hl, .Text_MaxOneGiftPerPerson ; Only one gift a day per person
jp c, .PrintTextAndExit
.skip_checks
ld a, [wMysteryGiftPlayerBackupItem]
and a
jp nz, .GiftWaiting
ld a, [wMysteryGiftPartnerBackupItem]
and a
jp nz, .FriendNotReady
ld a, [wc900]
cp 3
jr z, .skip_append_save
call .AddMysteryGiftPartnerID
ld a, [wc900]
cp 4
jr z, .skip_append_save
call .SaveMysteryGiftTrainerName
farcall RestoreMobileEventIndex
farcall StubbedTrainerRankings_MysteryGift
farcall BackupMobileEventIndex
.skip_append_save
ld a, [wMysteryGiftPartnerSentDeco]
and a
jr z, .item
ld a, [wMysteryGiftPartnerWhichDeco]
ld c, a
farcall MysteryGiftGetDecoration
push bc
call MysteryGift_CheckAndSetDecorationAlreadyReceived
pop bc
jr nz, .item
callfar GetDecorationName_c
ld h, d
ld l, e
ld de, wStringBuffer1
ld bc, ITEM_NAME_LENGTH
call CopyBytes
ld hl, .Text_SentToHome ; sent decoration to home
jr .PrintTextAndExit
.item
call GetMysteryGiftBank
ld a, [wMysteryGiftPartnerWhichItem]
ld c, a
farcall MysteryGiftGetItemHeldEffect
ld a, c
ld [sBackupMysteryGiftItem], a
ld [wNamedObjectIndexBuffer], a
call CloseSRAM
call GetItemName
ld hl, .Text_Sent ; sent item
jr .PrintTextAndExit
.LinkCanceled:
ld hl, .Text_LinkCanceled ; Link has been canceled
jr .PrintTextAndExit
.CommunicationError:
ld hl, .Text_CommunicationError ; Communication error
call PrintText
jp DoMysteryGift
.GiftWaiting:
ld hl, .Text_ReceiveGiftAtCounter ; receive gift at counter
jr .PrintTextAndExit
.FriendNotReady:
ld hl, .Text_FriendNotReady ; friend not ready
.PrintTextAndExit:
call PrintText
ld a, LCDC_DEFAULT
ldh [rLCDC], a
ret
.String_PressAToLink_BToCancel:
db "Press A to"
next "link IR-Device"
next "Press B to"
next "cancel it."
db "@"
.Text_LinkCanceled:
text_far UnknownText_0x1c0436
text_end
.Text_CommunicationError:
text_far UnknownText_0x1c0454
text_end
.Text_ReceiveGiftAtCounter:
text_far UnknownText_0x1c046a
text_end
.Text_FriendNotReady:
text_far UnknownText_0x1c048e
text_end
.Text_MaxFiveGifts:
text_far UnknownText_0x1c04a7
text_end
.Text_MaxOneGiftPerPerson:
text_far UnknownText_0x1c04c6
text_end
.Text_Sent:
text_far UnknownText_0x1c04e9
text_end
.Text_SentToHome:
text_far UnknownText_0x1c04fa
text_end
.CheckAlreadyGotFiveGiftsToday:
call GetMysteryGiftBank
ld a, [sNumDailyMysteryGiftPartnerIDs]
cp $5
jp CloseSRAM
.CheckAlreadyGotAGiftFromThatPerson:
call GetMysteryGiftBank
ld a, [wMysteryGiftPartnerID]
ld b, a
ld a, [wMysteryGiftPartnerID + 1]
ld c, a
ld a, [sNumDailyMysteryGiftPartnerIDs]
ld d, a
ld hl, sDailyMysteryGiftPartnerIDs
.loop
ld a, d
and a
jr z, .No
ld a, [hli]
cp b
jr nz, .skip
ld a, [hl]
cp c
jr z, .Yes
.skip
inc hl
dec d
jr .loop
.Yes:
scf
.No:
jp CloseSRAM
.AddMysteryGiftPartnerID:
call GetMysteryGiftBank
ld hl, sNumDailyMysteryGiftPartnerIDs
ld a, [hl]
inc [hl]
ld hl, sDailyMysteryGiftPartnerIDs ; inc hl
ld e, a
ld d, $0
add hl, de
add hl, de
ld a, [wMysteryGiftPartnerID]
ld [hli], a
ld a, [wMysteryGiftPartnerID + 1]
ld [hl], a
jp CloseSRAM
.SaveMysteryGiftTrainerName:
call GetMysteryGiftBank
ld a, $1
ld [sMysteryGiftTrainerHouseFlag], a
ld hl, wMysteryGiftPartnerName
ld de, sMysteryGiftPartnerName
ld bc, NAME_LENGTH
call CopyBytes
ld a, $1
ld [de], a
inc de
ld hl, wMysteryGiftTrainerData
ld bc, (1 + 1 + NUM_MOVES) * PARTY_LENGTH + 2
call CopyBytes
jp CloseSRAM
Function104a95:
di
farcall ClearChannels
call Function104d5e
.loop2
call Function104d96
call Function104ddd
ldh a, [hMGStatusFlags]
cp $10
jp z, Function104bd0
cp $6c
jr nz, .loop2
ldh a, [hPrintNumBuffer + 8]
cp $2
jr z, Function104b22
ld hl, hPrintNumBuffer
ld b, $1
call Function104d56
jr nz, .ly_loop
call Function104b49
jp nz, Function104bd0
jr Function104b0a
; Delay frame
.ly_loop
ldh a, [rLY]
cp LY_VBLANK
jr c, .ly_loop
ld c, LOW(rRP)
ld a, $c0
ldh [c], a
ld b, 240 ; This might have been intended as a 4-second timeout buffer.
; However, it is reset with each frame.
.loop3
push bc
call MysteryGift_ReadJoypad
ld b, $2
ld c, LOW(rRP)
; Delay frame
.ly_loop2
ldh a, [c]
and b
ld b, a
ldh a, [rLY]
cp LY_VBLANK
jr nc, .ly_loop2
.ly_loop3
ldh a, [c]
and b
ld b, a
ldh a, [rLY]
cp LY_VBLANK
jr c, .ly_loop3
ld a, b
pop bc
dec b
jr z, .loop2 ; we never jump here
or a
jr nz, .loop2
; Check if we've pressed the B button
ldh a, [hMGJoypadReleased]
bit B_BUTTON_F, a
jr z, .loop3
ld a, $10
ldh [hMGStatusFlags], a
jp Function104bd0
Function104b04:
call Function104b40
jp nz, Function104bd0
Function104b0a:
call Function104d38
jp nz, Function104bd0
call Function104b88
jp nz, Function104bd0
call Function104d43
jp nz, Function104bd0
call Function105033
jp Function104bd0
Function104b22:
call Function104b88
jp nz, Function104bd0
call Function104d43
jp nz, Function104bd0
call Function104b40
jp nz, Function104bd0
call Function104d38
jp nz, Function104bd0
call Function10502e
jp Function104bd0
Function104b40:
ld hl, hPrintNumBuffer
ld b, $1
call Function104d56
ret nz
Function104b49:
call Function105033
ldh a, [hMGStatusFlags]
cp $6c
ret nz
ldh a, [hPrintNumBuffer]
cp $96
jp nz, Function104d32
ld a, $90
ldh [hPrintNumBuffer], a
call Function104d38
ret nz
ld hl, hPrintNumBuffer
ld b, $1
call Function104d4e
ret nz
call Function10502e
ldh a, [hMGStatusFlags]
cp $6c
ret nz
call Function104d43
ret nz
ld hl, wMysteryGiftTrainerData
ld a, [wca02]
ld b, a
call Function104d56
ret nz
call Function105033
ldh a, [hMGStatusFlags]
cp $6c
ret
Function104b88:
ld a, $96
ldh [hPrintNumBuffer], a
ld hl, hPrintNumBuffer
ld b, $1
call Function104d4e
ret nz
call Function10502e
ldh a, [hMGStatusFlags]
cp $6c
ret nz
call Function104d43
ret nz
ld hl, hPrintNumBuffer
ld b, $1
call Function104d56
ret nz
call Function105033
ldh a, [hMGStatusFlags]
cp $6c
ret nz
ldh a, [hPrintNumBuffer]
cp $90
jp nz, Function104d32
call Function104d38
ret nz
ld hl, wLinkData
ld a, [wca02]
ld b, a
call Function104d4e
ret nz
call Function10502e
ldh a, [hMGStatusFlags]
cp $6c
ret
Function104bd0:
nop
ldh a, [hMGStatusFlags]
cp $10
jr z, .quit
cp $6c
jr nz, .quit
ld hl, wca01
dec [hl]
jr z, .quit
ld hl, wMysteryGiftTrainerData
ld de, wMysteryGiftPartnerData
ld bc, wMysteryGiftPartnerDataEnd - wMysteryGiftPartnerData
call CopyBytes
ld a, [wMysteryGiftTrainerData]
cp $3
jr nc, .quit
farcall StagePartyDataForMysteryGift
call MysteryGift_ClearTrainerData
ld a, $26
ld [wca02], a
ldh a, [hPrintNumBuffer + 8]
cp $2
jr z, .asm_104c10
call Function104d43
jr nz, Function104bd0
jp Function104b04
.asm_104c10
call Function104d38
jr nz, Function104bd0
jp Function104b22
.quit
ldh a, [hMGStatusFlags]
push af
call Function104da0
xor a
ldh [rIF], a
ldh a, [rIE]
or 1 << VBLANK
ldh [rIE], a
ei
call DelayFrame
pop af
ret
Function104c2d:
di
farcall ClearChannels
call Function104d5e
.asm_104c37
call Function104d96
call Function104ddd
ldh a, [hMGStatusFlags]
cp $10
jp z, Function104d1c
cp $6c
jr nz, .asm_104c37
ldh a, [hPrintNumBuffer + 8]
cp $2
jr z, .asm_104c6c
call Function104c8a
jp nz, Function104d1c
call Function104d38
jp nz, Function104d1c
call Function104cd2
jp nz, Function104d1c
call Function104d43
jp nz, Function104d1c
call Function105033
jp Function104d1c
.asm_104c6c
call Function104cd2
jp nz, Function104d1c
call Function104d43
jp nz, Function104d1c
call Function104c8a
jp nz, Function104d1c
call Function104d38
jp nz, Function104d1c
call Function10502e
jp Function104d1c
Function104c8a:
ld hl, hPrintNumBuffer
ld b, $1
call Function104d56
ret nz
call Function105033
ldh a, [hMGStatusFlags]
cp $6c
ret nz
ldh a, [hPrintNumBuffer]
cp $3c
jp nz, Function104d32
swap a
ldh [hPrintNumBuffer], a
call Function104d38
ret nz
ld hl, hPrintNumBuffer
ld b, $1
call Function104d4e
ret nz
call Function10502e
ldh a, [hMGStatusFlags]
cp $6c
ret nz
call Function104d43
ret nz
ld hl, wMysteryGiftTrainerData
ld a, [wca02]
ld b, a
call Function104d56
ret nz
call Function105033
ldh a, [hMGStatusFlags]
cp $6c
ret
Function104cd2:
ld a, $3c
ldh [hPrintNumBuffer], a
ld hl, hPrintNumBuffer
ld b, $1
call Function104d4e
ret nz
call Function10502e
ldh a, [hMGStatusFlags]
cp $6c
ret nz
call Function104d43
ret nz
ld hl, hPrintNumBuffer
ld b, $1
call Function104d56
ret nz
call Function105033
ldh a, [hMGStatusFlags]
cp $6c
ret nz
ldh a, [hPrintNumBuffer]
swap a
cp $3c
jp nz, Function104d32
call Function104d38
ret nz
ld hl, wLinkData
ld a, [wca02]
ld b, a
call Function104d4e
ret nz
call Function10502e
ldh a, [hMGStatusFlags]
cp $6c
ret
Function104d1c:
nop
ldh a, [hMGStatusFlags]
push af
call Function104da0
xor a
ldh [rIF], a
ldh a, [rIE]
or 1 << VBLANK
ldh [rIE], a
ei
call DelayFrame
pop af
ret
Function104d32:
ld a, $80
ldh [hMGStatusFlags], a
and a
ret
Function104d38:
call Function104d96
call Function104e46
ldh a, [hMGStatusFlags]
cp $6c
ret
Function104d43:
call Function104d96
call Function104dfe
ldh a, [hMGStatusFlags]
cp $6c
ret
Function104d4e:
call Function104e93
ldh a, [hMGStatusFlags]
cp $6c
ret
Function104d56:
call Function104f57
ldh a, [hMGStatusFlags]
cp $6c
ret
Function104d5e:
call Function104d74
ld a, 1 << TIMER
ldh [rIE], a
xor a
ldh [rIF], a
call Function104d96
xor a
ld b, a
.asm_104d6d
inc a
jr nz, .asm_104d6d
inc b
jr nz, .asm_104d6d
ret
Function104d74:
xor a
ldh [rTAC], a
ld a, $fe
ldh [rTMA], a
ldh [rTIMA], a
ld a, $2
ldh [rTAC], a
or $4
ldh [rTAC], a
ret
Function104d86:
xor a
ldh [rTAC], a
ldh [rTMA], a
ldh [rTIMA], a
ld a, $2
ldh [rTAC], a
or $4
ldh [rTAC], a
ret
Function104d96:
ld a, $c0
call Function104e8c
ld a, $1
ldh [hPrintNumBuffer + 8], a
ret
Function104da0:
xor a
call Function104e8c
ld a, $2
ldh [rTAC], a
ret
Function104da9:
inc d
ret z
xor a
ldh [rIF], a
halt
ldh a, [c]
bit 1, a
jr z, Function104da9
or a
ret
Function104db7:
inc d
ret z
xor a
ldh [rIF], a
halt
ldh a, [c]
bit 1, a
jr nz, Function104db7
or a
ret
Function104dc5:
ld a, $c1
ldh [c], a
.wait
dec d
ret z
xor a
ldh [rIF], a
halt
jr .wait
Function104dd1:
ld a, $c0
ldh [c], a
.wait
dec d
ret z
xor a
ldh [rIF], a
halt
jr .wait
Function104ddd:
ld d, $0
ld e, d
ld a, $1
ldh [hPrintNumBuffer + 8], a
.loop
call MysteryGift_ReadJoypad
ld b, $2
ld c, LOW(rRP)
ldh a, [hMGJoypadReleased]
bit B_BUTTON_F, a
jr z, .next
ld a, $10
ldh [hMGStatusFlags], a
ret
.next
bit 0, a
jr nz, Function104e3a
ldh a, [c]
and b
jr nz, .loop
Function104dfe:
ld c, LOW(rRP)
ld d, $0
ld e, d
call Function104db7
jp z, Function104f42
ld d, e
call Function104da9
jp z, Function104f42
call Function104db7
jp z, Function104f42
call Function104da9
jp z, Function104f42
ld a, $6c
ldh [hMGStatusFlags], a
ld d, $3d
call Function104dd1
ld d, $5
call Function104dc5
ld d, $15
call Function104dd1
ld d, $5
call Function104dc5
ld d, $5
call Function104dd1
ret
Function104e3a:
; Wait a random amount of time
call Random
ld e, a
and $f
ld d, a
.loop
dec de
ld a, d
or e
jr nz, .loop
Function104e46:
ld a, $2
ldh [hPrintNumBuffer + 8], a
ld c, LOW(rRP)
ld d, $0
ld e, d
ld d, $3d
call Function104dd1
ld d, $5
call Function104dc5
ld d, $15
call Function104dd1
ld d, $5
call Function104dc5
ld d, $5
call Function104dd1
ld d, e
call Function104db7
jp z, Function104f42
ld d, e
call Function104da9
jp z, Function104f42
call Function104db7
jp z, Function104f42
call Function104da9
jp z, Function104f42
ld d, $3d
call Function104dd1
ld a, $6c
ldh [hMGStatusFlags], a
ret
Function104e8c:
ldh [rRP], a
ld a, $ff
ldh [hMGStatusFlags], a
ret
Function104e93:
xor a
ldh [hPrintNumBuffer + 4], a
ldh [hPrintNumBuffer + 5], a
push hl
push bc
ld c, LOW(rRP)
ld d, $3d
call Function104dd1
ld hl, hPrintNumBuffer + 1
ld a, $5a
ld [hli], a
ld [hl], b
dec hl
ld b, $2
call Function104ed6
pop bc
pop hl
call Function104ed6
ldh a, [hPrintNumBuffer + 4]
ldh [hPrintNumBuffer + 1], a
ldh a, [hPrintNumBuffer + 5]
ldh [hPrintNumBuffer + 2], a
push hl
ld hl, hPrintNumBuffer + 1
ld b, $2
call Function104ed6
ld hl, hMGStatusFlags
ld b, $1
call Function104faf
ldh a, [hPrintNumBuffer + 1]
ldh [hPrintNumBuffer + 4], a
ldh a, [hPrintNumBuffer + 2]
ldh [hPrintNumBuffer + 5], a
pop hl
ret
Function104ed6:
ld c, LOW(rRP)
ld d, $5
call Function104dd1
ld d, $5
call Function104dc5
ld d, $15
call Function104dd1
ld a, b
cpl
ld b, a
ld a, $f4
ldh [rTMA], a
.asm_104eee
inc b
jr z, .asm_104f2e
ld a, $8
ldh [hPrintNumBuffer + 3], a
ld a, [hli]
ld e, a
ldh a, [hPrintNumBuffer + 4]
add e
ldh [hPrintNumBuffer + 4], a
ldh a, [hPrintNumBuffer + 5]
adc 0
ldh [hPrintNumBuffer + 5], a
.asm_104f02
xor a
ldh [rIF], a
halt
ld a, $c1
ldh [rRP], a
ld d, $1
ld a, e
rlca
ld e, a
jr nc, .asm_104f13
inc d
.asm_104f13
ldh a, [rTIMA]
cp $f8
jr c, .asm_104f13
ld a, $c0
ldh [rRP], a
dec d
jr z, .asm_104f25
xor a
ldh [rIF], a
halt
.asm_104f25
ldh a, [hPrintNumBuffer + 3]
dec a
jr z, .asm_104eee
ldh [hPrintNumBuffer + 3], a
jr .asm_104f02
.asm_104f2e
ld a, $fe
ldh [rTMA], a
xor a
ldh [rIF], a
halt
ld d, $5
call Function104dc5
ld d, $11
call Function104dd1
ret
Function104f42:
ldh a, [hMGStatusFlags]
or $2
ldh [hMGStatusFlags], a
ret
Function104f49:
ldh a, [hMGStatusFlags]
or $1
ldh [hMGStatusFlags], a
ret
Function104f50:
ldh a, [hMGStatusFlags]
or $80
ldh [hMGStatusFlags], a
ret
Function104f57:
xor a
ldh [hPrintNumBuffer + 4], a
ldh [hPrintNumBuffer + 5], a
push bc
push hl
ld hl, hPrintNumBuffer + 1
ld b, $2
call Function104faf
ldh a, [hPrintNumBuffer + 2]
ldh [hPrintNumBuffer + 7], a
ld b, a
pop hl
pop af
cp b
jp c, Function104f50
ldh a, [hPrintNumBuffer + 1]
cp $5a
jp nz, Function104f50
call Function104faf
ldh a, [hPrintNumBuffer + 4]
ld d, a
ldh a, [hPrintNumBuffer + 5]
ld e, a
push hl
push de
ld hl, hPrintNumBuffer + 1
ld b, $2
call Function104faf
pop de
ld hl, hPrintNumBuffer + 1
ld a, [hli]
xor d
ld b, a
ld a, [hl]
xor e
or b
call nz, Function104f49
push de
ld d, $3d
call Function104dd1
ld hl, hMGStatusFlags
ld b, $1
call Function104ed6
pop de
pop hl
ld a, d
ldh [hPrintNumBuffer + 4], a
ld a, e
ldh [hPrintNumBuffer + 5], a
ret
Function104faf:
ld c, LOW(rRP)
ld d, $0
call Function104db7
jp z, Function104f42
ld d, $0
call Function104da9
jp z, Function104f42
ld d, $0
call Function104db7
jp z, Function104f42
ld a, b
cpl
ld b, a
xor a
ldh [hMGJoypadPressed + 2], a
call Function104d86
.asm_104fd2
inc b
jr z, .asm_10501a
ld a, $8
ldh [hPrintNumBuffer + 3], a
.asm_104fd9
ld d, $0
.asm_104fdb
inc d
jr z, .asm_104fe5
ldh a, [c]
bit 1, a
jr z, .asm_104fdb
ld d, $0
.asm_104fe5
inc d
jr z, .asm_104fed
ldh a, [c]
bit 1, a
jr nz, .asm_104fe5
.asm_104fed
ldh a, [hMGJoypadPressed + 2]
ld d, a
ldh a, [rTIMA]
ldh [hMGJoypadPressed + 2], a
sub d
cp $12
jr c, .asm_104ffd
set 0, e
jr .asm_104fff
.asm_104ffd
res 0, e
.asm_104fff
ldh a, [hPrintNumBuffer + 3]
dec a
ldh [hPrintNumBuffer + 3], a
jr z, .asm_10500b
ld a, e
rlca
ld e, a
jr .asm_104fd9
.asm_10500b
ld a, e
ld [hli], a
ldh a, [hPrintNumBuffer + 4]
add e
ldh [hPrintNumBuffer + 4], a
ldh a, [hPrintNumBuffer + 5]
adc 0
ldh [hPrintNumBuffer + 5], a
jr .asm_104fd2
.asm_10501a
call Function104d74
xor a
ldh [rIF], a
ld d, $0
call Function104da9
jp z, Function104f42
ld d, $10
call Function104dd1
ret
Function10502e:
ld b, $0
jp Function104e93
Function105033:
ld b, $0
jp Function104f57
MysteryGift_ReadJoypad:
; We can only get four inputs at a time.
; We take d-pad first for no particular reason.
ld a, R_DPAD
ldh [rJOYP], a
; Read twice to give the request time to take.
ldh a, [rJOYP]
ldh a, [rJOYP]
; The Joypad register output is in the lo nybble (inversed).
; We make the hi nybble of our new container d-pad input.
cpl
and $f
swap a
; We'll keep this in b for now.
ld b, a
; Buttons make 8 total inputs (A, B, Select, Start).
; We can fit this into one byte.
ld a, R_BUTTONS
ldh [rJOYP], a
; Wait for input to stabilize.
rept 6
ldh a, [rJOYP]
endr
; Buttons take the lo nybble.
cpl
and $f
or b
ld c, a
; To get the delta we xor the last frame's input with the new one.
ldh a, [hMGJoypadPressed]
xor c
; Released this frame:
and c
ldh [hMGJoypadReleased], a
; Pressed this frame:
ld a, c
ldh [hMGJoypadPressed], a
ld a, $30
; Reset the joypad register since we're done with it.
ldh [rJOYP], a
ret
MysteryGift_CheckAndSetDecorationAlreadyReceived:
call GetMysteryGiftBank
ld d, $0
ld b, CHECK_FLAG
ld hl, sMysteryGiftDecorationsReceived
predef_id SmallFarFlagAction
push hl
push bc
call Predef
call CloseSRAM
ld a, c
and a
pop bc
pop hl
ret nz
call GetMysteryGiftBank
ld b, SET_FLAG
predef SmallFarFlagAction
call CloseSRAM
xor a
ret
MysteryGift_CopyReceivedDecosToPC:
call GetMysteryGiftBank
ld c, $0
.loop
push bc
ld d, $0
ld b, CHECK_FLAG
ld hl, sMysteryGiftDecorationsReceived
predef SmallFarFlagAction
ld a, c
and a
pop bc
jr z, .skip
push bc
callfar SetSpecificDecorationFlag
pop bc
.skip
inc c
ld a, c
cp TrophyIDs - DecorationIDs
jr c, .loop
jp CloseSRAM
UnlockMysteryGift:
call GetMysteryGiftBank
ld hl, sMysteryGiftUnlocked
ld a, [hl]
inc a
jr nz, .ok
ld [hld], a
ld [hl], a
.ok
jp CloseSRAM
Function1050c8:
call GetMysteryGiftBank
ld a, [sNumDailyMysteryGiftPartnerIDs]
cp $ff
jr z, .okay
xor a
ld [sNumDailyMysteryGiftPartnerIDs], a
.okay
jp CloseSRAM
BackupMysteryGift:
call GetMysteryGiftBank
ld hl, sMysteryGiftItem
ld de, sBackupMysteryGiftItem
ld a, [hli]
ld [de], a
inc de
ld a, [hl]
ld [de], a
jp CloseSRAM
RestoreMysteryGift:
call GetMysteryGiftBank
ld hl, sBackupMysteryGiftItem
ld de, sMysteryGiftItem
ld a, [hli]
ld [de], a
inc de
ld a, [hl]
ld [de], a
jp CloseSRAM
MysteryGift_ClearTrainerData:
ld hl, wMysteryGiftTrainerData
xor a
ld b, wMysteryGiftTrainerDataEnd - wMysteryGiftTrainerData
.loop
ld [hli], a
dec b
jr nz, .loop
ret
GetMysteryGiftBank:
ld a, BANK(sBackupMysteryGiftItem)
jp GetSRAMBank
StagePartyDataForMysteryGift:
; You will be sending this data to your mystery gift partner.
; Structure is the same as a trainer with species and moves
; defined.
ld a, BANK(sPokemonData)
call GetSRAMBank
ld de, wMysteryGiftStaging
ld bc, sPokemonData + wPartyMons - wPokemonData
ld hl, sPokemonData + wPartySpecies - wPokemonData
.loop
ld a, [hli]
cp -1
jr z, .party_end
cp EGG
jr z, .next
push hl
; copy level
ld hl, MON_LEVEL
add hl, bc
ld a, [hl]
ld [de], a
inc de
; copy species
ld hl, MON_SPECIES
add hl, bc
ld a, [hl]
ld [de], a
inc de
; copy moves
ld hl, MON_MOVES
add hl, bc
push bc
ld bc, NUM_MOVES
call CopyBytes
pop bc
pop hl
.next
push hl
ld hl, PARTYMON_STRUCT_LENGTH
add hl, bc
ld b, h
ld c, l
pop hl
jr .loop
.party_end
ld a, -1
ld [de], a
ld a, $26
ld [wca00], a
jp CloseSRAM
InitMysteryGiftLayout:
call ClearBGPalettes
call DisableLCD
ld hl, MysteryGiftGFX
ld de, vTiles2 tile $00
ld a, BANK(MysteryGiftGFX)
ld bc, MysteryGiftGFX.End - MysteryGiftGFX
call FarCopyBytes
hlcoord 0, 0
ld a, $42
ld bc, SCREEN_HEIGHT * SCREEN_WIDTH
call ByteFill
hlcoord 3, 7
lb bc, 9, 15
call ClearBox
hlcoord 0, 0
ld a, $0
ld [hli], a
inc a
ld [hl], a
hlcoord 0, 1
inc a
ld [hli], a
inc a
ld [hl], a
hlcoord 7, 1
ld a, $12
call .Load5GFX
hlcoord 2, 2
ld a, $17
call .Load16GFX
hlcoord 2, 3
ld a, $27
call .Load16GFX
hlcoord 9, 4
ld a, $37
ld [hli], a
inc a
ld [hl], a
hlcoord 1, 2
ld [hl], $4
hlcoord 1, 3
ld a, $5
call .Load14Column
ld a, $9
hlcoord 18, 5
call .Load11Column
hlcoord 2, 5
ld a, $b
call .Load16Row
hlcoord 2, 16
ld a, $7
call .Load16Row
hlcoord 2, 5
ld a, $d
call .Load5GFX
hlcoord 7, 5
ld [hl], $c
hlcoord 18, 5
ld [hl], $a
hlcoord 18, 16
ld [hl], $8
hlcoord 1, 16
ld [hl], $6
hlcoord 2, 6
ld a, $3a
call .Load16Row
hlcoord 2, 15
ld a, $40
call .Load16Row
hlcoord 2, 6
ld a, $3c
call .Load9Column
hlcoord 17, 6
ld a, $3e
call .Load9Column
hlcoord 2, 6
ld [hl], $39
hlcoord 17, 6
ld [hl], $3b
hlcoord 2, 15
ld [hl], $3f
hlcoord 17, 15
ld [hl], $41
call EnableLCD
call WaitBGMap
ld b, SCGB_MYSTERY_GIFT
call GetSGBLayout
call SetPalettes
ret
.Load5GFX:
ld b, 5
jr .gfx_loop
.Unreferenced_Load6GFX:
ld b, 6
jr .gfx_loop
.Load16GFX:
ld b, 16
.gfx_loop
ld [hli], a
inc a
dec b
jr nz, .gfx_loop
ret
.Load9Column:
ld b, 9
jr .col_loop
.Load11Column:
ld b, 11
jr .col_loop
.Load14Column:
ld b, 14
.col_loop
ld [hl], a
ld de, SCREEN_WIDTH
add hl, de
dec b
jr nz, .col_loop
ret
.Load16Row:
ld b, 16
.row_loop
ld [hli], a
dec b
jr nz, .row_loop
ret
MysteryGiftGFX:
INCBIN "gfx/mystery_gift/mystery_gift.2bpp"
.End
Function105688:
call ClearTileMap
call ClearSprites
call WaitBGMap
call Function1057d7
hlcoord 3, 8
ld de, String_PressAToLink_BToCancel_JP
call PlaceString
call WaitBGMap
call Function10578c
call MysteryGift_ClearTrainerData
ld a, $24
ld [wca02], a
ldh a, [rIE]
push af
call Function104c2d
ld d, a
xor a
ldh [rIF], a
pop af
ldh [rIE], a
ld a, d
cp $10
jp z, Function105712
cp $6c
jp nz, Function10571a
call Function1056eb
ld c, 60
call DelayFrames
call Function105777
ld hl, Text_ReceivedCard
call PrintText
ld de, wMysteryGiftTrainerData
farcall Function8ac70
ld a, c
ld [wDeciramBuffer], a
ld hl, Text_CardNotRegistered
jr c, PrintTextAndExit_JP
ld hl, Text_ListedCardAsNumber
jr PrintTextAndExit_JP
Function1056eb:
ld c, 16
.loop
ld hl, wVirtualOAMSprite00YCoord
ld b, 8
.dec_y_loop
dec [hl]
rept SPRITEOAMSTRUCT_LENGTH
inc hl
endr
dec b
jr nz, .dec_y_loop
ld hl, wVirtualOAMSprite08YCoord
ld b, 8
.inc_y_loop
inc [hl]
rept SPRITEOAMSTRUCT_LENGTH
inc hl
endr
dec b
jr nz, .inc_y_loop
dec c
ret z
push bc
ld c, 4
call DelayFrames
pop bc
jr .loop
Function105712:
call Function105777
ld hl, Text_MGLinkCanceled
jr PrintTextAndExit_JP
Function10571a:
call Function105777
ld hl, Text_MGCommError
call PrintText
jp Function105688
PrintTextAndExit_JP:
call PrintText
ld a, LCDC_DEFAULT
ldh [rLCDC], a
ret
String_PressAToLink_BToCancel_JP:
db "エーボタン<WO>おすと"
next "つうしん<PKMN>おこなわれるよ!"
next "ビーボタン<WO>おすと"
next "つうしん<WO>ちゅうし します"
db "@"
Text_ReceivedCard:
text_far UnknownText_0x1c051a
text_end
Text_ListedCardAsNumber:
text_far UnknownText_0x1c0531
text_end
Text_CardNotRegistered:
text_far UnknownText_0x1c0555
text_end
Text_MGLinkCanceled:
text_far UnknownText_0x1c0573
text_end
Text_MGCommError:
text_far UnknownText_0x1c0591
text_end
Function105777:
call ClearSprites
call ClearTileMap
call EnableLCD
call WaitBGMap
ld b, SCGB_DIPLOMA
call GetSGBLayout
call SetPalettes
ret
Function10578c:
ld de, wLinkData
ld a, BANK(sPlayerData)
call GetSRAMBank
ld hl, sPlayerData + wPlayerName - wPlayerData
ld bc, NAME_LENGTH
call CopyBytes
ld hl, sPlayerData + wPlayerID - wPlayerData
ld bc, 2
call CopyBytes
ld hl, sPlayerData + wSecretID - wPlayerData
ld bc, 2
call CopyBytes
call CloseSRAM
ld a, BANK(sCrystalData)
call GetSRAMBank
ld a, [sCrystalData + 0]
ld [de], a
inc de
ld a, 4 ; MBC30 bank used by JP Crystal; inaccessible by MBC3
call GetSRAMBank
ld hl, $a603 ; address of MBC30 bank
ld bc, $8
call CopyBytes
ld hl, $a007 ; address of MBC30 bank
ld bc, $c
call CopyBytes
call CloseSRAM
ret
Function1057d7:
call ClearBGPalettes
call DisableLCD
ld hl, MysteryGiftJP_GFX
ld de, vTiles2 tile $00
ld a, BANK(MysteryGiftJP_GFX)
lb bc, 4, 0
call FarCopyBytes
ld hl, MysteryGiftJP_GFX + $40 tiles
ld de, vTiles0 tile $00
ld a, BANK(MysteryGiftJP_GFX)
ld bc, $80
call FarCopyBytes
hlcoord 0, 0
ld a, $3f
ld bc, SCREEN_HEIGHT * SCREEN_WIDTH
call ByteFill
hlcoord 3, 7
lb bc, 9, 15
call ClearBox
hlcoord 0, 0
ld a, $0
ld [hli], a
inc a
ld [hl], a
hlcoord 0, 1
inc a
ld [hli], a
inc a
ld [hl], a
hlcoord 4, 2
ld a, $13
call .Load11Row
hlcoord 4, 3
ld a, $1e
call .Load12Row
hlcoord 4, 4
ld a, $2a
call .Load12Row
hlcoord 1, 2
ld [hl], $4
hlcoord 1, 3
ld a, $5
call .Load14Column
ld a, $9
hlcoord 18, 5
call .Load11Column
hlcoord 2, 5
ld a, $b
call .Load16Row
hlcoord 2, 16
ld a, $7
call .Load16Row
hlcoord 2, 5
ld a, $d
call .Load6Row
hlcoord 8, 5
ld [hl], $c
hlcoord 18, 5
ld [hl], $a
hlcoord 18, 16
ld [hl], $8
hlcoord 1, 16
ld [hl], $6
hlcoord 2, 6
ld a, $37
call .Load16Row
hlcoord 2, 15
ld a, $3d
call .Load16Row
hlcoord 2, 6
ld a, $39
call .Load9Column
hlcoord 17, 6
ld a, $3b
call .Load9Column
hlcoord 2, 6
ld [hl], $36
hlcoord 17, 6
ld [hl], $38
hlcoord 2, 15
ld [hl], $3c
hlcoord 17, 15
ld [hl], $3e
ld de, wVirtualOAMSprite00
ld hl, .OAM_data
ld bc, 16 * SPRITEOAMSTRUCT_LENGTH
call CopyBytes
call EnableLCD
call WaitBGMap
ld b, $2
farcall GetMysteryGift_MobileAdapterLayout
jp SetPalettes
.Load6Row:
ld b, 6
jr .row_loop
.Load11Row:
ld b, 11
jr .row_loop
.Load12Row:
ld b, 12
.row_loop
ld [hli], a
inc a
dec b
jr nz, .row_loop
ret
.Load9Column:
ld b, 9
jr .column_loop
.Load11Column:
ld b, 11
jr .column_loop
.Load14Column:
ld b, 14
.column_loop
ld [hl], a
ld de, SCREEN_WIDTH
add hl, de
dec b
jr nz, .column_loop
ret
.Load16Row:
ld b, 16
.row_loop_no_inc
ld [hli], a
dec b
jr nz, .row_loop_no_inc
ret
.OAM_data:
dsprite 2, 1, 6, 4, $00, 0
dsprite 2, 1, 7, 4, $01, 0
dsprite 2, 1, 8, 4, $02, 0
dsprite 2, 1, 9, 4, $03, 0
dsprite 3, 1, 6, 4, $04, 0
dsprite 3, 1, 7, 4, $05, 0
dsprite 3, 1, 8, 4, $06, 0
dsprite 3, 1, 9, 4, $07, 0
dsprite 0, 1, 11, 4, $00, 0
dsprite 0, 1, 12, 4, $01, 0
dsprite 0, 1, 13, 4, $02, 0
dsprite 0, 1, 14, 4, $03, 0
dsprite 1, 1, 11, 4, $04, 0
dsprite 1, 1, 12, 4, $05, 0
dsprite 1, 1, 13, 4, $06, 0
dsprite 1, 1, 14, 4, $07, 0
; japanese mystery gift gfx
MysteryGiftJP_GFX:
INCBIN "gfx/mystery_gift/mystery_gift_jp.2bpp"
|
.byte $01 ; Unknown purpose
.byte OBJ_BONUSCONTROLLER, $00, $1C
.byte OBJ_PARATROOPAGREENHOP, $12, $15
.byte OBJ_PARATROOPAGREENHOP, $17, $15
.byte OBJ_PARAGOOMBAWITHMICROS, $14, $17
.byte OBJ_PARATROOPAGREENHOP, $2D, $16
.byte OBJ_VENUSFIRETRAP_CEIL, $30, $11
.byte OBJ_VENUSFIRETRAP, $37, $17
.byte OBJ_PARAGOOMBAWITHMICROS, $4E, $17
.byte OBJ_FIRECHOMP, $52, $13
.byte OBJ_REDPIRANHA, $54, $17
.byte OBJ_VENUSFIRETRAP_CEIL, $69, $10
.byte OBJ_PARATROOPAGREENHOP, $70, $15
.byte OBJ_PARAGOOMBAWITHMICROS, $78, $17
.byte OBJ_ENDLEVELCARD, $98, $15
.byte $FF ; Terminator
|
; A083336: a(n)=4a(n-2)-a(n-4).
; Submitted by Christian Krause
; 3,3,9,12,33,45,123,168,459,627,1713,2340,6393,8733,23859,32592,89043,121635,332313,453948,1240209,1694157,4628523,6322680,17273883,23596563,64467009,88063572,240594153,328657725,897909603
mov $2,1
lpb $0
sub $0,2
add $1,$2
add $2,$1
add $2,$1
lpe
lpb $0
add $2,$1
trn $0,$2
lpe
mov $0,$2
mul $0,3
|
; A156561: Floor(Fibonacci(2n+1)/9).
; 0,0,0,1,3,9,25,67,177,464,1216,3184,8336,21824,57136,149585,391619,1025273,2684201,7027331,18397793,48166048,126100352,330135008,864304672,2262779008,5924032352,15509318049,40603921795,106302447337,278303420217
seq $0,122367 ; Dimension of 3-variable non-commutative harmonics (twisted derivative). The dimension of the space of non-commutative polynomials in 3 variables which are killed by all symmetric differential operators (where for a monomial w, d_{xi} ( xi w ) = w and d_{xi} ( xj w ) = 0 for i != j).
div $0,9
|
;
;
; Z88 Maths Routines
;
; C Interface for Small C+ Compiler
;
; 7/12/98 djm
;
; fmod(z,x) = z-x*floor(z/x)
; if x>0 then 0 <= fmod(z,x) < x
; if x<0 then x < fmod(z,x) <= 0
;
;x is in the FA
;z is on the stack +8 (+2=x)
INCLUDE "#fpp.def"
XLIB fmod
LIB fsetup
LIB stkequ2
XREF fa
.fmod
ld ix,8
add ix,sp
ld l,(ix+1)
ld h,(ix+2)
ld de,(fa+1)
exx ;main set
ld c,(ix+5)
ld l,(ix+3)
ld h,(ix+4)
ld de,(fa+3)
ld a,(fa+5)
ld b,a
push ix
fpp(FP_DIV)
fpp(FP_INT) ;floor
;Load up x from the FA and multiply
ld de,(fa+3)
ld a,(fa+5)
ld b,a
exx
ld de,(fa+1)
exx
fpp(FP_MUL)
fpp(FP_NEG) ;negate
;load up z again
pop ix
ld e,(ix+3)
ld d,(ix+4)
ld b,(ix+5) ;exponent
exx
ld e,(ix+1)
ld d,(ix+2)
exx
fpp(FP_ADD)
jp stkequ2
|
SECTION code_fp_math32
PUBLIC ___uchar2fs_callee
EXTERN cm32_sdcc___uchar2fs_callee
defc ___uchar2fs_callee = cm32_sdcc___uchar2fs_callee
|
.size 8000
.text@50
jp ltimaint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
xor a, a
ldff(0f), a
ldff(ff), a
ld a, fe
ldff(05), a
ldff(06), a
ld a, 04
ldff(ff), a
ld a, 04
ldff(07), a
ei
nop
halt
.text@1000
ltimaint:
nop
.text@116f
ld c, 05
ld a, 00
ldff(07), a
ldff a, (c)
.text@1202
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
ld bc, 7a00
ld hl, 8000
ld d, 00
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
pop af
ld b, a
srl a
srl a
srl a
srl a
ld(9800), a
ld a, b
and a, 0f
ld(9801), a
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
00 00 08 08 22 22 41 41
7f 7f 41 41 41 41 41 41
00 00 7e 7e 41 41 41 41
7e 7e 41 41 41 41 7e 7e
00 00 3e 3e 41 41 40 40
40 40 40 40 41 41 3e 3e
00 00 7e 7e 41 41 41 41
41 41 41 41 41 41 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 40 40
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include <cstring>
#include <ctime>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef _WIN32
#include <direct.h>
#endif /* _WIN32 */
#include "utility.hpp"
#include "opencv2/core.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/calib3d.hpp"
using namespace cv;
#ifndef PATH_MAX
#define PATH_MAX 512
#endif /* PATH_MAX */
#define __BEGIN__ __CV_BEGIN__
#define __END__ __CV_END__
#define EXIT __CV_EXIT__
static int icvMkDir( const char* filename )
{
char path[PATH_MAX];
char* p;
int pos;
#ifdef _WIN32
struct _stat st;
#else /* _WIN32 */
struct stat st;
mode_t mode;
mode = 0755;
#endif /* _WIN32 */
strcpy( path, filename );
p = path;
for( ; ; )
{
pos = (int)strcspn( p, "/\\" );
if( pos == (int) strlen( p ) ) break;
if( pos != 0 )
{
p[pos] = '\0';
#ifdef _WIN32
if( p[pos-1] != ':' )
{
if( _stat( path, &st ) != 0 )
{
if( _mkdir( path ) != 0 ) return 0;
}
}
#else /* _WIN32 */
if( stat( path, &st ) != 0 )
{
if( mkdir( path, mode ) != 0 ) return 0;
}
#endif /* _WIN32 */
}
p[pos] = '/';
p += pos + 1;
}
return 1;
}
static void icvWriteVecHeader( FILE* file, int count, int width, int height )
{
int vecsize;
short tmp;
/* number of samples */
fwrite( &count, sizeof( count ), 1, file );
/* vector size */
vecsize = width * height;
fwrite( &vecsize, sizeof( vecsize ), 1, file );
/* min/max values */
tmp = 0;
fwrite( &tmp, sizeof( tmp ), 1, file );
fwrite( &tmp, sizeof( tmp ), 1, file );
}
static void icvWriteVecSample( FILE* file, Mat sample )
{
uchar chartmp = 0;
fwrite( &chartmp, sizeof( chartmp ), 1, file );
for(int r = 0; r < sample.rows; r++ )
{
for(int c = 0; c < sample.cols; c++ )
{
short tmp = sample.at<uchar>(r,c);
fwrite( &tmp, sizeof( tmp ), 1, file );
}
}
}
/* Calculates coefficients of perspective transformation
* which maps <quad> into rectangle ((0,0), (w,0), (w,h), (h,0)):
*
* c00*xi + c01*yi + c02
* ui = ---------------------
* c20*xi + c21*yi + c22
*
* c10*xi + c11*yi + c12
* vi = ---------------------
* c20*xi + c21*yi + c22
*
* Coefficients are calculated by solving linear system:
* / x0 y0 1 0 0 0 -x0*u0 -y0*u0 \ /c00\ /u0\
* | x1 y1 1 0 0 0 -x1*u1 -y1*u1 | |c01| |u1|
* | x2 y2 1 0 0 0 -x2*u2 -y2*u2 | |c02| |u2|
* | x3 y3 1 0 0 0 -x3*u3 -y3*u3 |.|c10|=|u3|,
* | 0 0 0 x0 y0 1 -x0*v0 -y0*v0 | |c11| |v0|
* | 0 0 0 x1 y1 1 -x1*v1 -y1*v1 | |c12| |v1|
* | 0 0 0 x2 y2 1 -x2*v2 -y2*v2 | |c20| |v2|
* \ 0 0 0 x3 y3 1 -x3*v3 -y3*v3 / \c21/ \v3/
*
* where:
* (xi, yi) = (quad[i][0], quad[i][1])
* cij - coeffs[i][j], coeffs[2][2] = 1
* (ui, vi) - rectangle vertices
*/
static void cvGetPerspectiveTransform( Size src_size, double quad[4][2], double coeffs[3][3] )
{
double a[8][8];
double b[8];
Mat A( 8, 8, CV_64FC1, a );
Mat B( 8, 1, CV_64FC1, b );
Mat X( 8, 1, CV_64FC1, coeffs );
int i;
for( i = 0; i < 4; ++i )
{
a[i][0] = quad[i][0]; a[i][1] = quad[i][1]; a[i][2] = 1;
a[i][3] = a[i][4] = a[i][5] = a[i][6] = a[i][7] = 0;
b[i] = 0;
}
for( i = 4; i < 8; ++i )
{
a[i][3] = quad[i-4][0]; a[i][4] = quad[i-4][1]; a[i][5] = 1;
a[i][0] = a[i][1] = a[i][2] = a[i][6] = a[i][7] = 0;
b[i] = 0;
}
int u = src_size.width - 1;
int v = src_size.height - 1;
a[1][6] = -quad[1][0] * u; a[1][7] = -quad[1][1] * u;
a[2][6] = -quad[2][0] * u; a[2][7] = -quad[2][1] * u;
b[1] = b[2] = u;
a[6][6] = -quad[2][0] * v; a[6][7] = -quad[2][1] * v;
a[7][6] = -quad[3][0] * v; a[7][7] = -quad[3][1] * v;
b[6] = b[7] = v;
solve( A, B, X );
coeffs[2][2] = 1;
}
/* Warps source into destination by a perspective transform */
static void cvWarpPerspective( Mat src, Mat dst, double quad[4][2] )
{
int fill_value = 0;
double c[3][3]; /* transformation coefficients */
double q[4][2]; /* rearranged quad */
int left = 0;
int right = 0;
int next_right = 0;
int next_left = 0;
double y_min = 0;
double y_max = 0;
double k_left, b_left, k_right, b_right;
double d = 0;
int direction = 0;
int i;
if( src.type() != CV_8UC1 || src.dims != 2 )
{
CV_Error( Error::StsBadArg,
"Source must be two-dimensional array of CV_8UC1 type." );
}
if( dst.type() != CV_8UC1 || dst.dims != 2 )
{
CV_Error( Error::StsBadArg,
"Destination must be two-dimensional array of CV_8UC1 type." );
}
cvGetPerspectiveTransform( src.size(), quad, c );
/* if direction > 0 then vertices in quad follow in a CW direction,
otherwise they follow in a CCW direction */
direction = 0;
for( i = 0; i < 4; ++i )
{
int ni = i + 1; if( ni == 4 ) ni = 0;
int pi = i - 1; if( pi == -1 ) pi = 3;
d = (quad[i][0] - quad[pi][0])*(quad[ni][1] - quad[i][1]) -
(quad[i][1] - quad[pi][1])*(quad[ni][0] - quad[i][0]);
int cur_direction = d > 0 ? 1 : d < 0 ? -1 : 0;
if( direction == 0 )
{
direction = cur_direction;
}
else if( direction * cur_direction < 0 )
{
direction = 0;
break;
}
}
if( direction == 0 )
{
CV_Error(Error::StsBadArg, "Quadrangle is nonconvex or degenerated." );
}
/* <left> is the index of the topmost quad vertice
if there are two such vertices <left> is the leftmost one */
left = 0;
for( i = 1; i < 4; ++i )
{
if( (quad[i][1] < quad[left][1]) ||
((quad[i][1] == quad[left][1]) && (quad[i][0] < quad[left][0])) )
{
left = i;
}
}
/* rearrange <quad> vertices in such way that they follow in a CW
direction and the first vertice is the topmost one and put them
into <q> */
if( direction > 0 )
{
for( i = left; i < 4; ++i )
{
q[i-left][0] = quad[i][0];
q[i-left][1] = quad[i][1];
}
for( i = 0; i < left; ++i )
{
q[4-left+i][0] = quad[i][0];
q[4-left+i][1] = quad[i][1];
}
}
else
{
for( i = left; i >= 0; --i )
{
q[left-i][0] = quad[i][0];
q[left-i][1] = quad[i][1];
}
for( i = 3; i > left; --i )
{
q[4+left-i][0] = quad[i][0];
q[4+left-i][1] = quad[i][1];
}
}
left = right = 0;
/* if there are two topmost points, <right> is the index of the rightmost one
otherwise <right> */
if( q[left][1] == q[left+1][1] )
{
right = 1;
}
/* <next_left> follows <left> in a CCW direction */
next_left = 3;
/* <next_right> follows <right> in a CW direction */
next_right = right + 1;
/* subtraction of 1 prevents skipping of the first row */
y_min = q[left][1] - 1;
/* left edge equation: y = k_left * x + b_left */
k_left = (q[left][0] - q[next_left][0]) /
(q[left][1] - q[next_left][1]);
b_left = (q[left][1] * q[next_left][0] -
q[left][0] * q[next_left][1]) /
(q[left][1] - q[next_left][1]);
/* right edge equation: y = k_right * x + b_right */
k_right = (q[right][0] - q[next_right][0]) /
(q[right][1] - q[next_right][1]);
b_right = (q[right][1] * q[next_right][0] -
q[right][0] * q[next_right][1]) /
(q[right][1] - q[next_right][1]);
for(;;)
{
int x, y;
y_max = MIN( q[next_left][1], q[next_right][1] );
int iy_min = MAX( cvRound(y_min), 0 ) + 1;
int iy_max = MIN( cvRound(y_max), dst.rows - 1 );
double x_min = k_left * iy_min + b_left;
double x_max = k_right * iy_min + b_right;
/* walk through the destination quadrangle row by row */
for( y = iy_min; y <= iy_max; ++y )
{
int ix_min = MAX( cvRound( x_min ), 0 );
int ix_max = MIN( cvRound( x_max ), dst.cols - 1 );
for( x = ix_min; x <= ix_max; ++x )
{
/* calculate coordinates of the corresponding source array point */
double div = (c[2][0] * x + c[2][1] * y + c[2][2]);
double src_x = (c[0][0] * x + c[0][1] * y + c[0][2]) / div;
double src_y = (c[1][0] * x + c[1][1] * y + c[1][2]) / div;
int isrc_x = cvFloor( src_x );
int isrc_y = cvFloor( src_y );
double delta_x = src_x - isrc_x;
double delta_y = src_y - isrc_y;
int i00, i10, i01, i11;
i00 = i10 = i01 = i11 = (int) fill_value;
/* linear interpolation using 2x2 neighborhood */
if( isrc_x >= 0 && isrc_x <= src.cols &&
isrc_y >= 0 && isrc_y <= src.rows )
{
i00 = src.at<uchar>(isrc_y, isrc_x);
}
if( isrc_x >= -1 && isrc_x < src.cols &&
isrc_y >= 0 && isrc_y <= src.rows )
{
i10 = src.at<uchar>(isrc_y, isrc_x + 1);
}
if( isrc_x >= 0 && isrc_x <= src.cols &&
isrc_y >= -1 && isrc_y < src.rows )
{
i01 = src.at<uchar>(isrc_y + 1, isrc_x);
}
if( isrc_x >= -1 && isrc_x < src.cols &&
isrc_y >= -1 && isrc_y < src.rows )
{
i11 = src.at<uchar>(isrc_y + 1, isrc_x + 1);
}
double i0 = i00 + (i10 - i00)*delta_x;
double i1 = i01 + (i11 - i01)*delta_x;
dst.at<uchar>(y, x) = (uchar) (i0 + (i1 - i0)*delta_y);
}
x_min += k_left;
x_max += k_right;
}
if( (next_left == next_right) ||
(next_left+1 == next_right && q[next_left][1] == q[next_right][1]) )
{
break;
}
if( y_max == q[next_left][1] )
{
left = next_left;
next_left = left - 1;
k_left = (q[left][0] - q[next_left][0]) /
(q[left][1] - q[next_left][1]);
b_left = (q[left][1] * q[next_left][0] -
q[left][0] * q[next_left][1]) /
(q[left][1] - q[next_left][1]);
}
if( y_max == q[next_right][1] )
{
right = next_right;
next_right = right + 1;
k_right = (q[right][0] - q[next_right][0]) /
(q[right][1] - q[next_right][1]);
b_right = (q[right][1] * q[next_right][0] -
q[right][0] * q[next_right][1]) /
(q[right][1] - q[next_right][1]);
}
y_min = y_max;
}
}
static
void icvRandomQuad( int width, int height, double quad[4][2],
double maxxangle,
double maxyangle,
double maxzangle )
{
double distfactor = 3.0;
double distfactor2 = 1.0;
double halfw, halfh;
int i;
double rotVectData[3];
double vectData[3];
double rotMatData[9];
double d;
Mat rotVect( 3, 1, CV_64FC1, &rotVectData[0] );
Mat rotMat( 3, 3, CV_64FC1, &rotMatData[0] );
Mat vect( 3, 1, CV_64FC1, &vectData[0] );
rotVectData[0] = maxxangle * (2.0 * rand() / RAND_MAX - 1.0);
rotVectData[1] = ( maxyangle - fabs( rotVectData[0] ) )
* (2.0 * rand() / RAND_MAX - 1.0);
rotVectData[2] = maxzangle * (2.0 * rand() / RAND_MAX - 1.0);
d = (distfactor + distfactor2 * (2.0 * rand() / RAND_MAX - 1.0)) * width;
Rodrigues( rotVect, rotMat );
halfw = 0.5 * width;
halfh = 0.5 * height;
quad[0][0] = -halfw;
quad[0][1] = -halfh;
quad[1][0] = halfw;
quad[1][1] = -halfh;
quad[2][0] = halfw;
quad[2][1] = halfh;
quad[3][0] = -halfw;
quad[3][1] = halfh;
for( i = 0; i < 4; i++ )
{
rotVectData[0] = quad[i][0];
rotVectData[1] = quad[i][1];
rotVectData[2] = 0.0;
gemm(rotMat, rotVect, 1., Mat(), 1., vect);
quad[i][0] = vectData[0] * d / (d + vectData[2]) + halfw;
quad[i][1] = vectData[1] * d / (d + vectData[2]) + halfh;
}
}
typedef struct CvSampleDistortionData
{
Mat src;
Mat erode;
Mat dilate;
Mat mask;
Mat img;
Mat maskimg;
int dx;
int dy;
int bgcolor;
} CvSampleDistortionData;
#if defined CV_OPENMP && (defined _MSC_VER || defined CV_ICC)
#define CV_OPENMP 1
#else
#undef CV_OPENMP
#endif
typedef struct CvBackgroundData
{
int count;
char** filename;
int last;
int round;
Size winsize;
} CvBackgroundData;
typedef struct CvBackgroundReader
{
Mat src;
Mat img;
Point offset;
float scale;
float scalefactor;
float stepfactor;
Point point;
} CvBackgroundReader;
/*
* Background reader
* Created in each thread
*/
CvBackgroundReader* cvbgreader = NULL;
#if defined CV_OPENMP
#pragma omp threadprivate(cvbgreader)
#endif
CvBackgroundData* cvbgdata = NULL;
static int icvStartSampleDistortion( const char* imgfilename, int bgcolor, int bgthreshold,
CvSampleDistortionData* data )
{
memset( data, 0, sizeof( *data ) );
data->src = imread( imgfilename, IMREAD_GRAYSCALE );
if( !(data->src.empty()) && data->src.type() == CV_8UC1 )
{
int r, c;
data->dx = data->src.cols / 2;
data->dy = data->src.rows / 2;
data->bgcolor = bgcolor;
data->mask = data->src.clone();
data->erode = data->src.clone();
data->dilate = data->src.clone();
/* make mask image */
for( r = 0; r < data->mask.rows; r++ )
{
for( c = 0; c < data->mask.cols; c++ )
{
uchar& pmask = data->mask.at<uchar>(r, c);
if( bgcolor - bgthreshold <= (int)pmask &&
(int)pmask <= bgcolor + bgthreshold )
{
pmask = (uchar) 0;
}
else
{
pmask = (uchar) 255;
}
}
}
/* extend borders of source image */
erode( data->src, data->erode, Mat() );
dilate( data->src, data->dilate, Mat() );
for( r = 0; r < data->mask.rows; r++ )
{
for( c = 0; c < data->mask.cols; c++ )
{
uchar& pmask = data->mask.at<uchar>(r, c);
if( pmask == 0 )
{
uchar& psrc = data->src.at<uchar>(r, c);
uchar& perode = data->erode.at<uchar>(r, c);
uchar& pdilate = data->dilate.at<uchar>(r, c);
uchar de = (uchar)(bgcolor - perode);
uchar dd = (uchar)(pdilate - bgcolor);
if( de >= dd && de > bgthreshold )
{
psrc = perode;
}
if( dd > de && dd > bgthreshold )
{
psrc = pdilate;
}
}
}
}
data->img = Mat(Size( data->src.cols + 2 * data->dx, data->src.rows + 2 * data->dy ), CV_8UC1);
data->maskimg = Mat(Size(data->src.cols + 2 * data->dx, data->src.rows + 2 * data->dy), CV_8UC1);
return 1;
}
return 0;
}
static
void icvPlaceDistortedSample( Mat background,
int inverse, int maxintensitydev,
double maxxangle, double maxyangle, double maxzangle,
int inscribe, double maxshiftf, double maxscalef,
CvSampleDistortionData* data )
{
double quad[4][2];
int r, c;
int forecolordev;
float scale;
Rect cr;
Rect roi;
double xshift, yshift, randscale;
icvRandomQuad( data->src.cols, data->src.rows, quad,
maxxangle, maxyangle, maxzangle );
quad[0][0] += (double) data->dx;
quad[0][1] += (double) data->dy;
quad[1][0] += (double) data->dx;
quad[1][1] += (double) data->dy;
quad[2][0] += (double) data->dx;
quad[2][1] += (double) data->dy;
quad[3][0] += (double) data->dx;
quad[3][1] += (double) data->dy;
data->img = data->bgcolor;
data->maskimg = 0;
cvWarpPerspective( data->src, data->img, quad );
cvWarpPerspective( data->mask, data->maskimg, quad );
GaussianBlur( data->maskimg, data->maskimg, Size(3, 3), 0, 0 );
cr.x = data->dx;
cr.y = data->dy;
cr.width = data->src.cols;
cr.height = data->src.rows;
if( inscribe )
{
/* quad's circumscribing rectangle */
cr.x = (int) MIN( quad[0][0], quad[3][0] );
cr.y = (int) MIN( quad[0][1], quad[1][1] );
cr.width = (int) (MAX( quad[1][0], quad[2][0] ) + 0.5F ) - cr.x;
cr.height = (int) (MAX( quad[2][1], quad[3][1] ) + 0.5F ) - cr.y;
}
xshift = maxshiftf * rand() / RAND_MAX;
yshift = maxshiftf * rand() / RAND_MAX;
cr.x -= (int) ( xshift * cr.width );
cr.y -= (int) ( yshift * cr.height );
cr.width = (int) ((1.0 + maxshiftf) * cr.width );
cr.height = (int) ((1.0 + maxshiftf) * cr.height);
randscale = maxscalef * rand() / RAND_MAX;
cr.x -= (int) ( 0.5 * randscale * cr.width );
cr.y -= (int) ( 0.5 * randscale * cr.height );
cr.width = (int) ((1.0 + randscale) * cr.width );
cr.height = (int) ((1.0 + randscale) * cr.height);
scale = MAX( ((float) cr.width) / background.cols, ((float) cr.height) / background.rows );
roi.x = (int) (-0.5F * (scale * background.cols - cr.width) + cr.x);
roi.y = (int) (-0.5F * (scale * background.rows - cr.height) + cr.y);
roi.width = (int) (scale * background.cols);
roi.height = (int) (scale * background.rows);
Mat img( background.size(), CV_8UC1 );
Mat maskimg( background.size(), CV_8UC1 );
resize( data->img(roi), img, img.size(), 0, 0, INTER_LINEAR_EXACT);
resize( data->maskimg(roi), maskimg, maskimg.size(), 0, 0, INTER_LINEAR_EXACT);
forecolordev = (int) (maxintensitydev * (2.0 * rand() / RAND_MAX - 1.0));
for( r = 0; r < img.rows; r++ )
{
for( c = 0; c < img.cols; c++ )
{
uchar& pbg = background.at<uchar>(r, c);
uchar& palpha = maskimg.at<uchar>(r, c);
uchar chartmp = (uchar) MAX( 0, MIN( 255, forecolordev + img.at<uchar>(r, c)) );
if( inverse )
{
chartmp ^= 0xFF;
}
pbg = (uchar) ((chartmp*palpha + (255 - palpha)*pbg) / 255);
}
}
}
static
CvBackgroundData* icvCreateBackgroundData( const char* filename, Size winsize )
{
CvBackgroundData* data = NULL;
const char* dir = NULL;
char full[PATH_MAX];
char* imgfilename = NULL;
size_t datasize = 0;
int count = 0;
FILE* input = NULL;
char* tmp = NULL;
int len = 0;
CV_Assert( filename != NULL );
dir = strrchr( filename, '\\' );
if( dir == NULL )
{
dir = strrchr( filename, '/' );
}
if( dir == NULL )
{
imgfilename = &(full[0]);
}
else
{
strncpy( &(full[0]), filename, (dir - filename + 1) );
imgfilename = &(full[(dir - filename + 1)]);
}
input = fopen( filename, "r" );
if( input != NULL )
{
count = 0;
datasize = 0;
/* count */
while( !feof( input ) )
{
*imgfilename = '\0';
if( !fgets( imgfilename, PATH_MAX - (int)(imgfilename - full) - 1, input ))
break;
len = (int)strlen( imgfilename );
for( ; len > 0 && isspace(imgfilename[len-1]); len-- )
imgfilename[len-1] = '\0';
if( len > 0 )
{
if( (*imgfilename) == '#' ) continue; /* comment */
count++;
datasize += sizeof( char ) * (strlen( &(full[0]) ) + 1);
}
}
if( count > 0 )
{
//rewind( input );
fseek( input, 0, SEEK_SET );
datasize += sizeof( *data ) + sizeof( char* ) * count;
data = (CvBackgroundData*) fastMalloc( datasize );
memset( (void*) data, 0, datasize );
data->count = count;
data->filename = (char**) (data + 1);
data->last = 0;
data->round = 0;
data->winsize = winsize;
tmp = (char*) (data->filename + data->count);
count = 0;
while( !feof( input ) )
{
*imgfilename = '\0';
if( !fgets( imgfilename, PATH_MAX - (int)(imgfilename - full) - 1, input ))
break;
len = (int)strlen( imgfilename );
if( len > 0 && imgfilename[len-1] == '\n' )
imgfilename[len-1] = 0, len--;
if( len > 0 )
{
if( (*imgfilename) == '#' ) continue; /* comment */
data->filename[count++] = tmp;
strcpy( tmp, &(full[0]) );
tmp += strlen( &(full[0]) ) + 1;
}
}
}
fclose( input );
}
return data;
}
static
CvBackgroundReader* icvCreateBackgroundReader()
{
CvBackgroundReader* reader = NULL;
reader = new CvBackgroundReader;
reader->scale = 1.0F;
reader->scalefactor = 1.4142135623730950488016887242097F;
reader->stepfactor = 0.5F;
return reader;
}
static
void icvGetNextFromBackgroundData( CvBackgroundData* data,
CvBackgroundReader* reader )
{
Mat img;
int round = 0;
int i = 0;
Point offset;
CV_Assert( data != NULL && reader != NULL );
#ifdef CV_OPENMP
#pragma omp critical(c_background_data)
#endif /* CV_OPENMP */
{
for( i = 0; i < data->count; i++ )
{
round = data->round;
data->last = rand() % data->count;
#ifdef CV_VERBOSE
printf( "Open background image: %s\n", data->filename[data->last] );
#endif /* CV_VERBOSE */
img = imread( data->filename[data->last], IMREAD_GRAYSCALE );
if( img.empty() )
continue;
data->round += data->last / data->count;
data->round = data->round % (data->winsize.width * data->winsize.height);
offset.x = round % data->winsize.width;
offset.y = round / data->winsize.width;
offset.x = MIN( offset.x, img.cols - data->winsize.width );
offset.y = MIN( offset.y, img.rows - data->winsize.height );
if( !img.empty() && img.type() == CV_8UC1 && offset.x >= 0 && offset.y >= 0 )
{
break;
}
img = Mat();
}
}
if( img.empty() )
{
/* no appropriate image */
#ifdef CV_VERBOSE
printf( "Invalid background description file.\n" );
#endif /* CV_VERBOSE */
CV_Assert( 0 );
exit( 1 );
}
reader->src = img;
//reader->offset.x = round % data->winsize.width;
//reader->offset.y = round / data->winsize.width;
reader->offset = offset;
reader->point = reader->offset;
reader->scale = MAX(
((float) data->winsize.width + reader->point.x) / ((float) reader->src.cols),
((float) data->winsize.height + reader->point.y) / ((float) reader->src.rows) );
resize( reader->src, reader->img,
Size((int)(reader->scale * reader->src.rows + 0.5F), (int)(reader->scale * reader->src.cols + 0.5F)), 0, 0, INTER_LINEAR_EXACT );
}
/*
* icvGetBackgroundImage
*
* Get an image from background
* <img> must be allocated and have size, previously passed to icvInitBackgroundReaders
*
* Usage example:
* icvInitBackgroundReaders( "bg.txt", cvSize( 24, 24 ) );
* ...
* #pragma omp parallel
* {
* ...
* icvGetBackgourndImage( cvbgdata, cvbgreader, img );
* ...
* }
* ...
* icvDestroyBackgroundReaders();
*/
static
void icvGetBackgroundImage( CvBackgroundData* data,
CvBackgroundReader* reader,
Mat& img )
{
CV_Assert( data != NULL && reader != NULL );
if( reader->img.empty() )
{
icvGetNextFromBackgroundData( data, reader );
}
img = reader->img(Rect(reader->point.x, reader->point.y, data->winsize.height, data->winsize.width)).clone();
if( (int) ( reader->point.x + (1.0F + reader->stepfactor ) * data->winsize.width )
< reader->img.cols )
{
reader->point.x += (int) (reader->stepfactor * data->winsize.width);
}
else
{
reader->point.x = reader->offset.x;
if( (int) ( reader->point.y + (1.0F + reader->stepfactor ) * data->winsize.height )
< reader->img.rows )
{
reader->point.y += (int) (reader->stepfactor * data->winsize.height);
}
else
{
reader->point.y = reader->offset.y;
reader->scale *= reader->scalefactor;
if( reader->scale <= 1.0F )
{
resize(reader->src, reader->img,
Size((int)(reader->scale * reader->src.rows), (int)(reader->scale * reader->src.cols)), 0, 0, INTER_LINEAR_EXACT);
}
else
{
icvGetNextFromBackgroundData( data, reader );
}
}
}
}
/*
* icvInitBackgroundReaders
*
* Initialize background reading process.
* <cvbgreader> and <cvbgdata> are initialized.
* Must be called before any usage of background
*
* filename - name of background description file
* winsize - size of images will be obtained from background
*
* return 1 on success, 0 otherwise.
*/
static int icvInitBackgroundReaders( const char* filename, Size winsize )
{
if( cvbgdata == NULL && filename != NULL )
{
cvbgdata = icvCreateBackgroundData( filename, winsize );
}
if( cvbgdata )
{
#ifdef CV_OPENMP
#pragma omp parallel
#endif /* CV_OPENMP */
{
#ifdef CV_OPENMP
#pragma omp critical(c_create_bg_data)
#endif /* CV_OPENMP */
{
if( cvbgreader == NULL )
{
cvbgreader = icvCreateBackgroundReader();
}
}
}
}
return (cvbgdata != NULL);
}
/*
* icvDestroyBackgroundReaders
*
* Finish backgournd reading process
*/
static
void icvDestroyBackgroundReaders()
{
/* release background reader in each thread */
#ifdef CV_OPENMP
#pragma omp parallel
#endif /* CV_OPENMP */
{
#ifdef CV_OPENMP
#pragma omp critical(c_release_bg_data)
#endif /* CV_OPENMP */
{
if( cvbgreader != NULL )
{
delete cvbgreader;
cvbgreader = NULL;
}
}
}
if( cvbgdata != NULL )
{
fastFree(cvbgdata);
cvbgdata = NULL;
}
}
void cvCreateTrainingSamples( const char* filename,
const char* imgfilename, int bgcolor, int bgthreshold,
const char* bgfilename, int count,
int invert, int maxintensitydev,
double maxxangle, double maxyangle, double maxzangle,
int showsamples,
int winwidth, int winheight )
{
CvSampleDistortionData data;
CV_Assert( filename != NULL );
CV_Assert( imgfilename != NULL );
if( !icvMkDir( filename ) )
{
fprintf( stderr, "Unable to create output file: %s\n", filename );
return;
}
if( icvStartSampleDistortion( imgfilename, bgcolor, bgthreshold, &data ) )
{
FILE* output = NULL;
output = fopen( filename, "wb" );
if( output != NULL )
{
int hasbg;
int i;
int inverse;
hasbg = 0;
hasbg = (bgfilename != NULL && icvInitBackgroundReaders( bgfilename,
Size( winwidth,winheight ) ) );
Mat sample( winheight, winwidth, CV_8UC1 );
icvWriteVecHeader( output, count, sample.cols, sample.rows );
if( showsamples )
{
namedWindow( "Sample", WINDOW_AUTOSIZE );
}
inverse = invert;
for( i = 0; i < count; i++ )
{
if( hasbg )
{
icvGetBackgroundImage( cvbgdata, cvbgreader, sample );
}
else
{
sample = bgcolor;
}
if( invert == CV_RANDOM_INVERT )
{
inverse = (rand() > (RAND_MAX/2));
}
icvPlaceDistortedSample( sample, inverse, maxintensitydev,
maxxangle, maxyangle, maxzangle,
0 /* nonzero means placing image without cut offs */,
0.0 /* nozero adds random shifting */,
0.0 /* nozero adds random scaling */,
&data );
if( showsamples )
{
imshow( "Sample", sample );
if( (waitKey( 0 ) & 0xFF) == 27 )
{
showsamples = 0;
}
}
icvWriteVecSample( output, sample );
#ifdef CV_VERBOSE
if( i % 500 == 0 )
{
printf( "\r%3d%%", 100 * i / count );
}
#endif /* CV_VERBOSE */
}
icvDestroyBackgroundReaders();
fclose( output );
} /* if( output != NULL ) */
}
#ifdef CV_VERBOSE
printf( "\r \r" );
#endif /* CV_VERBOSE */
}
#define CV_INFO_FILENAME "info.dat"
void cvCreateTestSamples( const char* infoname,
const char* imgfilename, int bgcolor, int bgthreshold,
const char* bgfilename, int count,
int invert, int maxintensitydev,
double maxxangle, double maxyangle, double maxzangle,
int showsamples,
int winwidth, int winheight, double maxscale )
{
CvSampleDistortionData data;
CV_Assert( infoname != NULL );
CV_Assert( imgfilename != NULL );
CV_Assert( bgfilename != NULL );
if( !icvMkDir( infoname ) )
{
#if CV_VERBOSE
fprintf( stderr, "Unable to create directory hierarchy: %s\n", infoname );
#endif /* CV_VERBOSE */
return;
}
if( icvStartSampleDistortion( imgfilename, bgcolor, bgthreshold, &data ) )
{
char fullname[PATH_MAX];
char* filename;
FILE* info;
if( icvInitBackgroundReaders( bgfilename, Size( 10, 10 ) ) )
{
int i;
int x, y, width, height;
float scale;
int inverse;
if( showsamples )
{
namedWindow( "Image", WINDOW_AUTOSIZE );
}
info = fopen( infoname, "w" );
strcpy( fullname, infoname );
filename = strrchr( fullname, '\\' );
if( filename == NULL )
{
filename = strrchr( fullname, '/' );
}
if( filename == NULL )
{
filename = fullname;
}
else
{
filename++;
}
count = MIN( count, cvbgdata->count );
inverse = invert;
for( i = 0; i < count; i++ )
{
icvGetNextFromBackgroundData( cvbgdata, cvbgreader );
if( maxscale < 0.0 )
{
maxscale = MIN( 0.7F * cvbgreader->src.cols / winwidth,
0.7F * cvbgreader->src.rows / winheight );
}
if( maxscale < 1.0F ) continue;
scale = ((float)maxscale - 1.0F) * rand() / RAND_MAX + 1.0F;
width = (int) (scale * winwidth);
height = (int) (scale * winheight);
x = (int) ((0.1+0.8 * rand()/RAND_MAX) * (cvbgreader->src.cols - width));
y = (int) ((0.1+0.8 * rand()/RAND_MAX) * (cvbgreader->src.rows - height));
if( invert == CV_RANDOM_INVERT )
{
inverse = (rand() > (RAND_MAX/2));
}
icvPlaceDistortedSample( cvbgreader->src(Rect(x, y, width, height)), inverse, maxintensitydev,
maxxangle, maxyangle, maxzangle,
1, 0.0, 0.0, &data );
sprintf( filename, "%04d_%04d_%04d_%04d_%04d.jpg",
(i + 1), x, y, width, height );
if( info )
{
fprintf( info, "%s %d %d %d %d %d\n",
filename, 1, x, y, width, height );
}
imwrite( fullname, cvbgreader->src );
if( showsamples )
{
imshow( "Image", cvbgreader->src );
if( (waitKey( 0 ) & 0xFF) == 27 )
{
showsamples = 0;
}
}
}
if( info ) fclose( info );
icvDestroyBackgroundReaders();
}
}
}
int cvCreateTrainingSamplesFromInfo( const char* infoname, const char* vecfilename,
int num,
int showsamples,
int winwidth, int winheight )
{
char fullname[PATH_MAX];
char* filename;
FILE* info;
FILE* vec;
int line;
int error;
int i;
int x, y, width, height;
int total;
CV_Assert( infoname != NULL );
CV_Assert( vecfilename != NULL );
total = 0;
if( !icvMkDir( vecfilename ) )
{
#if CV_VERBOSE
fprintf( stderr, "Unable to create directory hierarchy: %s\n", vecfilename );
#endif /* CV_VERBOSE */
return total;
}
info = fopen( infoname, "r" );
if( info == NULL )
{
#if CV_VERBOSE
fprintf( stderr, "Unable to open file: %s\n", infoname );
#endif /* CV_VERBOSE */
return total;
}
vec = fopen( vecfilename, "wb" );
if( vec == NULL )
{
#if CV_VERBOSE
fprintf( stderr, "Unable to open file: %s\n", vecfilename );
#endif /* CV_VERBOSE */
fclose( info );
return total;
}
icvWriteVecHeader( vec, num, winwidth, winheight );
if( showsamples )
{
namedWindow( "Sample", WINDOW_AUTOSIZE );
}
strcpy( fullname, infoname );
filename = strrchr( fullname, '\\' );
if( filename == NULL )
{
filename = strrchr( fullname, '/' );
}
if( filename == NULL )
{
filename = fullname;
}
else
{
filename++;
}
for( line = 1, error = 0, total = 0; total < num ;line++ )
{
Mat src;
int count;
if(fscanf(info, "%s %d", filename, &count) == 2)
{
src = imread( fullname, IMREAD_GRAYSCALE );
if(src.empty())
{
#if CV_VERBOSE
fprintf( stderr, "Unable to open image: %s\n", fullname );
#endif /* CV_VERBOSE */
}
}
for( i = 0; (i < count) && (total < num); i++, total++ )
{
error = ( fscanf( info, "%d %d %d %d", &x, &y, &width, &height ) != 4 );
if( error ) break;
Mat sample;
resize( src(Rect(x, y, width, height)), sample, Size(winwidth, winheight), 0, 0,
width >= winwidth && height >= winheight ? INTER_AREA : INTER_LINEAR_EXACT );
if( showsamples )
{
imshow( "Sample", sample );
if( (waitKey( 0 ) & 0xFF) == 27 )
{
showsamples = 0;
}
}
icvWriteVecSample( vec, sample );
}
if( error )
{
#if CV_VERBOSE
fprintf( stderr, "%s(%d) : parse error", infoname, line );
#endif /* CV_VERBOSE */
break;
}
}
fclose( vec );
fclose( info );
return total;
}
typedef struct CvVecFile
{
FILE* input;
int count;
int vecsize;
int last;
} CvVecFile;
static
int icvGetTraininDataFromVec( Mat& img, CvVecFile& userdata )
{
AutoBuffer<short> vector(userdata.vecsize);
uchar tmp = 0;
int r = 0;
int c = 0;
CV_Assert( img.rows * img.cols == userdata.vecsize );
size_t elements_read = fread( &tmp, sizeof( tmp ), 1, userdata.input );
CV_Assert(elements_read == 1);
elements_read = fread( vector, sizeof( short ), userdata.vecsize, userdata.input );
CV_Assert(elements_read == (size_t)userdata.vecsize);
if( feof( userdata.input ) || userdata.last++ >= userdata.count )
{
return 0;
}
for( r = 0; r < img.rows; r++ )
{
for( c = 0; c < img.cols; c++ )
{
img.at<uchar>(r, c) = (uchar) ( vector[r * img.cols + c] );
}
}
return 1;
}
void cvShowVecSamples( const char* filename, int winwidth, int winheight,
double scale )
{
CvVecFile file;
short tmp;
int i;
tmp = 0;
file.input = fopen( filename, "rb" );
if( file.input != NULL )
{
size_t elements_read1 = fread( &file.count, sizeof( file.count ), 1, file.input );
size_t elements_read2 = fread( &file.vecsize, sizeof( file.vecsize ), 1, file.input );
size_t elements_read3 = fread( &tmp, sizeof( tmp ), 1, file.input );
size_t elements_read4 = fread( &tmp, sizeof( tmp ), 1, file.input );
CV_Assert(elements_read1 == 1 && elements_read2 == 1 && elements_read3 == 1 && elements_read4 == 1);
if( file.vecsize != winwidth * winheight )
{
int guessed_w = 0;
int guessed_h = 0;
fprintf( stderr, "Warning: specified sample width=%d and height=%d "
"does not correspond to .vec file vector size=%d.\n",
winwidth, winheight, file.vecsize );
if( file.vecsize > 0 )
{
guessed_w = cvFloor( sqrt( (float) file.vecsize ) );
if( guessed_w > 0 )
{
guessed_h = file.vecsize / guessed_w;
}
}
if( guessed_w <= 0 || guessed_h <= 0 || guessed_w * guessed_h != file.vecsize)
{
fprintf( stderr, "Error: failed to guess sample width and height\n" );
fclose( file.input );
return;
}
else
{
winwidth = guessed_w;
winheight = guessed_h;
fprintf( stderr, "Guessed width=%d, guessed height=%d\n",
winwidth, winheight );
}
}
if( !feof( file.input ) && scale > 0 )
{
file.last = 0;
namedWindow( "Sample", WINDOW_AUTOSIZE );
for( i = 0; i < file.count; i++ )
{
Mat sample(winheight, winwidth, CV_8UC1);
icvGetTraininDataFromVec( sample, file );
if( scale != 1.0 )
resize( sample, sample,
Size(MAX(1, cvCeil(scale * winheight)), MAX(1, cvCeil(scale * winwidth))), 0, 0, INTER_LINEAR_EXACT);
imshow( "Sample", sample );
if( (waitKey( 0 ) & 0xFF) == 27 ) break;
}
}
fclose( file.input );
}
}
|
;
; Copyright (c) 2010 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.
;
EXPORT |vp8_bilinear_predict16x16_neon|
ARM
REQUIRE8
PRESERVE8
AREA ||.text||, CODE, READONLY, ALIGN=2
; r0 unsigned char *src_ptr,
; r1 int src_pixels_per_line,
; r2 int xoffset,
; r3 int yoffset,
; r4 unsigned char *dst_ptr,
; stack(r5) int dst_pitch
|vp8_bilinear_predict16x16_neon| PROC
push {r4-r5, lr}
ldr r12, _bifilter16_coeff_
ldr r4, [sp, #12] ;load parameters from stack
ldr r5, [sp, #16] ;load parameters from stack
cmp r2, #0 ;skip first_pass filter if xoffset=0
beq secondpass_bfilter16x16_only
add r2, r12, r2, lsl #3 ;calculate filter location
cmp r3, #0 ;skip second_pass filter if yoffset=0
vld1.s32 {d31}, [r2] ;load first_pass filter
beq firstpass_bfilter16x16_only
sub sp, sp, #272 ;reserve space on stack for temporary storage
vld1.u8 {d2, d3, d4}, [r0], r1 ;load src data
mov lr, sp
vld1.u8 {d5, d6, d7}, [r0], r1
mov r2, #3 ;loop counter
vld1.u8 {d8, d9, d10}, [r0], r1
vdup.8 d0, d31[0] ;first_pass filter (d0 d1)
vld1.u8 {d11, d12, d13}, [r0], r1
vdup.8 d1, d31[4]
;First Pass: output_height lines x output_width columns (17x16)
filt_blk2d_fp16x16_loop_neon
pld [r0]
pld [r0, r1]
pld [r0, r1, lsl #1]
vmull.u8 q7, d2, d0 ;(src_ptr[0] * vp8_filter[0])
vmull.u8 q8, d3, d0
vmull.u8 q9, d5, d0
vmull.u8 q10, d6, d0
vmull.u8 q11, d8, d0
vmull.u8 q12, d9, d0
vmull.u8 q13, d11, d0
vmull.u8 q14, d12, d0
vext.8 d2, d2, d3, #1 ;construct src_ptr[1]
vext.8 d5, d5, d6, #1
vext.8 d8, d8, d9, #1
vext.8 d11, d11, d12, #1
vmlal.u8 q7, d2, d1 ;(src_ptr[0] * vp8_filter[1])
vmlal.u8 q9, d5, d1
vmlal.u8 q11, d8, d1
vmlal.u8 q13, d11, d1
vext.8 d3, d3, d4, #1
vext.8 d6, d6, d7, #1
vext.8 d9, d9, d10, #1
vext.8 d12, d12, d13, #1
vmlal.u8 q8, d3, d1 ;(src_ptr[0] * vp8_filter[1])
vmlal.u8 q10, d6, d1
vmlal.u8 q12, d9, d1
vmlal.u8 q14, d12, d1
subs r2, r2, #1
vqrshrn.u16 d14, q7, #7 ;shift/round/saturate to u8
vqrshrn.u16 d15, q8, #7
vqrshrn.u16 d16, q9, #7
vqrshrn.u16 d17, q10, #7
vqrshrn.u16 d18, q11, #7
vqrshrn.u16 d19, q12, #7
vqrshrn.u16 d20, q13, #7
vld1.u8 {d2, d3, d4}, [r0], r1 ;load src data
vqrshrn.u16 d21, q14, #7
vld1.u8 {d5, d6, d7}, [r0], r1
vst1.u8 {d14, d15, d16, d17}, [lr]! ;store result
vld1.u8 {d8, d9, d10}, [r0], r1
vst1.u8 {d18, d19, d20, d21}, [lr]!
vld1.u8 {d11, d12, d13}, [r0], r1
bne filt_blk2d_fp16x16_loop_neon
;First-pass filtering for rest 5 lines
vld1.u8 {d14, d15, d16}, [r0], r1
vmull.u8 q9, d2, d0 ;(src_ptr[0] * vp8_filter[0])
vmull.u8 q10, d3, d0
vmull.u8 q11, d5, d0
vmull.u8 q12, d6, d0
vmull.u8 q13, d8, d0
vmull.u8 q14, d9, d0
vext.8 d2, d2, d3, #1 ;construct src_ptr[1]
vext.8 d5, d5, d6, #1
vext.8 d8, d8, d9, #1
vmlal.u8 q9, d2, d1 ;(src_ptr[0] * vp8_filter[1])
vmlal.u8 q11, d5, d1
vmlal.u8 q13, d8, d1
vext.8 d3, d3, d4, #1
vext.8 d6, d6, d7, #1
vext.8 d9, d9, d10, #1
vmlal.u8 q10, d3, d1 ;(src_ptr[0] * vp8_filter[1])
vmlal.u8 q12, d6, d1
vmlal.u8 q14, d9, d1
vmull.u8 q1, d11, d0
vmull.u8 q2, d12, d0
vmull.u8 q3, d14, d0
vmull.u8 q4, d15, d0
vext.8 d11, d11, d12, #1 ;construct src_ptr[1]
vext.8 d14, d14, d15, #1
vmlal.u8 q1, d11, d1 ;(src_ptr[0] * vp8_filter[1])
vmlal.u8 q3, d14, d1
vext.8 d12, d12, d13, #1
vext.8 d15, d15, d16, #1
vmlal.u8 q2, d12, d1 ;(src_ptr[0] * vp8_filter[1])
vmlal.u8 q4, d15, d1
vqrshrn.u16 d10, q9, #7 ;shift/round/saturate to u8
vqrshrn.u16 d11, q10, #7
vqrshrn.u16 d12, q11, #7
vqrshrn.u16 d13, q12, #7
vqrshrn.u16 d14, q13, #7
vqrshrn.u16 d15, q14, #7
vqrshrn.u16 d16, q1, #7
vqrshrn.u16 d17, q2, #7
vqrshrn.u16 d18, q3, #7
vqrshrn.u16 d19, q4, #7
vst1.u8 {d10, d11, d12, d13}, [lr]! ;store result
vst1.u8 {d14, d15, d16, d17}, [lr]!
vst1.u8 {d18, d19}, [lr]!
;Second pass: 16x16
;secondpass_filter
add r3, r12, r3, lsl #3
sub lr, lr, #272
vld1.u32 {d31}, [r3] ;load second_pass filter
vld1.u8 {d22, d23}, [lr]! ;load src data
vdup.8 d0, d31[0] ;second_pass filter parameters (d0 d1)
vdup.8 d1, d31[4]
mov r12, #4 ;loop counter
filt_blk2d_sp16x16_loop_neon
vld1.u8 {d24, d25}, [lr]!
vmull.u8 q1, d22, d0 ;(src_ptr[0] * vp8_filter[0])
vld1.u8 {d26, d27}, [lr]!
vmull.u8 q2, d23, d0
vld1.u8 {d28, d29}, [lr]!
vmull.u8 q3, d24, d0
vld1.u8 {d30, d31}, [lr]!
vmull.u8 q4, d25, d0
vmull.u8 q5, d26, d0
vmull.u8 q6, d27, d0
vmull.u8 q7, d28, d0
vmull.u8 q8, d29, d0
vmlal.u8 q1, d24, d1 ;(src_ptr[pixel_step] * vp8_filter[1])
vmlal.u8 q2, d25, d1
vmlal.u8 q3, d26, d1
vmlal.u8 q4, d27, d1
vmlal.u8 q5, d28, d1
vmlal.u8 q6, d29, d1
vmlal.u8 q7, d30, d1
vmlal.u8 q8, d31, d1
subs r12, r12, #1
vqrshrn.u16 d2, q1, #7 ;shift/round/saturate to u8
vqrshrn.u16 d3, q2, #7
vqrshrn.u16 d4, q3, #7
vqrshrn.u16 d5, q4, #7
vqrshrn.u16 d6, q5, #7
vqrshrn.u16 d7, q6, #7
vqrshrn.u16 d8, q7, #7
vqrshrn.u16 d9, q8, #7
vst1.u8 {d2, d3}, [r4], r5 ;store result
vst1.u8 {d4, d5}, [r4], r5
vst1.u8 {d6, d7}, [r4], r5
vmov q11, q15
vst1.u8 {d8, d9}, [r4], r5
bne filt_blk2d_sp16x16_loop_neon
add sp, sp, #272
pop {r4-r5,pc}
;--------------------
firstpass_bfilter16x16_only
mov r2, #4 ;loop counter
vdup.8 d0, d31[0] ;first_pass filter (d0 d1)
vdup.8 d1, d31[4]
;First Pass: output_height lines x output_width columns (16x16)
filt_blk2d_fpo16x16_loop_neon
vld1.u8 {d2, d3, d4}, [r0], r1 ;load src data
vld1.u8 {d5, d6, d7}, [r0], r1
vld1.u8 {d8, d9, d10}, [r0], r1
vld1.u8 {d11, d12, d13}, [r0], r1
pld [r0]
pld [r0, r1]
pld [r0, r1, lsl #1]
vmull.u8 q7, d2, d0 ;(src_ptr[0] * vp8_filter[0])
vmull.u8 q8, d3, d0
vmull.u8 q9, d5, d0
vmull.u8 q10, d6, d0
vmull.u8 q11, d8, d0
vmull.u8 q12, d9, d0
vmull.u8 q13, d11, d0
vmull.u8 q14, d12, d0
vext.8 d2, d2, d3, #1 ;construct src_ptr[1]
vext.8 d5, d5, d6, #1
vext.8 d8, d8, d9, #1
vext.8 d11, d11, d12, #1
vmlal.u8 q7, d2, d1 ;(src_ptr[0] * vp8_filter[1])
vmlal.u8 q9, d5, d1
vmlal.u8 q11, d8, d1
vmlal.u8 q13, d11, d1
vext.8 d3, d3, d4, #1
vext.8 d6, d6, d7, #1
vext.8 d9, d9, d10, #1
vext.8 d12, d12, d13, #1
vmlal.u8 q8, d3, d1 ;(src_ptr[0] * vp8_filter[1])
vmlal.u8 q10, d6, d1
vmlal.u8 q12, d9, d1
vmlal.u8 q14, d12, d1
subs r2, r2, #1
vqrshrn.u16 d14, q7, #7 ;shift/round/saturate to u8
vqrshrn.u16 d15, q8, #7
vqrshrn.u16 d16, q9, #7
vqrshrn.u16 d17, q10, #7
vqrshrn.u16 d18, q11, #7
vqrshrn.u16 d19, q12, #7
vqrshrn.u16 d20, q13, #7
vst1.u8 {d14, d15}, [r4], r5 ;store result
vqrshrn.u16 d21, q14, #7
vst1.u8 {d16, d17}, [r4], r5
vst1.u8 {d18, d19}, [r4], r5
vst1.u8 {d20, d21}, [r4], r5
bne filt_blk2d_fpo16x16_loop_neon
pop {r4-r5,pc}
;---------------------
secondpass_bfilter16x16_only
;Second pass: 16x16
;secondpass_filter
add r3, r12, r3, lsl #3
mov r12, #4 ;loop counter
vld1.u32 {d31}, [r3] ;load second_pass filter
vld1.u8 {d22, d23}, [r0], r1 ;load src data
vdup.8 d0, d31[0] ;second_pass filter parameters (d0 d1)
vdup.8 d1, d31[4]
filt_blk2d_spo16x16_loop_neon
vld1.u8 {d24, d25}, [r0], r1
vmull.u8 q1, d22, d0 ;(src_ptr[0] * vp8_filter[0])
vld1.u8 {d26, d27}, [r0], r1
vmull.u8 q2, d23, d0
vld1.u8 {d28, d29}, [r0], r1
vmull.u8 q3, d24, d0
vld1.u8 {d30, d31}, [r0], r1
vmull.u8 q4, d25, d0
vmull.u8 q5, d26, d0
vmull.u8 q6, d27, d0
vmull.u8 q7, d28, d0
vmull.u8 q8, d29, d0
vmlal.u8 q1, d24, d1 ;(src_ptr[pixel_step] * vp8_filter[1])
vmlal.u8 q2, d25, d1
vmlal.u8 q3, d26, d1
vmlal.u8 q4, d27, d1
vmlal.u8 q5, d28, d1
vmlal.u8 q6, d29, d1
vmlal.u8 q7, d30, d1
vmlal.u8 q8, d31, d1
vqrshrn.u16 d2, q1, #7 ;shift/round/saturate to u8
vqrshrn.u16 d3, q2, #7
vqrshrn.u16 d4, q3, #7
vqrshrn.u16 d5, q4, #7
vqrshrn.u16 d6, q5, #7
vqrshrn.u16 d7, q6, #7
vqrshrn.u16 d8, q7, #7
vqrshrn.u16 d9, q8, #7
vst1.u8 {d2, d3}, [r4], r5 ;store result
subs r12, r12, #1
vst1.u8 {d4, d5}, [r4], r5
vmov q11, q15
vst1.u8 {d6, d7}, [r4], r5
vst1.u8 {d8, d9}, [r4], r5
bne filt_blk2d_spo16x16_loop_neon
pop {r4-r5,pc}
ENDP
;-----------------
_bifilter16_coeff_
DCD bifilter16_coeff
bifilter16_coeff
DCD 128, 0, 112, 16, 96, 32, 80, 48, 64, 64, 48, 80, 32, 96, 16, 112
END
|
/*
* Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
*
* 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.
*
*/
#ifndef SOSS__DDS__INTERNAL__PUBLISHER_HPP
#define SOSS__DDS__INTERNAL__PUBLISHER_HPP
#include "DDSMiddlewareException.hpp"
#include "Participant.hpp"
#include "DynamicTypeAdapter.hpp"
#include <soss/Message.hpp>
#include <soss/SystemHandle.hpp>
#include <fastrtps/publisher/PublisherListener.h>
namespace soss {
namespace dds {
class Participant;
class Publisher : public virtual TopicPublisher, private eprosima::fastrtps::PublisherListener
{
public:
Publisher(
Participant* participant,
const std::string& topic_name,
const std::string& message_type);
virtual ~Publisher() override;
Publisher(
const Publisher& rhs) = delete;
Publisher& operator = (
const Publisher& rhs) = delete;
Publisher(
Publisher&& rhs) = delete;
Publisher& operator = (
Publisher&& rhs) = delete;
bool publish(
const soss::Message& message) override;
private:
void onPublicationMatched(
eprosima::fastrtps::Publisher* pub,
eprosima::fastrtps::rtps::MatchingInfo& info) override;
eprosima::fastrtps::Publisher* dds_publisher_;
DynamicData_ptr dynamic_data_;
const std::string topic_name_;
const std::string message_type_;
};
} //namespace dds
} //namespace soss
#endif // SOSS__DDS__INTERNAL__PUBLISHER_HPP
|
MANIA_OT_ID EQU 00518
GiveShuckle:
; Adding to the party.
xor a
ld [wMonType], a
; Level 15 Shuckle.
ld a, SHUCKLE
ld [wCurPartySpecies], a
ld a, 15
ld [wCurPartyLevel], a
predef TryAddMonToParty
jr nc, .NotGiven
; Caught data.
ld b, 0
farcall SetGiftPartyMonCaughtData
; Holding a Berry.
ld bc, PARTYMON_STRUCT_LENGTH
ld a, [wPartyCount]
dec a
push af
push bc
ld hl, wPartyMon1Item
call AddNTimes
ld [hl], BERRY
pop bc
pop af
; OT ID.
ld hl, wPartyMon1ID
call AddNTimes
ld a, HIGH(MANIA_OT_ID)
ld [hli], a
ld [hl], LOW(MANIA_OT_ID)
; Nickname.
ld a, [wPartyCount]
dec a
ld hl, wPartyMonNicknames
call SkipNames
ld de, SpecialShuckleNick
call CopyName2
; OT.
ld a, [wPartyCount]
dec a
ld hl, wPartyMonOT
call SkipNames
ld de, SpecialShuckleOT
call CopyName2
; Engine flag for this event.
ld hl, wDailyFlags1
set DAILYFLAGS1_GOT_SHUCKIE_TODAY_F, [hl]
ld a, 1
ld [wScriptVar], a
ret
.NotGiven:
xor a
ld [wScriptVar], a
ret
SpecialShuckleOT:
db "MANIA@"
SpecialShuckleNick:
db "SHUCKIE@"
ReturnShuckle:
farcall SelectMonFromParty
jr c, .refused
ld a, [wCurPartySpecies]
cp SHUCKLE
jr nz, .DontReturn
ld a, [wCurPartyMon]
ld hl, wPartyMon1ID
ld bc, PARTYMON_STRUCT_LENGTH
call AddNTimes
; OT ID
ld a, [hli]
cp HIGH(MANIA_OT_ID)
jr nz, .DontReturn
ld a, [hl]
cp LOW(MANIA_OT_ID)
jr nz, .DontReturn
; OT
ld a, [wCurPartyMon]
ld hl, wPartyMonOT
call SkipNames
ld de, SpecialShuckleOT
.CheckOT:
ld a, [de]
cp [hl]
jr nz, .DontReturn
cp "@"
jr z, .done
inc de
inc hl
jr .CheckOT
.done
farcall CheckCurPartyMonFainted
jr c, .fainted
ld a, [wCurPartyMon]
ld hl, wPartyMon1Happiness
ld bc, PARTYMON_STRUCT_LENGTH
call AddNTimes
ld a, [hl]
cp 150
ld a, SHUCKIE_HAPPY
jr nc, .HappyToStayWithYou
xor a ; REMOVE_PARTY
ld [wPokemonWithdrawDepositParameter], a
callfar RemoveMonFromPartyOrBox
ld a, SHUCKIE_RETURNED
.HappyToStayWithYou:
ld [wScriptVar], a
ret
.refused
ld a, SHUCKIE_REFUSED
ld [wScriptVar], a
ret
.DontReturn:
xor a ; SHUCKIE_WRONG_MON
ld [wScriptVar], a
ret
.fainted
ld a, SHUCKIE_FAINTED
ld [wScriptVar], a
ret
|
; A192802: Coefficient of x in the reduction of the polynomial (x+2)^n by x^3->x^2+x+1.
; Submitted by Christian Krause
; 0,1,4,13,42,143,514,1915,7268,27805,106680,409633,1573086,6040587,23193782,89051615,341901032,1312664601,5039704492,19348873781,74285859698,285204660583,1094982340202,4203950929347,16140172668812
mov $1,1
lpb $0
sub $0,1
mul $2,2
add $4,$3
add $3,$1
sub $4,$1
sub $1,$4
sub $1,$4
sub $2,5
add $4,5
add $2,$4
mov $4,$2
lpe
mov $0,$3
|
.global s_prepare_buffers
s_prepare_buffers:
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0xa170, %rsi
lea addresses_D_ht+0x7670, %rdi
clflush (%rdi)
nop
cmp %rbx, %rbx
mov $95, %rcx
rep movsb
nop
nop
nop
nop
sub $57436, %rax
lea addresses_normal_ht+0x79e8, %rsi
lea addresses_D_ht+0x1c770, %rdi
add %rbx, %rbx
mov $5, %rcx
rep movsq
nop
nop
add $35535, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r15
push %r8
push %rax
push %rbp
push %rcx
push %rdx
// Load
lea addresses_WC+0x1b0, %r15
nop
nop
nop
xor %rbp, %rbp
movb (%r15), %r11b
nop
add %rdx, %rdx
// Store
lea addresses_WC+0x1c1b0, %r11
nop
nop
nop
cmp $19528, %rdx
mov $0x5152535455565758, %r15
movq %r15, %xmm7
vmovups %ymm7, (%r11)
nop
cmp %r11, %r11
// Faulty Load
lea addresses_WC+0x5970, %r11
nop
nop
nop
cmp %rax, %rax
mov (%r11), %r15
lea oracles, %rbp
and $0xff, %r15
shlq $12, %r15
mov (%rbp,%r15,1), %r15
pop %rdx
pop %rcx
pop %rbp
pop %rax
pop %r8
pop %r15
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 6}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 6}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 3, 'type': 'addresses_normal_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_D_ht'}}
{'38': 21829}
38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38
*/
|
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef CPU_S390_C2_MACROASSEMBLER_S390_HPP
#define CPU_S390_C2_MACROASSEMBLER_S390_HPP
// C2_MacroAssembler contains high-level macros for C2
public:
//-------------------------------------------
// Special String Intrinsics Implementation.
//-------------------------------------------
// Intrinsics for CompactStrings
// Restores: src, dst
// Uses: cnt
// Kills: tmp, Z_R0, Z_R1.
// Early clobber: result.
// Boolean precise controls accuracy of result value.
unsigned int string_compress(Register result, Register src, Register dst, Register cnt,
Register tmp, bool precise);
// Inflate byte[] to char[].
unsigned int string_inflate_trot(Register src, Register dst, Register cnt, Register tmp);
// Inflate byte[] to char[].
// Restores: src, dst
// Uses: cnt
// Kills: tmp, Z_R0, Z_R1.
unsigned int string_inflate(Register src, Register dst, Register cnt, Register tmp);
// Inflate byte[] to char[], length known at compile time.
// Restores: src, dst
// Kills: tmp, Z_R0, Z_R1.
// Note:
// len is signed int. Counts # characters, not bytes.
unsigned int string_inflate_const(Register src, Register dst, Register tmp, int len);
// Kills src.
unsigned int has_negatives(Register result, Register src, Register cnt,
Register odd_reg, Register even_reg, Register tmp);
unsigned int string_compare(Register str1, Register str2, Register cnt1, Register cnt2,
Register odd_reg, Register even_reg, Register result, int ae);
unsigned int array_equals(bool is_array_equ, Register ary1, Register ary2, Register limit,
Register odd_reg, Register even_reg, Register result, bool is_byte);
unsigned int string_indexof(Register result, Register haystack, Register haycnt,
Register needle, Register needlecnt, int needlecntval,
Register odd_reg, Register even_reg, int ae);
unsigned int string_indexof_char(Register result, Register haystack, Register haycnt,
Register needle, jchar needleChar, Register odd_reg, Register even_reg, bool is_byte);
#endif // CPU_S390_C2_MACROASSEMBLER_S390_HPP
|
; A160550: a(n) = A001065(n) mod A000005(n).
; Submitted by Christian Krause
; 0,1,1,0,1,2,1,3,1,0,1,4,1,2,1,0,1,3,1,4,3,2,1,4,0,0,1,4,1,2,1,1,3,0,1,1,1,2,1,2,1,6,1,4,3,2,1,6,2,1,1,4,1,2,1,0,3,0,1,0,1,2,5,0,3,6,1,4,3,2,1,3,1,0,1,4,3,2,1,6,0,0,1,8,3,2,1,4,1,0,1,4,3,2,1,0,1,1,3,0
add $0,1
mov $1,1
mov $2,$0
mov $4,1
lpb $0
mov $3,$2
dif $3,$0
cmp $3,$2
sub $1,$3
cmp $3,0
add $4,$3
mul $3,$0
sub $0,1
add $1,$3
lpe
add $1,1
mod $1,$4
mov $0,$1
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/certificate_provider/certificate_info.h"
#include "net/cert/x509_certificate.h"
namespace ash {
namespace certificate_provider {
CertificateInfo::CertificateInfo() {}
CertificateInfo::CertificateInfo(const CertificateInfo& other) = default;
CertificateInfo::~CertificateInfo() {}
bool CertificateInfo::operator==(const CertificateInfo& other) const {
return net::X509Certificate::CalculateFingerprint256(
this->certificate->cert_buffer()) ==
net::X509Certificate::CalculateFingerprint256(
other.certificate->cert_buffer()) &&
this->supported_algorithms == other.supported_algorithms;
}
} // namespace certificate_provider
} // namespace ash
|
; A118265: Coefficient of q^n in (1-q)^4/(1-4q); dimensions of the enveloping algebra of the derived free Lie algebra on 4 letters.
; 1,0,6,20,81,324,1296,5184,20736,82944,331776,1327104,5308416,21233664,84934656,339738624,1358954496,5435817984,21743271936,86973087744,347892350976,1391569403904,5566277615616,22265110462464,89060441849856
mov $3,2
mov $5,$0
lpb $3
mov $0,$5
sub $3,1
add $0,$3
trn $0,1
seq $0,56120 ; a(n) = (3^3)*4^(n-3) with a(0)=1, a(1)=1 and a(2)=7.
mov $2,$3
mul $2,$0
add $4,$2
lpe
min $5,1
mul $5,$0
mov $0,$4
sub $0,$5
|
; A048755: Partial sums of A048693.
; 1,7,20,52,129,315,764,1848,4465,10783,26036,62860,151761,366387,884540,2135472,5155489,12446455,30048404,72543268,175134945,422813163,1020761276,2464335720,5949432721,14363201167,34675835060,83714871292,202105577649,487926026595
mov $1,1
mov $3,1
lpb $0,1
sub $0,1
add $3,3
add $2,$3
add $2,2
add $2,$1
mov $3,$1
mov $1,$2
lpe
|
/*
* Copyright (c) 2017, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
L0:
mov (1|M0) r22.5<1>:ud 0x1200120:ud
mov (1|M0) f0.0<1>:uw r24.0<0;1,0>:ub
(W&~f0.0)jmpi L624
L48:
mov (8|M0) r17.0<1>:ud r26.0<8;8,1>:ud
cmp (1|M0) (eq)f1.0 null.0<1>:w r24.2<0;1,0>:ub 0x1:uw
mov (1|M0) r16.2<1>:ud 0xE000:ud
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x43EA100:ud
(~f1.0) mov (1|M0) r17.2<1>:f r9.0<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.4<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.2<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.4<0;1,0>:f
send (1|M0) r46:uw r16:ub 0x2 a0.0
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x43EA102:ud
send (1|M0) r48:uw r16:ub 0x2 a0.0
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x43EA100:ud
(~f1.0) mov (1|M0) r17.2<1>:f r9.0<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.7<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.2<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.7<0;1,0>:f
send (1|M0) r55:uw r16:ub 0x2 a0.0
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x43EA102:ud
send (1|M0) r57:uw r16:ub 0x2 a0.0
add (1|M0) a0.0<1>:ud r24.5<0;1,0>:ud 0x44EC201:ud
mov (1|M0) r16.2<1>:ud 0xC000:ud
(~f1.0) mov (1|M0) r17.2<1>:f r9.0<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.4<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.2<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.4<0;1,0>:f
send (1|M0) r50:uw r16:ub 0x2 a0.0
(~f1.0) mov (1|M0) r17.2<1>:f r9.0<0;1,0>:f
(~f1.0) mov (1|M0) r17.3<1>:f r9.7<0;1,0>:f
(f1.0) mov (1|M0) r17.2<1>:f r9.2<0;1,0>:f
(f1.0) mov (1|M0) r17.3<1>:f r9.7<0;1,0>:f
send (1|M0) r59:uw r16:ub 0x2 a0.0
mov (1|M0) a0.8<1>:uw 0x5C0:uw
mov (1|M0) a0.11<1>:uw 0x600:uw
mov (1|M0) a0.9<1>:uw 0x640:uw
mov (1|M0) a0.10<1>:uw 0x680:uw
add (4|M0) a0.12<1>:uw a0.8<4;4,1>:uw 0x120:uw
L624:
nop
|
//===--- SwiftASTManager.cpp ----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SwiftASTManager.h"
#include "SwiftEditorDiagConsumer.h"
#include "SwiftInvocation.h"
#include "SwiftLangSupport.h"
#include "SourceKit/Core/Context.h"
#include "SourceKit/Support/Concurrency.h"
#include "SourceKit/Support/ImmutableTextBuffer.h"
#include "SourceKit/Support/Logging.h"
#include "SourceKit/Support/Tracing.h"
#include "swift/Basic/Cache.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/Strings.h"
#include "swift/Subsystems.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
// This is included only for createLazyResolver(). Move to different header ?
#include "swift/Sema/CodeCompletionTypeChecking.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace SourceKit;
using namespace swift;
using namespace swift::sys;
namespace {
class StreamDiagConsumer : public DiagnosticConsumer {
llvm::raw_ostream &OS;
public:
StreamDiagConsumer(llvm::raw_ostream &OS) : OS(OS) {}
void handleDiagnostic(SourceManager &SM, SourceLoc Loc,
DiagnosticKind Kind, StringRef Text,
const DiagnosticInfo &Info) override {
// FIXME: Print location info if available.
switch (Kind) {
case DiagnosticKind::Error: OS << "error: "; break;
case DiagnosticKind::Warning: OS << "warning: "; break;
case DiagnosticKind::Note: OS << "note: "; break;
}
OS << Text;
}
};
} // anonymous namespace.
void SwiftASTConsumer::failed(StringRef Error) { }
//============================================================================//
// SwiftInvocation
//============================================================================//
namespace {
struct InvocationOptions {
const std::vector<std::string> Args;
const std::string PrimaryFile;
const CompilerInvocation Invok;
InvocationOptions(ArrayRef<const char *> CArgs, StringRef PrimaryFile,
CompilerInvocation Invok)
: Args(_convertArgs(CArgs)),
PrimaryFile(PrimaryFile),
Invok(std::move(Invok)) {
// Assert invocation with a primary file. We want to avoid full typechecking
// for all files.
assert(!this->PrimaryFile.empty());
assert(this->Invok.getFrontendOptions().PrimaryInput.hasValue());
}
void applyTo(CompilerInvocation &CompInvok) const;
void profile(llvm::FoldingSetNodeID &ID) const;
void raw(std::vector<std::string> &Args, std::string &PrimaryFile) const;
private:
static std::vector<std::string> _convertArgs(ArrayRef<const char *> CArgs) {
std::vector<std::string> Args;
Args.reserve(CArgs.size());
for (auto Arg : CArgs)
Args.push_back(Arg);
return Args;
}
};
struct ASTKey {
llvm::FoldingSetNodeID FSID;
};
} // anonymous namespace.
struct SwiftInvocation::Implementation {
InvocationOptions Opts;
ASTKey Key;
explicit Implementation(InvocationOptions opts) : Opts(std::move(opts)) {
Opts.profile(Key.FSID);
}
};
SwiftInvocation::~SwiftInvocation() {
delete &Impl;
}
void SwiftInvocation::applyTo(swift::CompilerInvocation &CompInvok) const {
return Impl.Opts.applyTo(CompInvok);
}
void SwiftInvocation::raw(std::vector<std::string> &Args,
std::string &PrimaryFile) const {
return Impl.Opts.raw(Args, PrimaryFile);
}
void InvocationOptions::applyTo(CompilerInvocation &CompInvok) const {
CompInvok = this->Invok;
}
void InvocationOptions::raw(std::vector<std::string> &Args,
std::string &PrimaryFile) const {
Args.assign(this->Args.begin(), this->Args.end());
PrimaryFile = this->PrimaryFile;
}
void InvocationOptions::profile(llvm::FoldingSetNodeID &ID) const {
// FIXME: This ties ASTs to every argument and the exact order that they were
// provided, preventing much sharing of ASTs.
// Note though that previously we tried targeting specific options considered
// semantically relevant but it proved too fragile (very easy to miss some new
// compiler invocation option).
// Possibly have all compiler invocation options auto-generated from a
// tablegen definition file, thus forcing a decision for each option if it is
// ok to share ASTs with the option differing.
for (auto &Arg : Args)
ID.AddString(Arg);
ID.AddString(PrimaryFile);
}
//============================================================================//
// SwiftASTManager
//============================================================================//
namespace SourceKit {
struct ASTUnit::Implementation {
const uint64_t Generation;
SmallVector<ImmutableTextSnapshotRef, 4> Snapshots;
EditorDiagConsumer CollectDiagConsumer;
CompilerInstance CompInst;
OwnedResolver TypeResolver{ nullptr, nullptr };
WorkQueue Queue{ WorkQueue::Dequeuing::Serial, "sourcekit.swift.ConsumeAST" };
Implementation(uint64_t Generation) : Generation(Generation) {}
void consumeAsync(SwiftASTConsumerRef ASTConsumer, ASTUnitRef ASTRef);
};
void ASTUnit::Implementation::consumeAsync(SwiftASTConsumerRef ConsumerRef,
ASTUnitRef ASTRef) {
Queue.dispatch([ASTRef, ConsumerRef]{
SwiftASTConsumer &ASTConsumer = *ConsumerRef;
CompilerInstance &CI = ASTRef->getCompilerInstance();
if (CI.getPrimarySourceFile()) {
ASTConsumer.handlePrimaryAST(ASTRef);
} else {
LOG_WARN_FUNC("did not find primary SourceFile");
ConsumerRef->failed("did not find primary SourceFile");
}
});
}
ASTUnit::ASTUnit(uint64_t Generation) : Impl(*new Implementation(Generation)) {
}
ASTUnit::~ASTUnit() {
delete &Impl;
}
swift::CompilerInstance &ASTUnit::getCompilerInstance() const {
return Impl.CompInst;
}
uint64_t ASTUnit::getGeneration() const {
return Impl.Generation;
}
ArrayRef<ImmutableTextSnapshotRef> ASTUnit::getSnapshots() const {
return Impl.Snapshots;
}
SourceFile &ASTUnit::getPrimarySourceFile() const {
return *Impl.CompInst.getPrimarySourceFile();
}
EditorDiagConsumer &ASTUnit::getEditorDiagConsumer() const {
return Impl.CollectDiagConsumer;
}
}
namespace {
typedef uint64_t BufferStamp;
struct FileContent {
ImmutableTextSnapshotRef Snapshot;
std::unique_ptr<llvm::MemoryBuffer> Buffer;
BufferStamp Stamp;
FileContent(ImmutableTextSnapshotRef Snapshot,
std::unique_ptr<llvm::MemoryBuffer> Buffer,
BufferStamp Stamp)
: Snapshot(std::move(Snapshot)),
Buffer(std::move(Buffer)),
Stamp(Stamp) {}
};
class ASTProducer : public ThreadSafeRefCountedBase<ASTProducer> {
SwiftInvocationRef InvokRef;
SmallVector<BufferStamp, 8> Stamps;
ThreadSafeRefCntPtr<ASTUnit> AST;
SmallVector<std::pair<std::string, BufferStamp>, 8> DependencyStamps;
std::vector<std::pair<SwiftASTConsumerRef, const void*>> QueuedConsumers;
llvm::sys::Mutex Mtx;
public:
explicit ASTProducer(SwiftInvocationRef InvokRef)
: InvokRef(std::move(InvokRef)) {}
ASTUnitRef getExistingAST() {
// FIXME: ThreadSafeRefCntPtr is racy.
llvm::sys::ScopedLock L(Mtx);
return AST;
}
void getASTUnitAsync(SwiftASTManager::Implementation &MgrImpl,
ArrayRef<ImmutableTextSnapshotRef> Snapshots,
std::function<void(ASTUnitRef Unit, StringRef Error)> Receiver);
bool shouldRebuild(SwiftASTManager::Implementation &MgrImpl,
ArrayRef<ImmutableTextSnapshotRef> Snapshots);
void enqueueConsumer(SwiftASTConsumerRef Consumer, const void *OncePerASTToken);
std::vector<SwiftASTConsumerRef> popQueuedConsumers();
size_t getMemoryCost() const {
// FIXME: Report the memory cost of the overall CompilerInstance.
if (AST && AST->getCompilerInstance().hasASTContext())
return AST->Impl.CompInst.getASTContext().getTotalMemory();
return sizeof(*this) + sizeof(*AST);
}
private:
ASTUnitRef getASTUnitImpl(SwiftASTManager::Implementation &MgrImpl,
ArrayRef<ImmutableTextSnapshotRef> Snapshots,
std::string &Error);
ASTUnitRef createASTUnit(SwiftASTManager::Implementation &MgrImpl,
ArrayRef<ImmutableTextSnapshotRef> Snapshots,
std::string &Error);
};
typedef IntrusiveRefCntPtr<ASTProducer> ASTProducerRef;
} // anonymous namespace.
namespace swift {
namespace sys {
template <>
struct CacheValueCostInfo<ASTProducer> {
static size_t getCost(const ASTProducer &Unit) {
return Unit.getMemoryCost();
}
};
template <>
struct CacheKeyHashInfo<ASTKey> {
static uintptr_t getHashValue(const ASTKey &Key) {
return Key.FSID.ComputeHash();
}
static bool isEqual(void *LHS, void *RHS) {
return static_cast<ASTKey*>(LHS)->FSID == static_cast<ASTKey*>(RHS)->FSID;
}
};
} // namespace sys
} // namespace swift.
struct SwiftASTManager::Implementation {
explicit Implementation(SwiftLangSupport &LangSupport)
: EditorDocs(LangSupport.getEditorDocuments()),
RuntimeResourcePath(LangSupport.getRuntimeResourcePath()) { }
SwiftEditorDocumentFileMap &EditorDocs;
std::string RuntimeResourcePath;
SourceManager SourceMgr;
Cache<ASTKey, ASTProducerRef> ASTCache{ "sourcekit.swift.ASTCache" };
llvm::sys::Mutex CacheMtx;
WorkQueue ASTBuildQueue{ WorkQueue::Dequeuing::Serial,
"sourcekit.swift.ASTBuilding" };
ASTProducerRef getASTProducer(SwiftInvocationRef InvokRef);
FileContent getFileContent(StringRef FilePath, std::string &Error);
BufferStamp getBufferStamp(StringRef FilePath);
std::unique_ptr<llvm::MemoryBuffer> getMemoryBuffer(StringRef Filename,
std::string &Error);
};
SwiftASTManager::SwiftASTManager(SwiftLangSupport &LangSupport)
: Impl(*new Implementation(LangSupport)) {
}
SwiftASTManager::~SwiftASTManager() {
delete &Impl;
}
std::unique_ptr<llvm::MemoryBuffer>
SwiftASTManager::getMemoryBuffer(StringRef Filename, std::string &Error) {
return Impl.getMemoryBuffer(Filename, Error);
}
static void setModuleName(CompilerInvocation &Invocation) {
if (!Invocation.getModuleName().empty())
return;
StringRef Filename = Invocation.getOutputFilename();
if (Filename.empty()) {
if (Invocation.getInputFilenames().empty()) {
Invocation.setModuleName("__main__");
return;
}
Filename = Invocation.getInputFilenames()[0];
}
Filename = llvm::sys::path::filename(Filename);
StringRef ModuleName = llvm::sys::path::stem(Filename);
if (ModuleName.empty() || !Lexer::isIdentifier(ModuleName)) {
Invocation.setModuleName("__main__");
return;
}
Invocation.setModuleName(ModuleName);
}
static void sanitizeCompilerArgs(ArrayRef<const char *> Args,
SmallVectorImpl<const char *> &NewArgs) {
for (const char *CArg : Args) {
StringRef Arg = CArg;
if (Arg.startswith("-j"))
continue;
if (Arg == "-c")
continue;
if (Arg == "-Xfrontend")
continue;
if (Arg == "-embed-bitcode")
continue;
NewArgs.push_back(CArg);
}
}
bool SwiftASTManager::initCompilerInvocation(CompilerInvocation &Invocation,
ArrayRef<const char *> OrigArgs,
DiagnosticEngine &Diags,
StringRef UnresolvedPrimaryFile,
std::string &Error) {
SmallVector<const char *, 16> Args;
sanitizeCompilerArgs(OrigArgs, Args);
Invocation.setRuntimeResourcePath(Impl.RuntimeResourcePath);
bool Err = Invocation.parseArgs(Args, Diags);
if (Err) {
// FIXME: Get the actual diagnostic.
Error = "error when parsing the compiler arguments";
return Err;
}
// FIXME: The frontend should be dealing with symlinks, maybe similar to
// clang's FileManager ?
std::string PrimaryFile =
SwiftLangSupport::resolvePathSymlinks(UnresolvedPrimaryFile);
for (auto &InputFile : Invocation.getFrontendOptions().InputFilenames) {
InputFile = SwiftLangSupport::resolvePathSymlinks(InputFile);
}
ClangImporterOptions &ImporterOpts = Invocation.getClangImporterOptions();
ImporterOpts.DetailedPreprocessingRecord = true;
setModuleName(Invocation);
Invocation.setSerializedDiagnosticsPath(StringRef());
Invocation.getLangOptions().AttachCommentsToDecls = true;
auto &FrontendOpts = Invocation.getFrontendOptions();
if (FrontendOpts.PlaygroundTransform) {
// The playground instrumenter changes the AST in ways that disrupt the
// SourceKit functionality. Since we don't need the instrumenter, and all we
// actually need is the playground semantics visible to the user, like
// silencing the "expression resolves to an unused l-value" error, disable it.
FrontendOpts.PlaygroundTransform = false;
}
if (!PrimaryFile.empty()) {
Optional<unsigned> PrimaryIndex;
for (auto i : indices(Invocation.getFrontendOptions().InputFilenames)) {
auto &CurFile = Invocation.getFrontendOptions().InputFilenames[i];
if (PrimaryFile == CurFile) {
PrimaryIndex = i;
break;
}
}
if (!PrimaryIndex) {
llvm::SmallString<64> Err;
llvm::raw_svector_ostream OS(Err);
OS << "'" << PrimaryFile << "' is not part of the input files";
Error = OS.str();
return true;
}
Invocation.getFrontendOptions().PrimaryInput = SelectedInput(*PrimaryIndex);
}
return Err;
}
bool SwiftASTManager::initCompilerInvocation(CompilerInvocation &CompInvok,
ArrayRef<const char *> OrigArgs,
StringRef PrimaryFile,
std::string &Error) {
SmallString<32> ErrStr;
llvm::raw_svector_ostream ErrOS(ErrStr);
DiagnosticEngine Diagnostics(Impl.SourceMgr);
StreamDiagConsumer DiagConsumer(ErrOS);
Diagnostics.addConsumer(DiagConsumer);
if (initCompilerInvocation(CompInvok, OrigArgs, Diagnostics, PrimaryFile,
Error)) {
if (!ErrOS.str().empty())
Error = ErrOS.str();
return true;
}
return false;
}
SwiftInvocationRef
SwiftASTManager::getInvocation(ArrayRef<const char *> OrigArgs,
StringRef PrimaryFile,
std::string &Error) {
CompilerInvocation CompInvok;
if (initCompilerInvocation(CompInvok, OrigArgs, PrimaryFile, Error)) {
return nullptr;
}
InvocationOptions Opts(OrigArgs, PrimaryFile, CompInvok);
return new SwiftInvocation(
*new SwiftInvocation::Implementation(std::move(Opts)));
}
void SwiftASTManager::processASTAsync(SwiftInvocationRef InvokRef,
SwiftASTConsumerRef ASTConsumer,
const void *OncePerASTToken,
ArrayRef<ImmutableTextSnapshotRef> Snapshots) {
ASTProducerRef Producer = Impl.getASTProducer(InvokRef);
if (ASTUnitRef Unit = Producer->getExistingAST()) {
if (ASTConsumer->canUseASTWithSnapshots(Unit->getSnapshots())) {
Unit->Impl.consumeAsync(std::move(ASTConsumer), Unit);
return;
}
}
Producer->enqueueConsumer(std::move(ASTConsumer), OncePerASTToken);
Producer->getASTUnitAsync(Impl, Snapshots,
[Producer](ASTUnitRef Unit, StringRef Error) {
auto Consumers = Producer->popQueuedConsumers();
for (auto &Consumer : Consumers) {
if (Unit)
Unit->Impl.consumeAsync(std::move(Consumer), Unit);
else
Consumer->failed(Error);
}
});
}
void SwiftASTManager::removeCachedAST(SwiftInvocationRef Invok) {
Impl.ASTCache.remove(Invok->Impl.Key);
}
ASTProducerRef
SwiftASTManager::Implementation::getASTProducer(SwiftInvocationRef InvokRef) {
llvm::sys::ScopedLock L(CacheMtx);
llvm::Optional<ASTProducerRef> OptProducer = ASTCache.get(InvokRef->Impl.Key);
if (OptProducer.hasValue())
return OptProducer.getValue();
ASTProducerRef Producer = new ASTProducer(InvokRef);
ASTCache.set(InvokRef->Impl.Key, Producer);
return Producer;
}
static FileContent getFileContentFromSnap(ImmutableTextSnapshotRef Snap,
StringRef FilePath) {
auto Buf = llvm::MemoryBuffer::getMemBufferCopy(
Snap->getBuffer()->getText(), FilePath);
return FileContent(Snap, std::move(Buf), Snap->getStamp());
}
FileContent
SwiftASTManager::Implementation::getFileContent(StringRef UnresolvedPath,
std::string &Error) {
std::string FilePath = SwiftLangSupport::resolvePathSymlinks(UnresolvedPath);
if (auto EditorDoc = EditorDocs.findByPath(FilePath))
return getFileContentFromSnap(EditorDoc->getLatestSnapshot(), FilePath);
// FIXME: Is there a way to get timestamp and buffer for a file atomically ?
auto Stamp = getBufferStamp(FilePath);
auto Buffer = getMemoryBuffer(FilePath, Error);
return FileContent(nullptr, std::move(Buffer), Stamp);
}
BufferStamp SwiftASTManager::Implementation::getBufferStamp(StringRef FilePath){
if (auto EditorDoc = EditorDocs.findByPath(FilePath))
return EditorDoc->getLatestSnapshot()->getStamp();
llvm::sys::fs::file_status Status;
if (std::error_code Ret = llvm::sys::fs::status(FilePath, Status)) {
// Failure to read the file.
LOG_WARN_FUNC("failed to stat file: " << FilePath
<< " (" << Ret.message() << ')');
return -1;
}
return Status.getLastModificationTime().toEpochTime();
}
std::unique_ptr<llvm::MemoryBuffer>
SwiftASTManager::Implementation::getMemoryBuffer(StringRef Filename,
std::string &Error) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFile(Filename);
if (FileBufOrErr)
return std::move(FileBufOrErr.get());
llvm::raw_string_ostream OSErr(Error);
OSErr << "error opening input file '" << Filename << "' ("
<< FileBufOrErr.getError().message() << ')';
return nullptr;
}
void ASTProducer::getASTUnitAsync(SwiftASTManager::Implementation &MgrImpl,
ArrayRef<ImmutableTextSnapshotRef> Snaps,
std::function<void(ASTUnitRef Unit, StringRef Error)> Receiver) {
ASTProducerRef ThisProducer = this;
SmallVector<ImmutableTextSnapshotRef, 4> Snapshots;
Snapshots.append(Snaps.begin(), Snaps.end());
MgrImpl.ASTBuildQueue.dispatch([ThisProducer, &MgrImpl, Snapshots, Receiver] {
std::string Error;
ASTUnitRef Unit = ThisProducer->getASTUnitImpl(MgrImpl, Snapshots, Error);
Receiver(Unit, Error);
}, /*isStackDeep=*/true);
}
ASTUnitRef ASTProducer::getASTUnitImpl(SwiftASTManager::Implementation &MgrImpl,
ArrayRef<ImmutableTextSnapshotRef> Snapshots,
std::string &Error) {
if (!AST || shouldRebuild(MgrImpl, Snapshots)) {
bool IsRebuild = AST != nullptr;
const InvocationOptions &Opts = InvokRef->Impl.Opts;
LOG_FUNC_SECTION(InfoHighPrio) {
Log->getOS() << "AST build (";
if (IsRebuild)
Log->getOS() << "rebuild";
else
Log->getOS() << "first";
Log->getOS() << "): ";
Log->getOS() << Opts.Invok.getModuleName() << '/' << Opts.PrimaryFile;
}
auto NewAST = createASTUnit(MgrImpl, Snapshots, Error);
{
// FIXME: ThreadSafeRefCntPtr is racy.
llvm::sys::ScopedLock L(Mtx);
AST = NewAST;
}
{
llvm::sys::ScopedLock L(MgrImpl.CacheMtx);
// Re-register the object with the cache to update its memory cost.
ASTProducerRef ThisProducer = this;
MgrImpl.ASTCache.set(InvokRef->Impl.Key, ThisProducer);
}
}
return AST;
}
void ASTProducer::enqueueConsumer(SwiftASTConsumerRef Consumer,
const void *OncePerASTToken) {
llvm::sys::ScopedLock L(Mtx);
if (OncePerASTToken) {
for (auto I = QueuedConsumers.begin(),
E = QueuedConsumers.end(); I != E; ++I) {
if (I->second == OncePerASTToken) {
I->first->cancelled();
QueuedConsumers.erase(I);
break;
}
}
}
QueuedConsumers.push_back({ std::move(Consumer), OncePerASTToken });
}
std::vector<SwiftASTConsumerRef> ASTProducer::popQueuedConsumers() {
llvm::sys::ScopedLock L(Mtx);
std::vector<SwiftASTConsumerRef> Consumers;
Consumers.reserve(QueuedConsumers.size());
for (auto &C : QueuedConsumers)
Consumers.push_back(std::move(C.first));
QueuedConsumers.clear();
return Consumers;
}
bool ASTProducer::shouldRebuild(SwiftASTManager::Implementation &MgrImpl,
ArrayRef<ImmutableTextSnapshotRef> Snapshots) {
const SwiftInvocation::Implementation &Invok = InvokRef->Impl;
// Check if the inputs changed.
SmallVector<BufferStamp, 8> InputStamps;
InputStamps.reserve(Invok.Opts.Invok.getInputFilenames().size());
for (auto &File : Invok.Opts.Invok.getInputFilenames()) {
bool FoundSnapshot = false;
for (auto &Snap : Snapshots) {
if (Snap->getFilename() == File) {
FoundSnapshot = true;
InputStamps.push_back(Snap->getStamp());
break;
}
}
if (!FoundSnapshot)
InputStamps.push_back(MgrImpl.getBufferStamp(File));
}
assert(InputStamps.size() == Invok.Opts.Invok.getInputFilenames().size());
if (Stamps != InputStamps)
return true;
for (auto &Dependency : DependencyStamps) {
if (Dependency.second != MgrImpl.getBufferStamp(Dependency.first))
return true;
}
return false;
}
static void collectModuleDependencies(Module *TopMod,
llvm::SmallPtrSetImpl<Module *> &Visited,
SmallVectorImpl<std::string> &Filenames) {
if (!TopMod)
return;
auto ClangModuleLoader = TopMod->getASTContext().getClangModuleLoader();
SmallVector<Module::ImportedModule, 8> Imports;
TopMod->getImportedModules(Imports, Module::ImportFilter::All);
for (auto Import : Imports) {
Module *Mod = Import.second;
if (Mod->isSystemModule())
continue;
// FIXME: Setup dependecies on the included headers.
if (ClangModuleLoader &&
Mod == ClangModuleLoader->getImportedHeaderModule())
continue;
bool NewVisit = Visited.insert(Mod).second;
if (!NewVisit)
continue;
// FIXME: Handle modules with multiple source files; these will fail on
// getModuleFilename() (by returning an empty path). Note that such modules
// may be heterogeneous.
{
std::string Path = Mod->getModuleFilename();
if (Path.empty() || Path == TopMod->getModuleFilename())
continue; // this is a submodule.
Filenames.push_back(std::move(Path));
}
bool IsClangModule = false;
for (auto File : Mod->getFiles()) {
if (File->getKind() == FileUnitKind::ClangModule) {
IsClangModule = true;
break;
}
}
if (IsClangModule) {
// No need to keep track of the clang module dependencies.
continue;
}
collectModuleDependencies(Mod, Visited, Filenames);
}
}
static std::atomic<uint64_t> ASTUnitGeneration{ 0 };
ASTUnitRef ASTProducer::createASTUnit(SwiftASTManager::Implementation &MgrImpl,
ArrayRef<ImmutableTextSnapshotRef> Snapshots,
std::string &Error) {
Stamps.clear();
DependencyStamps.clear();
const InvocationOptions &Opts = InvokRef->Impl.Opts;
SmallVector<FileContent, 8> Contents;
for (auto &File : Opts.Invok.getInputFilenames()) {
bool FoundSnapshot = false;
for (auto &Snap : Snapshots) {
if (Snap->getFilename() == File) {
FoundSnapshot = true;
Contents.push_back(getFileContentFromSnap(Snap, File));
break;
}
}
if (FoundSnapshot)
continue;
auto Content = MgrImpl.getFileContent(File, Error);
if (!Content.Buffer) {
LOG_WARN_FUNC("failed getting file contents for " << File << ": " << Error);
// File may not exist, continue and recover as if it was empty.
Content.Buffer = llvm::MemoryBuffer::getNewMemBuffer(0, File);
}
Contents.push_back(std::move(Content));
}
assert(Contents.size() == Opts.Invok.getInputFilenames().size());
for (auto &Content : Contents)
Stamps.push_back(Content.Stamp);
trace::SwiftInvocation TraceInfo;
if (trace::enabled()) {
TraceInfo.Args.PrimaryFile = Opts.PrimaryFile;
TraceInfo.Args.Args = Opts.Args;
}
ASTUnitRef ASTRef = new ASTUnit(++ASTUnitGeneration);
for (auto &Content : Contents) {
if (Content.Snapshot)
ASTRef->Impl.Snapshots.push_back(Content.Snapshot);
if (trace::enabled()) {
TraceInfo.addFile(Content.Buffer->getBufferIdentifier(),
Content.Buffer->getBuffer());
}
}
auto &CompIns = ASTRef->Impl.CompInst;
auto &Consumer = ASTRef->Impl.CollectDiagConsumer;
// Display diagnostics to stderr.
CompIns.addDiagnosticConsumer(&Consumer);
CompilerInvocation Invocation;
Opts.applyTo(Invocation);
for (auto &Content : Contents)
Invocation.addInputBuffer(Content.Buffer.get());
if (CompIns.setup(Invocation)) {
// FIXME: Report the diagnostic.
LOG_WARN_FUNC("Compilation setup failed!!!");
Error = "compilation setup failed";
return nullptr;
}
trace::TracedOperation TracedOp;
if (trace::enabled()) {
TracedOp.start(trace::OperationKind::PerformSema, TraceInfo);
}
CloseClangModuleFiles scopedCloseFiles(
*CompIns.getASTContext().getClangModuleLoader());
Consumer.setInputBufferIDs(ASTRef->getCompilerInstance().getInputBufferIDs());
CompIns.performSema();
llvm::SmallPtrSet<Module *, 16> Visited;
SmallVector<std::string, 8> Filenames;
collectModuleDependencies(CompIns.getMainModule(), Visited, Filenames);
// FIXME: There exists a small window where the module file may have been
// modified after compilation finished and before we get its stamp.
for (auto &Filename : Filenames) {
DependencyStamps.push_back(std::make_pair(Filename,
MgrImpl.getBufferStamp(Filename)));
}
// Since we only typecheck the primary file (plus referenced constructs
// from other files), any error is likely to break SIL generation.
if (!Consumer.hadAnyError()) {
// FIXME: Any error anywhere in the SourceFile will switch off SIL
// diagnostics. This means that this can happen:
// - The user sees a SIL diagnostic in one function
// - The user edits another function in the same file and introduces a
// typechecking error.
// - The SIL diagnostic in the first function will be gone.
//
// Could we maybe selectively SILGen functions from the SourceFile, so
// that we avoid SILGen'ing the second function with the typecheck error
// but still allow SILGen'ing the first function ?
// Or try to keep track of SIL diagnostics emitted previously ?
// FIXME: We should run SIL diagnostis asynchronously after typechecking
// so that they don't delay reporting of typechecking diagnostics and they
// don't block any other AST processing for the same SwiftInvocation.
if (auto SF = CompIns.getPrimarySourceFile()) {
SILOptions SILOpts;
std::unique_ptr<SILModule> SILMod = performSILGeneration(*SF, SILOpts);
runSILDiagnosticPasses(*SILMod);
}
}
// We mirror the compiler and don't set the TypeResolver during SIL
// processing. This is to avoid unnecessary typechecking that can occur if the
// TypeResolver is set before.
ASTRef->Impl.TypeResolver = createLazyResolver(CompIns.getASTContext());
return ASTRef;
}
|
C nettle, low-level cryptographics library
C
C Copyright (C) 2013 Niels Möller
C
C The nettle library is free software; you can redistribute it and/or modify
C it under the terms of the GNU Lesser General Public License as published by
C the Free Software Foundation; either version 2.1 of the License, or (at your
C option) any later version.
C
C The nettle library is distributed in the hope that it will be useful, but
C WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
C or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
C License for more details.
C
C You should have received a copy of the GNU Lesser General Public License
C along with the nettle library; see the file COPYING.LIB. If not, write to
C the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
C MA 02111-1301, USA.
define(<KEY>, <%rdi>)
define(<LENGTH>, <%rsi>)
define(<MSG>, <%rdx>)
define(<XA>, <%xmm0>)
define(<XB>, <%xmm1>)
define(<XK0>, <%xmm2>)
define(<XK1>, <%xmm3>)
define(<XY>, <%xmm4>)
define(<XT0>, <%xmm5>)
define(<XT1>, <%xmm6>)
C FIXME: Would be nice if we could force the key array to be 16-byte
C aligned.
.file "umac-nh.asm"
C umac_nh(const uint32_t *key, unsigned length, const uint8_t *msg)
.text
ALIGN(16)
PROLOGUE(_nettle_umac_nh)
W64_ENTRY(3, 7)
pxor XY, XY
.Loop:
movups (KEY), XK0
movups 16(KEY), XK1
movups (MSG), XA
movups 16(MSG), XB
paddd XK0, XA
paddd XK1, XB
pshufd $0x31, XA, XT0
pshufd $0x31, XB, XT1
pmuludq XT0, XT1
paddq XT1, XY
pmuludq XA, XB
paddq XB, XY
C Length is only 32 bits
subl $32, XREG(LENGTH)
lea 32(KEY), KEY
lea 32(MSG), MSG
ja .Loop
pshufd $0xe, XY, XT0
paddq XT0, XY
C Really a movq, but write as movd to please Apple's assembler
movd XY, %rax
W64_EXIT(3, 7)
ret
EPILOGUE(_nettle_umac_nh)
|
;;
;; Copyright (c) 2020-2021, Intel Corporation
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice,
;; this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;; * Neither the name of Intel Corporation nor the names of its contributors
;; may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;
%include "include/os.asm"
%include "include/imb_job.asm"
%include "include/memcpy.asm"
%include "include/clear_regs.asm"
%include "include/transpose_avx2.asm"
%include "include/chacha_poly_defines.asm"
%include "include/cet.inc"
section .data
default rel
align 32
constants:
dd 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574
dd 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574
align 16
dword_1:
dd 0x00000001, 0x00000000, 0x00000000, 0x00000000
align 16
dword_2:
dd 0x00000002, 0x00000000, 0x00000000, 0x00000000
align 32
dword_1_8:
dd 0x00000001, 0x00000002, 0x00000003, 0x00000004
dd 0x00000005, 0x00000006, 0x00000007, 0x00000008
align 32
dword_8:
dd 0x00000008, 0x00000008, 0x00000008, 0x00000008
dd 0x00000008, 0x00000008, 0x00000008, 0x00000008
align 32
add_1_2:
dd 0x00000001, 0x00000000, 0x00000000, 0x00000000
dd 0x00000002, 0x00000000, 0x00000000, 0x00000000
align 32
add_3_4:
dd 0x00000003, 0x00000000, 0x00000000, 0x00000000
dd 0x00000004, 0x00000000, 0x00000000, 0x00000000
align 32
shuf_mask_rotl8:
db 3, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10, 15, 12, 13, 14
db 3, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10, 15, 12, 13, 14
align 32
shuf_mask_rotl16:
db 2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13
db 2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13
struc STACK
_STATE: reso 32 ; Space to store first 8 states
_YMM_SAVE: resy 2 ; Space to store up to 2 temporary YMM registers
_GP_SAVE: resq 7 ; Space to store up to 7 GP registers
_RSP_SAVE: resq 1 ; Space to store rsp pointer
endstruc
%define STACK_SIZE STACK_size
%ifdef LINUX
%define arg1 rdi
%define arg2 rsi
%define arg3 rdx
%define arg4 rcx
%define arg5 r8
%else
%define arg1 rcx
%define arg2 rdx
%define arg3 r8
%define arg4 r9
%define arg5 [rsp + 40]
%endif
%define job arg1
%define APPEND(a,b) a %+ b
section .text
%macro ENCRYPT_0B_64B 10-11
%define %%SRC %1 ; [in/out] Source pointer
%define %%DST %2 ; [in/out] Destination pointer
%define %%LEN %3 ; [in/clobbered] Length to encrypt
%define %%OFF %4 ; [in] Offset into src/dst
%define %%KS0 %5 ; [in/out] Bytes 0-31 of keystream
%define %%KS1 %6 ; [in/out] Bytes 32-63 of keystream
%define %%PT0 %7 ; [in/clobbered] Bytes 0-31 of plaintext
%define %%PT1 %8 ; [in/clobbered] Bytes 32-63 of plaintext
%define %%TMP %9 ; [clobbered] Temporary GP register
%define %%TMP2 %10 ; [clobbered] Temporary GP register
%define %%KS_PTR %11 ; [in] Pointer to keystream
or %%LEN, %%LEN
jz %%end_encrypt
cmp %%LEN, 32
jbe %%up_to_32B
%%up_to_64B:
vmovdqu %%PT0, [%%SRC + %%OFF]
%if %0 == 11
vmovdqu %%KS0, [%%KS_PTR]
vmovdqu %%KS1, [%%KS_PTR + 32]
%endif
vpxor %%PT0, %%KS0
vmovdqu [%%DST + %%OFF], %%PT0
add %%SRC, %%OFF
add %%DST, %%OFF
add %%SRC, 32
add %%DST, 32
sub %%LEN, 32
simd_load_avx2 %%PT1, %%SRC, %%LEN, %%TMP, %%TMP2
vpxor %%PT1, %%KS1
simd_store_avx2 %%DST, %%PT1, %%LEN, %%TMP, %%TMP2
jmp %%end_encrypt
%%up_to_32B:
add %%SRC, %%OFF
add %%DST, %%OFF
; XOR KS with plaintext and store resulting ciphertext
%if %0 == 11
vmovdqu %%KS0, [%%KS_PTR]
%endif
simd_load_avx2 %%PT0, %%SRC, %%LEN, %%TMP, %%TMP2
vpxor %%PT0, %%KS0
simd_store_avx2 %%DST, %%PT0, %%LEN, %%TMP, %%TMP2
%%end_encrypt:
add %%SRC, %%LEN
add %%DST, %%LEN
%endmacro
; Rotate dwords on a YMM registers to the left N_BITS
%macro VPROLD 3
%define %%YMM_IN %1 ; [in/out] YMM register to be rotated
%define %%N_BITS %2 ; [immediate] Number of bits to rotate
%define %%YTMP %3 ; [clobbered] YMM temporary register
%if %%N_BITS == 8
vpshufb %%YMM_IN, [rel shuf_mask_rotl8]
%elif %%N_BITS == 16
vpshufb %%YMM_IN, [rel shuf_mask_rotl16]
%else
vpsrld %%YTMP, %%YMM_IN, (32-%%N_BITS)
vpslld %%YMM_IN, %%N_BITS
vpor %%YMM_IN, %%YTMP
%endif
%endmacro
;;
;; Performs a quarter round on all 4 columns,
;; resulting in a full round
;;
%macro QUARTER_ROUND_X4 5
%define %%A %1 ;; [in/out] YMM register containing value A of all 4 columns
%define %%B %2 ;; [in/out] YMM register containing value B of all 4 columns
%define %%C %3 ;; [in/out] YMM register containing value C of all 4 columns
%define %%D %4 ;; [in/out] YMM register containing value D of all 4 columns
%define %%YTMP %5 ;; [clobbered] Temporary YMM register
vpaddd %%A, %%B
vpxor %%D, %%A
VPROLD %%D, 16, %%YTMP
vpaddd %%C, %%D
vpxor %%B, %%C
VPROLD %%B, 12, %%YTMP
vpaddd %%A, %%B
vpxor %%D, %%A
VPROLD %%D, 8, %%YTMP
vpaddd %%C, %%D
vpxor %%B, %%C
VPROLD %%B, 7, %%YTMP
%endmacro
%macro QUARTER_ROUND_X8 9
%define %%A_L %1 ;; [in/out] YMM register containing value A of all 4 columns
%define %%B_L %2 ;; [in/out] YMM register containing value B of all 4 columns
%define %%C_L %3 ;; [in/out] YMM register containing value C of all 4 columns
%define %%D_L %4 ;; [in/out] YMM register containing value D of all 4 columns
%define %%A_H %5 ;; [in/out] YMM register containing value A of all 4 columns
%define %%B_H %6 ;; [in/out] YMM register containing value B of all 4 columns
%define %%C_H %7 ;; [in/out] YMM register containing value C of all 4 columns
%define %%D_H %8 ;; [in/out] YMM register containing value D of all 4 columns
%define %%YTMP %9 ;; [clobbered] Temporary XMM register
vpaddd %%A_L, %%B_L
vpaddd %%A_H, %%B_H
vpxor %%D_L, %%A_L
vpxor %%D_H, %%A_H
VPROLD %%D_L, 16, %%YTMP
VPROLD %%D_H, 16, %%YTMP
vpaddd %%C_L, %%D_L
vpaddd %%C_H, %%D_H
vpxor %%B_L, %%C_L
vpxor %%B_H, %%C_H
VPROLD %%B_L, 12, %%YTMP
VPROLD %%B_H, 12, %%YTMP
vpaddd %%A_L, %%B_L
vpaddd %%A_H, %%B_H
vpxor %%D_L, %%A_L
vpxor %%D_H, %%A_H
VPROLD %%D_L, 8, %%YTMP
VPROLD %%D_H, 8, %%YTMP
vpaddd %%C_L, %%D_L
vpaddd %%C_H, %%D_H
vpxor %%B_L, %%C_L
vpxor %%B_H, %%C_H
VPROLD %%B_L, 7, %%YTMP
VPROLD %%B_H, 7, %%YTMP
%endmacro
;;
;; Rotates the registers to prepare the data
;; from column round to diagonal round
;;
%macro COLUMN_TO_DIAG 3
%define %%B %1 ;; [in/out] XMM register containing value B of all 4 columns
%define %%C %2 ;; [in/out] XMM register containing value C of all 4 columns
%define %%D %3 ;; [in/out] XMM register containing value D of all 4 columns
vpshufd %%B, %%B, 0x39 ; 0b00111001 ;; 0,3,2,1
vpshufd %%C, %%C, 0x4E ; 0b01001110 ;; 1,0,3,2
vpshufd %%D, %%D, 0x93 ; 0b10010011 ;; 2,1,0,3
%endmacro
;;
;; Rotates the registers to prepare the data
;; from diagonal round to column round
;;
%macro DIAG_TO_COLUMN 3
%define %%B %1 ;; [in/out] XMM register containing value B of all 4 columns
%define %%C %2 ;; [in/out] XMM register containing value C of all 4 columns
%define %%D %3 ;; [in/out] XMM register containing value D of all 4 columns
vpshufd %%B, %%B, 0x93 ; 0b10010011 ; 2,1,0,3
vpshufd %%C, %%C, 0x4E ; 0b01001110 ; 1,0,3,2
vpshufd %%D, %%D, 0x39 ; 0b00111001 ; 0,3,2,1
%endmacro
;;
;; Generates up to 64*4 bytes of keystream
;;
%macro GENERATE_256_KS 15
%define %%A_L_KS0 %1 ;; [out] YMM A / Bytes 0-31 of KS
%define %%B_L_KS2 %2 ;; [out] YMM B / Bytes 64-95 of KS
%define %%C_L_KS1 %3 ;; [out] YMM C / Bytes 32-63 of KS
%define %%D_L_KS3 %4 ;; [out] YMM D / Bytes 96-127 of KS
%define %%A_H_KS4 %5 ;; [out] YMM A / Bytes 128-159 of KS (or "none" in NUM_BLOCKS == 2)
%define %%B_H_KS6 %6 ;; [out] YMM B / Bytes 192-223 of KS (or "none" in NUM_BLOCKS == 2)
%define %%C_H_KS5 %7 ;; [out] YMM C / Bytes 160-191 of KS (or "none" in NUM_BLOCKS == 2)
%define %%D_H_KS7 %8 ;; [out] YMM D / Bytes 224-255 of KS (or "none" in NUM_BLOCKS == 2)
%define %%STATE_IN_A_L %9 ;; [in] YMM containing state "A" part
%define %%STATE_IN_B_L %10 ;; [in] YMM containing state "B" part
%define %%STATE_IN_C_L %11 ;; [in] YMM containing state "C" part
%define %%STATE_IN_D_L %12 ;; [in] YMM containing state "D" part
%define %%STATE_IN_D_H %13 ;; [in] YMM containing state "D" part (or "none" in NUM_BLOCKS == 4)
%define %%YTMP %14 ;; [clobbered] Temp YMM reg
%define %%NUM_BLOCKS %15 ;; [in] Num blocks to encrypt (2 or 4)
vmovdqa %%A_L_KS0, %%STATE_IN_A_L
vmovdqa %%B_L_KS2, %%STATE_IN_B_L
vmovdqa %%C_L_KS1, %%STATE_IN_C_L
vmovdqa %%D_L_KS3, %%STATE_IN_D_L
%if %%NUM_BLOCKS == 4
vmovdqa %%A_H_KS4, %%STATE_IN_A_L
vmovdqa %%B_H_KS6, %%STATE_IN_B_L
vmovdqa %%C_H_KS5, %%STATE_IN_C_L
vmovdqa %%D_H_KS7, %%STATE_IN_D_H
%endif
%rep 10
%if %%NUM_BLOCKS == 2
QUARTER_ROUND_X4 %%A_L_KS0, %%B_L_KS2, %%C_L_KS1, %%D_L_KS3, %%YTMP
COLUMN_TO_DIAG %%B_L_KS2, %%C_L_KS1, %%D_L_KS3
QUARTER_ROUND_X4 %%A_L_KS0, %%B_L_KS2, %%C_L_KS1, %%D_L_KS3, %%YTMP
DIAG_TO_COLUMN %%B_L_KS2, %%C_L_KS1, %%D_L_KS3
%else
QUARTER_ROUND_X8 %%A_L_KS0, %%B_L_KS2, %%C_L_KS1, %%D_L_KS3, \
%%A_H_KS4, %%B_H_KS6, %%C_H_KS5, %%D_H_KS7, %%YTMP
COLUMN_TO_DIAG %%B_L_KS2, %%C_L_KS1, %%D_L_KS3
COLUMN_TO_DIAG %%B_H_KS6, %%C_H_KS5, %%D_H_KS7
QUARTER_ROUND_X8 %%A_L_KS0, %%B_L_KS2, %%C_L_KS1, %%D_L_KS3, \
%%A_H_KS4, %%B_H_KS6, %%C_H_KS5, %%D_H_KS7, %%YTMP
DIAG_TO_COLUMN %%B_L_KS2, %%C_L_KS1, %%D_L_KS3
DIAG_TO_COLUMN %%B_H_KS6, %%C_H_KS5, %%D_H_KS7
%endif ;; %%NUM_BLOCKS == 4
%endrep
vpaddd %%A_L_KS0, %%STATE_IN_A_L
vpaddd %%B_L_KS2, %%STATE_IN_B_L
vpaddd %%C_L_KS1, %%STATE_IN_C_L
vpaddd %%D_L_KS3, %%STATE_IN_D_L
vperm2i128 %%YTMP, %%A_L_KS0, %%B_L_KS2, 0x20
vperm2i128 %%B_L_KS2, %%A_L_KS0, %%B_L_KS2, 0x31
vmovdqa %%A_L_KS0, %%YTMP
vperm2i128 %%YTMP, %%C_L_KS1, %%D_L_KS3, 0x20
vperm2i128 %%D_L_KS3, %%C_L_KS1, %%D_L_KS3, 0x31
vmovdqa %%C_L_KS1, %%YTMP
%if %%NUM_BLOCKS == 4
vpaddd %%A_H_KS4, %%STATE_IN_A_L
vpaddd %%B_H_KS6, %%STATE_IN_B_L
vpaddd %%C_H_KS5, %%STATE_IN_C_L
vpaddd %%D_H_KS7, %%STATE_IN_D_H
vperm2i128 %%YTMP, %%A_H_KS4, %%B_H_KS6, 0x20
vperm2i128 %%B_H_KS6, %%A_H_KS4, %%B_H_KS6, 0x31
vmovdqa %%A_H_KS4, %%YTMP
vperm2i128 %%YTMP, %%C_H_KS5, %%D_H_KS7, 0x20
vperm2i128 %%D_H_KS7, %%C_H_KS5, %%D_H_KS7, 0x31
vmovdqa %%C_H_KS5, %%YTMP
%endif
%endmacro
; Perform 4 times the operation in first parameter
%macro YMM_OP_X8 9
%define %%OP %1 ; [immediate] Instruction
%define %%DST_SRC1_1 %2 ; [in/out] First source/Destination 1
%define %%DST_SRC1_2 %3 ; [in/out] First source/Destination 2
%define %%DST_SRC1_3 %4 ; [in/out] First source/Destination 3
%define %%DST_SRC1_4 %5 ; [in/out] First source/Destination 4
%define %%SRC2_1 %6 ; [in] Second source 1
%define %%SRC2_2 %7 ; [in] Second source 2
%define %%SRC2_3 %8 ; [in] Second source 3
%define %%SRC2_4 %9 ; [in] Second source 4
%%OP %%DST_SRC1_1, %%SRC2_1
%%OP %%DST_SRC1_2, %%SRC2_2
%%OP %%DST_SRC1_3, %%SRC2_3
%%OP %%DST_SRC1_4, %%SRC2_4
%endmacro
%macro YMM_ROLS_X8 6
%define %%YMM_OP1_1 %1
%define %%YMM_OP1_2 %2
%define %%YMM_OP1_3 %3
%define %%YMM_OP1_4 %4
%define %%BITS_TO_ROTATE %5
%define %%YTMP %6
; Store temporary register when bits to rotate is not 8 and 16,
; as the register will be clobbered in these cases,
; containing needed information
%if %%BITS_TO_ROTATE != 8 && %%BITS_TO_ROTATE != 16
vmovdqa [rsp + _YMM_SAVE], %%YTMP
%endif
VPROLD %%YMM_OP1_1, %%BITS_TO_ROTATE, %%YTMP
VPROLD %%YMM_OP1_2, %%BITS_TO_ROTATE, %%YTMP
VPROLD %%YMM_OP1_3, %%BITS_TO_ROTATE, %%YTMP
VPROLD %%YMM_OP1_4, %%BITS_TO_ROTATE, %%YTMP
%if %%BITS_TO_ROTATE != 8 && %%BITS_TO_ROTATE != 16
vmovdqa %%YTMP, [rsp + _YMM_SAVE]
%endif
%endmacro
;;
;; Performs a full chacha20 round on 8 states,
;; consisting of 8 quarter rounds, which are done in parallel
;;
%macro CHACHA20_ROUND 16
%define %%YMM_DWORD_A1 %1 ;; [in/out] YMM register containing dword A for first quarter round
%define %%YMM_DWORD_A2 %2 ;; [in/out] YMM register containing dword A for second quarter round
%define %%YMM_DWORD_A3 %3 ;; [in/out] YMM register containing dword A for third quarter round
%define %%YMM_DWORD_A4 %4 ;; [in/out] YMM register containing dword A for fourth quarter round
%define %%YMM_DWORD_B1 %5 ;; [in/out] YMM register containing dword B for first quarter round
%define %%YMM_DWORD_B2 %6 ;; [in/out] YMM register containing dword B for second quarter round
%define %%YMM_DWORD_B3 %7 ;; [in/out] YMM register containing dword B for third quarter round
%define %%YMM_DWORD_B4 %8 ;; [in/out] YMM register containing dword B for fourth quarter round
%define %%YMM_DWORD_C1 %9 ;; [in/out] YMM register containing dword C for first quarter round
%define %%YMM_DWORD_C2 %10 ;; [in/out] YMM register containing dword C for second quarter round
%define %%YMM_DWORD_C3 %11 ;; [in/out] YMM register containing dword C for third quarter round
%define %%YMM_DWORD_C4 %12 ;; [in/out] YMM register containing dword C for fourth quarter round
%define %%YMM_DWORD_D1 %13 ;; [in/out] YMM register containing dword D for first quarter round
%define %%YMM_DWORD_D2 %14 ;; [in/out] YMM register containing dword D for second quarter round
%define %%YMM_DWORD_D3 %15 ;; [in/out] YMM register containing dword D for third quarter round
%define %%YMM_DWORD_D4 %16 ;; [in/out] YMM register containing dword D for fourth quarter round
; A += B
YMM_OP_X8 vpaddd, %%YMM_DWORD_A1, %%YMM_DWORD_A2, %%YMM_DWORD_A3, %%YMM_DWORD_A4, \
%%YMM_DWORD_B1, %%YMM_DWORD_B2, %%YMM_DWORD_B3, %%YMM_DWORD_B4
; D ^= A
YMM_OP_X8 vpxor, %%YMM_DWORD_D1, %%YMM_DWORD_D2, %%YMM_DWORD_D3, %%YMM_DWORD_D4, \
%%YMM_DWORD_A1, %%YMM_DWORD_A2, %%YMM_DWORD_A3, %%YMM_DWORD_A4
; D <<< 16
YMM_ROLS_X8 %%YMM_DWORD_D1, %%YMM_DWORD_D2, %%YMM_DWORD_D3, %%YMM_DWORD_D4, 16, \
%%YMM_DWORD_B1
; C += D
YMM_OP_X8 vpaddd, %%YMM_DWORD_C1, %%YMM_DWORD_C2, %%YMM_DWORD_C3, %%YMM_DWORD_C4, \
%%YMM_DWORD_D1, %%YMM_DWORD_D2, %%YMM_DWORD_D3, %%YMM_DWORD_D4
; B ^= C
YMM_OP_X8 vpxor, %%YMM_DWORD_B1, %%YMM_DWORD_B2, %%YMM_DWORD_B3, %%YMM_DWORD_B4, \
%%YMM_DWORD_C1, %%YMM_DWORD_C2, %%YMM_DWORD_C3, %%YMM_DWORD_C4
; B <<< 12
YMM_ROLS_X8 %%YMM_DWORD_B1, %%YMM_DWORD_B2, %%YMM_DWORD_B3, %%YMM_DWORD_B4, 12, \
%%YMM_DWORD_D1
; A += B
YMM_OP_X8 vpaddd, %%YMM_DWORD_A1, %%YMM_DWORD_A2, %%YMM_DWORD_A3, %%YMM_DWORD_A4, \
%%YMM_DWORD_B1, %%YMM_DWORD_B2, %%YMM_DWORD_B3, %%YMM_DWORD_B4
; D ^= A
YMM_OP_X8 vpxor, %%YMM_DWORD_D1, %%YMM_DWORD_D2, %%YMM_DWORD_D3, %%YMM_DWORD_D4, \
%%YMM_DWORD_A1, %%YMM_DWORD_A2, %%YMM_DWORD_A3, %%YMM_DWORD_A4
; D <<< 8
YMM_ROLS_X8 %%YMM_DWORD_D1, %%YMM_DWORD_D2, %%YMM_DWORD_D3, %%YMM_DWORD_D4, 8, \
%%YMM_DWORD_B1
; C += D
YMM_OP_X8 vpaddd, %%YMM_DWORD_C1, %%YMM_DWORD_C2, %%YMM_DWORD_C3, %%YMM_DWORD_C4, \
%%YMM_DWORD_D1, %%YMM_DWORD_D2, %%YMM_DWORD_D3, %%YMM_DWORD_D4
; B ^= C
YMM_OP_X8 vpxor, %%YMM_DWORD_B1, %%YMM_DWORD_B2, %%YMM_DWORD_B3, %%YMM_DWORD_B4, \
%%YMM_DWORD_C1, %%YMM_DWORD_C2, %%YMM_DWORD_C3, %%YMM_DWORD_C4
; B <<< 7
YMM_ROLS_X8 %%YMM_DWORD_B1, %%YMM_DWORD_B2, %%YMM_DWORD_B3, %%YMM_DWORD_B4, 7, \
%%YMM_DWORD_D1
%endmacro
;;
;; Encodes 8 Chacha20 states, outputting 512 bytes of keystream
;; Data still needs to be transposed to get the keystream in the correct order
;;
%macro GENERATE_512_KS 16
%define %%YMM_DWORD_0 %1 ;; [out] YMM register to contain encoded dword 0 of the 8 Chacha20 states
%define %%YMM_DWORD_1 %2 ;; [out] YMM register to contain encoded dword 1 of the 8 Chacha20 states
%define %%YMM_DWORD_2 %3 ;; [out] YMM register to contain encoded dword 2 of the 8 Chacha20 states
%define %%YMM_DWORD_3 %4 ;; [out] YMM register to contain encoded dword 3 of the 8 Chacha20 states
%define %%YMM_DWORD_4 %5 ;; [out] YMM register to contain encoded dword 4 of the 8 Chacha20 states
%define %%YMM_DWORD_5 %6 ;; [out] YMM register to contain encoded dword 5 of the 8 Chacha20 states
%define %%YMM_DWORD_6 %7 ;; [out] YMM register to contain encoded dword 6 of the 8 Chacha20 states
%define %%YMM_DWORD_7 %8 ;; [out] YMM register to contain encoded dword 7 of the 8 Chacha20 states
%define %%YMM_DWORD_8 %9 ;; [out] YMM register to contain encoded dword 8 of the 8 Chacha20 states
%define %%YMM_DWORD_9 %10 ;; [out] YMM register to contain encoded dword 9 of the 8 Chacha20 states
%define %%YMM_DWORD_10 %11 ;; [out] YMM register to contain encoded dword 10 of the 8 Chacha20 states
%define %%YMM_DWORD_11 %12 ;; [out] YMM register to contain encoded dword 11 of the 8 Chacha20 states
%define %%YMM_DWORD_12 %13 ;; [out] YMM register to contain encoded dword 12 of the 8 Chacha20 states
%define %%YMM_DWORD_13 %14 ;; [out] YMM register to contain encoded dword 13 of the 8 Chacha20 states
%define %%YMM_DWORD_14 %15 ;; [out] YMM register to contain encoded dword 14 of the 8 Chacha20 states
%define %%YMM_DWORD_15 %16 ;; [out] YMM register to contain encoded dword 15 of the 8 Chacha20 states
%assign i 0
%rep 16
vmovdqa APPEND(%%YMM_DWORD_, i), [rsp + _STATE + 32*i]
%assign i (i + 1)
%endrep
%rep 10
CHACHA20_ROUND %%YMM_DWORD_0, %%YMM_DWORD_1, %%YMM_DWORD_2, %%YMM_DWORD_3, \
%%YMM_DWORD_4, %%YMM_DWORD_5, %%YMM_DWORD_6, %%YMM_DWORD_7, \
%%YMM_DWORD_8, %%YMM_DWORD_9, %%YMM_DWORD_10, %%YMM_DWORD_11, \
%%YMM_DWORD_12, %%YMM_DWORD_13, %%YMM_DWORD_14, %%YMM_DWORD_15
CHACHA20_ROUND %%YMM_DWORD_0, %%YMM_DWORD_1, %%YMM_DWORD_2, %%YMM_DWORD_3, \
%%YMM_DWORD_5, %%YMM_DWORD_6, %%YMM_DWORD_7, %%YMM_DWORD_4, \
%%YMM_DWORD_10, %%YMM_DWORD_11, %%YMM_DWORD_8, %%YMM_DWORD_9, \
%%YMM_DWORD_15, %%YMM_DWORD_12, %%YMM_DWORD_13, %%YMM_DWORD_14
%endrep
%assign i 0
%rep 16
vpaddd APPEND(%%YMM_DWORD_, i), [rsp + _STATE + 32*i]
%assign i (i + 1)
%endrep
%endmacro
%macro PREPARE_NEXT_STATES_2_TO_4 11
%define %%STATE_IN_A_L %1 ;; [out] YMM containing state "A" part for states 1-2
%define %%STATE_IN_B_L %2 ;; [out] YMM containing state "B" part for states 1-2
%define %%STATE_IN_C_L %3 ;; [out] YMM containing state "C" part for states 1-2
%define %%STATE_IN_D_L %4 ;; [out] YMM containing state "D" part for states 1-2
%define %%STATE_IN_D_H %5 ;; [out] YMM containing state "D" part for states 3-4 (or "none" in NUM_BLOCKS == 4)
%define %%YTMP0 %6 ;; [clobbered] YMM temp reg
%define %%YTMP1 %7 ;; [clobbered] YMM temp reg
%define %%LAST_BLK_CNT %8 ;; [in] Last block counter
%define %%IV %9 ;; [in] Pointer to IV
%define %%KEY %10 ;; [in] Pointer to key
%define %%NUM_BLOCKS %11 ;; [in] Number of state blocks to prepare (numerical)
;; Prepare next 4 states (or 2, if 2 or less blocks left)
vmovdqu %%STATE_IN_B_L, [%%KEY] ; Load key bytes 0-15
vmovdqu %%STATE_IN_C_L, [%%KEY + 16] ; Load key bytes 16-31
vperm2i128 %%STATE_IN_B_L,%%STATE_IN_B_L, 0x0
vperm2i128 %%STATE_IN_C_L, %%STATE_IN_C_L, 0x0
vmovq XWORD(%%STATE_IN_D_L), [%%IV]
vpinsrd XWORD(%%STATE_IN_D_L), [%%IV + 8], 2
vpslldq %%STATE_IN_D_L, 4
vperm2i128 %%STATE_IN_D_L, %%STATE_IN_D_L, 0x0
vmovdqa %%STATE_IN_A_L, [rel constants]
%if %%NUM_BLOCKS == 4
;; Prepare chacha states 2-3 (A-C same as states 0-3)
vmovdqa %%STATE_IN_D_H, %%STATE_IN_D_L
%endif
; Broadcast last block counter
vmovd XWORD(%%YTMP0), DWORD(%%LAST_BLK_CNT)
vperm2i128 %%YTMP0, %%YTMP0, 0x00
%if %%NUM_BLOCKS == 2
; Add 1-2 to construct next block counters
vpaddd %%YTMP0, [rel add_1_2]
vpor %%STATE_IN_D_L, %%YTMP0
%else
; Add 1-8 to construct next block counters
vmovdqa %%YTMP1, %%YTMP0
vpaddd %%YTMP0, [rel add_1_2]
vpaddd %%YTMP1, [rel add_3_4]
vpor %%STATE_IN_D_L, %%YTMP0
vpor %%STATE_IN_D_H, %%YTMP1
%endif
%endmacro
align 32
MKGLOBAL(submit_job_chacha20_enc_dec_avx2,function,internal)
submit_job_chacha20_enc_dec_avx2:
endbranch64
%define src r8
%define dst r9
%define len r10
%define iv r11
%define keys rdx
%define off rax
%define tmp iv
%define tmp2 keys
; Read pointers and length
mov len, [job + _msg_len_to_cipher_in_bytes]
; Check if there is nothing to encrypt
or len, len
jz exit
mov keys, [job + _enc_keys]
mov iv, [job + _iv]
mov src, [job + _src]
add src, [job + _cipher_start_src_offset_in_bytes]
mov dst, [job + _dst]
mov rax, rsp
sub rsp, STACK_SIZE
and rsp, -32
mov [rsp + _RSP_SAVE], rax ; save RSP
xor off, off
; If less than or equal to 64*4 bytes, prepare directly states for up to 4 blocks
cmp len, 64*4
jbe exit_loop
; Prepare first 8 chacha states from IV, key, constants and counter values
vbroadcastss ymm0, [rel constants]
vbroadcastss ymm1, [rel constants + 4]
vbroadcastss ymm2, [rel constants + 8]
vbroadcastss ymm3, [rel constants + 12]
vbroadcastss ymm4, [keys]
vbroadcastss ymm5, [keys + 4]
vbroadcastss ymm6, [keys + 8]
vbroadcastss ymm7, [keys + 12]
vbroadcastss ymm8, [keys + 16]
vbroadcastss ymm9, [keys + 20]
vbroadcastss ymm10, [keys + 24]
vbroadcastss ymm11, [keys + 28]
vbroadcastss ymm13, [iv]
vbroadcastss ymm14, [iv + 4]
vbroadcastss ymm15, [iv + 8]
; Set block counters for first 8 Chacha20 states
vmovdqa ymm12, [rel dword_1_8]
%assign i 0
%rep 16
vmovdqa [rsp + _STATE + 32*i], ymm %+ i
%assign i (i + 1)
%endrep
cmp len, 64*8
jb exit_loop
align 32
start_loop:
; Generate 512 bytes of keystream
GENERATE_512_KS ymm0, ymm1, ymm2, ymm3, ymm4, ymm5, ymm6, ymm7, \
ymm8, ymm9, ymm10, ymm11, ymm12, ymm13, ymm14, ymm15
;; Transpose state to get keystream and XOR with plaintext
;; to get ciphertext
; Save registers to be used as temp registers
vmovdqa [rsp + _YMM_SAVE], ymm14
vmovdqa [rsp + _YMM_SAVE + 32], ymm15
; Transpose to get [64*I : 64*I + 31] (I = 0-7) bytes of KS
TRANSPOSE8_U32 ymm0, ymm1, ymm2, ymm3, ymm4, ymm5, ymm6, ymm7, ymm14, ymm15
vpxor ymm0, [src + off]
vpxor ymm1, [src + off + 64]
vmovdqu [dst + off], ymm0
vmovdqu [dst + off + 64], ymm1
vpxor ymm2, [src + off + 64*2]
vpxor ymm3, [src + off + 64*3]
vmovdqu [dst + off + 64*2], ymm2
vmovdqu [dst + off + 64*3], ymm3
vpxor ymm4, [src + off + 64*4]
vpxor ymm5, [src + off + 64*5]
vmovdqu [dst + off + 64*4], ymm4
vmovdqu [dst + off + 64*5], ymm5
vpxor ymm6, [src + off + 64*6]
vpxor ymm7, [src + off + 64*7]
vmovdqu [dst + off + 64*6], ymm6
vmovdqu [dst + off + 64*7], ymm7
; Restore registers and use ymm0, ymm1 now that they are free
vmovdqa ymm14, [rsp + _YMM_SAVE]
vmovdqa ymm15, [rsp + _YMM_SAVE + 32]
; Transpose to get [64*I + 32 : 64*I + 63] (I = 0-7) bytes of KS
TRANSPOSE8_U32 ymm8, ymm9, ymm10, ymm11, ymm12, ymm13, ymm14, ymm15, ymm0, ymm1
vpxor ymm8, [src + off + 32]
vpxor ymm9, [src + off + 64 + 32]
vmovdqu [dst + off + 32], ymm8
vmovdqu [dst + off + 64 + 32], ymm9
vpxor ymm10, [src + off + 64*2 + 32]
vpxor ymm11, [src + off + 64*3 + 32]
vmovdqu [dst + off + 64*2 + 32], ymm10
vmovdqu [dst + off + 64*3 + 32], ymm11
vpxor ymm12, [src + off + 64*4 + 32]
vpxor ymm13, [src + off + 64*5 + 32]
vmovdqu [dst + off + 64*4 + 32], ymm12
vmovdqu [dst + off + 64*5 + 32], ymm13
vpxor ymm14, [src + off + 64*6 + 32]
vpxor ymm15, [src + off + 64*7 + 32]
vmovdqu [dst + off + 64*6 + 32], ymm14
vmovdqu [dst + off + 64*7 + 32], ymm15
; Update remaining length
sub len, 64*8
add off, 64*8
; Update counter values
vmovdqa ymm12, [rsp + 32*12]
vpaddd ymm12, [rel dword_8]
vmovdqa [rsp + 32*12], ymm12
cmp len, 64*8
jae start_loop
exit_loop:
; Check if there are no more bytes to encrypt
or len, len
jz no_partial_block
cmp len, 64*4
ja more_than_4_blocks_left
cmp len, 64*2
ja more_than_2_blocks_left
;; up to 2 blocks left
; Get last block counter dividing offset by 64
shr off, 6
PREPARE_NEXT_STATES_2_TO_4 ymm4, ymm5, ymm6, ymm7, none, \
ymm8, ymm9, off, iv, keys, 2
shl off, 6 ; Restore offset
GENERATE_256_KS ymm0, ymm1, ymm8, ymm9, none, none, none, none, \
ymm4, ymm5, ymm6, ymm7, none, ymm10, 2
cmp len, 64*2
jbe less_than_2_full_blocks
; XOR next 128 bytes
vpxor ymm8, [src + off]
vpxor ymm9, [src + off + 32]
vmovdqu [dst + off], ymm8
vmovdqu [dst + off + 32], ymm9
vpxor ymm10, [src + off + 32*2]
vpxor ymm11, [src + off + 32*3]
vmovdqu [dst + off + 32*2], ymm10
vmovdqu [dst + off + 32*3], ymm11
jmp no_partial_block
more_than_2_blocks_left:
; Get last block counter dividing offset by 64
shr off, 6
PREPARE_NEXT_STATES_2_TO_4 ymm4, ymm5, ymm6, ymm7, ymm12, \
ymm8, ymm9, off, iv, keys, 4
shl off, 6 ; Restore offset
GENERATE_256_KS ymm0, ymm1, ymm8, ymm9, ymm2, ymm3, ymm10, ymm11, \
ymm4, ymm5, ymm6, ymm7, ymm12, ymm13, 4
cmp len, 64*4
jb less_than_4_full_blocks
; XOR next 256 bytes
vpxor ymm0, [src + off]
vpxor ymm8, [src + off + 32]
vmovdqu [dst + off], ymm0
vmovdqu [dst + off + 32], ymm8
vpxor ymm1, [src + off + 32*2]
vpxor ymm9, [src + off + 32*3]
vmovdqu [dst + off + 32*2], ymm1
vmovdqu [dst + off + 32*3], ymm9
vpxor ymm2, [src + off + 32*4]
vpxor ymm10, [src + off + 32*5]
vmovdqu [dst + off + 32*4], ymm2
vmovdqu [dst + off + 32*5], ymm10
vpxor ymm3, [src + off + 32*6]
vpxor ymm11, [src + off + 32*7]
vmovdqu [dst + off + 32*6], ymm3
vmovdqu [dst + off + 32*7], ymm11
jmp no_partial_block
more_than_4_blocks_left:
; Generate 512 bytes of keystream
GENERATE_512_KS ymm0, ymm1, ymm2, ymm3, ymm4, ymm5, ymm6, ymm7, \
ymm8, ymm9, ymm10, ymm11, ymm12, ymm13, ymm14, ymm15
; Save registers to be used as temp registers
vmovdqa [rsp + _YMM_SAVE], ymm14
vmovdqa [rsp + _YMM_SAVE + 32], ymm15
; Transpose to get [64*I : 64*I + 31] (I = 0-7) bytes of KS
TRANSPOSE8_U32 ymm0, ymm1, ymm2, ymm3, ymm4, ymm5, ymm6, ymm7, ymm14, ymm15
; Restore registers and save another two registers to be used as temp registers
vmovdqa ymm14, [rsp + _YMM_SAVE]
vmovdqa ymm15, [rsp + _YMM_SAVE + 32]
vmovdqa [rsp + _YMM_SAVE], ymm0
vmovdqa [rsp + _YMM_SAVE + 32], ymm1
; Transpose to get [64*I + 32 : 64*I + 63] (I = 0-7) bytes of KS
TRANSPOSE8_U32 ymm8, ymm9, ymm10, ymm11, ymm12, ymm13, ymm14, ymm15, ymm0, ymm1
; Restore registers
vmovdqa ymm0, [rsp + _YMM_SAVE]
vmovdqa ymm1, [rsp + _YMM_SAVE + 32]
; XOR next 256 bytes
vpxor ymm0, [src + off]
vpxor ymm8, [src + off + 32]
vmovdqu [dst + off], ymm0
vmovdqu [dst + off + 32], ymm8
vpxor ymm1, [src + off + 32*2]
vpxor ymm9, [src + off + 32*3]
vmovdqu [dst + off + 32*2], ymm1
vmovdqu [dst + off + 32*3], ymm9
vpxor ymm2, [src + off + 32*4]
vpxor ymm10, [src + off + 32*5]
vmovdqu [dst + off + 32*4], ymm2
vmovdqu [dst + off + 32*5], ymm10
vpxor ymm3, [src + off + 32*6]
vpxor ymm11, [src + off + 32*7]
vmovdqu [dst + off + 32*6], ymm3
vmovdqu [dst + off + 32*7], ymm11
; Update remaining length
sub len, 64*4
add off, 64*4
or len, len
jz no_partial_block
; Move last 256 bytes of KS to registers YMM0-3,YMM8-11
vmovdqa ymm0, ymm4
vmovdqa ymm1, ymm5
vmovdqa ymm2, ymm6
vmovdqa ymm3, ymm7
vmovdqa ymm8, ymm12
vmovdqa ymm9, ymm13
vmovdqa ymm10, ymm14
vmovdqa ymm11, ymm15
cmp len, 64*2
jb less_than_2_full_blocks
less_than_4_full_blocks:
; XOR next 128 bytes
vpxor ymm0, [src + off]
vpxor ymm8, [src + off + 32]
vmovdqu [dst + off], ymm0
vmovdqu [dst + off + 32], ymm8
vpxor ymm1, [src + off + 32*2]
vpxor ymm9, [src + off + 32*3]
vmovdqu [dst + off + 32*2], ymm1
vmovdqu [dst + off + 32*3], ymm9
; Update remaining length
sub len, 64*2
add off, 64*2
or len, len
jz no_partial_block
; Move last 128 bytes of KS to registers YMM0-1,YMM8-9
vmovdqa ymm0, ymm2
vmovdqa ymm1, ymm3
vmovdqa ymm8, ymm10
vmovdqa ymm9, ymm11
less_than_2_full_blocks:
cmp len, 64
jb less_than_1_full_block
; XOR next 64 bytes
vpxor ymm0, [src + off]
vpxor ymm8, [src + off + 32]
vmovdqu [dst + off], ymm0
vmovdqu [dst + off + 32], ymm8
; Update remaining length
sub len, 64
add off, 64
or len, len
jz no_partial_block
; Move last 64 bytes of KS to registers YMM0,YMM8
vmovdqa ymm0, ymm1
vmovdqa ymm8, ymm9
less_than_1_full_block:
cmp len, 32
jb partial_block
; XOR next 32 bytes
vpxor ymm0, [src + off]
vmovdqu [dst + off], ymm0
; Update remaining length
sub len, 32
add off, 32
or len, len
jz no_partial_block
; Move last 32 bytes of KS to registers YMM0
vmovdqa ymm0, ymm8
partial_block:
add src, off
add dst, off
simd_load_avx2 ymm1, src, len, tmp, tmp2
vpxor ymm1, ymm0
simd_store_avx2 dst, ymm1, len, tmp, tmp2
no_partial_block:
endbranch64
%ifdef SAFE_DATA
vpxor ymm0, ymm0
; Clear stack frame
%assign i 0
%rep 16
vmovdqa [rsp + _STATE + 32*i], ymm0
%assign i (i + 1)
%endrep
vmovdqa [rsp + _YMM_SAVE], ymm0
vmovdqa [rsp + _YMM_SAVE + 32], ymm0
%endif
mov rsp, [rsp + _RSP_SAVE]
exit:
mov rax, job
or dword [rax + _status], IMB_STATUS_COMPLETED_CIPHER
clear_all_ymms_asm
ret
align 32
MKGLOBAL(chacha20_enc_dec_ks_avx2,function,internal)
chacha20_enc_dec_ks_avx2:
endbranch64
%define blk_cnt r10
%define prev_ks r13
%define remain_ks r12
%define ctx r11
%define src arg1
%define dst arg2
%define len arg3
%define keys arg4
%define iv r15
%define off rax
%define tmp iv
%define tmp3 r14
%define tmp4 rbp
%define tmp5 rbx
%ifdef LINUX
%define tmp2 r9
%else
%define tmp2 rdi
%endif
; Check if there is nothing to encrypt
or len, len
jz exit_ks
mov ctx, arg5
mov rax, rsp
sub rsp, STACK_SIZE
and rsp, -32
mov [rsp + _GP_SAVE], r12
mov [rsp + _GP_SAVE + 8], r13
mov [rsp + _GP_SAVE + 16], r14
mov [rsp + _GP_SAVE + 24], r15
mov [rsp + _GP_SAVE + 32], rbx
mov [rsp + _GP_SAVE + 40], rbp
%ifndef LINUX
mov [rsp + _GP_SAVE + 48], rdi
%endif
mov [rsp + _RSP_SAVE], rax ; save RSP
xor off, off
mov blk_cnt, [ctx + LastBlkCount]
lea prev_ks, [ctx + LastKs]
mov remain_ks, [ctx + RemainKsBytes]
; Check if there are any remaining bytes of keystream
mov tmp3, remain_ks
or tmp3, tmp3
jz no_remain_ks_bytes
mov tmp4, 64
sub tmp4, tmp3
; Adjust pointer of previous KS to point at start of unused KS
add prev_ks, tmp4
; Set remaining bytes to length of input segment, if lower
cmp len, tmp3
cmovbe tmp3, len
mov tmp5, tmp3
; Read up to 63 bytes of KS and XOR the first bytes of message
; with the previous unused bytes of keystream
ENCRYPT_0B_64B src, dst, tmp3, off, ymm9, ymm10, \
ymm0, ymm1, tmp, tmp2, prev_ks
; Update remain bytes of KS
sub [ctx + RemainKsBytes], tmp5
; Restore pointer to previous KS
sub prev_ks, tmp4
sub len, tmp5
jz no_partial_block_ks
no_remain_ks_bytes:
; Reset remaining number of KS bytes
mov qword [ctx + RemainKsBytes], 0
lea iv, [ctx + IV]
; If less than or equal to 64*4 bytes, prepare directly states for up to 4 blocks
cmp len, 64*4
jbe exit_loop_ks
; Prepare first 8 chacha states from IV, key, constants and counter values
vbroadcastss ymm0, [rel constants]
vbroadcastss ymm1, [rel constants + 4]
vbroadcastss ymm2, [rel constants + 8]
vbroadcastss ymm3, [rel constants + 12]
vbroadcastss ymm4, [keys]
vbroadcastss ymm5, [keys + 4]
vbroadcastss ymm6, [keys + 8]
vbroadcastss ymm7, [keys + 12]
vbroadcastss ymm8, [keys + 16]
vbroadcastss ymm9, [keys + 20]
vbroadcastss ymm10, [keys + 24]
vbroadcastss ymm11, [keys + 28]
vbroadcastss ymm13, [iv]
vbroadcastss ymm14, [iv + 4]
vbroadcastss ymm15, [iv + 8]
; Set block counters for next 8 Chacha20 states
vmovd xmm12, DWORD(blk_cnt)
vpshufd xmm12, xmm12, 0
vperm2i128 ymm12, ymm12, ymm12, 0
vpaddd ymm12, [rel dword_1_8]
%assign i 0
%rep 16
vmovdqa [rsp + _STATE + 32*i], ymm %+ i
%assign i (i + 1)
%endrep
cmp len, 64*8
jb exit_loop_ks
align 32
start_loop_ks:
; Generate 512 bytes of keystream
GENERATE_512_KS ymm0, ymm1, ymm2, ymm3, ymm4, ymm5, ymm6, ymm7, \
ymm8, ymm9, ymm10, ymm11, ymm12, ymm13, ymm14, ymm15
;; Transpose state to get keystream and XOR with plaintext
;; to get ciphertext
; Save registers to be used as temp registers
vmovdqa [rsp + _YMM_SAVE], ymm14
vmovdqa [rsp + _YMM_SAVE + 32], ymm15
; Transpose to get [64*I : 64*I + 31] (I = 0-7) bytes of KS
TRANSPOSE8_U32 ymm0, ymm1, ymm2, ymm3, ymm4, ymm5, ymm6, ymm7, ymm14, ymm15
vpxor ymm0, [src + off]
vpxor ymm1, [src + off + 64]
vmovdqu [dst + off], ymm0
vmovdqu [dst + off + 64], ymm1
vpxor ymm2, [src + off + 64*2]
vpxor ymm3, [src + off + 64*3]
vmovdqu [dst + off + 64*2], ymm2
vmovdqu [dst + off + 64*3], ymm3
vpxor ymm4, [src + off + 64*4]
vpxor ymm5, [src + off + 64*5]
vmovdqu [dst + off + 64*4], ymm4
vmovdqu [dst + off + 64*5], ymm5
vpxor ymm6, [src + off + 64*6]
vpxor ymm7, [src + off + 64*7]
vmovdqu [dst + off + 64*6], ymm6
vmovdqu [dst + off + 64*7], ymm7
; Restore registers and use ymm0, ymm1 now that they are free
vmovdqa ymm14, [rsp + _YMM_SAVE]
vmovdqa ymm15, [rsp + _YMM_SAVE + 32]
; Transpose to get [64*I + 32 : 64*I + 63] (I = 0-7) bytes of KS
TRANSPOSE8_U32 ymm8, ymm9, ymm10, ymm11, ymm12, ymm13, ymm14, ymm15, ymm0, ymm1
vpxor ymm8, [src + off + 32]
vpxor ymm9, [src + off + 64 + 32]
vmovdqu [dst + off + 32], ymm8
vmovdqu [dst + off + 64 + 32], ymm9
vpxor ymm10, [src + off + 64*2 + 32]
vpxor ymm11, [src + off + 64*3 + 32]
vmovdqu [dst + off + 64*2 + 32], ymm10
vmovdqu [dst + off + 64*3 + 32], ymm11
vpxor ymm12, [src + off + 64*4 + 32]
vpxor ymm13, [src + off + 64*5 + 32]
vmovdqu [dst + off + 64*4 + 32], ymm12
vmovdqu [dst + off + 64*5 + 32], ymm13
vpxor ymm14, [src + off + 64*6 + 32]
vpxor ymm15, [src + off + 64*7 + 32]
vmovdqu [dst + off + 64*6 + 32], ymm14
vmovdqu [dst + off + 64*7 + 32], ymm15
; Update remaining length
sub len, 64*8
add off, 64*8
add blk_cnt, 8
; Update counter values
vmovdqa ymm12, [rsp + 32*12]
vpaddd ymm12, [rel dword_8]
vmovdqa [rsp + 32*12], ymm12
cmp len, 64*8
jae start_loop_ks
exit_loop_ks:
; Check if there are no more bytes to encrypt
or len, len
jz no_partial_block_ks
cmp len, 64*4
ja more_than_4_blocks_left_ks
cmp len, 64*2
ja more_than_2_blocks_left_ks
;; up to 2 blocks left
; Get last block counter dividing offset by 64
PREPARE_NEXT_STATES_2_TO_4 ymm4, ymm5, ymm6, ymm7, none, \
ymm8, ymm9, blk_cnt, iv, keys, 2
GENERATE_256_KS ymm0, ymm1, ymm8, ymm9, none, none, none, none, \
ymm4, ymm5, ymm6, ymm7, none, ymm10, 2
cmp len, 64*2
jbe less_than_2_full_blocks_ks
; XOR next 128 bytes
vpxor ymm8, [src + off]
vpxor ymm9, [src + off + 32]
vmovdqu [dst + off], ymm8
vmovdqu [dst + off + 32], ymm9
vpxor ymm10, [src + off + 32*2]
vpxor ymm11, [src + off + 32*3]
vmovdqu [dst + off + 32*2], ymm10
vmovdqu [dst + off + 32*3], ymm11
add blk_cnt, 2
jmp no_partial_block_ks
more_than_2_blocks_left_ks:
; Get last block counter dividing offset by 64
PREPARE_NEXT_STATES_2_TO_4 ymm4, ymm5, ymm6, ymm7, ymm12, \
ymm8, ymm9, blk_cnt, iv, keys, 4
GENERATE_256_KS ymm0, ymm1, ymm8, ymm9, ymm2, ymm3, ymm10, ymm11, \
ymm4, ymm5, ymm6, ymm7, ymm12, ymm13, 4
cmp len, 64*4
jb less_than_4_full_blocks_ks
; XOR next 256 bytes
vpxor ymm0, [src + off]
vpxor ymm8, [src + off + 32]
vmovdqu [dst + off], ymm0
vmovdqu [dst + off + 32], ymm8
vpxor ymm1, [src + off + 32*2]
vpxor ymm9, [src + off + 32*3]
vmovdqu [dst + off + 32*2], ymm1
vmovdqu [dst + off + 32*3], ymm9
vpxor ymm2, [src + off + 32*4]
vpxor ymm10, [src + off + 32*5]
vmovdqu [dst + off + 32*4], ymm2
vmovdqu [dst + off + 32*5], ymm10
vpxor ymm3, [src + off + 32*6]
vpxor ymm11, [src + off + 32*7]
vmovdqu [dst + off + 32*6], ymm3
vmovdqu [dst + off + 32*7], ymm11
add blk_cnt, 4
jmp no_partial_block_ks
more_than_4_blocks_left_ks:
; Generate 512 bytes of keystream
GENERATE_512_KS ymm0, ymm1, ymm2, ymm3, ymm4, ymm5, ymm6, ymm7, \
ymm8, ymm9, ymm10, ymm11, ymm12, ymm13, ymm14, ymm15
; Save registers to be used as temp registers
vmovdqa [rsp + _YMM_SAVE], ymm14
vmovdqa [rsp + _YMM_SAVE + 32], ymm15
; Transpose to get [64*I : 64*I + 31] (I = 0-7) bytes of KS
TRANSPOSE8_U32 ymm0, ymm1, ymm2, ymm3, ymm4, ymm5, ymm6, ymm7, ymm14, ymm15
; Restore registers and save another two registers to be used as temp registers
vmovdqa ymm14, [rsp + _YMM_SAVE]
vmovdqa ymm15, [rsp + _YMM_SAVE + 32]
vmovdqa [rsp + _YMM_SAVE], ymm0
vmovdqa [rsp + _YMM_SAVE + 32], ymm1
; Transpose to get [64*I + 32 : 64*I + 63] (I = 0-7) bytes of KS
TRANSPOSE8_U32 ymm8, ymm9, ymm10, ymm11, ymm12, ymm13, ymm14, ymm15, ymm0, ymm1
; Restore registers
vmovdqa ymm0, [rsp + _YMM_SAVE]
vmovdqa ymm1, [rsp + _YMM_SAVE + 32]
; XOR next 256 bytes
vpxor ymm0, [src + off]
vpxor ymm8, [src + off + 32]
vmovdqu [dst + off], ymm0
vmovdqu [dst + off + 32], ymm8
vpxor ymm1, [src + off + 32*2]
vpxor ymm9, [src + off + 32*3]
vmovdqu [dst + off + 32*2], ymm1
vmovdqu [dst + off + 32*3], ymm9
vpxor ymm2, [src + off + 32*4]
vpxor ymm10, [src + off + 32*5]
vmovdqu [dst + off + 32*4], ymm2
vmovdqu [dst + off + 32*5], ymm10
vpxor ymm3, [src + off + 32*6]
vpxor ymm11, [src + off + 32*7]
vmovdqu [dst + off + 32*6], ymm3
vmovdqu [dst + off + 32*7], ymm11
; Update remaining length
sub len, 64*4
add off, 64*4
add blk_cnt, 4
or len, len
jz no_partial_block_ks
; Move last 256 bytes of KS to registers YMM0-3,YMM8-11
vmovdqa ymm0, ymm4
vmovdqa ymm1, ymm5
vmovdqa ymm2, ymm6
vmovdqa ymm3, ymm7
vmovdqa ymm8, ymm12
vmovdqa ymm9, ymm13
vmovdqa ymm10, ymm14
vmovdqa ymm11, ymm15
cmp len, 64*2
jb less_than_2_full_blocks_ks
less_than_4_full_blocks_ks:
; XOR next 128 bytes
vpxor ymm0, [src + off]
vpxor ymm8, [src + off + 32]
vmovdqu [dst + off], ymm0
vmovdqu [dst + off + 32], ymm8
vpxor ymm1, [src + off + 32*2]
vpxor ymm9, [src + off + 32*3]
vmovdqu [dst + off + 32*2], ymm1
vmovdqu [dst + off + 32*3], ymm9
; Update remaining length
sub len, 64*2
add off, 64*2
add blk_cnt, 2
or len, len
jz no_partial_block_ks
; Move last 128 bytes of KS to registers YMM0-1,YMM8-9
vmovdqa ymm0, ymm2
vmovdqa ymm1, ymm3
vmovdqa ymm8, ymm10
vmovdqa ymm9, ymm11
less_than_2_full_blocks_ks:
cmp len, 64
jb less_than_1_full_block_ks
; XOR next 64 bytes
vpxor ymm0, [src + off]
vpxor ymm8, [src + off + 32]
vmovdqu [dst + off], ymm0
vmovdqu [dst + off + 32], ymm8
; Update remaining length
sub len, 64
add off, 64
inc blk_cnt
or len, len
jz no_partial_block_ks
; Move last 64 bytes of KS to registers YMM0,YMM8
vmovdqa ymm0, ymm1
vmovdqa ymm8, ymm9
less_than_1_full_block_ks:
; Preserve len
mov tmp5, len
ENCRYPT_0B_64B src, dst, len, off, ymm0, ymm8, \
ymm1, ymm2, tmp, tmp2
inc blk_cnt
; Save last 64-byte block of keystream,
; in case it is needed in next segments
vmovdqu [prev_ks], ymm0
vmovdqu [prev_ks + 32], ymm8
; Update remain number of KS bytes
mov tmp, 64
sub tmp, tmp5
mov [ctx + RemainKsBytes], tmp
no_partial_block_ks:
endbranch64
mov [ctx + LastBlkCount], blk_cnt
%ifdef SAFE_DATA
vpxor ymm0, ymm0
; Clear stack frame
%assign i 0
%rep 16
vmovdqa [rsp + _STATE + 32*i], ymm0
%assign i (i + 1)
%endrep
vmovdqa [rsp + _YMM_SAVE], ymm0
vmovdqa [rsp + _YMM_SAVE + 32], ymm0
%endif
mov r12, [rsp + _GP_SAVE]
mov r13, [rsp + _GP_SAVE + 8]
mov r14, [rsp + _GP_SAVE + 16]
mov r15, [rsp + _GP_SAVE + 24]
mov rbx, [rsp + _GP_SAVE + 32]
mov rbp, [rsp + _GP_SAVE + 40]
%ifndef LINUX
mov rdi, [rsp + _GP_SAVE + 48]
%endif
mov rsp, [rsp + _RSP_SAVE]
exit_ks:
clear_all_ymms_asm
ret
%ifdef LINUX
section .note.GNU-stack noalloc noexec nowrite progbits
%endif
|
.global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r14
push %r9
push %rdi
push %rdx
push %rsi
// Store
lea addresses_RW+0x15cf4, %r14
nop
nop
nop
inc %r9
movw $0x5152, (%r14)
nop
nop
add $2363, %rdi
// Store
lea addresses_normal+0xbb74, %r14
nop
cmp $41803, %r11
mov $0x5152535455565758, %rdx
movq %rdx, %xmm7
vmovups %ymm7, (%r14)
nop
xor $14524, %rsi
// Store
lea addresses_UC+0x7574, %r11
nop
nop
nop
nop
xor $24764, %r12
movl $0x51525354, (%r11)
nop
nop
xor %r11, %r11
// Store
lea addresses_UC+0xa4ec, %r14
nop
nop
nop
nop
nop
and %rdx, %rdx
mov $0x5152535455565758, %r12
movq %r12, (%r14)
nop
nop
nop
nop
sub $64152, %r11
// Store
lea addresses_D+0x1c05c, %r9
nop
add $16560, %r12
movw $0x5152, (%r9)
nop
nop
nop
inc %rdi
// Store
mov $0x95f, %r11
nop
nop
nop
nop
nop
sub $41484, %rdi
movl $0x51525354, (%r11)
nop
nop
nop
nop
add %r14, %r14
// Store
lea addresses_D+0x145f4, %r14
nop
nop
nop
xor %rsi, %rsi
movw $0x5152, (%r14)
nop
nop
nop
nop
xor $36804, %rdi
// Faulty Load
lea addresses_normal+0x90f4, %r11
clflush (%r11)
nop
nop
nop
nop
nop
cmp $19781, %r9
vmovups (%r11), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $1, %xmm5, %rsi
lea oracles, %rdi
and $0xff, %rsi
shlq $12, %rsi
mov (%rdi,%rsi,1), %rsi
pop %rsi
pop %rdx
pop %rdi
pop %r9
pop %r14
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 10, 'same': False, 'type': 'addresses_RW'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 7, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 6, 'same': False, 'type': 'addresses_UC'}, 'OP': 'STOR'}
{'dst': {'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 3, 'same': False, 'type': 'addresses_UC'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 1, 'same': False, 'type': 'addresses_D'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_P'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 8, 'same': False, 'type': 'addresses_D'}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': True, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'34': 34}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
; A059502: a(n) = (3*n*F(2n-1) + (3-n)*F(2n))/5 where F() = Fibonacci numbers A000045.
; 0,1,3,9,27,80,234,677,1941,5523,15615,43906,122868,342409,950727,2631165,7260579,19982612,54865566,150316973,411015705,1121818311,3056773383,8316416134,22593883752,61301547025,166118284299,449639574897,1215751720491,3283883157848,8861749186770,23892651132341,64364212966173,173252727304059,466004178803727,1252537699142410,3364332378871644,9030851928181657,24226677417552591,64954149869404773,174052226813568435,466146924895091996,1247805276220175238,3338574694487045309,8928419451057327777
lpb $0
sub $0,1
mov $2,$0
max $2,0
seq $2,94864 ; a(0)=1, a(1)=2, a(2)=6, a(3)=18; for n >= 4, a(n) = 6*a(n-1) - 11*a(n-2) + 6*a(n-3) - a(n-4).
add $1,$2
lpe
mov $0,$1
|
##############################################
# Fall 2015, CIS 314 Computer Organization #
# Major Class Project #
##############################################
# This tests for function calls #############
# By calculating (a*b) , (a* (b-1)), ...(a*1)
#############################################
# Setting the stack pointer #
addi $sp, $0, 256
#############################
add $t0, $0, $0
addi $t1, $0, 6 #a= 6
addi $t2, $0, 5 #b= 5
addi $sp, $sp, -4
sw $ra, 0($sp)
loop: add $a0, $t1, $0 #Passing of the 2 arguments
add $a1, $t2, $0
jal product
add $t3, $0, $v0 #Result return
sw $t3, 24($t0)
addi $t2, $t2, -1
addi $t0, $t0, 4
bne $t2, $0, loop
lw $ra, 0($sp)
addi $sp, $sp, 4
j end
# The function
product: addi $sp, $sp, -4
sw $ra, 0($sp)
mult $v0, $a0, $a1
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
end:
|
//=================================================================================================
/*!
// \file src/mathtest/dmatdvecmult/M3x3aVDa.cpp
// \brief Source file for the M3x3aVDa dense matrix/dense vector multiplication math test
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/StaticMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdvecmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'M3x3aVDa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Matrix type definitions
using M3x3a = blaze::StaticMatrix<TypeA,3UL,3UL>;
using VDa = blaze::DynamicVector<TypeA>;
// Creator type definitions
using CM3x3a = blazetest::Creator<M3x3a>;
using CVDa = blazetest::Creator<VDa>;
// Running the tests
RUN_DMATDVECMULT_OPERATION_TEST( CM3x3a(), CVDa( 3UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense vector multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
; A026587: a(n) = T(n, n-2), T given by A026584. Also a(n) = number of integer strings s(0),...,s(n) counted by T, such that s(n)=2.
; Submitted by Jamie Morken(w1)
; 1,1,5,9,28,62,167,399,1024,2518,6359,15819,39759,99427,249699,626203,1573524,3953446,9943905,25019005,62994733,158680545,399936573,1008438757,2543992514,6420413940,16210331727,40943722115,103453402718,261489463036,661164765879,1672259390975,4230874777682,10707374650428,27105456280491,68635052760575,173838468040879,440404536471699,1115987495619427,2828553479946699,7170725839251598,18182426456794524,46113396476943241,116973011089058085,296773029762031990,753078887018468208,1911309537927897841
mov $3,$0
mov $5,$0
lpb $5
mov $0,$3
sub $5,1
sub $0,$5
mov $1,$0
add $1,$0
add $1,2
bin $1,$0
mov $2,$5
bin $2,$0
mul $1,$2
add $4,$1
lpe
mov $0,$4
add $0,1
|
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main() {
ll t;
cin >> t;
while (t--) {
ll n;
cin >> n;
ll a[n];
ll b[n];
for (ll i = 0; i < n; i++) {
cin >> a[i];
b[i] = 0;
}
for (ll i = 0; i < n; i++) {
bool swap = false;
for (ll j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
//swap
swap = true;
ll temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
//dir
temp = b[j + 1];
b[j + 1] = (b[j] == 1) ? 0 : 1;
b[j] = (temp == 1) ? 0 : 1;
}
}
if (!swap) break;
}
bool flag = true;
for (int i = 0; i < n; i++) {
if (b[i]) flag = false;
}
if (flag) {
cout << "YES\n";
} else {
cout << "NO\n";
}
}
return 0;
} |
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/pybind/imperative.h"
#include <Python.h>
#include <pybind11/chrono.h>
#include <pybind11/complex.h>
#include <pybind11/functional.h>
#include <pybind11/stl.h>
#include <algorithm>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "paddle/fluid/imperative/all_reduce.h"
#include "paddle/fluid/imperative/amp_auto_cast.h"
#include "paddle/fluid/imperative/basic_engine.h"
#include "paddle/fluid/imperative/bkcl_context.h"
#include "paddle/fluid/imperative/data_loader.h"
#include "paddle/fluid/imperative/hooks.h"
#include "paddle/fluid/imperative/layer.h"
#include "paddle/fluid/imperative/nccl_context.h"
#include "paddle/fluid/imperative/partial_grad_engine.h"
#include "paddle/fluid/imperative/profiler.h"
#include "paddle/fluid/imperative/py_layer_fwd.h"
#include "paddle/fluid/imperative/reducer.h"
#include "paddle/fluid/imperative/tracer.h"
#include "paddle/fluid/imperative/type_defs.h"
#include "paddle/fluid/memory/allocation/mmap_allocator.h"
#include "paddle/fluid/pybind/op_function.h"
#include "paddle/fluid/pybind/pybind_boost_headers.h"
#include "paddle/fluid/pybind/tensor_py.h"
namespace paddle {
namespace pybind {
namespace py = ::pybind11;
class Layer : public imperative::Layer {
public:
using imperative::Layer::Layer; // Inherit constructors
std::vector<std::shared_ptr<imperative::VarBase>> Forward(
const std::vector<std::shared_ptr<imperative::VarBase>> &inputs)
override {
PYBIND11_OVERLOAD(std::vector<std::shared_ptr<imperative::VarBase>>, Layer,
Forward, inputs); // NOLINT
}
};
template <typename T>
static T PyObjectCast(PyObject *obj) {
try {
return py::cast<T>(py::handle(obj));
} catch (py::cast_error &) {
PADDLE_THROW(platform::errors::InvalidArgument(
"Python object is not type of %s", typeid(T).name()));
}
}
class PyVariableWrapperHook : public imperative::VariableWrapperHook {
public:
explicit PyVariableWrapperHook(PyObject *func) : py_func_(func) {
Py_INCREF(py_func_);
}
~PyVariableWrapperHook() {
py::gil_scoped_acquire gil;
Py_DECREF(py_func_);
}
std::shared_ptr<imperative::VariableWrapper> operator()(
const std::shared_ptr<imperative::VariableWrapper> &var) override {
py::gil_scoped_acquire gil;
VLOG(3) << "Call PyVariableWrapperHook for var " << var->Name();
// 1. unpack temp VarBase from VariableWrapper
std::shared_ptr<imperative::VarBase> tmp_varbase =
std::make_shared<imperative::VarBase>(var);
// 2. call hook and return
PyObject *res = nullptr;
try {
res = PyObject_CallFunctionObjArgs(py_func_, py::cast(tmp_varbase).ptr(),
nullptr);
} catch (platform::EnforceNotMet &e) {
throw std::move(e);
} catch (std::exception &e) {
PADDLE_THROW(platform::errors::Unavailable(
"Hook function of Tensor raises an exception: %s.", e.what()));
} catch (...) {
PADDLE_THROW(platform::errors::Fatal(
"Hook function of Tensor raises an unknown exception."));
}
PADDLE_ENFORCE_NOT_NULL(res,
platform::errors::Unavailable(
"Hook function of Tensor return a nullptr."));
if (res == Py_None) {
return var;
}
return PyObjectCast<std::shared_ptr<imperative::VarBase>>(res)->SharedVar();
}
private:
PyObject *py_func_;
};
static const platform::Place PyObjectToPlace(const py::object &place_obj) {
if (py::isinstance<platform::CPUPlace>(place_obj)) {
return place_obj.cast<platform::CPUPlace>();
} else if (py::isinstance<platform::CUDAPlace>(place_obj)) {
return place_obj.cast<platform::CUDAPlace>();
} else if (py::isinstance<platform::XPUPlace>(place_obj)) {
return place_obj.cast<platform::XPUPlace>();
} else if (py::isinstance<platform::CUDAPinnedPlace>(place_obj)) {
return place_obj.cast<platform::CUDAPinnedPlace>();
} else if (py::isinstance<platform::Place>(place_obj)) {
return place_obj.cast<platform::Place>();
} else {
PADDLE_THROW(platform::errors::InvalidArgument(
"Place should be one of "
"Place/CPUPlace/XPUPlace/CUDAPlace/CUDAPinnedPlace"));
}
}
static void InitTensorForVarBase(imperative::VarBase *self,
const py::array &array,
const platform::Place place,
bool persistable = false,
bool zero_copy = false, std::string name = "",
int stop_gradient = -1) {
if (name == "") {
name =
imperative::GetCurrentTracer()->GenerateUniqueName("generated_tensor");
}
VLOG(5) << "Init Tensor as: / name: " << name
<< " / persistable: " << persistable << " / zero_copy: " << zero_copy
<< " / stop_gradient: " << stop_gradient;
new (self) imperative::VarBase(name);
auto *tensor = self->MutableVar()->GetMutable<framework::LoDTensor>();
if (platform::is_cpu_place(place)) {
SetTensorFromPyArray<platform::CPUPlace>(
tensor, array, BOOST_GET_CONST(platform::CPUPlace, place), zero_copy);
} else if (platform::is_xpu_place(place)) {
SetTensorFromPyArray<platform::XPUPlace>(
tensor, array, BOOST_GET_CONST(platform::XPUPlace, place), zero_copy);
} else if (platform::is_gpu_place(place)) {
SetTensorFromPyArray<platform::CUDAPlace>(
tensor, array, BOOST_GET_CONST(platform::CUDAPlace, place), zero_copy);
} else if (platform::is_cuda_pinned_place(place)) {
SetTensorFromPyArray<platform::CUDAPinnedPlace>(
tensor, array, BOOST_GET_CONST(platform::CUDAPinnedPlace, place),
zero_copy);
} else {
PADDLE_THROW(platform::errors::InvalidArgument(
"Place should be one of CPUPlace/XPUPlace/CUDAPlace/CUDAPinnedPlace"));
}
if (stop_gradient != -1) {
self->SetOverridedStopGradient(stop_gradient);
}
self->SetPersistable(persistable);
self->SetType(framework::proto::VarType::LOD_TENSOR);
self->SetDataType(tensor->type());
}
static void InitVarBaseFromNumpyWithKwargs(imperative::VarBase *self,
const py::kwargs &kwargs) {
VLOG(4) << "Init VarBase from kwargs: ";
PADDLE_ENFORCE_EQ(
kwargs.contains("value"), true,
platform::errors::NotFound(
"The kwargs used to create Varbase misses argument: value"));
auto persistable = kwargs.contains("persistable")
? kwargs["persistable"].cast<bool>()
: false;
auto array = kwargs.contains("value") ? kwargs["value"].cast<py::array>()
: py::array();
auto zero_copy =
kwargs.contains("zero_copy") ? kwargs["zero_copy"].cast<bool>() : false;
auto name = kwargs.contains("name") ? kwargs["name"].cast<std::string>() : "";
auto stop_gradient = kwargs.contains("stop_gradient")
? kwargs["stop_gradient"].cast<int>()
: -1;
auto default_place = imperative::GetCurrentTracer()->ExpectedPlace();
auto place = kwargs.contains("place") ? PyObjectToPlace(kwargs["place"])
: default_place;
InitTensorForVarBase(self, array, place, persistable, zero_copy, name,
stop_gradient);
}
template <typename P>
static void InitVarBaseFromNumpyWithArg(imperative::VarBase *self,
const py::array &array, const P &place,
bool persistable = false,
bool zero_copy = false,
std::string name = "",
int stop_gradient = -1) {
VLOG(4) << "Init VarBase from Arg: ";
// 0: self, 1: value, 2: place, 3: persistable, 4: zero_copy, 5: name , 6:
// stop_gradient
if (name == "") {
name =
imperative::GetCurrentTracer()->GenerateUniqueName("generated_tensor");
}
VLOG(5) << "Init Tensor as: / name: " << name
<< " / persistable: " << persistable << " / zero_copy: " << zero_copy
<< " / stop_gradient: " << stop_gradient << " / at " << place;
new (self) imperative::VarBase(name);
self->SetPersistable(persistable);
auto *tensor = self->MutableVar()->GetMutable<framework::LoDTensor>();
if (stop_gradient != -1) {
self->SetOverridedStopGradient(stop_gradient);
}
SetTensorFromPyArray<P>(tensor, array, place, zero_copy);
self->SetType(framework::proto::VarType::LOD_TENSOR);
self->SetDataType(tensor->type());
}
static void InitVarBaseFromNumpyWithArgDefault(imperative::VarBase *self,
const py::array &array) {
auto place = imperative::GetCurrentTracer()->ExpectedPlace();
VLOG(4) << "Init VarBase from numpy at " << place;
InitTensorForVarBase(self, array, place);
}
static void InitVarBaseFromTensorWithArgDefault(
imperative::VarBase *self, const framework::LoDTensor &tensor) {
VLOG(4) << "Init VarBase";
auto place = imperative::GetCurrentTracer()->ExpectedPlace();
new (self) imperative::VarBase(
imperative::GetCurrentTracer()->GenerateUniqueName("generated_tensor"));
self->SetPersistable(false);
self->SetType(framework::proto::VarType::LOD_TENSOR);
self->SetDataType(tensor.type());
auto *new_tensor = self->MutableVar()->GetMutable<framework::LoDTensor>();
// Same place,share data directly
if (place == tensor.place()) {
new_tensor->ShareDataWith(tensor);
VLOG(4) << "Same place, do ShareDataWith";
} else {
framework::TensorCopy(tensor, place, new_tensor);
VLOG(4) << "Different place, do TensorCopy";
}
}
static std::string GetTypeName(const imperative::VarBase &var) {
if (var.Type() == framework::proto::VarType::RAW) {
return "RAW";
} else if (!var.Var().IsInitialized()) {
return "nullptr";
} else {
return framework::ToTypeName(var.Var().Type());
}
}
using PyNameVarBaseMap = std::unordered_map<std::string, py::handle>;
// NOTE(zjl): py::handle is a very light wrapper of PyObject *.
// Unlike py::object, py::handle does not change reference count of PyObject *.
static std::vector<std::shared_ptr<imperative::VarBase>>
GetVarBaseListFromPyHandle(const py::handle &handle) {
PyObject *py_obj = handle.ptr(); // get underlying PyObject
// Python None is not nullptr in C++!
if (!py_obj || py_obj == Py_None) {
return {};
}
std::vector<std::shared_ptr<imperative::VarBase>> result;
if (PyList_Check(py_obj)) { // List of VarBase
size_t len = PyList_GET_SIZE(py_obj);
result.reserve(len);
for (size_t i = 0; i < len; ++i) {
PyObject *py_ivar = PyList_GET_ITEM(py_obj, i);
PADDLE_ENFORCE_NOT_NULL(
py_ivar, platform::errors::InvalidArgument("Python Object is NULL"));
result.emplace_back(
PyObjectCast<std::shared_ptr<imperative::VarBase>>(py_ivar));
}
} else if (PyTuple_Check(py_obj)) { // Tuple of VarBase
size_t len = PyTuple_GET_SIZE(py_obj);
result.reserve(len);
for (size_t i = 0; i < len; ++i) {
PyObject *py_ivar = PyTuple_GET_ITEM(py_obj, i);
PADDLE_ENFORCE_NOT_NULL(
py_ivar, platform::errors::InvalidArgument("Python Object is NULL"));
result.emplace_back(
PyObjectCast<std::shared_ptr<imperative::VarBase>>(py_ivar));
}
} else { // VarBase
result.emplace_back(
PyObjectCast<std::shared_ptr<imperative::VarBase>>(py_obj));
}
return result;
}
static imperative::NameVarBaseMap ConvertToNameVarBaseMap(
const PyNameVarBaseMap &map) {
imperative::NameVarBaseMap result;
for (auto &pair : map) {
auto var_vec = GetVarBaseListFromPyHandle(pair.second);
if (!var_vec.empty()) {
result.emplace(pair.first, std::move(var_vec));
}
}
PADDLE_ENFORCE_EQ(
PyErr_Occurred(), nullptr,
platform::errors::InvalidArgument(py::str(py::handle(PyErr_Occurred()))));
return result;
}
static bool PyCheckInteger(PyObject *obj) {
#if PY_VERSION_HEX < 0x03000000
return (PyLong_Check(obj) || PyInt_Check(obj)) && !PyBool_Check(obj);
#else
return PyLong_Check(obj) && !PyBool_Check(obj);
#endif
}
// NOTE(zhiqiu): Revised version of PySlice_GetIndices. From:
// https://github.com/python/cpython/blob/8d21aa21f2cbc6d50aab3f420bb23be1d081dac4/Objects/sliceobject.c#L103
// Original PySlice_GetIndices return wrong result when
// slice_item contains long int, such as arr[:180L].
// NOT sure why this happens !!!
// Besides, PySlice_GetIndices cannot raise error when float in slice item.
// So, I make a revised version of PySlice_GetIndices, named to
// _PySlice_GetIndices. Try to use _PySlice_Unpack which is more robust than
// PySlice_GetIndices in the future.
static int _PySlice_GetIndices(PySliceObject *r, Py_ssize_t length,
Py_ssize_t *start, Py_ssize_t *stop,
Py_ssize_t *step) {
/* XXX support long ints */
if (r->step == Py_None) {
*step = 1;
} else {
if (PyCheckInteger(r->step)) {
*step = PyLong_AsLong(r->step);
} else {
PADDLE_THROW(platform::errors::InvalidArgument(
"Currently, VarBase.__getitem__() only allows None or integers in "
"slice item, but received %s.",
std::string(Py_TYPE(r->step)->tp_name)));
}
}
if (r->start == Py_None) {
*start = *step < 0 ? length - 1 : 0;
} else {
if (PyCheckInteger(r->start)) {
*start = PyLong_AsLong(r->start);
} else {
PADDLE_THROW(platform::errors::InvalidArgument(
"Currently, VarBase.__getitem__() only allows None or integers in "
"slice item, but received %s.",
std::string(Py_TYPE(r->start)->tp_name)));
}
if (*start < 0) *start += length;
*start = std::max(*start, static_cast<Py_ssize_t>(0));
}
if (r->stop == Py_None) {
*stop = *step < 0 ? -1 : length;
} else {
if (PyCheckInteger(r->stop)) {
*stop = PyLong_AsLong(r->stop);
} else {
PADDLE_THROW(platform::errors::InvalidArgument(
"Currently, VarBase.__getitem__() only allows None or integers in "
"slice item, but received %s.",
std::string(Py_TYPE(r->stop)->tp_name)));
}
if (*stop < 0) *stop += length;
*stop = std::min(*stop, length);
}
if (*stop > length) return -1;
if (*start >= length) return -1;
if (*step == 0) return -1;
return 0;
}
static void ParseIndexingSlice(framework::LoDTensor *tensor, PyObject *_index,
std::vector<int> *slice_axes,
std::vector<int> *slice_starts,
std::vector<int> *slice_ends,
std::vector<int> *slice_strides,
std::vector<int> *decrease_axis,
std::vector<int> *infer_flags) {
// We allow indexing by Integers, Slices, and tuples of those
// types.
// Ellipsis and None are not supported yet.
// wrap to tuple
PyObject *index = !PyTuple_Check(_index) ? PyTuple_Pack(1, _index) : _index;
PADDLE_ENFORCE_EQ(
tensor->IsInitialized(), true,
platform::errors::InvalidArgument("tensor has not been initialized"));
const auto &shape = tensor->dims();
const int rank = shape.size();
const int size = PyTuple_GET_SIZE(index);
PADDLE_ENFORCE_EQ(
size <= rank, true,
platform::errors::InvalidArgument(
"too many indices (%d) for tensor of dimension %d", size, rank));
for (int dim = 0; dim < size; ++dim) {
PyObject *slice_item = PyTuple_GetItem(index, dim);
PADDLE_ENFORCE_EQ(PyCheckInteger(slice_item) || PySlice_Check(slice_item),
true,
platform::errors::InvalidArgument(
"Currently, VarBase.__getitem__() only allows "
"indexing by Integers, Slices, and tuples of "
"these types, but received %s in %dth slice item",
std::string(Py_TYPE(slice_item)->tp_name), dim + 1));
infer_flags->push_back(1);
int dim_len = shape[dim];
if (PyCheckInteger(slice_item)) {
// integer, PyLong_AsLong supports both int and long
int start = static_cast<int>(PyLong_AsLong(slice_item));
auto s_t = start;
start = start < 0 ? start + dim_len : start;
if (start >= dim_len || start < 0) {
std::string str_error_message =
"The starting index " + std::to_string(s_t) +
" of slice is out of bounds in tensor " + std::to_string(dim) +
"-th axis, it shound be in the range of [" +
std::to_string(-dim_len) + ", " + std::to_string(dim_len) + ")";
// py::index_error is corresponding to IndexError in Python
// Used to indicate out of bounds access in __getitem__, __setitem__
throw py::index_error(str_error_message);
}
slice_axes->push_back(dim);
slice_starts->push_back(start);
slice_ends->push_back(start + 1);
slice_strides->push_back(1);
decrease_axis->push_back(dim);
} else {
// slice item
Py_ssize_t start, end, step;
PySliceObject *p = reinterpret_cast<PySliceObject *>(slice_item);
_PySlice_GetIndices(p, dim_len, &start, &end, &step);
// :: or : or 0:dim_len:1
if (start == 0 && end == dim_len && step == 1) {
continue;
}
slice_axes->push_back(dim);
slice_starts->push_back(start);
slice_ends->push_back(end);
slice_strides->push_back(step);
}
}
if (!PyTuple_Check(_index)) Py_DecRef(index);
}
// Bind Methods
void BindImperative(py::module *m_ptr) {
auto &m = *m_ptr;
BindOpFunctions(&m);
#ifndef _WIN32
// Dygraph DataLoader signal handler
m.def("_set_process_pids", [](int64_t key, py::object &obj) {
PADDLE_ENFORCE_EQ(
py::isinstance<py::tuple>(obj) || py::isinstance<py::list>(obj), true,
platform::errors::InvalidArgument(
"The subprocess ids set in DataLoader is illegal."
"Expected data type is tuple or list, but received %s",
obj.get_type()));
py::list pids = py::cast<py::list>(obj);
std::set<pid_t> pids_set = {};
for (size_t i = 0; i < pids.size(); i++) {
pids_set.insert(pids[i].cast<pid_t>());
}
imperative::SetLoadProcessPIDs(key, pids_set);
});
m.def("_erase_process_pids",
[](int64_t key) { imperative::EraseLoadProcessPIDs(key); });
m.def("_set_process_signal_handler",
[]() { imperative::SetLoadProcessSignalHandler(); });
m.def("_throw_error_if_process_failed",
[]() { imperative::ThrowErrorIfLoadProcessFailed(); });
// Dygraph DataLoader reader process & thread related functions
m.def(
"_convert_to_tensor_list",
[](py::object &obj) -> py::list {
// 0. input data check
PADDLE_ENFORCE(
py::isinstance<py::tuple>(obj) || py::isinstance<py::list>(obj),
platform::errors::InvalidArgument(
"The batch data read into DataLoader is illegal."
"Expected data type is tuple or list, but received %s",
obj.get_type()));
py::list batch = py::cast<py::list>(obj);
py::list tensors;
for (size_t i = 0; i < batch.size(); ++i) {
// 1. cast to python array
auto array = batch[i].cast<py::array>();
PADDLE_ENFORCE_NE(
string::Sprintf("%s", array.dtype()).compare("object"), 0,
platform::errors::InvalidArgument(
"Faild to convert input data to a regular ndarray.\n * "
"Usually this means the input data contains nested "
"lists with different lengths.\n * Check the reader "
"function passed to 'set_(sample/sample_list/batch)"
"_generator' to locate the data causes this issue."));
// 2. construcct LoDTensor
framework::LoDTensor t;
SetTensorFromPyArray<platform::CPUPlace>(&t, array,
platform::CPUPlace(), true);
// 3. allocate shared memory
void *data_ptr = t.data<void>();
size_t data_size = t.numel() * framework::SizeOfType(t.type());
auto shared_writer_holder =
memory::allocation::AllocateMemoryMapWriterAllocation(data_size);
// 4. maintain mmap fd set & backup ipc_name
const std::string &ipc_name = shared_writer_holder->ipc_name();
memory::allocation::MemoryMapFdSet::Instance().Insert(ipc_name);
// 5. copy data & reset holder
memory::Copy(platform::CPUPlace(), shared_writer_holder->ptr(),
platform::CPUPlace(), data_ptr, data_size);
t.ResetHolder(shared_writer_holder);
// 6. append to result list
tensors.append(t);
}
return tensors;
},
py::return_value_policy::take_ownership);
m.def("_array_to_share_memory_tensor",
[](py::object &obj) {
// 1. cast to python array
auto array = obj.cast<py::array>();
PADDLE_ENFORCE_NE(
string::Sprintf("%s", array.dtype()).compare("object"), 0,
platform::errors::InvalidArgument(
"Faild to convert input data to a regular ndarray.\n * "
"Usually this means the input data contains nested "
"lists with different lengths.\n * Check the reader "
"function passed to 'set_(sample/sample_list/batch)"
"_generator' to locate the data causes this issue."));
// 2. construcct LoDTensor
framework::LoDTensor t;
SetTensorFromPyArray<platform::CPUPlace>(&t, array,
platform::CPUPlace(), true);
// 3. allocate shared memory
void *data_ptr = t.data<void>();
size_t data_size = t.numel() * framework::SizeOfType(t.type());
auto shared_writer_holder =
memory::allocation::AllocateMemoryMapWriterAllocation(data_size);
// 4. maintain mmap fd set & backup ipc_name
const std::string &ipc_name = shared_writer_holder->ipc_name();
memory::allocation::MemoryMapFdSet::Instance().Insert(ipc_name);
// 5. copy data & reset holder
memory::Copy(platform::CPUPlace(), shared_writer_holder->ptr(),
platform::CPUPlace(), data_ptr, data_size);
t.ResetHolder(shared_writer_holder);
return t;
},
py::return_value_policy::take_ownership);
m.def("_remove_tensor_list_mmap_fds", [](py::list &tensor_list) {
for (size_t i = 0; i < tensor_list.size(); ++i) {
auto t = tensor_list[i].cast<framework::LoDTensor>();
auto *mmap_writer_allocation =
dynamic_cast<memory::allocation::MemoryMapWriterAllocation *>(
t.Holder().get());
PADDLE_ENFORCE_NOT_NULL(
mmap_writer_allocation,
platform::errors::NotFound("The shared memory of LoDTensor in "
"DataLoader's child process has been "
"released."));
memory::allocation::MemoryMapFdSet::Instance().Remove(
mmap_writer_allocation->ipc_name());
}
});
m.def("_cleanup_mmap_fds",
[]() { memory::allocation::MemoryMapFdSet::Instance().Clear(); });
#endif
m.def("start_imperative_gperf_profiler",
[]() { imperative::StartProfile(); });
m.def("stop_imperative_gperf_profiler", []() { imperative::StopProfile(); });
m.def("_is_dygraph_debug_enabled",
[]() { return imperative::IsDebugEnabled(); });
m.def("_dygraph_debug_level", []() { return imperative::GetDebugLevel(); });
m.def("_switch_tracer",
[](const std::shared_ptr<imperative::Tracer> &tracer) {
imperative::SetCurrentTracer(tracer);
});
py::class_<imperative::VarBase, std::shared_ptr<imperative::VarBase>>(
m, "VarBase", R"DOC()DOC")
.def_static("_alive_vars", &imperative::VarBase::AliveVarNames)
.def("__init__",
[](imperative::VarBase &self) {
std::string name =
imperative::GetCurrentTracer()->GenerateUniqueName(
"generated_tensor");
new (&self) imperative::VarBase(name);
})
.def("__init__",
[](imperative::VarBase &self, framework::proto::VarType::Type dtype,
const std::vector<int> &dims, const py::handle &name,
framework::proto::VarType::Type type, bool persistable) {
VLOG(4) << "Init VarBase";
std::string act_name = "";
if (!name.ptr() || name.ptr() == Py_None) {
act_name = imperative::GetCurrentTracer()->GenerateUniqueName(
"generated_tensor");
} else {
act_name = name.cast<std::string>();
}
new (&self) imperative::VarBase(act_name);
self.SetPersistable(persistable);
self.SetType(type);
self.SetDataType(dtype);
if (type == framework::proto::VarType::LOD_TENSOR) {
auto *tensor =
self.MutableVar()->GetMutable<framework::LoDTensor>();
tensor->Resize(framework::make_ddim(dims));
}
})
.def("__init__", &InitVarBaseFromNumpyWithArg<platform::CPUPlace>,
py::arg("value"), py::arg("place"), py::arg("persistable") = false,
py::arg("zero_copy") = false, py::arg("name") = "",
py::arg("stop_gradient") = -1)
.def("__init__", &InitVarBaseFromNumpyWithArg<platform::XPUPlace>,
py::arg("value"), py::arg("place"), py::arg("persistable") = false,
py::arg("zero_copy") = false, py::arg("name") = "",
py::arg("stop_gradient") = -1)
.def("__init__", &InitVarBaseFromNumpyWithArg<platform::CUDAPlace>,
py::arg("value"), py::arg("place"), py::arg("persistable") = false,
py::arg("zero_copy") = false, py::arg("name") = "",
py::arg("stop_gradient") = -1)
.def("__init__", &InitVarBaseFromNumpyWithArg<platform::CUDAPinnedPlace>,
py::arg("value"), py::arg("place"), py::arg("persistable") = false,
py::arg("zero_copy") = false, py::arg("name") = "",
py::arg("stop_gradient") = -1)
.def("__init__", &InitVarBaseFromNumpyWithArgDefault, py::arg("value"))
.def("__init__", &InitVarBaseFromTensorWithArgDefault, py::arg("tensor"))
.def("__init__", &InitVarBaseFromNumpyWithKwargs)
.def("__setitem__",
[](std::shared_ptr<imperative::VarBase> &self, py::handle _index,
py::object &value_obj) {
auto self_tensor =
self->MutableVar()->GetMutable<framework::LoDTensor>();
PyObject *index_ptr = !PyTuple_Check(_index.ptr())
? PyTuple_Pack(1, _index.ptr())
: _index.ptr();
// 1. Check argumnets
// 1.1 Check whether value obj is a tensor.
bool value_is_tensor = true;
bool parse_index = true;
if (py::isinstance<py::array>(value_obj) ||
py::isinstance<py::int_>(value_obj) ||
py::isinstance<py::float_>(value_obj)) {
value_is_tensor = false;
}
// 1.2 Check whether _index can be parsed.
const int size = PyTuple_GET_SIZE(index_ptr);
for (int dim = 0; dim < size; ++dim) {
PyObject *slice_item = PyTuple_GetItem(index_ptr, dim);
if (!(PyCheckInteger(slice_item) || PySlice_Check(slice_item))) {
parse_index = false;
break;
}
}
// 2. Call op set_value to speed up if the condition is met,
// otherwise call TensorToPyArray.
// TODO(liym27): Try not to call TensorToPyArray because it always
// copys data to cpu place, which reduces performance.
if (parse_index && value_is_tensor) {
std::vector<int> axes, starts, ends, steps, decrease_axes,
infer_flags;
ParseIndexingSlice(self_tensor, index_ptr, &axes, &starts, &ends,
&steps, &decrease_axes, &infer_flags);
framework::AttributeMap attrs = {
{"axes", axes},
{"starts", starts},
{"ends", ends},
{"steps", steps},
{"decrease_axes", decrease_axes}};
imperative::NameVarBaseMap ins = {{"Input", {self}}};
imperative::NameVarBaseMap outs = {{"Out", {self}}};
auto value_tensor =
value_obj.cast<std::shared_ptr<imperative::VarBase>>();
ins.insert({"ValueTensor", {value_tensor}});
const auto &tracer = imperative::GetCurrentTracer();
{
// Release gil and do tracing
py::gil_scoped_release release;
tracer->TraceOp("set_value", ins, outs, std::move(attrs));
}
} else {
auto self_numpy = TensorToPyArray(*self_tensor);
if (value_is_tensor) {
auto value =
value_obj.cast<std::shared_ptr<imperative::VarBase>>();
auto value_tensor =
value->MutableVar()->GetMutable<framework::LoDTensor>();
auto value_numpy = TensorToPyArray(*value_tensor);
self_numpy[_index] = value_numpy;
SetTensorFromPyArray(self_tensor, self_numpy,
self_tensor->place(), true);
} else {
auto value_numpy = value_obj;
self_numpy[_index] = value_numpy;
SetTensorFromPyArray(self_tensor, self_numpy,
self_tensor->place(), true);
}
}
// NOTE(liym27):
// Increase the version of VarBase self because __setitem__ is an
// inplace operator for the VarBase self.
self->BumpInplaceVersion();
})
.def("__getitem__",
[](std::shared_ptr<imperative::VarBase> &self, py::handle _index) {
std::vector<int> slice_axes, slice_starts, slice_ends,
slice_strides, decrease_axis, infer_flags;
auto tensor =
self->MutableVar()->GetMutable<framework::LoDTensor>();
ParseIndexingSlice(tensor, _index.ptr(), &slice_axes,
&slice_starts, &slice_ends, &slice_strides,
&decrease_axis, &infer_flags);
// release gil and do tracing
py::gil_scoped_release release;
const auto &tracer = imperative::GetCurrentTracer();
if (slice_axes.empty()) {
return self;
} else {
imperative::NameVarBaseMap ins = {{"Input", {self}}};
framework::AttributeMap attrs = {
{"axes", slice_axes},
{"starts", slice_starts},
{"ends", slice_ends},
{"infer_flags", infer_flags},
{"decrease_axis", decrease_axis}};
auto out = std::shared_ptr<imperative::VarBase>(
new imperative::VarBase(tracer->GenerateUniqueName()));
imperative::NameVarBaseMap outs = {{"Out", {out}}};
std::string op_type = "slice";
for (auto stride : slice_strides) {
if (stride != 1) {
op_type = "strided_slice";
attrs.insert({"strides", slice_strides});
attrs.erase("decrease_axis");
break;
}
}
tracer->TraceOp(op_type, ins, outs, std::move(attrs));
return out;
}
})
.def("_inplace_version",
[](imperative::VarBase &self) -> uint32_t {
const auto &var = self.MutableVar();
PADDLE_ENFORCE_EQ(
var->IsInitialized(), true,
platform::errors::InvalidArgument(
"Tensor of %s is Empty, please check if it has no data.",
self.Name()));
return var->CurrentInplaceVersion();
})
.def("_bump_inplace_version",
[](std::shared_ptr<imperative::VarBase> &self) {
// NOTE(liym27): _bump_inplace_version is only used for inplace
// operation
self->BumpInplaceVersion();
},
R"DOC(
**Notes**:
**This API is ONLY available in Dygraph mode.**
**This is a very low level API. Users should not use it directly. **
Bump the version whenever the Tensor is modified through an inplace operation.
)DOC")
.def("numpy",
[](imperative::VarBase &self) -> py::array {
const auto &tensor =
self.MutableVar()->Get<framework::LoDTensor>();
PADDLE_ENFORCE_EQ(
tensor.IsInitialized(), true,
platform::errors::InvalidArgument(
"Tensor of %s is Empty, please check if it has no data.",
self.Name()));
return TensorToPyArray(tensor, true);
},
R"DOC(
Returns a numpy array shows the value of current Tensor.
Returns:
ndarray: The numpy value of current Tensor.
Returns type:
ndarray: dtype is same as current Tensor
Examples:
.. code-block:: python
import paddle
import numpy as np
data = np.random.uniform(-1, 1, [30, 10, 32]).astype('float32')
linear = paddle.nn.Linear(32, 64)
data = paddle.to_tensor(data)
x = linear(data)
print(x.numpy())
)DOC")
.def("detach",
[](const imperative::VarBase
&self) -> std::shared_ptr<imperative::VarBase> {
PADDLE_ENFORCE_EQ(
self.Var().IsInitialized(), true,
platform::errors::InvalidArgument(
"Tensor %s has not been initialized!", self.Name()));
PADDLE_ENFORCE_EQ(
self.Var().IsType<framework::LoDTensor>() ||
self.Var().IsType<framework::SelectedRows>(),
true,
platform::errors::InvalidArgument(
"Type of Tensor[%s] must be LoDTensor or SelectedRows!",
self.Name()));
auto detach_var = std::make_shared<imperative::VarBase>(
true, "detach_" + self.Name());
detach_var->SetPersistable(self.Persistable());
detach_var->SetType(self.Type());
detach_var->SetDataType(self.DataType());
if (self.Var().IsType<framework::LoDTensor>()) {
const auto &origin_tensor =
self.Var().Get<framework::LoDTensor>();
PADDLE_ENFORCE_EQ(
origin_tensor.IsInitialized(), true,
platform::errors::InvalidArgument(
"Tensor %s has not been initialized!", self.Name()));
auto *detach_tensor =
detach_var->MutableVar()->GetMutable<framework::LoDTensor>();
detach_tensor->ShareDataWith(origin_tensor);
// NOTE(liym27): Call ShareInplaceVersionCounterWith to share the
// same TensorInplaceVersion, which is used to check whether
// inplace
// operations are correct.
detach_tensor->ShareInplaceVersionCounterWith(origin_tensor);
} else {
const auto &origin_selected_rows =
self.Var().Get<framework::SelectedRows>();
PADDLE_ENFORCE_EQ(
origin_selected_rows.value().IsInitialized(), true,
platform::errors::InvalidArgument(
"Tensor %s has not been initialized!", self.Name()));
auto *detach_selected_rows =
detach_var->MutableVar()
->GetMutable<framework::SelectedRows>();
detach_selected_rows->set_height(origin_selected_rows.height());
detach_selected_rows->set_rows(origin_selected_rows.rows());
detach_selected_rows->mutable_value()->ShareDataWith(
origin_selected_rows.value());
detach_selected_rows->mutable_value()
->ShareInplaceVersionCounterWith(
origin_selected_rows.value());
}
VLOG(3) << "The detached Tensor(" << detach_var->Name()
<< ") share data with " << self.Name();
return detach_var;
},
py::return_value_policy::take_ownership, R"DOC(
Returns a new Tensor, detached from the current graph.
It will share data with origin Tensor and always doesn't have a Tensor copy.
In addition, the detached Tensor doesn't provide gradient propagation.
Returns: The detached Tensor.
Examples:
.. code-block:: python
import paddle
x = paddle.to_tensor(1.0, stop_gradient=False)
detach_x = x.detach()
detach_x[:] = 10.0
print(x) # Tensor(shape=[1], dtype=float32, place=CPUPlace, stop_gradient=False,
# [10.])
y = x**2
y.backward()
print(x.grad) # [20.0]
print(detach_x.grad) # None, 'stop_gradient=True' by default
detach_x.stop_gradient = False # Set stop_gradient to be False, supported auto-grad
z = detach_x**3
z.backward()
print(x.grad) # [20.0], detach_x is detached from x's graph, not affect each other
print(detach_x.grad) # [300.0], detach_x has its own graph
# Due to sharing of data with origin Tensor, There are some unsafe operations:
y = 2 * x
detach_x[:] = 5.0
y.backward()
# It will raise Error:
# one of the variables needed for gradient computation has been modified by an inplace operation.
)DOC")
.def("clear_gradient", &imperative::VarBase::ClearGradient, R"DOC(
Only for Tensor that has gradient, normally we use this for Parameters since other temporary Tensor doesen't has gradient.
The Gradient of current Tensor will be set to ``0`` .
Returns: None
Examples:
.. code-block:: python
import paddle
input = paddle.uniform([10, 2])
linear = paddle.nn.Linear(2, 3)
out = linear(input)
out.backward()
print("Before clear_gradient, linear.weight.grad: {}".format(linear.weight.grad))
linear.weight.clear_gradient()
print("After clear_gradient, linear.weight.grad: {}".format(linear.weight.grad))
)DOC")
.def("clone",
[](std::shared_ptr<imperative::VarBase> &self) {
const auto &tensor = self->Var().Get<framework::LoDTensor>();
PADDLE_ENFORCE_EQ(
tensor.IsInitialized(), true,
platform::errors::InvalidArgument(
"%s has not been initialized", self->Name()));
auto tracer = imperative::GetCurrentTracer();
auto new_var = std::make_shared<imperative::VarBase>(
true, tracer->GenerateUniqueName(self->Name() + "_clone"));
framework::AttributeMap attrs;
imperative::NameVarBaseMap ins = {{"X", {self}}};
imperative::NameVarBaseMap outs = {{"Out", {new_var}}};
tracer->TraceOp("assign", ins, outs, attrs);
return new_var;
},
py::return_value_policy::copy, R"DOC(
Returns a new Tensor, which is clone of origin Tensor, and it remains in the current graph.
It will always have a Tensor copy.
Tn addition, the cloned Tensor provides gradient propagation.
Returns: The cloned Tensor.
Examples:
.. code-block:: python
import paddle
x = paddle.to_tensor(1.0, stop_gradient=False)
clone_x = x.clone()
y = clone_x**2
y.backward()
print(clone_x.stop_gradient) # False
print(clone_x.grad) # [2.0], support gradient propagation
print(x.stop_gradient) # False
print(x.grad) # [2.0], clone_x support gradient propagation for x
x = paddle.to_tensor(1.0)
clone_x = x.clone()
clone_x.stop_gradient = False
z = clone_x**3
z.backward()
print(clone_x.stop_gradient) # False
print(clone_x.grad) # [3.0], support gradient propagation
print(x.stop_gradient) # True
print(x.grad) # None
)DOC")
.def("_grad_name", &imperative::VarBase::GradVarName)
.def("_grad_value",
[](imperative::VarBase &self) {
return self.MutableGradVar()->Get<framework::LoDTensor>();
},
py::return_value_policy::reference)
.def("_set_grad_type",
[](imperative::VarBase &self, framework::proto::VarType::Type type) {
self.MutableGradVarBase()->SetType(type);
})
.def("_grad_ivar",
[](const imperative::VarBase &self) {
auto &grad_var = self.GradVarBase();
if (grad_var && grad_var->Var().IsInitialized()) {
auto *tensor =
grad_var->MutableVar()->IsType<framework::LoDTensor>()
? grad_var->MutableVar()
->GetMutable<framework::LoDTensor>()
: grad_var->MutableVar()
->GetMutable<framework::SelectedRows>()
->mutable_value();
if (tensor->IsInitialized()) {
return grad_var;
}
}
return std::shared_ptr<imperative::VarBase>(nullptr);
},
py::return_value_policy::copy)
.def("_set_grad_ivar",
[](imperative::VarBase &self, imperative::VarBase &grad) {
self.SetGradVarBase(grad);
})
.def("_is_sparse",
[](imperative::VarBase &self) {
return self.Var().IsType<framework::SelectedRows>();
})
.def("_allreduce",
[](imperative::VarBase &self,
const imperative::ParallelStrategy &strategy) {
if (strategy.nranks_ > 1) {
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
#if NCCL_VERSION_CODE >= 2212
imperative::AllReduce(self.Var(), self.MutableVar(), strategy);
#else
if (!self.Var().IsType<framework::SelectedRows>()) {
imperative::AllReduce(self.Var(), self.MutableVar(), strategy);
} else {
PADDLE_THROW(platform::errors::Unimplemented(
"Imperative SelectedRows allreduce is not supported when "
"paddle is compiled with NCCL verison lower than v2.2.12. "
"You can set is_sparse=False for the Layer containing "
"this argument, such as Embedding(is_sparse=False)."));
}
#endif // NCCL_VERSION_CODE
#else
PADDLE_THROW(platform::errors::Unimplemented(
"Imperative allreduce is not supported when paddle is "
"not compiled with NCCL."));
#endif // PADDLE_WITH_NCCL or PADDLE_WITH_RCCL
}
},
py::call_guard<py::gil_scoped_release>())
.def("_register_grad_hook",
[](imperative::VarBase &self, const py::handle &hook) {
PADDLE_ENFORCE_EQ(
!self.OverridedStopGradient() && self.HasGradVar(), true,
platform::errors::InvalidArgument(
"Cannot register gradient hook on a Tensor that stop "
"gradient or without gradient."));
return self.GradVarBase()->AddVariableWrapperHook(
std::make_shared<PyVariableWrapperHook>(hook.ptr()));
})
.def("_remove_grad_hook",
[](imperative::VarBase &self, int64_t hook_id) {
PADDLE_ENFORCE_EQ(
!self.OverridedStopGradient() && self.HasGradVar(), true,
platform::errors::InvalidArgument(
"Cannot remove gradient hook on a Tensor that stop "
"gradient or without gradient."));
return self.GradVarBase()->RemoveVariableWrapperHook(hook_id);
})
.def("_register_backward_hook",
[](imperative::VarBase &self, const py::handle &hook) {
PADDLE_ENFORCE_EQ(
self.IsLeaf(), true,
platform::errors::InvalidArgument(
"Only can register backward hook for leaf Tensor."));
PADDLE_ENFORCE_EQ(
!self.OverridedStopGradient() && self.HasGradVar(), true,
platform::errors::InvalidArgument(
"Cannot register backward hook on a Tensor that stop "
"gradient or without gradient."));
auto py_func = PyObjectCast<std::function<void()>>(hook.ptr());
self.GradVarBase()->AddVoidHook(
std::make_shared<std::function<void()>>(py_func));
},
R"DOC(
Registers a backward hook for current Tensor.
This hook will be called every time the gradient of current Tensor has been fully calculated.
There are two differences with `_register_grad_hook`:
1. This backward hook will be executed after the gradient accumulation completed across batchs,
but the hook registered by `_register_grad_hook` will be executed the gradient accumulation
completed in current batch.
2. This backward hook function should have the following signature:
hook() -> None
It requires no input and no return value.
Args:
hook(function): A backward hook to be registered for Tensor.gradient
Returns:
None
)DOC")
.def("cpu",
[](const std::shared_ptr<imperative::VarBase> &self) {
if (platform::is_cpu_place(self->Place())) {
return self;
} else {
auto new_var = self->NewVarBase(platform::CPUPlace(), true);
new_var->SetOverridedStopGradient(self->OverridedStopGradient());
return new_var;
}
},
R"DOC(
Returns a copy of this Tensor in CPU memory.
If this Tensor is already in CPU memory, then no copy is performed and the original Tensor is returned.
Examples:
.. code-block:: python
import paddle
x = paddle.to_tensor(1.0, place=paddle.CUDAPlace(0))
print(x.place) # CUDAPlace(0)
y = x.cpu()
print(y.place) # CPUPlace
)DOC")
.def("pin_memory",
[](const std::shared_ptr<imperative::VarBase> &self) {
#if !defined(PADDLE_WITH_CUDA) && !defined(PADDLE_WITH_HIP)
PADDLE_THROW(platform::errors::PermissionDenied(
"Cannot copy this Tensor to pinned memory in CPU version "
"Paddle, "
"Please recompile or reinstall Paddle with CUDA support."));
#endif
if (platform::is_cuda_pinned_place(self->Place())) {
return self;
} else {
auto new_var =
self->NewVarBase(platform::CUDAPinnedPlace(), true);
new_var->SetOverridedStopGradient(self->OverridedStopGradient());
return new_var;
}
},
R"DOC(
Returns a copy of this Tensor in pin memory.
If this Tensor is already in pin memory, then no copy is performed and the original Tensor is returned.
Examples:
.. code-block:: python
import paddle
x = paddle.to_tensor(1.0, place=paddle.CUDAPlace(0))
print(x.place) # CUDAPlace(0)
y = x.pin_memory()
print(y.place) # CUDAPinnedPlace
)DOC")
.def("cuda",
[](const std::shared_ptr<imperative::VarBase> &self, int device_id,
bool blocking) {
#if !defined(PADDLE_WITH_CUDA) && !defined(PADDLE_WITH_HIP)
PADDLE_THROW(platform::errors::PermissionDenied(
"Cannot copy this Tensor to GPU in CPU version Paddle, "
"Please recompile or reinstall Paddle with CUDA support."));
#else
int device_count = platform::GetCUDADeviceCount();
if (device_id == -1) {
if (platform::is_gpu_place(self->Place())) {
return self;
} else {
device_id = 0;
}
}
PADDLE_ENFORCE_GE(
device_id, 0,
platform::errors::InvalidArgument(
"Can not copy Tensor to Invalid CUDAPlace(%d), device id "
"must inside [0, %d)",
device_id, device_count));
PADDLE_ENFORCE_LT(
device_id, device_count,
platform::errors::InvalidArgument(
"Can not copy Tensor to Invalid CUDAPlace(%d), device id "
"must inside [0, %d)",
device_id, device_count));
platform::CUDAPlace place = platform::CUDAPlace(device_id);
if (platform::is_same_place(self->Place(), place)) {
return self;
} else {
auto new_var = self->NewVarBase(place, blocking);
new_var->SetOverridedStopGradient(self->OverridedStopGradient());
return new_var;
}
#endif
},
py::arg("device_id") = -1, py::arg("blocking") = true, R"DOC(
Returns a copy of this Tensor in GPU memory.
If this Tensor is already in GPU memory and device_id is default,
then no copy is performed and the original Tensor is returned.
Args:
device_id(int, optional): The destination GPU device id. Defaults to the current device.
blocking(bool, optional): If False and the source is in pinned memory, the copy will be
asynchronous with respect to the host. Otherwise, the argument has no effect. Default: False.
Examples:
.. code-block:: python
import paddle
x = paddle.to_tensor(1.0, place=paddle.CPUPlace())
print(x.place) # CPUPlace
y = x.cuda()
print(y.place) # CUDAPlace(0)
y = x.cuda(1)
print(y.place) # CUDAPlace(1)
)DOC")
.def("_share_memory",
[](const std::shared_ptr<imperative::VarBase> &self) {
#ifndef _WIN32
PADDLE_ENFORCE_EQ(
platform::is_cpu_place(self->Place()), true,
platform::errors::InvalidArgument(
"Sharing memory only support CPU Tensor currently"));
// 1. get LoDTensor
auto *t = self->MutableVar()->GetMutable<framework::LoDTensor>();
// 2. allocate shared memory
void *data_ptr = t->data<void>();
size_t data_size = t->numel() * framework::SizeOfType(t->type());
auto shared_writer_holder =
memory::allocation::AllocateMemoryMapWriterAllocation(
data_size);
// 3. maintain mmap fd set & backup ipc_name
const std::string &ipc_name = shared_writer_holder->ipc_name();
memory::allocation::MemoryMapFdSet::Instance().Insert(ipc_name);
// 4. copy data & reset holder
memory::Copy(platform::CPUPlace(), shared_writer_holder->ptr(),
platform::CPUPlace(), data_ptr, data_size);
t->ResetHolder(shared_writer_holder);
return *t;
#else
PADDLE_THROW(platform::errors::PermissionDenied(
"Sharing memory in Windows OS is not supported currently"));
#endif
},
py::return_value_policy::reference)
.def("copy_", &imperative::VarBase::CopyFrom)
.def("_copy_to",
[](const std::shared_ptr<imperative::VarBase> &self,
const platform::CPUPlace &place, bool blocking) {
auto new_var = self->NewVarBase(place, blocking);
// Note(zhiqiu): Since NewVarBase may use GpuCopyAsync to
// copy data from the tensor of self to the tensor of new varbase,
// we need to ensure that the varbase self is not destructed until
// the GpuCopyAsync is completed. Otherwise, the memory may be
// freed
// when varbase self is destructed.
// To do that, we increase the reference count of self by 1 and
// add a cuda event to wait the GpuCopyAsync's completion.
if (!blocking) {
IncreaseVarbaseReferenceCountUntilCopyComplete(self, place);
}
return new_var;
},
py::return_value_policy::copy)
.def("_copy_to",
[](const std::shared_ptr<imperative::VarBase> &self,
const platform::CUDAPinnedPlace &place, bool blocking) {
auto new_var = self->NewVarBase(place, blocking);
if (!blocking) {
IncreaseVarbaseReferenceCountUntilCopyComplete(self, place);
}
return new_var;
},
py::return_value_policy::copy)
.def("_copy_to",
[](const std::shared_ptr<imperative::VarBase> &self,
const platform::XPUPlace &place, bool blocking) {
auto new_var = self->NewVarBase(place, blocking);
if (!blocking) {
IncreaseVarbaseReferenceCountUntilCopyComplete(self, place);
}
return new_var;
},
py::return_value_policy::copy)
.def("_copy_to",
[](const std::shared_ptr<imperative::VarBase> &self,
const platform::CUDAPlace &place, bool blocking) {
auto new_var = self->NewVarBase(place, blocking);
if (!blocking) {
IncreaseVarbaseReferenceCountUntilCopyComplete(self, place);
}
return new_var;
},
py::return_value_policy::copy)
.def("_copy_to",
[](const std::shared_ptr<imperative::VarBase> &self,
const platform::Place &place, bool blocking) {
auto new_var = self->NewVarBase(place, blocking);
if (!blocking) {
IncreaseVarbaseReferenceCountUntilCopyComplete(self, place);
}
return new_var;
},
py::return_value_policy::copy)
.def("value", [](imperative::VarBase &self) { return self.MutableVar(); },
py::return_value_policy::reference)
.def_property("name", &imperative::VarBase::Name,
&imperative::VarBase::SetName)
.def_property("stop_gradient",
&imperative::VarBase::OverridedStopGradient,
&imperative::VarBase::SetOverridedStopGradient)
.def_property("persistable", &imperative::VarBase::Persistable,
&imperative::VarBase::SetPersistable)
.def_property_readonly("shape",
[](imperative::VarBase &self) {
if (self.Var().IsType<framework::LoDTensor>()) {
return framework::vectorize<int>(
self.Var()
.Get<framework::LoDTensor>()
.dims());
} else if (self.Var()
.IsType<
framework::SelectedRows>()) {
return framework::vectorize<int>(
self.Var()
.Get<framework::SelectedRows>()
.value()
.dims());
} else {
VLOG(2) << "It is meaningless to get shape of "
"variable type "
<< GetTypeName(self);
return std::vector<int>();
}
})
.def_property_readonly("is_leaf", &imperative::VarBase::IsLeaf,
R"DOC(
Whether a Tensor is leaf Tensor.
For the Tensor whose stop_gradient is ``True`` , it will be leaf Tensor.
For the Tensor whose stop_gradient is ``False`` , it will be leaf Tensor too if it is created by user.
Returns:
bool: Whether a Tensor is leaf Tensor.
Examples:
.. code-block:: python
import paddle
x = paddle.to_tensor(1.)
print(x.is_leaf) # True
x = paddle.to_tensor(1., stop_gradient=True)
y = x + 1
print(x.is_leaf) # True
print(y.is_leaf) # True
x = paddle.to_tensor(1., stop_gradient=False)
y = x + 1
print(x.is_leaf) # True
print(y.is_leaf) # False
)DOC")
.def_property_readonly(
"place", [](imperative::VarBase &self) { return self.Place(); },
py::return_value_policy::copy)
.def_property_readonly("_place_str",
[](imperative::VarBase &self) {
std::stringstream ostr;
ostr << self.Place();
return ostr.str();
})
.def_property_readonly("type", &imperative::VarBase::Type)
.def_property_readonly("dtype", &imperative::VarBase::DataType);
py::class_<imperative::Layer, Layer /* <--- trampoline*/> layer(m, "Layer");
layer.def(py::init<>())
.def("forward",
[](imperative::Layer &self,
const std::vector<std::shared_ptr<imperative::VarBase>> &inputs) {
return self.Forward(inputs);
});
py::class_<imperative::jit::ProgramDescTracer>(m, "ProgramDescTracer", "")
.def("create_program_desc",
&imperative::jit::ProgramDescTracer::CreateProgramDesc)
.def("reset", &imperative::jit::ProgramDescTracer::Reset);
py::class_<imperative::Tracer, std::shared_ptr<imperative::Tracer>>(
m, "Tracer", R"DOC()DOC")
.def("__init__",
[](imperative::Tracer &self) { new (&self) imperative::Tracer(); })
.def_property("_enable_program_desc_tracing",
&imperative::Tracer::IsProgramDescTracingEnabled,
&imperative::Tracer::SetEnableProgramDescTracing)
.def_property("_enable_autocast", &imperative::Tracer::IsAutoCastEnabled,
&imperative::Tracer::SetEnableAutoCast)
.def_property("_has_grad", &imperative::Tracer::HasGrad,
&imperative::Tracer::SetHasGrad)
.def_property(
"_expected_place",
[](const imperative::Tracer &self) -> py::object {
return py::cast(self.ExpectedPlace());
},
[](imperative::Tracer &self, const py::object &obj) {
if (py::isinstance<platform::CUDAPlace>(obj)) {
auto p = obj.cast<platform::CUDAPlace *>();
self.SetExpectedPlace(*p);
VLOG(4) << "Tracer(" << &self << ")"
<< " set expected place " << *p;
} else if (py::isinstance<platform::XPUPlace>(obj)) {
auto p = obj.cast<platform::XPUPlace *>();
self.SetExpectedPlace(*p);
VLOG(4) << "Tracer(" << &self << ")"
<< " set expected place " << *p;
} else if (py::isinstance<platform::CPUPlace>(obj)) {
auto p = obj.cast<platform::CPUPlace *>();
self.SetExpectedPlace(*p);
VLOG(4) << "Tracer(" << &self << ")"
<< " set expected place " << *p;
} else if (py::isinstance<platform::CUDAPinnedPlace>(obj)) {
auto p = obj.cast<platform::CUDAPinnedPlace *>();
self.SetExpectedPlace(*p);
VLOG(4) << "Tracer(" << &self << ")"
<< " set expected place " << *p;
} else if (py::isinstance<platform::Place>(obj)) {
auto p = obj.cast<platform::Place *>();
self.SetExpectedPlace(*p);
VLOG(4) << "Tracer(" << &self << ")"
<< " set expected place " << *p;
} else {
PADDLE_THROW(platform::errors::InvalidArgument(
"Incompatible Place Type: supports XPUPlace, CUDAPlace, "
"CPUPlace, "
"and CUDAPinnedPlace, "
"but got Unknown Type!"));
}
})
.def("_get_program_desc_tracer",
&imperative::Tracer::GetProgramDescTracer,
py::return_value_policy::reference)
.def("_generate_unique_name", &imperative::Tracer::GenerateUniqueName,
py::arg("key") = "dygraph_tmp")
.def("_set_amp_op_list",
[](imperative::Tracer &self,
std::unordered_set<std::string> &allow_ops,
std::unordered_set<std::string> &block_ops) {
// NOTE(zhiqiu): The automatic conversion in pybind11 between
// c++
// STL and python set/list/dict involve a copy operation that
// prevents pass-by-reference semantics, so it is ok to swap.
// The reaseon why not directly pass
// std::shared_ptr<std::unordered_set<std::string>>
// is that pybind11 forbid shared_ptr<T> where T is not custom
// type.
imperative::AmpOperators::Instance().GetMutableAllowOps()->swap(
allow_ops);
imperative::AmpOperators::Instance().GetMutableBlockOps()->swap(
block_ops);
VLOG(4) << "AMP operators changed, "
<< imperative::AmpOperators::Instance();
})
.def("_get_amp_op_list",
[](imperative::Tracer &self) {
return std::make_tuple(
*(imperative::AmpOperators::Instance().GetMutableAllowOps()),
*(imperative::AmpOperators::Instance().GetMutableBlockOps()));
})
.def("trace",
[](imperative::Tracer &self, const std::string &type,
const PyNameVarBaseMap &ins, const PyNameVarBaseMap &outs,
framework::AttributeMap attrs, const platform::XPUPlace &place,
bool trace_backward) {
auto ins_map = ConvertToNameVarBaseMap(ins);
auto outs_map = ConvertToNameVarBaseMap(outs);
{
py::gil_scoped_release release;
self.TraceOp(type, std::move(ins_map), std::move(outs_map),
std::move(attrs), place, trace_backward);
}
})
.def("trace",
[](imperative::Tracer &self, const std::string &type,
const PyNameVarBaseMap &ins, const PyNameVarBaseMap &outs,
framework::AttributeMap attrs, const platform::CUDAPlace &place,
bool trace_backward) {
auto ins_map = ConvertToNameVarBaseMap(ins);
auto outs_map = ConvertToNameVarBaseMap(outs);
{
py::gil_scoped_release release;
self.TraceOp(type, std::move(ins_map), std::move(outs_map),
std::move(attrs), place, trace_backward);
}
})
.def("trace",
[](imperative::Tracer &self, const std::string &type,
const PyNameVarBaseMap &ins, const PyNameVarBaseMap &outs,
framework::AttributeMap attrs, const platform::CPUPlace &place,
bool trace_backward) {
auto ins_map = ConvertToNameVarBaseMap(ins);
auto outs_map = ConvertToNameVarBaseMap(outs);
{
py::gil_scoped_release release;
self.TraceOp(type, std::move(ins_map), std::move(outs_map),
std::move(attrs), place, trace_backward);
}
});
// define parallel context
py::class_<imperative::ParallelStrategy> parallel_strategy(
m, "ParallelStrategy", "");
parallel_strategy.def(py::init())
.def_property(
"nranks",
[](const imperative::ParallelStrategy &self) { return self.nranks_; },
[](imperative::ParallelStrategy &self, int nranks) {
self.nranks_ = nranks;
})
.def_property("local_rank",
[](const imperative::ParallelStrategy &self) {
return self.local_rank_;
},
[](imperative::ParallelStrategy &self, int local_rank) {
self.local_rank_ = local_rank;
})
.def_property(
"trainer_endpoints",
[](const imperative::ParallelStrategy &self) {
return self.trainer_endpoints_;
},
[](imperative::ParallelStrategy &self, std::vector<std::string> eps) {
self.trainer_endpoints_ = eps;
})
.def_property("current_endpoint",
[](const imperative::ParallelStrategy &self) {
return self.current_endpoint_;
},
[](imperative::ParallelStrategy &self,
const std::string &ep) { self.current_endpoint_ = ep; })
.def_property(
"nrings",
[](const imperative::ParallelStrategy &self) { return self.nrings_; },
[](imperative::ParallelStrategy &self, int nrings) {
self.nrings_ = nrings;
});
m.def(
"dygraph_partial_grad",
[](const std::vector<std::shared_ptr<imperative::VarBase>> &input_targets,
const std::vector<std::shared_ptr<imperative::VarBase>>
&output_targets,
const std::vector<std::shared_ptr<imperative::VarBase>> &output_grads,
const std::vector<std::shared_ptr<imperative::VarBase>> &no_grad_vars,
const platform::Place &place, bool create_graph, bool retain_graph,
bool allow_unused, bool only_inputs) {
imperative::PartialGradEngine engine(
input_targets, output_targets, output_grads, no_grad_vars, place,
create_graph, retain_graph, allow_unused, only_inputs);
engine.Execute();
return engine.GetResult();
},
py::call_guard<py::gil_scoped_release>());
m.def(
"dygraph_run_backward",
[](const std::vector<std::shared_ptr<imperative::VarBase>> &tensors,
const std::vector<std::shared_ptr<imperative::VarBase>> &grad_tensors,
bool retain_graph, const imperative::Tracer &tracer) {
auto *engine = tracer.GetEngine();
engine->Init(tensors, grad_tensors, retain_graph);
VLOG(3) << "Start backward";
engine->Execute();
VLOG(3) << "Finish backward";
},
py::call_guard<py::gil_scoped_release>());
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL) || \
defined(PADDLE_WITH_XPU_BKCL)
py::class_<imperative::ParallelContext,
std::shared_ptr<imperative::ParallelContext>>(m,
"ParallelContext");
py::class_<imperative::Reducer, std::shared_ptr<imperative::Reducer>>(
m, "Reducer", R"DOC()DOC")
.def(py::init<const std::vector<std::shared_ptr<imperative::VarBase>> &,
const std::vector<std::vector<size_t>> &,
const std::vector<bool> &,
std::shared_ptr<imperative::ParallelContext>,
const std::vector<size_t> &, bool>())
.def("prepare_for_backward", &imperative::Reducer::PrepareForBackward,
py::arg("vars"), py::call_guard<py::gil_scoped_release>());
m.def("assign_group_by_size", &imperative::AssignGroupBySize, py::arg("vars"),
py::arg("is_sparse_gradient"),
py::arg("group_size_limits") = std::vector<size_t>{25 * 1024 * 1024},
py::arg("tensor_indices") = std::vector<int64_t>{},
py::call_guard<py::gil_scoped_release>());
#endif
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
py::class_<imperative::NCCLParallelContext, imperative::ParallelContext,
std::shared_ptr<imperative::NCCLParallelContext>>(
m, "NCCLParallelContext")
.def(py::init<const imperative::ParallelStrategy &,
const platform::CUDAPlace &>())
.def("init", [](imperative::NCCLParallelContext &self) { self.Init(); })
.def("init_with_ring_id",
&imperative::NCCLParallelContext::InitWithRingID,
py::arg("ring_id"));
#endif
#if defined(PADDLE_WITH_XPU_BKCL)
py::class_<imperative::BKCLParallelContext, imperative::ParallelContext,
std::shared_ptr<imperative::BKCLParallelContext>>(
m, "BKCLParallelContext")
.def(py::init<const imperative::ParallelStrategy &,
const platform::XPUPlace &>())
.def("init", [](imperative::BKCLParallelContext &self) { self.Init(); })
.def("init_with_ring_id",
&imperative::BKCLParallelContext::InitWithRingID,
py::arg("ring_id"));
#endif
m.def("pylayer_apply",
[](const platform::CPUPlace &place, const py::object &cls,
const py::args args, const py::kwargs kwargs) {
return imperative::PyLayerApply(place, cls, args, kwargs);
});
m.def("pylayer_apply",
[](const platform::CUDAPlace &place, const py::object &cls,
const py::args args, const py::kwargs kwargs) {
return imperative::PyLayerApply(place, cls, args, kwargs);
});
m.def("pylayer_apply",
[](const platform::XPUPlace &place, const py::object &cls,
const py::args args, const py::kwargs kwargs) {
return imperative::PyLayerApply(place, cls, args, kwargs);
});
m.def("pylayer_apply",
[](const platform::CUDAPinnedPlace &place, const py::object &cls,
const py::args args, const py::kwargs kwargs) {
return imperative::PyLayerApply(place, cls, args, kwargs);
});
}
} // namespace pybind
} // namespace paddle
|
#include "PNGWriter.h"
int PNGWriter::maxHeight = 600;
int PNGWriter::maxOutBuf = 800 * 600 * 2;
int PNGWriter::maxWriteBuf = 800 * 600 * 2 * 2;
unsigned char* PNGWriter::outBuf = NULL;
unsigned char* PNGWriter::writeBuf = NULL;
png_bytep* PNGWriter::row_pointers = NULL;
png_text PNGWriter::pngtext[2] = {0};
void PNGWriter::Initialize()
{
outBuf = new unsigned char[maxOutBuf];
writeBuf = new unsigned char[maxWriteBuf];
row_pointers = new png_bytep[maxHeight];
}
void PNGWriter::Deinitialize()
{
delete[] outBuf;
delete[] writeBuf;
delete[] row_pointers;
}
bool PNGWriter::Write(string sFilename, int iHeight, int iWidth, int iStreamLength, unsigned char* pStream, ImageFormat format)
{
int sizeUncompressed;
int size8888;
switch(format){
case FORMAT_4444:
case FORMAT_565:
sizeUncompressed = iHeight * iWidth * 2;
break;
case FORMAT_8888:
sizeUncompressed = iHeight * iWidth * 4;
break;
case FORMAT_BIN:
sizeUncompressed = iHeight * iWidth / 128;
break;
}
size8888 = iHeight * iWidth * 4;
if(sizeUncompressed > maxOutBuf)
{
maxOutBuf = sizeUncompressed;
delete[] outBuf;
outBuf = new unsigned char[maxOutBuf];
}
if(size8888 > maxWriteBuf)
{
maxWriteBuf = size8888;
delete[] writeBuf;
writeBuf = new unsigned char[maxWriteBuf];
}
if(iHeight > maxHeight)
{
maxHeight = iHeight;
delete[] row_pointers;
row_pointers = new png_bytep[maxHeight];
}
//create zlib stream
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = iStreamLength;
strm.next_in = pStream;
strm.avail_out = sizeUncompressed;
strm.next_out = outBuf;
//init inflate stream
if(inflateInit(&strm) != Z_OK)
return false;
//attempt to inflate zlib stream
inflate(&strm, Z_NO_FLUSH);
//tidy up zlib
inflateEnd(&strm);
//some code to debug image formats
// FILE* rawFile = fopen((sFilename + ".raw").c_str(), "wb");
// fwrite(outBuf, 1, sizeUncompressed, rawFile);
// fclose(rawFile);
//transcode image data to 8888
if(format == FORMAT_4444)
{
for(int i = 0; i < sizeUncompressed; i++)
{
unsigned char low = outBuf[i] & 0x0F;
unsigned char high = outBuf[i] & 0xF0;
writeBuf[(i << 1)] = (low << 4) | low;
writeBuf[(i << 1) + 1] = high | (high >> 4);
}
}
else if(format == FORMAT_8888)
{
memcpy(writeBuf, outBuf, sizeUncompressed);
}
else if(format == FORMAT_565)
{
for(int i = 0; i < sizeUncompressed; i+=2)
{
unsigned char bBits = (outBuf[i] & 0x1F) << 3;
unsigned char gBits = ((outBuf[i + 1] & 0x07) << 5) | ((outBuf[i] & 0xE0) >> 3);
unsigned char rBits = outBuf[i + 1] & 0xF8;
writeBuf[(i << 1)] = bBits | (bBits >> 5);
writeBuf[(i << 1) + 1] = gBits | (gBits >> 6);
writeBuf[(i << 1) + 2] = rBits | (rBits >> 5);
writeBuf[(i << 1) + 3] = 0xFF;
}
}
else if(format == FORMAT_BIN)
{
unsigned char byte = 0;
int pixelIndex = 0;
for(int i = 0; i < sizeUncompressed; i++)
{
for(int j = 0; j < 8; j++)
{
byte = ((outBuf[i] & (0x01 << (7 - j))) >> (7 - j)) * 255;
for(int k = 0; k < 16; k++)
{
pixelIndex = (i << 9) + (j << 6) + (k << 2);
writeBuf[pixelIndex] = byte;
writeBuf[pixelIndex + 1] = byte;
writeBuf[pixelIndex + 2] = byte;
writeBuf[pixelIndex + 3] = 0xFF;
}
}
}
}
else
{
//unknown format
}
for(int iRow = 0; iRow < iHeight; iRow++)
row_pointers[iRow] = &writeBuf[iRow * iWidth * 4];
//create PNG file
FILE* pngFile = fopen(sFilename.c_str(), "wb");
if(!pngFile)
return false;
//create png write and info structs
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png_ptr)
return false;
png_infop info_ptr = png_create_info_struct(png_ptr);
if(!info_ptr)
return false;
info_ptr->text = pngtext;
info_ptr->num_text = 2;
pngtext[0].compression = PNG_TEXT_COMPRESSION_NONE;
pngtext[0].key = "Author";
pngtext[0].text = "Alan Horne (www.alanhorne.com)";
pngtext[1].compression = PNG_TEXT_COMPRESSION_NONE;
pngtext[1].key = "Copyright";
pngtext[1].text = "Wizet / Nexon";
//initialize IO
if(setjmp(png_jmpbuf(png_ptr)))
return false;
png_init_io(png_ptr, pngFile);
//write PNG header
if(setjmp(png_jmpbuf(png_ptr)))
return false;
png_set_bgr(png_ptr);
png_set_IHDR(png_ptr, info_ptr, iWidth, iHeight,
8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(png_ptr, info_ptr);
//write image data
if(setjmp(png_jmpbuf(png_ptr)))
return false;
png_write_image(png_ptr, row_pointers);
//write PNG end and close file
if (setjmp(png_jmpbuf(png_ptr)))
return false;
png_write_end(png_ptr, NULL);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(pngFile);
return true;
} |
; A163827: a(n) = 6n^3 + 1, solution z in Diophantine equation x^3 + y^3 = z^3 - 2. It may be considered a Fermat near miss by 2.
; 7,49,163,385,751,1297,2059,3073,4375,6001,7987,10369,13183,16465,20251,24577,29479,34993,41155,48001,55567,63889,73003,82945,93751,105457,118099,131713,146335,162001,178747,196609,215623,235825,257251,279937,303919,329233,355915,384001,413527,444529,477043,511105,546751,584017,622939,663553,705895,750001,795907,843649,893263,944785,998251,1053697,1111159,1170673,1232275,1296001,1361887,1429969,1500283,1572865,1647751,1724977,1804579,1886593,1971055,2058001,2147467,2239489,2334103,2431345
add $0,1
pow $0,3
mul $0,6
add $0,1
|
#include <string>
#include "Warriors.hpp"
//Default constructor
Warrior::Warrior(){
this->damage = 5;
this->health = 100;
this->name = "";
this->bonusDamage = 0;
this->bonusHealth = 0;
}
//Constructor with parameters
Warrior::Warrior(int damage, int health, std::string name){
this->damage = damage;
this->health = health;
this->name = name;
this->bonusDamage = 0;
this->bonusHealth = 0;
}
int Warrior::getDamage(){
return this->damage;
}
void Warrior::setDamage(int newDamage){
this->damage = newDamage;
}
int Warrior::getHealth(){
return this->health;
}
void Warrior::setHealth(int newHealth){
this->health = newHealth;
}
void Warrior::tookDamage(int damage){
this->health -= damage;
}
std::string Warrior::getName(){
return this->name;
}
void Warrior::setName(std::string name){
this->name = name;
}
void Warrior::setAllDetails(int damage, int health, std::string name){
this->damage = damage;
this->health = health;
this->name = name;
}
Warrior::~Warrior(){
}
|
; A158535: a(n) = Hermite(n,11).
; Submitted by Jon Maiga
; 1,22,482,10516,228460,4941992,106439224,2282359024,48721749392,1035360742240,21900944840224,461113571640128,9662677789597888,201512185651790464,4182038461809845120,86362504961566459648,1774513955300166758656,36275706857833541981696,737732076392132253803008,14924180233744902072325120,300298146239486819946638336,6009592007918913955933038592,119598502032157660592768038912,2366744996359036318979843158016,46566858826419546630289219686400,910867134355996282555330361516032
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
mov $3,$1
mov $1,$2
mul $2,22
mul $3,-1
mul $3,$0
mul $3,2
lpe
mov $0,$1
|
#ifndef UTIL___THREAD_POOL_CTRL__HPP
#define UTIL___THREAD_POOL_CTRL__HPP
/* $Id: thread_pool_ctrl.hpp 132195 2008-06-26 12:58:47Z ivanovp $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Pavel Ivanov
*
*/
/// @file thread_pool_ctrl.hpp
/// Implementations of controllers for ThreadPool
///
/// CThreadPool_Controller_PID -- default controller of pool of threads based
/// on Proportional-Integral-Derrivative algorithm depending on number
/// of requests waiting for execution per thread in pool
#include <util/thread_pool.hpp>
#include <deque>
/** @addtogroup ThreadedPools
*
* @{
*/
BEGIN_NCBI_SCOPE
/// Entry in "error" changing history
/// Information about "error" in some point of time in the past kept in
/// CThreadPool_Control_PID.
struct SThreadPool_PID_ErrInfo
{
/// Time of history entry
double call_time;
/// Value of the error
double err;
SThreadPool_PID_ErrInfo(double time_, double err_)
: call_time(time_), err(err_)
{}
};
/// Default ThreadPool controller based on Proportional-Integral-Derivative
/// algorithm. Controller looks at number of tasks waiting in the queue
/// per each thread running and adjusts number of threads with respect to
/// all coefficients set in it.
/// Implementation of the class assumes that all coefficients are set before
/// pool begin to work and controller begins to be extencively used.
/// All changing of coefficients implemented in non-threadsafe manner and if
/// they will be changed at the same time when OnEvent() is executed
/// unpredictable consequences can happen.
class CThreadPool_Controller_PID : public CThreadPool_Controller
{
public:
/// Constructor
/// @param max_threads
/// Maximum number of threads in pool
/// @param min_threads
/// Minimum number of threads in pool
CThreadPool_Controller_PID(unsigned int max_threads,
unsigned int min_threads);
/// Set maximum number of tasks in queue per each thread
/// The meaning of parameter is only approximate. In fact it is the
/// coefficient in proportional part of the algorithm and adjustment for
/// all other coefficients.
/// By default parameter is set to 3.
void SetQueuedTasksThreshold(double threshold);
/// Get maximum number of tasks in queue per each thread
///
/// @sa SetQueuedTasksThreshold()
double GetQueuedTasksThreshold(void);
/// Set maximum time (in seconds) that task can wait in queue for
/// processing until new thread will be launched.
/// The meaning of parameter is only approximate. In fact it is the
/// coefficient in integral part of the algorithm and effectively if only
/// one task will be considered then coefficient will be multiplied
/// by number of currently running threads and currently set threshold.
/// By default parameter is set to 0.2.
///
/// @sa SetQueuedTasksThreshold()
void SetTaskMaxQueuedTime(double queued_time);
/// Get maximum time that task can wait in queue for processing until
/// new thread will be launched.
///
/// @sa SetTaskMaxQueuedTime()
double GetTaskMaxQueuedTime(void);
/// Set the time period (in seconds) for which average speed of changing
/// of waiting tasks number is calculated.
/// Average speed is calculated by simple division of changing in waiting
/// tasks number during this time period per time period value (all
/// counts of tasks are calculated per each thread).
/// By default parameter is set to 0.3.
void SetChangeCalcTime(double calc_time);
/// Get the time period for which average speed of changing of waiting
/// tasks number is calculated.
double GetChangeCalcTime(void);
/// Set period of prediction of number of tasks in queue
/// The meaning of parameter is only approximate. In fact it is the
/// coefficient in derivative part of the algorithm. Meaning of the
/// coefficient is like this: take average speed of changing of tasks
/// count, multiply it by this prediction time, if the resulting value
/// is greater than threshold then new thread is needed.
/// By default parameter is set to 0.5.
///
/// @sa SetQueuedTasksThreshold()
void SetChangePredictTime(double predict_time);
/// Get period of prediction of number of tasks in queue
///
/// @sa SetChangePredictTime()
double GetChangePredictTime(void);
/// Get maximum timeout for which calls to method HandleEvent() can be
/// missing.
///
/// @sa CThreadPool_Controller::GetSafeSleepTime()
virtual CTimeSpan GetSafeSleepTime(void) const;
protected:
/// Main method for implementation of controlling algorithm
virtual void OnEvent(EEvent event);
private:
/// Timer for measuring time periods
CStopWatch m_Timer;
/// History of changing of "error" value
/// "error" - number of tasks per thread waiting in queue. Controller
/// will try to tend this value to zero.
deque<SThreadPool_PID_ErrInfo> m_ErrHistory;
/// Value of "error" integrated over all working time
double m_IntegrErr;
/// Threshold value
/// @sa SetQueuedTasksThreshold()
double m_Threshold;
/// Integral coefficient
/// @sa SetTaskMaxQueuedTime()
double m_IntegrCoeff;
/// Derivative coefficient
/// @sa SetChangePredictTime()
double m_DerivCoeff;
/// Period of taking average "error" change speed
/// @sa SetChangeCalcTime()
double m_DerivTime;
};
//////////////////////////////////////////////////////////////////////////
// All inline methods
//////////////////////////////////////////////////////////////////////////
inline
void CThreadPool_Controller_PID::SetQueuedTasksThreshold(double threshold)
{
m_Threshold = threshold;
}
inline
double CThreadPool_Controller_PID::GetQueuedTasksThreshold(void)
{
return m_Threshold;
}
inline
void CThreadPool_Controller_PID::SetTaskMaxQueuedTime(double queued_time)
{
m_IntegrCoeff = queued_time;
}
inline
double CThreadPool_Controller_PID::GetTaskMaxQueuedTime(void)
{
return m_IntegrCoeff;
}
inline
void CThreadPool_Controller_PID::SetChangeCalcTime(double calc_time)
{
m_DerivTime = calc_time;
}
inline
double CThreadPool_Controller_PID::GetChangeCalcTime(void)
{
return m_DerivTime;
}
inline
void CThreadPool_Controller_PID::SetChangePredictTime(double predict_time)
{
m_DerivCoeff = predict_time;
}
inline
double CThreadPool_Controller_PID::GetChangePredictTime(void)
{
return m_DerivCoeff;
}
END_NCBI_SCOPE
/* @} */
#endif /* UTIL___THREAD_POOL_CTRL__HPP */
|
[absolute 0]
HOSTENT:
.Name resd 1
.Aliases resd 1
.AddrList resd 1
HOSTENT_size:
[section .bss]
STRING_MAX equ 256
HOSTENT_ALIASES_MAX equ 16
HOSTENT_ADDRLIST_MAX equ 16
HostEnt_Name_static resb STRING_MAX
HostEnt_Aliases_static resd HOSTENT_ALIASES_MAX
HostEnt_AddrList_static resd HOSTENT_ADDRLIST_MAX
HostEnt_Aliases_data resb STRING_MAX*HOSTENT_ALIASES_MAX
HostEnt_AddrList_data resd HOSTENT_ADDRLIST_MAX
[section .data]
HostEnt_static :
..@44.strucstart:
times HOSTENT.Name-($-..@44.strucstart) db 0
dd HostEnt_Name_static
times HOSTENT.Aliases-($-..@44.strucstart) db 0
dd HostEnt_Aliases_static
times HOSTENT.AddrList-($-..@44.strucstart) db 0
dd HostEnt_AddrList_static
times HOSTENT_size-($-..@44.strucstart) db 0
HostEnt_static2 :
..@45.strucstart:
times HOSTENT.Name-($-..@45.strucstart) db 0
dd HostEnt_Name_static
times HOSTENT.Aliases-($-..@45.strucstart) db 0
dd HostEnt_Aliases_static
times HOSTENT_size-($-..@45.strucstart) db 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.