text
stringlengths
1
1.05M
; A141123: Primes of the form -x^2+2*x*y+2*y^2 (as well as of the form 3*x^2+6*x*y+2*y^2). ; Submitted by Jamie Morken(w2) ; 2,3,11,23,47,59,71,83,107,131,167,179,191,227,239,251,263,311,347,359,383,419,431,443,467,479,491,503,563,587,599,647,659,683,719,743,827,839,863,887,911,947,971,983,1019,1031,1091,1103,1151,1163,1187,1223,1259,1283,1307,1319,1367,1427,1439,1451,1487,1499,1511,1523,1559,1571,1583,1607,1619,1667,1787,1811,1823,1847,1871,1907,1931,1979,2003,2027,2039,2063,2087,2099,2111,2207,2243,2267,2339,2351,2399,2411,2423,2447,2459,2531,2543,2579,2591,2663 mov $2,332202 mov $6,1 lpb $2 add $1,4 mov $3,$6 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 mov $5,$1 add $1,2 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 sub $2,18 mod $5,4 sub $5,4 add $5,$1 mov $6,$5 lpe mov $0,$6 add $0,1
/* Copyright (c) 2019 Anakin Authors, Inc. 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 "include/saber_resize.h" namespace anakin { namespace saber { typedef TargetWrapper<AMD> AMD_API; template <DataType OpDtype> SaberStatus SaberResize<AMD, OpDtype>::init( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, ResizeParam<AMD>& param, Context<AMD>& ctx) { this->_ctx = &ctx; return create(inputs, outputs, param, ctx); } template <DataType OpDtype> SaberStatus SaberResize<AMD, OpDtype>::create( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, ResizeParam<AMD>& param, Context<AMD>& ctx) { int works = (outputs[0]->size() + 255) / 256 * 256; KernelInfo kernelInfo; kernelInfo.wk_dim = 3; kernelInfo.l_wk = {256, 1, 1}; kernelInfo.g_wk = {works, 1, 1}; kernelInfo.kernel_file = "Resize.cl"; kernelInfo.kernel_name = "resize_2D"; kernelInfo.comp_options = kernelInfo.comp_options + " -DRESIZE_TYPE=" + std::to_string(param.resize_type); AMDKernelPtr kptr = CreateKernel(inputs[0]->device_id(), &kernelInfo); if (!kptr.get()->isInit()) { LOG(ERROR) << "Failed to load program"; return SaberInvalidValue; } _kernel_ptr = kptr; LOG_IF_S(INFO, ENABLE_AMD_DEBUG_LOG) << "COMPLETE CREATE KERNEL"; return SaberSuccess; } template <DataType OpDtype> SaberStatus SaberResize<AMD, OpDtype>::dispatch( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, ResizeParam<AMD>& param) { // To get the commpute command queue AMD_API::stream_t cm = this->_ctx->get_compute_stream(); if (_kernel_ptr == NULL || _kernel_ptr.get() == NULL) { LOG(ERROR) << "Kernel is not exist"; return SaberInvalidValue; } AMDKernel* kernel = _kernel_ptr.get(); int w_out = outputs[0]->width(); int h_out = outputs[0]->height(); int c_out = outputs[0]->channel(); int n_out = outputs[0]->num(); int w_in = inputs[0]->width(); int h_in = inputs[0]->height(); int c_in = inputs[0]->channel(); int n_in = inputs[0]->num(); int num_idx = inputs[0]->num_index(); int channel_idx = inputs[0]->channel_index(); int height_idx = inputs[0]->height_index(); int width_idx = inputs[0]->width_index(); CHECK_EQ(c_in, c_out) << "input channel should = output channel"; CHECK_EQ(c_in, c_out) << "input batch size should = output batch size"; Shape src_real_shape; Shape dst_real_shape; if (inputs[0]->is_continue_mem()) { src_real_shape = inputs[0]->valid_shape(); } else { src_real_shape = inputs[0]->shape(); } if (outputs[0]->is_continue_mem()) { dst_real_shape = outputs[0]->valid_shape(); } else { dst_real_shape = outputs[0]->shape(); } int src_stride_w = src_real_shape.count(width_idx + 1); // inputs[0]->count(width_idx + 1, // dims); int src_stride_h = src_real_shape.count(height_idx + 1); // inputs[0]->count(height_idx + 1, dims); int src_stride_channel = src_real_shape.count(channel_idx + 1); // inputs[0]->count(channel_idx + 1, dims); int src_stride_batch = src_real_shape.count(num_idx + 1); // inputs[0]->count(num_idx + 1,// dims); int dst_stride_w = dst_real_shape.count(width_idx + 1); // outputs[0]->count(width_idx + 1, dims); int dst_stride_h = dst_real_shape.count(height_idx + 1); // outputs[0]->count(height_idx + 1, dims); int dst_stride_channel = dst_real_shape.count(channel_idx + 1); // outputs[0]->count(channel_idx + 1, dims); int dst_stride_batch = dst_real_shape.count(num_idx + 1); // outputs[0]->count(num_idx + 1, dims); LOG(INFO) << "In N C H W" << n_in << " " << c_in << " " << h_in << " " << w_in; LOG(INFO) << "Out N C H W" << n_out << " " << n_out << " " << h_out << " " << w_out; bool err {false}; float h_scale {1.0f}; float w_scale {1.0f}; switch (param.resize_type) { case BILINEAR_ALIGN: { h_scale = ((float)(h_in - 1)) / (h_out - 1); w_scale = ((float)(w_in - 1)) / (w_out - 1); } break; case BILINEAR_NO_ALIGN: { h_scale = ((float)h_in) / h_out; w_scale = ((float)w_in) / w_out; } break; case RESIZE_CUSTOM: { h_scale = 1.0f / param.height_scale; w_scale = 1.0f / param.width_scale; } break; default: LOG(INFO) << "errorr: invalid Resize Type"; } err = kernel->SetKernelArgs( (PtrDtype)inputs[0]->data(), (PtrDtype)outputs[0]->mutable_data(), n_in, c_in, h_in, w_in, h_out, w_out, src_stride_batch, src_stride_channel, src_stride_h, src_stride_w, dst_stride_batch, dst_stride_channel, dst_stride_h, dst_stride_w, h_scale, w_scale); if (!err) { LOG(ERROR) << "Failed to set kernel args"; return SaberInvalidValue; } amd_kernel_list list; list.push_back(_kernel_ptr); err = LaunchKernel(cm, list); if (!err) { LOG(ERROR) << "Failed to set execution"; return SaberInvalidValue; } LOG_IF_S(INFO, ENABLE_AMD_DEBUG_LOG) << "COMPLETE EXECUTION"; return SaberSuccess; } template class SaberResize<AMD, AK_FLOAT>; DEFINE_OP_TEMPLATE(SaberResize, ResizeParam, AMD, AK_INT8); DEFINE_OP_TEMPLATE(SaberResize, ResizeParam, AMD, AK_HALF); } // namespace saber } // namespace anakin
; A173858: Expansion of 4/3 in base phi. ; 1,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0,0 pow $0,2 mov $1,$0 div $1,8 mod $1,2 pow $1,$0
SECTION code_clib PUBLIC kmreadchar PUBLIC _kmreadchar .kmreadchar ._kmreadchar call 0xB9B3 jr c, kmread_1 ld bc, 0xffff kmread_1: ld h, b ld l, c ret
; A244635: 29*n^2. ; 0,29,116,261,464,725,1044,1421,1856,2349,2900,3509,4176,4901,5684,6525,7424,8381,9396,10469,11600,12789,14036,15341,16704,18125,19604,21141,22736,24389,26100,27869,29696,31581,33524,35525,37584,39701,41876,44109,46400,48749,51156,53621,56144,58725,61364,64061,66816,69629,72500,75429,78416,81461,84564,87725,90944,94221,97556,100949,104400,107909,111476,115101,118784,122525,126324,130181,134096,138069,142100,146189,150336,154541,158804,163125,167504,171941,176436,180989,185600,190269,194996,199781,204624,209525,214484,219501,224576,229709,234900,240149,245456,250821,256244,261725,267264,272861,278516,284229 pow $0,2 mul $0,29
#include "stdafx.h" #define NO_VALUE (-1) #define LEPT_TRUE 1 #define LEPT_FALSE 0 #define LEPT_OK 0 #define LEPT_ERROR 1 #define MAX_FILE_LEN 512 /* Minimum number of foreground pixels that a line must contain for it to be part of a span. Needed because sometimes furigana does not have a perfect gap between the text and itself. */ #define FURIGANA_MIN_FG_PIX_PER_LINE 2 /* Minimum width of a span (in pixels) for it to be included in the span list. */ #define FURIGANA_MIN_WIDTH 5 /* Maximum number of spans used during furigana removal */ #define FURIGANA_MAX_SPANS 50 typedef enum { NEGATE_NO = 0, /* Do not negate image */ NEGATE_YES, /* Force negate */ NEGATE_AUTO, /* Automatically negate if border pixels are dark */ } Negate_enum; typedef enum { REMOVE_FURIGANA_NO, /* Do not remove furigana */ REMOVE_FURIGANA_VERTICAL, /* Remove furigana from vertically formatted text */ REMOVE_FURIGANA_HORIZONTAL, /* Remove furigana from horizontally formatted text */ } Remove_furigana_enum; /* Span of lines that contain foreground text. Used during furigana removal. */ typedef struct { int start; int end; } Span; static int erase_furigana_vertical(PIX *pixs, float scale_factor); static int erase_furigana_horizontal(PIX *pixs, float scale_factor); static l_int32 erase_area_left_to_right(PIX *pixs, l_int32 x, l_int32 width); static l_int32 erase_area_top_to_bottom(PIX *pixs, l_int32 y, l_int32 height); int main_util(int argc, char *argv[]) { char source_file[MAX_FILE_LEN] = "in.png"; char dest_file[MAX_FILE_LEN] = "out.png"; Negate_enum perform_negate = NEGATE_NO; l_float32 dark_bg_threshold = 0.5f; /* From 0.0 to 1.0, with 0 being all white and 1 being all black */ int perform_scale = LEPT_TRUE; l_float32 scale_factor = 3.5f; int perform_unsharp_mask = LEPT_TRUE; l_int32 usm_halfwidth = 5; l_float32 usm_fract = 2.5f; int perform_otsu_binarize = LEPT_TRUE; l_int32 otsu_sx = 2000; l_int32 otsu_sy = 2000; l_int32 otsu_smoothx = 0; l_int32 otsu_smoothy = 0; l_float32 otsu_scorefract = 0.0f; Remove_furigana_enum remove_furigana = REMOVE_FURIGANA_NO; l_int32 status = LEPT_ERROR; l_float32 border_avg = 0.0f; PIX *pixs = NULL; char *ext = NULL; /* Get args. leptonica_util.exe in.png out.png 2 0.5 1 3.5 1 5 2.5 1 2000 2000 0 0 0.0 1 */ if (argc >= 17) { strcpy_s(source_file, MAX_FILE_LEN, argv[1]); strcpy_s(dest_file, MAX_FILE_LEN, argv[2]); perform_negate = (Negate_enum)atoi(argv[3]); dark_bg_threshold = (float)atof(argv[4]); perform_scale = atoi(argv[5]); scale_factor = (float)atof(argv[6]); perform_unsharp_mask = atoi(argv[7]); usm_halfwidth = atoi(argv[8]); usm_fract = (float)atof(argv[9]); perform_otsu_binarize = atoi(argv[10]); otsu_sx = atoi(argv[11]); otsu_sy = atoi(argv[12]); otsu_smoothx = atoi(argv[13]); otsu_smoothy = atoi(argv[14]); otsu_scorefract = (float)atof(argv[15]); remove_furigana = (Remove_furigana_enum)atoi(argv[16]); } l_float32 f[4] = { 10, 5, 5, 5 }; NUMA n; n.n = n.nalloc = 4; n.delx = n.refcount = 1; n.startx = 0; n.array = &f[0]; pmsCreate(1024*10, 1024*100, &n, "log.txt"); setPixMemoryManager(pmsCustomAlloc, pmsCustomDealloc); /* Read in source image */ pixs = pixRead(source_file); if (pixs == NULL) { return 1; } /* Convert to grayscale */ pixs = pixConvertRGBToGray(pixs, 0.0f, 0.0f, 0.0f); if (pixs == NULL) { return 2; } PERFTIME_INIT PERFTIME_START if (perform_negate == NEGATE_YES) { /* Negate image */ pixInvert(pixs, pixs); if (pixs == NULL) { return 3; } } else if (perform_negate == NEGATE_AUTO) { PIX *otsu_pixs = NULL; status = pixOtsuAdaptiveThreshold(pixs, otsu_sx, otsu_sy, otsu_smoothx, otsu_smoothy, otsu_scorefract, NULL, &otsu_pixs); if (status != LEPT_OK) { return 4; } /* Get the average intensity of the border pixels, with average of 0.0 being completely white and 1.0 being completely black. */ border_avg = pixAverageOnLine(otsu_pixs, 0, 0, otsu_pixs->w - 1, 0, 1); /* Top */ border_avg += pixAverageOnLine(otsu_pixs, 0, otsu_pixs->h - 1, otsu_pixs->w - 1, otsu_pixs->h - 1, 1); /* Bottom */ border_avg += pixAverageOnLine(otsu_pixs, 0, 0, 0, otsu_pixs->h - 1, 1); /* Left */ border_avg += pixAverageOnLine(otsu_pixs, otsu_pixs->w - 1, 0, otsu_pixs->w - 1, otsu_pixs->h - 1, 1); /* Right */ border_avg /= 4.0f; pixDestroy(&otsu_pixs); /* If background is dark */ if (border_avg > dark_bg_threshold) { /* Negate image */ pixInvert(pixs, pixs); if (pixs == NULL) { return 5; } } } if (perform_scale) { /* Scale the image (linear interpolation) */ pixs = pixScaleGrayLI(pixs, scale_factor, scale_factor); if (pixs == NULL) { return 6; } } //pixEqualizeTRC(pixs, pixs, 0.2, 2); //pixs = pixCloseGray(pixs, 1, 1); //pixs = pixBlockconv(pixs, 1, 1); //pixInvert(pixs, pixs); if (perform_unsharp_mask) { /* Apply unsharp mask */ pixs = pixUnsharpMaskingGray(pixs, usm_halfwidth, usm_fract); if (pixs == NULL) { return 7; } } pixContrastTRC(pixs, pixs, 2.0); if (perform_otsu_binarize) { /* Binarize */ status = pixOtsuAdaptiveThreshold(pixs, otsu_sx, otsu_sy, otsu_smoothx, otsu_smoothy, otsu_scorefract, NULL, &pixs); if (status != LEPT_OK) { return 8; } /* Remove furigana? */ if (remove_furigana == REMOVE_FURIGANA_VERTICAL) { status = erase_furigana_vertical(pixs, scale_factor); if (status != LEPT_OK) { return 9; } } else if (remove_furigana == REMOVE_FURIGANA_HORIZONTAL) { status = erase_furigana_horizontal(pixs, scale_factor); if (status != LEPT_OK) { return 10; } } } { //PIXA **ppixa BOXA * boxa = pixConnComp(pixs, NULL, 8); int n = boxaGetCount(boxa); PERFTIME_END //fprintf(stderr, "Num 4-cc boxes: %d\n", n); for (int i = 0; i < n; i++) { BOX * box = boxaGetBox(boxa, i, L_CLONE); if (box->w >= 4 && box->h >= 4) { fprintf(stderr, "box[%d]: %00d;%00d | %dpx, %dpx\n", i, box->x, box->y, box->w, box->h); //pixRenderBox(pixs, box, 1, L_FLIP_PIXELS); } boxDestroy(&box); /* remember, clones need to be destroyed */ } boxaDestroy(&boxa); } { pixDisplayWrite(NULL, -1); PIXA *pixa; BOXA * boxa = pixConnComp(pixs, &pixa, 4); PIX * pixd = pixaDisplayRandomCmap(pixa, pixGetWidth(pixs), pixGetHeight(pixs)); PIXCMAP * cmap = pixGetColormap(pixd); pixcmapResetColor(cmap, 0, 0, 0, 20); /* reset background to blue */ int n = boxaGetCount(boxa); for (int i = 0; i < n; i++) { BOX * box = boxaGetBox(boxa, i, L_CLONE); if (box->w >= 4 && box->h >= 4) { pixRenderBox(pixd, box, 1, L_FLIP_PIXELS); } boxDestroy(&box); /* remember, clones need to be destroyed */ } //pixDisplay(pixd, 100, 100); pixWriteImpliedFormat("box.bmp", pixd, 0, 0); boxaDestroy(&boxa); pixDestroy(&pixd); pixaDestroy(&pixa); } /* Get extension of output image */ status = splitPathAtExtension(dest_file, NULL, &ext); if (status != LEPT_OK) { return 11; } /* pixWriteImpliedFormat() doesn't recognize PBM/PGM/PPM extensions */ if ((strcmp(ext, ".pbm") == 0) || (strcmp(ext, ".pgm") == 0) || (strcmp(ext, ".ppm") == 0)) { /* Write the image to file as a PNM */ status = pixWrite(dest_file, pixs, IFF_PNM); } else { /* Write the image to file */ status = pixWriteImpliedFormat(dest_file, pixs, 0, 0); } if (status != LEPT_OK) { return 12; } /* Free image data */ pixDestroy(&pixs); pmsDestroy(); return 0; } /* main */ /* Erase the furigana from the provided binary PIX. Works by finding spans of foreground text and removing the spans that are too narrow and are likely furigana. Use this version for vertical text. Returns LEPT_OK on success. */ static int erase_furigana_vertical(PIX *pixs, float scale_factor) { int min_fg_pix_per_line = (int)(FURIGANA_MIN_FG_PIX_PER_LINE * scale_factor); int min_span_width = (int)(FURIGANA_MIN_WIDTH * scale_factor); l_uint32 x = 0; l_uint32 y = 0; int num_fg_pixels_on_line = 0; int good_line = LEPT_FALSE; int num_good_lines_in_cur_span = 0; int total_good_lines = 0; l_uint32 pixel_value = 0; Span span = { NO_VALUE, NO_VALUE }; Span span_list[FURIGANA_MAX_SPANS]; int total_spans = 0; int ave_span_width = 0; int span_idx = 0; Span *cur_span = NULL; l_int32 status = LEPT_ERROR; /* Get list of spans that contain fg pixels */ for (x = 0; x < pixs->w; x++) { num_fg_pixels_on_line = 0; good_line = LEPT_FALSE; for (y = 0; y < pixs->h; y++) { status = pixGetPixel(pixs, x, y, &pixel_value); if (status != LEPT_OK) { return status; } /* If this is a foreground pixel */ if (pixel_value == 1) { num_fg_pixels_on_line++; /* If this line has already meet the minimum number of fg pixels, stop scanning it */ if (num_fg_pixels_on_line >= min_fg_pix_per_line) { good_line = LEPT_TRUE; break; } } } /* If last line is good, set it bad in order to close the span */ if (good_line && (x == pixs->w - 1)) { good_line = LEPT_FALSE; num_good_lines_in_cur_span++; } /* If this line has the minimum number of fg pixels */ if (good_line) { /* Start a new span */ if (span.start == NO_VALUE) { span.start = x; } num_good_lines_in_cur_span++; } else /* Line doesn't have enough fg pixels to consider as part of a span */ { /* If a span has already been started, then end it */ if (span.start != NO_VALUE) { /* If this span isn't too small (needed so that the average isn't skewed) */ if (num_good_lines_in_cur_span >= min_span_width) { span.end = x; total_good_lines += num_good_lines_in_cur_span; /* Add span to the list */ span_list[total_spans] = span; total_spans++; /* Prevent span list overflow */ if (total_spans >= FURIGANA_MAX_SPANS) { break; } } } /* Reset span */ span.start = NO_VALUE; span.end = NO_VALUE; num_good_lines_in_cur_span = 0; } } if (total_spans == 0) { return LEPT_OK; } /* Get average width of the spans */ ave_span_width = total_good_lines / total_spans; x = 0; /* Erase areas of the PIX where either no span exists or where a span is too narrow */ for (span_idx = 0; span_idx < total_spans; span_idx++) { cur_span = &span_list[span_idx]; /* If span is at least of average width, erase area between the previous span and this span */ if ((cur_span->end - cur_span->start + 1) >= (int)(ave_span_width * 0.9)) { status = erase_area_left_to_right(pixs, x, cur_span->start - x); if (status != LEPT_OK) { return status; } x = cur_span->end + 1; } } /* Clear area between the end of the right-most span and the right edge of the PIX */ if ((x != 0) && (x < (pixs->w - 1))) { status = erase_area_left_to_right(pixs, x, pixs->w - x); if (status != LEPT_OK) { return status; } } return LEPT_OK; } /* erase_furigana_vertical */ /* Erase the furigana from the provided binary PIX. Works by finding spans of foreground text and removing the spans that are too narrow and are likely furigana. Use this version for horizontal text. Returns LEPT_OK on success. */ static int erase_furigana_horizontal(PIX *pixs, float scale_factor) { int min_fg_pix_per_line = (int)(FURIGANA_MIN_FG_PIX_PER_LINE * scale_factor); int min_span_width = (int)(FURIGANA_MIN_WIDTH * scale_factor); l_uint32 x = 0; l_uint32 y = 0; int num_fg_pixels_on_line = 0; int good_line = LEPT_FALSE; int num_good_lines_in_cur_span = 0; int total_good_lines = 0; l_uint32 pixel_value = 0; Span span = { NO_VALUE, NO_VALUE }; Span span_list[FURIGANA_MAX_SPANS]; int total_spans = 0; int ave_span_width = 0; int span_idx = 0; Span *cur_span = NULL; l_int32 status = LEPT_ERROR; /* Get list of spans that contain fg pixels */ for (y = 0; y < pixs->h; y++) { num_fg_pixels_on_line = 0; good_line = LEPT_FALSE; for (x = 0; x < pixs->w; x++) { status = pixGetPixel(pixs, x, y, &pixel_value); if (status != LEPT_OK) { return status; } /* If this is a foreground pixel */ if (pixel_value == 1) { num_fg_pixels_on_line++; /* If this line has already meet the minimum number of fg pixels, stop scanning it */ if (num_fg_pixels_on_line >= min_fg_pix_per_line) { good_line = LEPT_TRUE; break; } } } /* If last line is good, set it bad in order to close the span */ if (good_line && (y == pixs->h - 1)) { good_line = LEPT_FALSE; num_good_lines_in_cur_span++; } /* If this line has the minimum number of fg pixels */ if (good_line) { /* Start a new span */ if (span.start == NO_VALUE) { span.start = y; } num_good_lines_in_cur_span++; } else /* Line doesn't have enough fg pixels to consider as part of a span */ { /* If a span has already been started, then end it */ if (span.start != NO_VALUE) { /* If this span isn't too small (needed so that the average isn't skewed) */ if (num_good_lines_in_cur_span >= min_span_width) { span.end = y; total_good_lines += num_good_lines_in_cur_span; /* Add span to the list */ span_list[total_spans] = span; total_spans++; /* Prevent span list overflow */ if (total_spans >= FURIGANA_MAX_SPANS) { break; } } } /* Reset span */ span.start = NO_VALUE; span.end = NO_VALUE; num_good_lines_in_cur_span = 0; } } if (total_spans == 0) { return LEPT_OK; } /* Get average width of the spans */ ave_span_width = total_good_lines / total_spans; y = 0; /* Erase areas of the PIX where either no span exists or where a span is too narrow */ for (span_idx = 0; span_idx < total_spans; span_idx++) { cur_span = &span_list[span_idx]; /* If span is at least of average width, erase area between the previous span and this span */ if ((cur_span->end - cur_span->start + 1) >= (int)(ave_span_width * 0.9)) { status = erase_area_top_to_bottom(pixs, y, cur_span->start - y); if (status != LEPT_OK) { return status; } y = cur_span->end + 1; } } /* Clear area between the end of the right-most span and the right edge of the PIX */ if ((y != 0) && (y < (pixs->h - 1))) { status = erase_area_top_to_bottom(pixs, y, pixs->h - y); if (status != LEPT_OK) { return status; } } return LEPT_OK; } /* erase_furigana_horizontal */ /* Clear/erase a left-to-right section of the provided binary PIX. Returns 0 on success. */ static l_int32 erase_area_left_to_right(PIX *pixs, l_int32 x, l_int32 width) { l_int32 status = LEPT_ERROR; BOX box; box.x = x; box.y = 0; box.w = width; box.h = pixs->h; status = pixClearInRect(pixs, &box); return status; } /* erase_area_left_to_right */ /* Clear/erase a top-to-bottom section of the provided binary PIX. Returns 0 on success. */ static l_int32 erase_area_top_to_bottom(PIX *pixs, l_int32 y, l_int32 height) { l_int32 status = LEPT_ERROR; BOX box; box.x = 0; box.y = y; box.w = pixs->w; box.h = height; status = pixClearInRect(pixs, &box); return status; } /* erase_area_top_to_bottom */
// VirtualDub - Video processing and capture application // Graphics support library // Copyright (C) 1998-2009 Avery Lee // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include <stdafx.h> #include <math.h> #include <vector> #include <vd2/system/math.h> #include <vd2/system/cpuaccel.h> #include <vd2/system/vdalloc.h> #include <vd2/Kasumi/pixmap.h> #include <vd2/Kasumi/pixmaputils.h> #include <vd2/Kasumi/pixmapops.h> #include <vd2/Kasumi/resample.h> #include <vd2/Kasumi/tables.h> #include <vd2/Kasumi/triblt.h> namespace { uint32 lerp_RGB888(sint32 a, sint32 b, sint32 x) { sint32 a_rb = a & 0xff00ff; sint32 a_g = a & 0x00ff00; sint32 b_rb = b & 0xff00ff; sint32 b_g = b & 0x00ff00; const uint32 top_rb = (a_rb + (((b_rb - a_rb)*x + 0x00800080) >> 8)) & 0xff00ff; const uint32 top_g = (a_g + (((b_g - a_g )*x + 0x00008000) >> 8)) & 0x00ff00; return top_rb + top_g; } uint32 bilerp_RGB888(sint32 a, sint32 b, sint32 c, sint32 d, sint32 x, sint32 y) { sint32 a_rb = a & 0xff00ff; sint32 a_g = a & 0x00ff00; sint32 b_rb = b & 0xff00ff; sint32 b_g = b & 0x00ff00; sint32 c_rb = c & 0xff00ff; sint32 c_g = c & 0x00ff00; sint32 d_rb = d & 0xff00ff; sint32 d_g = d & 0x00ff00; const uint32 top_rb = (a_rb + (((b_rb - a_rb)*x + 0x00800080) >> 8)) & 0xff00ff; const uint32 top_g = (a_g + (((b_g - a_g )*x + 0x00008000) >> 8)) & 0x00ff00; const uint32 bot_rb = (c_rb + (((d_rb - c_rb)*x + 0x00800080) >> 8)) & 0xff00ff; const uint32 bot_g = (c_g + (((d_g - c_g )*x + 0x00008000) >> 8)) & 0x00ff00; const uint32 final_rb = (top_rb + (((bot_rb - top_rb)*y) >> 8)) & 0xff00ff; const uint32 final_g = (top_g + (((bot_g - top_g )*y) >> 8)) & 0x00ff00; return final_rb + final_g; } uint32 bicubic_RGB888(const uint32 *src0, const uint32 *src1, const uint32 *src2, const uint32 *src3, sint32 x, sint32 y) { const uint32 p00 = src0[0]; const uint32 p01 = src0[1]; const uint32 p02 = src0[2]; const uint32 p03 = src0[3]; const uint32 p10 = src1[0]; const uint32 p11 = src1[1]; const uint32 p12 = src1[2]; const uint32 p13 = src1[3]; const uint32 p20 = src2[0]; const uint32 p21 = src2[1]; const uint32 p22 = src2[2]; const uint32 p23 = src2[3]; const uint32 p30 = src3[0]; const uint32 p31 = src3[1]; const uint32 p32 = src3[2]; const uint32 p33 = src3[3]; const sint32 *htab = kVDCubicInterpTableFX14_075[x]; const sint32 *vtab = kVDCubicInterpTableFX14_075[y]; const int ch0 = htab[0]; const int ch1 = htab[1]; const int ch2 = htab[2]; const int ch3 = htab[3]; const int cv0 = vtab[0]; const int cv1 = vtab[1]; const int cv2 = vtab[2]; const int cv3 = vtab[3]; int r0 = ((int)((p00>>16)&0xff) * ch0 + (int)((p01>>16)&0xff) * ch1 + (int)((p02>>16)&0xff) * ch2 + (int)((p03>>16)&0xff) * ch3 + 128) >> 8; int g0 = ((int)((p00>> 8)&0xff) * ch0 + (int)((p01>> 8)&0xff) * ch1 + (int)((p02>> 8)&0xff) * ch2 + (int)((p03>> 8)&0xff) * ch3 + 128) >> 8; int b0 = ((int)((p00 )&0xff) * ch0 + (int)((p01 )&0xff) * ch1 + (int)((p02 )&0xff) * ch2 + (int)((p03 )&0xff) * ch3 + 128) >> 8; int r1 = ((int)((p10>>16)&0xff) * ch0 + (int)((p11>>16)&0xff) * ch1 + (int)((p12>>16)&0xff) * ch2 + (int)((p13>>16)&0xff) * ch3 + 128) >> 8; int g1 = ((int)((p10>> 8)&0xff) * ch0 + (int)((p11>> 8)&0xff) * ch1 + (int)((p12>> 8)&0xff) * ch2 + (int)((p13>> 8)&0xff) * ch3 + 128) >> 8; int b1 = ((int)((p10 )&0xff) * ch0 + (int)((p11 )&0xff) * ch1 + (int)((p12 )&0xff) * ch2 + (int)((p13 )&0xff) * ch3 + 128) >> 8; int r2 = ((int)((p20>>16)&0xff) * ch0 + (int)((p21>>16)&0xff) * ch1 + (int)((p22>>16)&0xff) * ch2 + (int)((p23>>16)&0xff) * ch3 + 128) >> 8; int g2 = ((int)((p20>> 8)&0xff) * ch0 + (int)((p21>> 8)&0xff) * ch1 + (int)((p22>> 8)&0xff) * ch2 + (int)((p23>> 8)&0xff) * ch3 + 128) >> 8; int b2 = ((int)((p20 )&0xff) * ch0 + (int)((p21 )&0xff) * ch1 + (int)((p22 )&0xff) * ch2 + (int)((p23 )&0xff) * ch3 + 128) >> 8; int r3 = ((int)((p30>>16)&0xff) * ch0 + (int)((p31>>16)&0xff) * ch1 + (int)((p32>>16)&0xff) * ch2 + (int)((p33>>16)&0xff) * ch3 + 128) >> 8; int g3 = ((int)((p30>> 8)&0xff) * ch0 + (int)((p31>> 8)&0xff) * ch1 + (int)((p32>> 8)&0xff) * ch2 + (int)((p33>> 8)&0xff) * ch3 + 128) >> 8; int b3 = ((int)((p30 )&0xff) * ch0 + (int)((p31 )&0xff) * ch1 + (int)((p32 )&0xff) * ch2 + (int)((p33 )&0xff) * ch3 + 128) >> 8; int r = (r0 * cv0 + r1 * cv1 + r2 * cv2 + r3 * cv3 + (1<<19)) >> 20; int g = (g0 * cv0 + g1 * cv1 + g2 * cv2 + g3 * cv3 + (1<<19)) >> 20; int b = (b0 * cv0 + b1 * cv1 + b2 * cv2 + b3 * cv3 + (1<<19)) >> 20; if (r<0) r=0; else if (r>255) r=255; if (g<0) g=0; else if (g>255) g=255; if (b<0) b=0; else if (b>255) b=255; return (r<<16) + (g<<8) + b; } } namespace { enum { kTop = 1, kBottom = 2, kLeft = 4, kRight = 8, kNear = 16, kFar = 32 }; struct VDTriBltMipInfo { const uint32 *mip; ptrdiff_t pitch; uint32 uvmul, _pad; }; struct VDTriBltInfo { VDTriBltMipInfo mips[16]; uint32 *dst; const uint32 *src; sint32 width; const int *cubictab; }; struct VDTriBltGenInfo { float u; float v; float rhw; float dudx; float dvdx; float drhwdx; }; typedef void (*VDTriBltSpanFunction)(const VDTriBltInfo *); typedef void (*VDTriBltGenFunction)(const VDTriBltGenInfo *); void vd_triblt_span_point(const VDTriBltInfo *pInfo) { sint32 w = -pInfo->width; uint32 *dst = pInfo->dst + pInfo->width; const uint32 *src = pInfo->src; const uint32 *texture = pInfo->mips[0].mip; const ptrdiff_t texpitch = pInfo->mips[0].pitch; do { dst[w] = vdptroffset(texture, texpitch * src[1])[src[0]]; src += 2; } while(++w); } void vd_triblt_span_bilinear(const VDTriBltInfo *pInfo) { sint32 w = -pInfo->width; uint32 *dst = pInfo->dst + pInfo->width; const uint32 *src = pInfo->src; const uint32 *texture = pInfo->mips[0].mip; const ptrdiff_t texpitch = pInfo->mips[0].pitch; do { const sint32 u = src[0]; const sint32 v = src[1]; src += 2; const uint32 *src1 = vdptroffset(texture, texpitch * (v>>8)) + (u>>8); const uint32 *src2 = vdptroffset(src1, texpitch); dst[w] = bilerp_RGB888(src1[0], src1[1], src2[0], src2[1], u&255, v&255); } while(++w); } void vd_triblt_span_trilinear(const VDTriBltInfo *pInfo) { sint32 w = -pInfo->width; uint32 *dst = pInfo->dst + pInfo->width; const uint32 *src = pInfo->src; do { sint32 u = src[0]; sint32 v = src[1]; const sint32 lambda = src[2]; src += 3; const sint32 lod = lambda >> 8; const uint32 *texture1 = pInfo->mips[lod].mip; const ptrdiff_t texpitch1 = pInfo->mips[lod].pitch; const uint32 *texture2 = pInfo->mips[lod+1].mip; const ptrdiff_t texpitch2 = pInfo->mips[lod+1].pitch; u >>= lod; v >>= lod; u += 128; v += 128; const uint32 *src1 = vdptroffset(texture1, texpitch1 * (v>>8)) + (u>>8); const uint32 *src2 = vdptroffset(src1, texpitch1); const uint32 p1 = bilerp_RGB888(src1[0], src1[1], src2[0], src2[1], u&255, v&255); u += 128; v += 128; const uint32 *src3 = vdptroffset(texture2, texpitch2 * (v>>9)) + (u>>9); const uint32 *src4 = vdptroffset(src3, texpitch2); const uint32 p2 = bilerp_RGB888(src3[0], src3[1], src4[0], src4[1], (u>>1)&255, (v>>1)&255); dst[w] = lerp_RGB888(p1, p2, lambda & 255); } while(++w); } void vd_triblt_span_bicubic_mip_linear(const VDTriBltInfo *pInfo) { sint32 w = -pInfo->width; uint32 *dst = pInfo->dst + pInfo->width; const uint32 *src = pInfo->src; do { sint32 u = src[0]; sint32 v = src[1]; const sint32 lambda = src[2]; src += 3; const sint32 lod = lambda >> 8; const uint32 *texture1 = pInfo->mips[lod].mip; const ptrdiff_t texpitch1 = pInfo->mips[lod].pitch; const uint32 *texture2 = pInfo->mips[lod+1].mip; const ptrdiff_t texpitch2 = pInfo->mips[lod+1].pitch; u >>= lod; v >>= lod; u += 128; v += 128; const uint32 *src1 = vdptroffset(texture1, texpitch1 * (v>>8)) + (u>>8); const uint32 *src2 = vdptroffset(src1, texpitch1); const uint32 *src3 = vdptroffset(src2, texpitch1); const uint32 *src4 = vdptroffset(src3, texpitch1); const uint32 p1 = bicubic_RGB888(src1, src2, src3, src4, u&255, v&255); u += 128; v += 128; const uint32 *src5 = vdptroffset(texture2, texpitch2 * (v>>9)) + (u>>9); const uint32 *src6 = vdptroffset(src5, texpitch2); const uint32 *src7 = vdptroffset(src6, texpitch2); const uint32 *src8 = vdptroffset(src7, texpitch2); const uint32 p2 = bicubic_RGB888(src5, src6, src7, src8, (u>>1)&255, (v>>1)&255); dst[w] = lerp_RGB888(p1, p2, lambda & 255); } while(++w); } #ifdef _M_IX86 extern "C" void vdasm_triblt_span_bilinear_mmx(const VDTriBltInfo *pInfo); extern "C" void vdasm_triblt_span_trilinear_mmx(const VDTriBltInfo *pInfo); extern "C" void vdasm_triblt_span_bicubic_mip_linear_mmx(const VDTriBltInfo *pInfo); extern "C" void vdasm_triblt_span_bicubic_mip_linear_sse2(const VDTriBltInfo *pInfo); extern "C" void vdasm_triblt_span_point(const VDTriBltInfo *pInfo); #endif struct VDTriBltTransformedVertex { float x, y, z; union { float w; float rhw; }; float r, g, b, a; float u, v; int outcode; void interp(const VDTriBltTransformedVertex *v1, const VDTriBltTransformedVertex *v2, float alpha) { x = v1->x + alpha * (v2->x - v1->x); y = v1->y + alpha * (v2->y - v1->y); z = v1->z + alpha * (v2->z - v1->z); w = v1->w + alpha * (v2->w - v1->w); r = v1->r + alpha * (v2->r - v1->r); g = v1->g + alpha * (v2->g - v1->g); b = v1->b + alpha * (v2->b - v1->b); a = v1->a + alpha * (v2->a - v1->a); u = v1->u + alpha * (v2->u - v1->u); v = v1->v + alpha * (v2->v - v1->v); outcode = (x < -w ? kLeft : 0) + (x > +w ? kRight : 0) + (y < -w ? kTop : 0) + (y > +w ? kBottom : 0) + (z < -w ? kNear : 0) + (z > +w ? kFar : 0); } }; void TransformVerts(VDTriBltTransformedVertex *dst, const VDTriBltVertex *src, int nVerts, const float xform[16]) { const float xflocal[16]={ xform[ 0], xform[ 1], xform[ 2], xform[ 3], xform[ 4], xform[ 5], xform[ 6], xform[ 7], xform[ 8], xform[ 9], xform[10], xform[11], xform[12], xform[13], xform[14], xform[15], }; if (nVerts <= 0) return; do { const float x0 = src->x; const float y0 = src->y; const float z0 = src->z; const float w = x0*xflocal[12] + y0*xflocal[13] + z0*xflocal[14] + xflocal[15]; const float x = x0*xflocal[ 0] + y0*xflocal[ 1] + z0*xflocal[ 2] + xflocal[ 3]; const float y = x0*xflocal[ 4] + y0*xflocal[ 5] + z0*xflocal[ 6] + xflocal[ 7]; const float z = x0*xflocal[ 8] + y0*xflocal[ 9] + z0*xflocal[10] + xflocal[11]; int outcode = 0; if (x < -w) outcode += kLeft; if (x > w) outcode += kRight; if (y < -w) outcode += kTop; if (y > w) outcode += kBottom; if (z < -w) outcode += kNear; if (z > w) outcode += kFar; dst->x = x; dst->y = y; dst->z = z; dst->w = w; dst->u = src->u; dst->v = src->v; dst->r = 1.0f; dst->g = 1.0f; dst->b = 1.0f; dst->a = 1.0f; dst->outcode = outcode; ++src; ++dst; } while(--nVerts); } void TransformVerts(VDTriBltTransformedVertex *dst, const VDTriColorVertex *src, int nVerts, const float xform[16]) { const float xflocal[16]={ xform[ 0], xform[ 1], xform[ 2], xform[ 3], xform[ 4], xform[ 5], xform[ 6], xform[ 7], xform[ 8], xform[ 9], xform[10], xform[11], xform[12], xform[13], xform[14], xform[15], }; if (nVerts <= 0) return; do { const float x0 = src->x; const float y0 = src->y; const float z0 = src->z; const float w = x0*xflocal[12] + y0*xflocal[13] + z0*xflocal[14] + xflocal[15]; const float x = x0*xflocal[ 0] + y0*xflocal[ 1] + z0*xflocal[ 2] + xflocal[ 3]; const float y = x0*xflocal[ 4] + y0*xflocal[ 5] + z0*xflocal[ 6] + xflocal[ 7]; const float z = x0*xflocal[ 8] + y0*xflocal[ 9] + z0*xflocal[10] + xflocal[11]; int outcode = 0; if (x < -w) outcode += kLeft; if (x > w) outcode += kRight; if (y < -w) outcode += kTop; if (y > w) outcode += kBottom; if (z < -w) outcode += kNear; if (z > w) outcode += kFar; dst->x = x; dst->y = y; dst->z = z; dst->w = w; dst->u = 0.0f; dst->v = 0.0f; dst->r = src->r; dst->g = src->g; dst->b = src->b; dst->a = src->a; dst->outcode = outcode; ++src; ++dst; } while(--nVerts); } struct VDTriangleSetupInfo { const VDTriBltTransformedVertex *pt, *pr, *pl; VDTriBltTransformedVertex tmp0, tmp1, tmp2; }; void SetupTri( VDTriangleSetupInfo& setup, VDPixmap& dst, const VDTriBltTransformedVertex *vx0, const VDTriBltTransformedVertex *vx1, const VDTriBltTransformedVertex *vx2, const VDTriBltFilterMode *filterMode ) { setup.tmp0 = *vx0; setup.tmp1 = *vx1; setup.tmp2 = *vx2; // adjust UVs for filter mode if (filterMode) { switch(*filterMode) { case kTriBltFilterBilinear: setup.tmp0.u += 0.5f; setup.tmp0.v += 0.5f; setup.tmp1.u += 0.5f; setup.tmp1.v += 0.5f; setup.tmp2.u += 0.5f; setup.tmp2.v += 0.5f; case kTriBltFilterTrilinear: case kTriBltFilterBicubicMipLinear: setup.tmp0.u *= 256.0f; setup.tmp0.v *= 256.0f; setup.tmp1.u *= 256.0f; setup.tmp1.v *= 256.0f; setup.tmp2.u *= 256.0f; setup.tmp2.v *= 256.0f; break; case kTriBltFilterPoint: setup.tmp0.u += 1.0f; setup.tmp0.v += 1.0f; setup.tmp1.u += 1.0f; setup.tmp1.v += 1.0f; setup.tmp2.u += 1.0f; setup.tmp2.v += 1.0f; break; } } // do perspective divide and NDC space conversion const float xscale = dst.w * 0.5f; const float yscale = dst.h * 0.5f; setup.tmp0.rhw = 1.0f / setup.tmp0.w; setup.tmp0.x = (1.0f+setup.tmp0.x*setup.tmp0.rhw)*xscale; setup.tmp0.y = (1.0f+setup.tmp0.y*setup.tmp0.rhw)*yscale; setup.tmp0.u *= setup.tmp0.rhw; setup.tmp0.v *= setup.tmp0.rhw; setup.tmp0.r *= setup.tmp0.rhw; setup.tmp0.g *= setup.tmp0.rhw; setup.tmp0.b *= setup.tmp0.rhw; setup.tmp0.a *= setup.tmp0.rhw; setup.tmp1.rhw = 1.0f / setup.tmp1.w; setup.tmp1.x = (1.0f+setup.tmp1.x*setup.tmp1.rhw)*xscale; setup.tmp1.y = (1.0f+setup.tmp1.y*setup.tmp1.rhw)*yscale; setup.tmp1.u *= setup.tmp1.rhw; setup.tmp1.v *= setup.tmp1.rhw; setup.tmp1.r *= setup.tmp1.rhw; setup.tmp1.g *= setup.tmp1.rhw; setup.tmp1.b *= setup.tmp1.rhw; setup.tmp1.a *= setup.tmp1.rhw; setup.tmp2.rhw = 1.0f / setup.tmp2.w; setup.tmp2.x = (1.0f+setup.tmp2.x*setup.tmp2.rhw)*xscale; setup.tmp2.y = (1.0f+setup.tmp2.y*setup.tmp2.rhw)*yscale; setup.tmp2.u *= setup.tmp2.rhw; setup.tmp2.v *= setup.tmp2.rhw; setup.tmp2.r *= setup.tmp2.rhw; setup.tmp2.g *= setup.tmp2.rhw; setup.tmp2.b *= setup.tmp2.rhw; setup.tmp2.a *= setup.tmp2.rhw; // verify clipping VDASSERT(setup.tmp0.x >= 0 && setup.tmp0.x <= dst.w); VDASSERT(setup.tmp1.x >= 0 && setup.tmp1.x <= dst.w); VDASSERT(setup.tmp2.x >= 0 && setup.tmp2.x <= dst.w); VDASSERT(setup.tmp0.y >= 0 && setup.tmp0.y <= dst.h); VDASSERT(setup.tmp1.y >= 0 && setup.tmp1.y <= dst.h); VDASSERT(setup.tmp2.y >= 0 && setup.tmp2.y <= dst.h); vx0 = &setup.tmp0; vx1 = &setup.tmp1; vx2 = &setup.tmp2; const VDTriBltTransformedVertex *pt, *pl, *pr; // sort points if (vx0->y < vx1->y) // 1 < 2 if (vx0->y < vx2->y) { // 1 < 2,3 pt = vx0; pr = vx1; pl = vx2; } else { // 3 < 1 < 2 pt = vx2; pr = vx0; pl = vx1; } else // 2 < 1 if (vx1->y < vx2->y) { // 2 < 1,3 pt = vx1; pr = vx2; pl = vx0; } else { // 3 < 2 < 1 pt = vx2; pr = vx0; pl = vx1; } setup.pl = pl; setup.pt = pt; setup.pr = pr; } void RenderTri(VDPixmap& dst, const VDPixmap *const *pSources, int nMipmaps, const VDTriBltTransformedVertex *vx0, const VDTriBltTransformedVertex *vx1, const VDTriBltTransformedVertex *vx2, VDTriBltFilterMode filterMode, float mipMapLODBias) { VDTriangleSetupInfo setup; SetupTri(setup, dst, vx0, vx1, vx2, &filterMode); const VDTriBltTransformedVertex *pt = setup.pt, *pl = setup.pl, *pr = setup.pr; const float x10 = pl->x - pt->x; const float x20 = pr->x - pt->x; const float y10 = pl->y - pt->y; const float y20 = pr->y - pt->y; const float A = x20*y10 - x10*y20; if (A <= 0.f) return; float invA = 0.f; if (A >= 1e-5f) invA = 1.0f / A; float x10_A = x10 * invA; float x20_A = x20 * invA; float y10_A = y10 * invA; float y20_A = y20 * invA; float u10 = pl->u - pt->u; float u20 = pr->u - pt->u; float v10 = pl->v - pt->v; float v20 = pr->v - pt->v; float rhw10 = pl->rhw - pt->rhw; float rhw20 = pr->rhw - pt->rhw; float dudx = u20*y10_A - u10*y20_A; float dudy = u10*x20_A - u20*x10_A; float dvdx = v20*y10_A - v10*y20_A; float dvdy = v10*x20_A - v20*x10_A; float drhwdx = rhw20*y10_A - rhw10*y20_A; float drhwdy = rhw10*x20_A - rhw20*x10_A; // Compute edge walking parameters float dxl1=0, dxr1=0, dul1=0, dvl1=0, drhwl1=0; float dxl2=0, dxr2=0, dul2=0, dvl2=0, drhwl2=0; // Compute left-edge interpolation parameters for first half. if (pl->y != pt->y) { dxl1 = (pl->x - pt->x) / (pl->y - pt->y); dul1 = dudy + dxl1 * dudx; dvl1 = dvdy + dxl1 * dvdx; drhwl1 = drhwdy + dxl1 * drhwdx; } // Compute right-edge interpolation parameters for first half. if (pr->y != pt->y) { dxr1 = (pr->x - pt->x) / (pr->y - pt->y); } // Compute third-edge interpolation parameters. if (pr->y != pl->y) { dxl2 = (pr->x - pl->x) / (pr->y - pl->y); dul2 = dudy + dxl2 * dudx; dvl2 = dvdy + dxl2 * dvdx; drhwl2 = drhwdy + dxl2 * drhwdx; dxr2 = dxl2; } // Initialize parameters for first half. // // We place pixel centers at (x+0.5, y+0.5). double xl, xr, ul, vl, rhwl, yf; int y, y1, y2; // y_start < y+0.5 to include pixel y. y = (int)floor(pt->y + 0.5); yf = (y+0.5) - pt->y; xl = pt->x + dxl1 * yf; xr = pt->x + dxr1 * yf; ul = pt->u + dul1 * yf; vl = pt->v + dvl1 * yf; rhwl = pt->rhw + drhwl1 * yf; // Initialize parameters for second half. double xl2, xr2, ul2, vl2, rhwl2; if (pl->y > pr->y) { // Left edge is long side dxl2 = dxl1; dul2 = dul1; dvl2 = dvl1; drhwl2 = drhwl1; y1 = (int)floor(pr->y + 0.5); y2 = (int)floor(pl->y + 0.5); yf = (y1+0.5) - pr->y; // Step left edge. xl2 = xl + dxl1 * (y1 - y); ul2 = ul + dul1 * (y1 - y); vl2 = vl + dvl1 * (y1 - y); rhwl2 = rhwl + drhwl1 * (y1 - y); // Prestep right edge. xr2 = pr->x + dxr2 * yf; } else { // Right edge is long side dxr2 = dxr1; y1 = (int)floor(pl->y + 0.5); y2 = (int)floor(pr->y + 0.5); yf = (y1+0.5) - pl->y; // Prestep left edge. xl2 = pl->x + dxl2 * yf; ul2 = pl->u + dul2 * yf; vl2 = pl->v + dvl2 * yf; rhwl2 = pl->rhw + drhwl2 * yf; // Step right edge. xr2 = xr + dxr1 * (y1 - y); } // rasterize const ptrdiff_t dstpitch = dst.pitch; uint32 *dstp = (uint32 *)((char *)dst.data + dstpitch * y); VDTriBltInfo texinfo; VDTriBltSpanFunction drawSpan; uint32 cpuflags = CPUGetEnabledExtensions(); bool triBlt16 = false; switch(filterMode) { case kTriBltFilterBicubicMipLinear: #ifdef _M_IX86 if (cpuflags & CPUF_SUPPORTS_SSE2) { drawSpan = vdasm_triblt_span_bicubic_mip_linear_sse2; triBlt16 = true; } else if (cpuflags & CPUF_SUPPORTS_MMX) { drawSpan = vdasm_triblt_span_bicubic_mip_linear_mmx; triBlt16 = true; } else #endif drawSpan = vd_triblt_span_bicubic_mip_linear; break; case kTriBltFilterTrilinear: #ifdef _M_IX86 if (cpuflags & CPUF_SUPPORTS_MMX) { drawSpan = vdasm_triblt_span_trilinear_mmx; triBlt16 = true; } else #endif drawSpan = vd_triblt_span_trilinear; break; case kTriBltFilterBilinear: #ifdef _M_IX86 if (cpuflags & CPUF_SUPPORTS_MMX) { drawSpan = vdasm_triblt_span_bilinear_mmx; triBlt16 = true; } else #endif drawSpan = vd_triblt_span_bilinear; break; case kTriBltFilterPoint: drawSpan = vd_triblt_span_point; break; } float rhobase = sqrtf(std::max<float>(dudx*dudx + dvdx*dvdx, dudy*dudy + dvdy*dvdy) * (1.0f / 65536.0f)) * powf(2.0f, mipMapLODBias); if (triBlt16) { ul *= 256.0f; vl *= 256.0f; ul2 *= 256.0f; vl2 *= 256.0f; dul1 *= 256.0f; dvl1 *= 256.0f; dul2 *= 256.0f; dvl2 *= 256.0f; dudx *= 256.0f; dvdx *= 256.0f; dudy *= 256.0f; dvdy *= 256.0f; } int minx1 = (int)floor(std::min<float>(std::min<float>(pl->x, pr->x), pt->x) + 0.5); int maxx2 = (int)floor(std::max<float>(std::max<float>(pl->x, pr->x), pt->x) + 0.5); uint32 *const spanptr = new uint32[3 * (maxx2 - minx1)]; while(y < y2) { if (y == y1) { xl = xl2; xr = xr2; ul = ul2; vl = vl2; rhwl = rhwl2; dxl1 = dxl2; dxr1 = dxr2; dul1 = dul2; dvl1 = dvl2; drhwl1 = drhwl2; } int x1, x2; double xf; double u, v, rhw; // x_left must be less than (x+0.5) to include pixel x. x1 = (int)floor(xl + 0.5); x2 = (int)floor(xr + 0.5); xf = (x1+0.5) - xl; u = ul + xf * dudx; v = vl + xf * dvdx; rhw = rhwl + xf * drhwdx; int x = x1; uint32 *spanp = spanptr; float w = 1.0f / (float)rhw; if (x < x2) { if (filterMode >= kTriBltFilterTrilinear) { do { int utexel = VDRoundToIntFastFullRange(u * w); int vtexel = VDRoundToIntFastFullRange(v * w); union{ float f; sint32 i; } rho = {rhobase * w}; int lambda = ((rho.i - 0x3F800000) >> (23-8)); if (lambda < 0) lambda = 0; if (lambda >= (nMipmaps<<8)-256) lambda = (nMipmaps<<8)-257; spanp[0] = utexel; spanp[1] = vtexel; spanp[2] = lambda; spanp += 3; u += dudx; v += dvdx; rhw += drhwdx; w *= (2.0f - w*(float)rhw); } while(++x < x2); } else { do { int utexel = VDFloorToInt(u * w); int vtexel = VDFloorToInt(v * w); spanp[0] = utexel; spanp[1] = vtexel; spanp += 2; u += dudx; v += dvdx; rhw += drhwdx; w *= (2.0f - w*(float)rhw); } while(++x < x2); } } for(int i=0; i<nMipmaps; ++i) { texinfo.mips[i].mip = (const uint32 *)pSources[i]->data; texinfo.mips[i].pitch = pSources[i]->pitch; texinfo.mips[i].uvmul = (pSources[i]->pitch << 16) + 4; } texinfo.dst = dstp+x1; texinfo.src = spanptr; texinfo.width = x2-x1; if (texinfo.width>0) drawSpan(&texinfo); dstp = vdptroffset(dstp, dstpitch); xl += dxl1; xr += dxr1; ul += dul1; vl += dvl1; rhwl += drhwl1; ++y; } delete[] spanptr; } void FillTri(VDPixmap& dst, uint32 c, const VDTriBltTransformedVertex *vx0, const VDTriBltTransformedVertex *vx1, const VDTriBltTransformedVertex *vx2 ) { VDTriangleSetupInfo setup; SetupTri(setup, dst, vx0, vx1, vx2, NULL); const VDTriBltTransformedVertex *pt = setup.pt, *pl = setup.pl, *pr = setup.pr; // Compute edge walking parameters float dxl1=0, dxr1=0; float dxl2=0, dxr2=0; float x_lt = pl->x - pt->x; float x_rt = pr->x - pt->x; float x_rl = pr->x - pl->x; float y_lt = pl->y - pt->y; float y_rt = pr->y - pt->y; float y_rl = pr->y - pl->y; // reject backfaces if (x_lt*y_rt >= x_rt*y_lt) return; // Compute left-edge interpolation parameters for first half. if (pl->y != pt->y) dxl1 = x_lt / y_lt; // Compute right-edge interpolation parameters for first half. if (pr->y != pt->y) dxr1 = x_rt / y_rt; // Compute third-edge interpolation parameters. if (pr->y != pl->y) { dxl2 = x_rl / y_rl; dxr2 = dxl2; } // Initialize parameters for first half. // // We place pixel centers at (x+0.5, y+0.5). double xl, xr, yf; int y, y1, y2; // y_start < y+0.5 to include pixel y. y = (int)floor(pt->y + 0.5); yf = (y+0.5) - pt->y; xl = pt->x + dxl1 * yf; xr = pt->x + dxr1 * yf; // Initialize parameters for second half. double xl2, xr2; if (pl->y > pr->y) { // Left edge is long side dxl2 = dxl1; y1 = (int)floor(pr->y + 0.5); y2 = (int)floor(pl->y + 0.5); yf = (y1+0.5) - pr->y; // Prestep right edge. xr2 = pr->x + dxr2 * yf; // Step left edge. xl2 = xl + dxl1 * (y1 - y); } else { // Right edge is long side dxr2 = dxr1; y1 = (int)floor(pl->y + 0.5); y2 = (int)floor(pr->y + 0.5); yf = (y1+0.5) - pl->y; // Prestep left edge. xl2 = pl->x + dxl2 * yf; // Step right edge. xr2 = xr + dxr1 * (y1 - y); } // rasterize const ptrdiff_t dstpitch = dst.pitch; uint32 *dstp = (uint32 *)((char *)dst.data + dstpitch * y); while(y < y2) { if (y == y1) { xl = xl2; xr = xr2; dxl1 = dxl2; dxr1 = dxr2; } int x1, x2; double xf; // x_left must be less than (x+0.5) to include pixel x. x1 = (int)floor(xl + 0.5); x2 = (int)floor(xr + 0.5); xf = (x1+0.5) - xl; while(x1 < x2) dstp[x1++] = c; dstp = vdptroffset(dstp, dstpitch); xl += dxl1; xr += dxr1; ++y; } } void FillTriGrad(VDPixmap& dst, const VDTriBltTransformedVertex *vx0, const VDTriBltTransformedVertex *vx1, const VDTriBltTransformedVertex *vx2 ) { VDTriangleSetupInfo setup; SetupTri(setup, dst, vx0, vx1, vx2, NULL); const VDTriBltTransformedVertex *pt = setup.pt, *pl = setup.pl, *pr = setup.pr; const float x10 = pl->x - pt->x; const float x20 = pr->x - pt->x; const float y10 = pl->y - pt->y; const float y20 = pr->y - pt->y; const float A = x20*y10 - x10*y20; if (A <= 0.f) return; float invA = 0.f; if (A >= 1e-5f) invA = 1.0f / A; float x10_A = x10 * invA; float x20_A = x20 * invA; float y10_A = y10 * invA; float y20_A = y20 * invA; float r10 = pl->r - pt->r; float r20 = pr->r - pt->r; float g10 = pl->g - pt->g; float g20 = pr->g - pt->g; float b10 = pl->b - pt->b; float b20 = pr->b - pt->b; float a10 = pl->a - pt->a; float a20 = pr->a - pt->a; float rhw10 = pl->rhw - pt->rhw; float rhw20 = pr->rhw - pt->rhw; float drdx = r20*y10_A - r10*y20_A; float drdy = r10*x20_A - r20*x10_A; float dgdx = g20*y10_A - g10*y20_A; float dgdy = g10*x20_A - g20*x10_A; float dbdx = b20*y10_A - b10*y20_A; float dbdy = b10*x20_A - b20*x10_A; float dadx = a20*y10_A - a10*y20_A; float dady = a10*x20_A - a20*x10_A; float drhwdx = rhw20*y10_A - rhw10*y20_A; float drhwdy = rhw10*x20_A - rhw20*x10_A; // Compute edge walking parameters float dxl1=0; float drl1=0; float dgl1=0; float dbl1=0; float dal1=0; float drhwl1=0; float dxr1=0; float dxl2=0; float drl2=0; float dgl2=0; float dbl2=0; float dal2=0; float drhwl2=0; float dxr2=0; float x_lt = pl->x - pt->x; float x_rt = pr->x - pt->x; float x_rl = pr->x - pl->x; float y_lt = pl->y - pt->y; float y_rt = pr->y - pt->y; float y_rl = pr->y - pl->y; // Compute left-edge interpolation parameters for first half. if (pl->y != pt->y) { dxl1 = x_lt / y_lt; drl1 = drdy + dxl1 * drdx; dgl1 = dgdy + dxl1 * dgdx; dbl1 = dbdy + dxl1 * dbdx; dal1 = dady + dxl1 * dadx; drhwl1 = drhwdy + dxl1 * drhwdx; } // Compute right-edge interpolation parameters for first half. if (pr->y != pt->y) dxr1 = x_rt / y_rt; // Compute third-edge interpolation parameters. if (pr->y != pl->y) { dxl2 = x_rl / y_rl; drl2 = drdy + dxl2 * drdx; dgl2 = dgdy + dxl2 * dgdx; dbl2 = dbdy + dxl2 * dbdx; dal2 = dady + dxl2 * dadx; drhwl2 = drhwdy + dxl2 * drhwdx; dxr2 = dxl2; } // Initialize parameters for first half. // // We place pixel centers at (x+0.5, y+0.5). double xl, xr, yf; double rl, gl, bl, al, rhwl; double rl2, gl2, bl2, al2, rhwl2; int y, y1, y2; // y_start < y+0.5 to include pixel y. y = (int)floor(pt->y + 0.5); yf = (y+0.5) - pt->y; xl = pt->x + dxl1 * yf; xr = pt->x + dxr1 * yf; rl = pt->r + drl1 * yf; gl = pt->g + dgl1 * yf; bl = pt->b + dbl1 * yf; al = pt->a + dal1 * yf; rhwl = pt->rhw + drhwl1 * yf; // Initialize parameters for second half. double xl2, xr2; if (pl->y > pr->y) { // Left edge is long side dxl2 = dxl1; drl2 = drl1; dgl2 = dgl1; dbl2 = dbl1; dal2 = dal1; drhwl2 = drhwl1; y1 = (int)floor(pr->y + 0.5); y2 = (int)floor(pl->y + 0.5); yf = (y1+0.5) - pr->y; // Step left edge. xl2 = xl + dxl1 * (y1 - y); rl2 = rl + drl1 * (y1 - y); gl2 = gl + dgl1 * (y1 - y); bl2 = bl + dbl1 * (y1 - y); al2 = al + dal1 * (y1 - y); rhwl2 = rhwl + drhwl1 * (y1 - y); // Prestep right edge. xr2 = pr->x + dxr2 * yf; } else { // Right edge is long side dxr2 = dxr1; y1 = (int)floor(pl->y + 0.5); y2 = (int)floor(pr->y + 0.5); yf = (y1+0.5) - pl->y; // Prestep left edge. xl2 = pl->x + dxl2 * yf; rl2 = pl->r + drl2 * yf; gl2 = pl->g + dgl2 * yf; bl2 = pl->b + dbl2 * yf; al2 = pl->a + dal2 * yf; rhwl2 = pl->rhw + drhwl2 * yf; // Step right edge. xr2 = xr + dxr2 * (y1 - y); } // rasterize const ptrdiff_t dstpitch = dst.pitch; char *dstp0 = (char *)dst.data + dstpitch * y; while(y < y2) { if (y == y1) { xl = xl2; xr = xr2; rl = rl2; gl = gl2; bl = bl2; al = al2; rhwl = rhwl2; dxl1 = dxl2; drl1 = drl2; dgl1 = dgl2; dbl1 = dbl2; dal1 = dal2; drhwl1 = drhwl2; dxr1 = dxr2; } int x1, x2; double xf; double r, g, b, a, rhw; // x_left must be less than (x+0.5) to include pixel x. x1 = (int)floor(xl + 0.5); x2 = (int)floor(xr + 0.5); xf = (x1+0.5) - xl; r = rl + xf * drdx; g = gl + xf * dgdx; b = bl + xf * dbdx; a = al + xf * dadx; rhw = rhwl + xf * drhwdx; float w = 1.0f / (float)rhw; if (x1 < x2) { if (dst.format == nsVDPixmap::kPixFormat_XRGB8888) { uint32 *dstp = (uint32 *)dstp0; do { float sr = (float)(r * w); float sg = (float)(g * w); float sb = (float)(b * w); float sa = (float)(a * w); uint8 ir = VDClampedRoundFixedToUint8Fast(sr); uint8 ig = VDClampedRoundFixedToUint8Fast(sg); uint8 ib = VDClampedRoundFixedToUint8Fast(sb); uint8 ia = VDClampedRoundFixedToUint8Fast(sa); dstp[x1] = ((uint32)ia << 24) + ((uint32)ir << 16) + ((uint32)ig << 8) + ib; r += drdx; g += dgdx; b += dbdx; a += dadx; rhw += drhwdx; w *= (2.0f - w*(float)rhw); } while(++x1 < x2); } else { uint8 *dstp = (uint8 *)dstp0; do { float sg = (float)(g * w); uint8 ig = VDClampedRoundFixedToUint8Fast(sg); dstp[x1] = ig; g += dgdx; rhw += drhwdx; w *= (2.0f - w*(float)rhw); } while(++x1 < x2); } } dstp0 = vdptroffset(dstp0, dstpitch); xl += dxl1; rl += drl1; gl += dgl1; bl += dbl1; al += dal1; rhwl += drhwl1; xr += dxr1; ++y; } } struct VDTriClipWorkspace { VDTriBltTransformedVertex *vxheapptr[2][19]; VDTriBltTransformedVertex vxheap[21]; }; VDTriBltTransformedVertex **VDClipTriangle(VDTriClipWorkspace& ws, const VDTriBltTransformedVertex *vx0, const VDTriBltTransformedVertex *vx1, const VDTriBltTransformedVertex *vx2, int orflags) { // Each line segment can intersect all six planes, meaning the maximum bound is // 18 vertices. Add 3 for the original. VDTriBltTransformedVertex *vxheapnext; VDTriBltTransformedVertex **vxlastheap = ws.vxheapptr[0], **vxnextheap = ws.vxheapptr[1]; ws.vxheap[0] = *vx0; ws.vxheap[1] = *vx1; ws.vxheap[2] = *vx2; vxlastheap[0] = &ws.vxheap[0]; vxlastheap[1] = &ws.vxheap[1]; vxlastheap[2] = &ws.vxheap[2]; vxlastheap[3] = NULL; vxheapnext = ws.vxheap + 3; // Current Next Action // ------- ---- ------ // Unclipped Unclipped Copy vertex // Unclipped Clipped Copy vertex and add intersection // Clipped Unclipped Add intersection // Clipped Clipped No action #define DOCLIP(cliptype, _sign_, cliparg) \ if (orflags & k##cliptype) { \ VDTriBltTransformedVertex **src = vxlastheap; \ VDTriBltTransformedVertex **dst = vxnextheap; \ \ while(*src) { \ VDTriBltTransformedVertex *cur = *src; \ VDTriBltTransformedVertex *next = src[1]; \ \ if (!next) \ next = vxlastheap[0]; \ \ if (!(cur->outcode & k##cliptype)) \ *dst++ = cur; \ \ if ((cur->outcode ^ next->outcode) & k##cliptype) { \ double alpha = (cur->w _sign_ cur->cliparg) / ((cur->w _sign_ cur->cliparg) - (next->w _sign_ next->cliparg)); \ \ if (alpha >= 0.0 && alpha <= 1.0) { \ vxheapnext->interp(cur, next, (float)alpha); \ vxheapnext->cliparg = -(_sign_ vxheapnext->w); \ *dst++ = vxheapnext++; \ } \ } \ ++src; \ } \ *dst = NULL; \ if (dst < vxnextheap+3) return NULL; \ src = vxlastheap; vxlastheap = vxnextheap; vxnextheap = src; \ } DOCLIP(Far, -, z); DOCLIP(Near, +, z); DOCLIP(Bottom, -, y); DOCLIP(Top, +, y); DOCLIP(Right, -, x); DOCLIP(Left, +, x); #undef DOCLIP return vxlastheap; } void RenderClippedTri(VDPixmap& dst, const VDPixmap *const *pSources, int nMipmaps, const VDTriBltTransformedVertex *vx0, const VDTriBltTransformedVertex *vx1, const VDTriBltTransformedVertex *vx2, VDTriBltFilterMode filterMode, float mipMapLODBias, int orflags) { VDTriBltTransformedVertex *vxheapnext; VDTriBltTransformedVertex vxheap[21]; VDTriBltTransformedVertex *vxheapptr[2][19]; VDTriBltTransformedVertex **vxlastheap = vxheapptr[0], **vxnextheap = vxheapptr[1]; vxheap[0] = *vx0; vxheap[1] = *vx1; vxheap[2] = *vx2; vxlastheap[0] = &vxheap[0]; vxlastheap[1] = &vxheap[1]; vxlastheap[2] = &vxheap[2]; vxlastheap[3] = NULL; vxheapnext = vxheap + 3; // Current Next Action // ------- ---- ------ // Unclipped Unclipped Copy vertex // Unclipped Clipped Copy vertex and add intersection // Clipped Unclipped Add intersection // Clipped Clipped No action #define DOCLIP(cliptype, _sign_, cliparg) \ if (orflags & k##cliptype) { \ VDTriBltTransformedVertex **src = vxlastheap; \ VDTriBltTransformedVertex **dst = vxnextheap; \ \ while(*src) { \ VDTriBltTransformedVertex *cur = *src; \ VDTriBltTransformedVertex *next = src[1]; \ \ if (!next) \ next = vxlastheap[0]; \ \ if (!(cur->outcode & k##cliptype)) \ *dst++ = cur; \ \ if ((cur->outcode ^ next->outcode) & k##cliptype) { \ double alpha = (cur->w _sign_ cur->cliparg) / ((cur->w _sign_ cur->cliparg) - (next->w _sign_ next->cliparg)); \ \ if (alpha >= 0.0 && alpha <= 1.0) { \ vxheapnext->interp(cur, next, (float)alpha); \ vxheapnext->cliparg = -(_sign_ vxheapnext->w); \ *dst++ = vxheapnext++; \ } \ } \ ++src; \ } \ *dst = NULL; \ if (dst < vxnextheap+3) return; \ src = vxlastheap; vxlastheap = vxnextheap; vxnextheap = src; \ } DOCLIP(Far, -, z); DOCLIP(Near, +, z); DOCLIP(Bottom, -, y); DOCLIP(Top, +, y); DOCLIP(Right, -, x); DOCLIP(Left, +, x); #undef DOCLIP VDTriBltTransformedVertex **src = vxlastheap+1; while(src[1]) { RenderTri(dst, pSources, nMipmaps, vxlastheap[0], src[0], src[1], filterMode, mipMapLODBias); ++src; } } } bool VDPixmapTriFill(VDPixmap& dst, const uint32 c, const VDTriBltVertex *pVertices, int nVertices, const int *pIndices, int nIndices, const float pTransform[16]) { if (dst.format != nsVDPixmap::kPixFormat_XRGB8888) return false; static const float xf_ident[16]={1.f,0.f,0.f,0.f,0.f,1.f,0.f,0.f,0.f,0.f,1.f,0.f,0.f,0.f,0.f,1.f}; vdfastvector<VDTriBltTransformedVertex> xverts(nVertices); if (!pTransform) pTransform = xf_ident; TransformVerts(xverts.data(), pVertices, nVertices, pTransform); const VDTriBltTransformedVertex *xsrc = xverts.data(); VDTriClipWorkspace clipws; while(nIndices >= 3) { const int idx0 = pIndices[0]; const int idx1 = pIndices[1]; const int idx2 = pIndices[2]; const VDTriBltTransformedVertex *xv0 = &xsrc[idx0]; const VDTriBltTransformedVertex *xv1 = &xsrc[idx1]; const VDTriBltTransformedVertex *xv2 = &xsrc[idx2]; const int kode0 = xv0->outcode; const int kode1 = xv1->outcode; const int kode2 = xv2->outcode; if (!(kode0 & kode1 & kode2)) { if (int orflags = kode0 | kode1 | kode2) { VDTriBltTransformedVertex **src = VDClipTriangle(clipws, xv0, xv1, xv2, orflags); if (src) { VDTriBltTransformedVertex *src0 = *src++; // fan out triangles while(src[1]) { FillTri(dst, c, src0, src[0], src[1]); ++src; } } } else FillTri(dst, c, xv0, xv1, xv2); } pIndices += 3; nIndices -= 3; } return true; } bool VDPixmapTriFill(VDPixmap& dst, const VDTriColorVertex *pVertices, int nVertices, const int *pIndices, int nIndices, const float pTransform[16], const float *chroma_yoffset) { VDPixmap pxY; VDPixmap pxCb; VDPixmap pxCr; bool ycbcr = false; float ycbcr_xoffset = 0; switch(dst.format) { case nsVDPixmap::kPixFormat_XRGB8888: case nsVDPixmap::kPixFormat_Y8: break; case nsVDPixmap::kPixFormat_YUV444_Planar: case nsVDPixmap::kPixFormat_YUV444_Planar_FR: case nsVDPixmap::kPixFormat_YUV444_Planar_709: case nsVDPixmap::kPixFormat_YUV444_Planar_709_FR: case nsVDPixmap::kPixFormat_YUV422_Planar: case nsVDPixmap::kPixFormat_YUV422_Planar_FR: case nsVDPixmap::kPixFormat_YUV422_Planar_709: case nsVDPixmap::kPixFormat_YUV422_Planar_709_FR: case nsVDPixmap::kPixFormat_YUV420_Planar: case nsVDPixmap::kPixFormat_YUV420_Planar_FR: case nsVDPixmap::kPixFormat_YUV420_Planar_709: case nsVDPixmap::kPixFormat_YUV420_Planar_709_FR: case nsVDPixmap::kPixFormat_YUV410_Planar: case nsVDPixmap::kPixFormat_YUV410_Planar_FR: case nsVDPixmap::kPixFormat_YUV410_Planar_709: case nsVDPixmap::kPixFormat_YUV410_Planar_709_FR: pxY.format = nsVDPixmap::kPixFormat_Y8; pxY.data = dst.data; pxY.pitch = dst.pitch; pxY.w = dst.w; pxY.h = dst.h; pxCb.format = nsVDPixmap::kPixFormat_Y8; pxCb.data = dst.data2; pxCb.pitch = dst.pitch2; pxCb.w = dst.w; pxCb.h = dst.h; pxCr.format = nsVDPixmap::kPixFormat_Y8; pxCr.data = dst.data3; pxCr.pitch = dst.pitch3; pxCr.w = dst.w; pxCr.h = dst.h; switch(dst.format) { case nsVDPixmap::kPixFormat_YUV410_Planar: case nsVDPixmap::kPixFormat_YUV410_Planar_FR: case nsVDPixmap::kPixFormat_YUV410_Planar_709: case nsVDPixmap::kPixFormat_YUV410_Planar_709_FR: pxCr.w = pxCb.w = dst.w >> 2; pxCr.h = pxCb.h = dst.h >> 2; ycbcr_xoffset = 0.75f / (float)pxCr.w; break; case nsVDPixmap::kPixFormat_YUV420_Planar: case nsVDPixmap::kPixFormat_YUV420_Planar_FR: case nsVDPixmap::kPixFormat_YUV420_Planar_709: case nsVDPixmap::kPixFormat_YUV420_Planar_709_FR: pxCr.w = pxCb.w = dst.w >> 1; pxCr.h = pxCb.h = dst.h >> 1; ycbcr_xoffset = 0.5f / (float)pxCr.w; break; case nsVDPixmap::kPixFormat_YUV422_Planar: case nsVDPixmap::kPixFormat_YUV422_Planar_FR: case nsVDPixmap::kPixFormat_YUV422_Planar_709: case nsVDPixmap::kPixFormat_YUV422_Planar_709_FR: pxCr.w = pxCb.w = dst.w >> 1; ycbcr_xoffset = 0.5f / (float)pxCr.w; break; case nsVDPixmap::kPixFormat_YUV444_Planar: case nsVDPixmap::kPixFormat_YUV444_Planar_FR: case nsVDPixmap::kPixFormat_YUV444_Planar_709: case nsVDPixmap::kPixFormat_YUV444_Planar_709_FR: pxCr.w = pxCb.w = dst.w; ycbcr_xoffset = 0.0f; break; } ycbcr = true; break; default: return false; } VDTriBltTransformedVertex fastxverts[64]; vdfastvector<VDTriBltTransformedVertex> xverts; VDTriBltTransformedVertex *xsrc; if (nVertices <= 64) { xsrc = fastxverts; } else { xverts.resize(nVertices); xsrc = xverts.data(); } static const float xf_ident[16]={1.f,0.f,0.f,0.f,0.f,1.f,0.f,0.f,0.f,0.f,1.f,0.f,0.f,0.f,0.f,1.f}; if (!pTransform) pTransform = xf_ident; VDTriClipWorkspace clipws; for(int plane=0; plane<(ycbcr?3:1); ++plane) { VDPixmap& pxPlane = ycbcr ? plane == 0 ? pxY : plane == 1 ? pxCb : pxCr : dst; if (ycbcr && plane) { float xf_ycbcr[16]; memcpy(xf_ycbcr, pTransform, sizeof(float) * 16); // translate in x by ycbcr_xoffset xf_ycbcr[0] += xf_ycbcr[12]*ycbcr_xoffset; xf_ycbcr[1] += xf_ycbcr[13]*ycbcr_xoffset; xf_ycbcr[2] += xf_ycbcr[14]*ycbcr_xoffset; xf_ycbcr[3] += xf_ycbcr[15]*ycbcr_xoffset; // translate in y by chroma_yoffset if (chroma_yoffset) { xf_ycbcr[4] += xf_ycbcr[12]*(*chroma_yoffset); xf_ycbcr[5] += xf_ycbcr[13]*(*chroma_yoffset); xf_ycbcr[6] += xf_ycbcr[14]*(*chroma_yoffset); xf_ycbcr[7] += xf_ycbcr[15]*(*chroma_yoffset); } TransformVerts(xsrc, pVertices, nVertices, xf_ycbcr); switch(plane) { case 1: for(int i=0; i<nVertices; ++i) xsrc[i].g = xsrc[i].b; break; case 2: for(int i=0; i<nVertices; ++i) xsrc[i].g = xsrc[i].r; break; } } else { TransformVerts(xsrc, pVertices, nVertices, pTransform); } const int *nextIndex = pIndices; int indicesLeft = nIndices; while(indicesLeft >= 3) { const int idx0 = nextIndex[0]; const int idx1 = nextIndex[1]; const int idx2 = nextIndex[2]; const VDTriBltTransformedVertex *xv0 = &xsrc[idx0]; const VDTriBltTransformedVertex *xv1 = &xsrc[idx1]; const VDTriBltTransformedVertex *xv2 = &xsrc[idx2]; const int kode0 = xv0->outcode; const int kode1 = xv1->outcode; const int kode2 = xv2->outcode; if (!(kode0 & kode1 & kode2)) { if (int orflags = kode0 | kode1 | kode2) { VDTriBltTransformedVertex **src = VDClipTriangle(clipws, xv0, xv1, xv2, orflags); if (src) { VDTriBltTransformedVertex *src0 = *src++; // fan out triangles while(src[1]) { FillTriGrad(pxPlane, src0, src[0], src[1]); ++src; } } } else { FillTriGrad(pxPlane, xv0, xv1, xv2); } } nextIndex += 3; indicesLeft -= 3; } } return true; } bool VDPixmapTriBlt(VDPixmap& dst, const VDPixmap *const *pSources, int nMipmaps, const VDTriBltVertex *pVertices, int nVertices, const int *pIndices, int nIndices, VDTriBltFilterMode filterMode, float mipMapLODBias, const float pTransform[16]) { if (dst.format != nsVDPixmap::kPixFormat_XRGB8888) return false; static const float xf_ident[16]={1.f,0.f,0.f,0.f,0.f,1.f,0.f,0.f,0.f,0.f,1.f,0.f,0.f,0.f,0.f,1.f}; vdfastvector<VDTriBltTransformedVertex> xverts(nVertices); if (!pTransform) pTransform = xf_ident; TransformVerts(xverts.data(), pVertices, nVertices, pTransform); const VDTriBltTransformedVertex *xsrc = xverts.data(); VDTriClipWorkspace clipws; while(nIndices >= 3) { const int idx0 = pIndices[0]; const int idx1 = pIndices[1]; const int idx2 = pIndices[2]; const VDTriBltTransformedVertex *xv0 = &xsrc[idx0]; const VDTriBltTransformedVertex *xv1 = &xsrc[idx1]; const VDTriBltTransformedVertex *xv2 = &xsrc[idx2]; const int kode0 = xv0->outcode; const int kode1 = xv1->outcode; const int kode2 = xv2->outcode; if (!(kode0 & kode1 & kode2)) { if (int orflags = kode0 | kode1 | kode2) { VDTriBltTransformedVertex **src = VDClipTriangle(clipws, xv0, xv1, xv2, orflags); if (src) { VDTriBltTransformedVertex *src0 = *src++; // fan out triangles while(src[1]) { RenderTri(dst, pSources, nMipmaps, src0, src[0], src[1], filterMode, mipMapLODBias); ++src; } } } else RenderTri(dst, pSources, nMipmaps, xv0, xv1, xv2, filterMode, mipMapLODBias); } pIndices += 3; nIndices -= 3; } return true; } /////////////////////////////////////////////////////////////////////////// void VDPixmapSetTextureBorders(VDPixmap& px, bool wrap) { const int w = px.w; const int h = px.h; VDPixmapBlt(px, 0, 1, px, wrap ? w-2 : 1, 1, 1, h-2); VDPixmapBlt(px, w-1, 1, px, wrap ? 1 : w-2, 1, 1, h-2); VDPixmapBlt(px, 0, 0, px, 0, wrap ? h-2 : 1, w, 1); VDPixmapBlt(px, 0, h-1, px, 0, wrap ? 1 : h-2, w, 1); } void VDPixmapSetTextureBordersCubic(VDPixmap& px) { const int w = px.w; const int h = px.h; VDPixmapBlt(px, 0, 1, px, 2, 1, 1, h-2); VDPixmapBlt(px, 1, 1, px, 2, 1, 1, h-2); VDPixmapBlt(px, w-2, 1, px, w-3, 1, 1, h-2); VDPixmapBlt(px, w-1, 1, px, w-3, 1, 1, h-2); VDPixmapBlt(px, 0, 0, px, 0, 2, w, 1); VDPixmapBlt(px, 0, 1, px, 0, 2, w, 1); VDPixmapBlt(px, 0, h-2, px, 0, h-3, w, 1); VDPixmapBlt(px, 0, h-1, px, 0, h-3, w, 1); } /////////////////////////////////////////////////////////////////////////// VDPixmapTextureMipmapChain::VDPixmapTextureMipmapChain(const VDPixmap& src, bool wrap, bool cubic, int maxlevels) { int w = src.w; int h = src.h; int mipcount = 0; while((w>1 || h>1) && maxlevels--) { ++mipcount; w >>= 1; h >>= 1; } mBuffers.resize(mipcount); mMipMaps.resize(mipcount); vdautoptr<IVDPixmapResampler> r(VDCreatePixmapResampler()); r->SetFilters(IVDPixmapResampler::kFilterLinear, IVDPixmapResampler::kFilterLinear, false); float fw = (float)src.w; float fh = (float)src.h; for(int mip=0; mip<mipcount; ++mip) { const int mipw = VDCeilToInt(fw); const int miph = VDCeilToInt(fh); mMipMaps[mip] = &mBuffers[mip]; if (cubic) { mBuffers[mip].init(mipw+4, miph+4, nsVDPixmap::kPixFormat_XRGB8888); if (!mip) { VDPixmapBlt(mBuffers[0], 2, 2, src, 0, 0, src.w, src.h); VDPixmapSetTextureBordersCubic(mBuffers[0]); } else { const VDPixmap& curmip = mBuffers[mip]; const VDPixmap& prevmip = mBuffers[mip-1]; vdrect32f rdst( 0.0f, 0.0f, (float)curmip.w , (float)curmip.h ); vdrect32f rsrc(-2.0f, -2.0f, 2.0f*(float)curmip.w - 2.0f, 2.0f*(float)curmip.h - 2.0f); r->Init(rdst, curmip.w, curmip.h, curmip.format, rsrc, prevmip.w, prevmip.h, prevmip.format); r->Process(curmip, prevmip); } } else { mBuffers[mip].init(mipw+2, miph+2, nsVDPixmap::kPixFormat_XRGB8888); if (!mip) { VDPixmapBlt(mBuffers[0], 1, 1, src, 0, 0, src.w, src.h); VDPixmapSetTextureBorders(mBuffers[0], wrap); } else { const VDPixmap& curmip = mBuffers[mip]; const VDPixmap& prevmip = mBuffers[mip-1]; vdrect32f rdst( 0.0f, 0.0f, (float)curmip.w , (float)curmip.h ); vdrect32f rsrc(-1.0f, -1.0f, 2.0f*(float)curmip.w - 1.0f, 2.0f*(float)curmip.h - 1.0f); r->Init(rdst, curmip.w, curmip.h, curmip.format, rsrc, prevmip.w, prevmip.h, prevmip.format); r->Process(curmip, prevmip); } } fw *= 0.5f; fh *= 0.5f; } }
; A338920: a(n) is the number of times it takes to iteratively subtract m from n where m is the largest nonzero proper suffix of n less than or equal to the remainder until no further subtraction is possible. ; 0,0,0,0,0,0,0,0,0,0,11,6,4,3,3,2,2,2,2,0,21,11,7,6,5,4,3,3,3,0,31,16,11,8,7,6,5,4,4,0,41,21,14,11,9,7,6,6,5,0,51,26,17,13,11,9,8,7,6,0,61,31,21,16,13,11,9,8,7,0,71,36,24,18,15,12,11,9 lpb $0 add $0,1 mov $1,$0 lpb $0 mod $0,10 lpe cmp $3,0 mul $3,$0 sub $0,1 lpe mov $2,$3 cmp $2,0 add $3,$2 div $1,$3 mov $0,$1
; A153134: Numbers n such that 6n - 7 is prime. ; Submitted by Jon Maiga ; 2,3,4,5,6,8,9,10,11,13,15,16,18,19,20,23,24,26,29,30,31,33,34,39,40,41,43,44,45,46,48,50,53,54,59,60,61,65,66,68,71,73,75,76,78,79,81,83,85,86,88,94,95,96,99,100,101,104,108,109,110,111,114,115,118,121,125,128,130,134,136,138,139,141,144,145,148,149,153,156,158,159,160,163,164,165,170,171,173,176,178,183,184,185,186,193,195,198,199,200 mov $1,4 mov $2,$0 pow $2,2 lpb $2 mov $3,$1 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,6 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 sub $2,1 lpe mov $0,$1 div $0,6 add $0,2
//========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include <vgui/KeyCode.h> #include <KeyValues.h> #include <vgui_controls/Button.h> #include <vgui_controls/PropertyDialog.h> #include <vgui_controls/PropertySheet.h> // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> using namespace vgui; //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- PropertyDialog::PropertyDialog(Panel *parent, const char *panelName) : Frame(parent, panelName) { // create the property sheet _propertySheet = new PropertySheet(this, "Sheet"); _propertySheet->AddActionSignalTarget(this); _propertySheet->SetTabPosition(1); // add the buttons _okButton = new Button(this, "OKButton", "#PropertyDialog_OK"); _okButton->AddActionSignalTarget(this); _okButton->SetTabPosition(2); _okButton->SetCommand("OK"); GetFocusNavGroup().SetDefaultButton(_okButton); _cancelButton = new Button(this, "CancelButton", "#PropertyDialog_Cancel"); _cancelButton->AddActionSignalTarget(this); _cancelButton->SetTabPosition(3); _cancelButton->SetCommand("Cancel"); _applyButton = new Button(this, "ApplyButton", "#PropertyDialog_Apply"); _applyButton->AddActionSignalTarget(this); _applyButton->SetTabPosition(4); _applyButton->SetVisible(false); // default to not visible _applyButton->SetEnabled(false); // default to not enabled _applyButton->SetCommand("Apply"); SetSizeable(false); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- PropertyDialog::~PropertyDialog() { } //----------------------------------------------------------------------------- // Purpose: Returns a pointer to the PropertySheet this dialog encapsulates // Output : PropertySheet * //----------------------------------------------------------------------------- PropertySheet *PropertyDialog::GetPropertySheet() { return _propertySheet; } //----------------------------------------------------------------------------- // Purpose: Gets a pointer to the currently active page. // Output : Panel //----------------------------------------------------------------------------- Panel *PropertyDialog::GetActivePage() { return _propertySheet->GetActivePage(); } //----------------------------------------------------------------------------- // Purpose: Wrapped function //----------------------------------------------------------------------------- void PropertyDialog::AddPage(Panel *page, const char *title) { _propertySheet->AddPage(page, title); } //----------------------------------------------------------------------------- // Purpose: reloads the data in all the property page //----------------------------------------------------------------------------- void PropertyDialog::ResetAllData() { _propertySheet->ResetAllData(); } //----------------------------------------------------------------------------- // Purpose: Applies any changes //----------------------------------------------------------------------------- void PropertyDialog::ApplyChanges() { OnCommand("Apply"); } //----------------------------------------------------------------------------- // Purpose: Sets up the sheet //----------------------------------------------------------------------------- void PropertyDialog::PerformLayout() { BaseClass::PerformLayout(); int iBottom = m_iSheetInsetBottom; if (IsProportional()) { iBottom = scheme()->GetProportionalScaledValueEx(GetScheme(), iBottom); } int x, y, wide, tall; GetClientArea(x, y, wide, tall); _propertySheet->SetBounds(x, y, wide, tall - iBottom); // move the buttons to the bottom-right corner int xpos = x + wide - 80; int ypos = tall + y - 28; if (_applyButton->IsVisible()) { _applyButton->SetBounds(xpos, ypos, 72, 24); xpos -= 80; } if (_cancelButton->IsVisible()) { _cancelButton->SetBounds(xpos, ypos, 72, 24); xpos -= 80; } _okButton->SetBounds(xpos, ypos, 72, 24); _propertySheet->InvalidateLayout(); // tell the propertysheet to redraw! Repaint(); } //----------------------------------------------------------------------------- // Purpose: Handles command text from the buttons //----------------------------------------------------------------------------- void PropertyDialog::OnCommand(const char *command) { if (!stricmp(command, "OK")) { if (OnOK(false)) { OnCommand("Close"); } _applyButton->SetEnabled(false); } else if (!stricmp(command, "Cancel")) { OnCancel(); Close(); } else if (!stricmp(command, "Apply")) { OnOK(true); _applyButton->SetEnabled(false); InvalidateLayout(); } else { BaseClass::OnCommand(command); } } //----------------------------------------------------------------------------- // Purpose: called when the Cancel button is pressed //----------------------------------------------------------------------------- void PropertyDialog::OnCancel() { // designed to be overridden } //----------------------------------------------------------------------------- // Purpose: // Input : code - //----------------------------------------------------------------------------- void PropertyDialog::OnKeyCodeTyped(KeyCode code) { // this has been removed, since it conflicts with how we use the escape key in the game // if (code == KEY_ESCAPE) // { // OnCommand("Cancel"); // } // else { BaseClass::OnKeyCodeTyped(code); } } //----------------------------------------------------------------------------- // Purpose: Command handler //----------------------------------------------------------------------------- bool PropertyDialog::OnOK(bool applyOnly) { // the sheet should have the pages apply changes before we tell the world _propertySheet->ApplyChanges(); // this should tell anybody who's watching us that we're done PostActionSignal(new KeyValues("ApplyChanges")); // default to closing return true; } //----------------------------------------------------------------------------- // Purpose: Overrides build mode so it edits the sub panel //----------------------------------------------------------------------------- void PropertyDialog::ActivateBuildMode() { // no subpanel, no build mode EditablePanel *panel = dynamic_cast<EditablePanel *>(GetActivePage()); if (!panel) return; panel->ActivateBuildMode(); } //----------------------------------------------------------------------------- // Purpose: sets the text on the OK/Cancel buttons, overriding the default //----------------------------------------------------------------------------- void PropertyDialog::SetOKButtonText(const char *text) { _okButton->SetText(text); } //----------------------------------------------------------------------------- // Purpose: sets the text on the OK/Cancel buttons, overriding the default //----------------------------------------------------------------------------- void PropertyDialog::SetCancelButtonText(const char *text) { _cancelButton->SetText(text); } //----------------------------------------------------------------------------- // Purpose: sets the text on the apply buttons, overriding the default //----------------------------------------------------------------------------- void PropertyDialog::SetApplyButtonText(const char *text) { _applyButton->SetText(text); } //----------------------------------------------------------------------------- // Purpose: changes the visibility of the buttons //----------------------------------------------------------------------------- void PropertyDialog::SetOKButtonVisible(bool state) { _okButton->SetVisible(state); InvalidateLayout(); } //----------------------------------------------------------------------------- // Purpose: changes the visibility of the buttons //----------------------------------------------------------------------------- void PropertyDialog::SetCancelButtonVisible(bool state) { _cancelButton->SetVisible(state); InvalidateLayout(); } //----------------------------------------------------------------------------- // Purpose: changes the visibility of the buttons //----------------------------------------------------------------------------- void PropertyDialog::SetApplyButtonVisible(bool state) { _applyButton->SetVisible(state); InvalidateLayout(); } //----------------------------------------------------------------------------- // Purpose: when a sheet changes, enable the apply button //----------------------------------------------------------------------------- void PropertyDialog::OnApplyButtonEnable() { if (_applyButton->IsEnabled()) return; EnableApplyButton(true); } //----------------------------------------------------------------------------- // Purpose: enable/disable the apply button //----------------------------------------------------------------------------- void PropertyDialog::EnableApplyButton(bool bEnable) { _applyButton->SetEnabled(bEnable); InvalidateLayout(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PropertyDialog::RequestFocus(int direction) { _propertySheet->RequestFocus(direction); }
; A017266: a(n) = (9*n + 8)^10. ; 1073741824,2015993900449,141167095653376,2758547353515625,27197360938418176,174887470365513049,839299365868340224,3255243551009881201,10737418240000000000,31181719929966183601,81707280688754689024,196715135728956532249,441143507864991563776,931322574615478515625,1866585911861003723776,3575694237941010577249,6583182266716099969024,11701964070276793473601,20159939004490000000000,33769941616283277616201,55154187683317729460224,88036397287336250493049,137617037244838084658176,211049631965666494140625,318038856534447018213376,471584161164422542970449,688895994810941449421824,992515310305509690315001,1411670956533760000000000,1983913807584764801017801,2757071057097666970215424,3791569030877467700422849,5163178154897836475416576,6966239371707837900390625,9317437338664347031806976,12360192178975492163652649,16269748403915564986138624,21259046894411315872085401,27585473535156250000000000,35558586247136301325508401,45548930777599929298714624,57998064692731100928561649,73429918590237631550718976,92463633619402804697265625,115828024977517918028824576,144377832156670251607183849,179111928356257770093159424,221193673666991494984864801,271973609384181760000000000,333014704134438335386608001,406120376413199518554317824,493365532643394582186749449,597130874990690290159845376,720140748920828379384765625,865504816872179805351986176,1036763861454476003909724049,1237940039285380274899124224,1473591924952786487925133201,1748874703655130490000000000,2069605890837224702290236601,2442336977617831271961985024,2874431422010026638388426249,3374149427879033323990475776,3950739976277256011962890625,4614540597255411369326411776,5377085394484537457377033249,6251221860048961785910273024,7251237042597649955815770601,8392993658683402240000000000,9694076764588766218336714201,11173951634246942551700276224,12854133518028030996340632049,14758369987188347666144690176,16912836599685895189931640625,19346346654861037627083621376,22090575837180674640752471449,25180302582859377326842445824,28653665037714694102182057001,32552435510098812010000000000,36922313359187619548244760801,41813237296313614509669351424,47279718115413687185176006849,53381192908039238466914968576,60182401858757016738291015625,67753788758167129797585534976,76171926413192561273584998649,85519968177764847898653082624,95888126871556007450327672401,107374182400000000000000000000,120084019435520610159775496401,134132196567649308139458970624,149642548378589035457984790649,166748821950770619940760190976,185595349364070307019541015625,206337757792622353177848472576,229143718864582415495797174849,254193739002788241486773223424,281681992520036568627910696801,311817199299661836010000000000,344823548950275944213556441001 mul $0,9 add $0,8 pow $0,10
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 c0 .text@150 lbegin: ld a, 00 ldff(ff), a ld b, 97 call lwaitly_b ld a, b1 ldff(40), a ld a, 20 ldff(4b), a ld c, 41 ld a, ff ldff(4a), a ld a, 01 ldff(45), a ld a, 40 ldff(c), a xor a, a ldff(0f), a ld a, 02 ldff(ff), a ei .text@1000 lstatint: nop .text@115c ld c, 4a ld a, 04 ldff(43), a nop nop nop nop ldff(c), a ld c, 41 .text@1189 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
/* * commontrain.cc * * License: Artistic License, see file LICENSE.TXT or * https://opensource.org/licenses/artistic-license-1.0 */ #include "commontrain.hh" #include <iostream> void scaleDblVector(vector<Double>& v, Double sum) { Double kumSum(0.0), factor; for (int i=0; i<v.size(); i++) { kumSum += v[i]; } if (kumSum != 0) { factor = sum / kumSum; for (int i=0; i<v.size(); i++) { v[i] *= factor; } } } /*--- Smooth methods -------------------------------------------------*/ void Smooth::smoothCounts(const vector<Integer> &counts, vector<Double> &result, int resultSize){ int n = counts.size(); if (resultSize < 0) resultSize = n; if (int(result.size()) > resultSize) resultSize = result.size(); result.assign(resultSize, 0.0); int i, j; int bandwidth; int cumcountl, cumcountr, numevents=0; Boolean negligible; for (i=0; i<n; i++) numevents += counts[i]; /* for debugging only Double sum2 = 0; for (i=0; i<n; i++) { sum2+=result[i]; } cout << "Summe vorher: " << sum2 << endl; int sum1=0; for (i=0; i<n; i++) { sum1 += counts[i]; } cout << "Anzahl vorher: " << sum1 << endl; */ /* * loop over the positions relevant for the final result vector */ for (i=0; (i<n) && (i < resultSize + 4 * slope_of_bandwidth * resultSize); i++) { if (counts[i]>0) { cumcountl= 0; cumcountr= 0; bandwidth = (int) (.01 + slope_of_bandwidth*pow((double)numevents, -.2) * i); if (bandwidth < 1) bandwidth = 1; for (j=i-bandwidth+1; j <= i+bandwidth-1; j++) { if (j>= 0 && j<n) { if (j <= i) cumcountl += (counts[j]) ? 1 : 0; if (j>= i) cumcountr += (counts[j]) ? 1 : 0; } } // starting from minWindowsSize, enlarge bandwidth until in the // symmetric window with radius bandwidth are at least minwindowcount // positions with at least one event while (cumcountl < minwindowcount && cumcountr < minwindowcount && bandwidth < n){ bandwidth++; if (i+bandwidth-1<n) { cumcountl += (counts[i+bandwidth-1]) ? 1 : 0; } if (i-bandwidth+1>=0) { cumcountr += (counts[i-bandwidth+1]) ? 1 : 0; } } if (i<resultSize) result[i] += phi_normal(bandwidth, 0) * counts[i]; negligible = false; j=1; while (!negligible && (i-j>=0 || i+j<resultSize)){ Double weight_j = phi_normal(bandwidth, j) * counts[i]; if (i-j>=0 && i-j<resultSize ) { result[i-j] += weight_j; } if (i+j<resultSize && i+j>=0) { result[i+j] += weight_j; } negligible = (weight_j < SMOOTH_EPSILON); j++; } } } } /* * Smooth::geoCutOff(const vector<Integer> &lencount, vector<Double>& result) * lencount[i] is the weighed number of introns of length i * result holds the probabilities of the smoothed length distribution, * memory is allocated in this function */ int Smooth::geoCutOff(const vector<Integer> &lencount, vector<Double>& result){ int d, dtemp; int maxpos; Double maxvalue, PlenD, PlenDp1, bestRelDiff; vector<Double> wholeLenDist; smoothCounts(lencount, wholeLenDist); scaleDblVector(wholeLenDist, 1.0); // search the maximum of the length distribution maxvalue = -1; maxpos = -1; for (int i = 0; i < wholeLenDist.size(); i++) { if (wholeLenDist[i] > maxvalue) { maxvalue = wholeLenDist[i]; maxpos = i; } } cout << "the most probable length is " << maxpos << endl; /* * search for the best place d to cut off */ bestRelDiff = 1000.0; // = "infinity" d = 0; Double relDiff; /* * start with dtemp as the position of the maximum of the length distribution * increase dtemp and check the size of the jump of the model-distribution * if we introduce the cutoff at dtemp */ int numleD = 0, // number of intron with length <= dtemp numgD = 0, // number of intron with length > dtemp sumgD = 0; // sum of intron length > dtemp for (int i=0; i < maxpos; i++) { numleD += lencount[i]; } for (int i = maxpos + 1; i < lencount.size(); i++) { numgD += lencount[i]; sumgD += lencount[i] * i; } for (dtemp = maxpos; dtemp < int(lencount.size()); dtemp++){ PlenD = wholeLenDist[dtemp]; // we make a very small error here PlenDp1 = (double) numgD/(numleD + numgD) /((double) sumgD/numgD-dtemp); relDiff = (PlenDp1 > 0) ? PlenD/PlenDp1 : 1000; /* cout << "d= " << dtemp << " "; cout << " P(len=D) = " << PlenD << " P(len=D+1) = " << PlenDp1 << " numleD = " << numleD << endl;*/ if (relDiff < 1.0 && relDiff > 0) { relDiff = Double(1.0) / relDiff; } if (relDiff == 0) { relDiff = 1000; } if (relDiff < bestRelDiff) { bestRelDiff = relDiff; d = dtemp; } // TODO: tradeoff between performance and accuracy if (relDiff < 1 + (double) dtemp/1000) { // relDiff < 1.2 // good cutoff found, don't search any further d = dtemp; break; } // compute the new counters numleD += lencount[dtemp+1]; numgD -= lencount[dtemp+1]; sumgD -= lencount[dtemp+1] * (dtemp+1); } result.resize(d+1); for (int i=0; i < result.size(); i++) { result[i] = wholeLenDist[i]; } //shorte: result.assign(wholeLenDist.begin(), wholeLenDist.begin()+d+1); scaleDblVector(result, 1.0); return d; }
; DCD 0x20000678 ; Setup stack pointer ; DCD 0x06daa0e3 ; mov sp, #0x60 << 8 mov sp, 0x30000 BL main_main ; Branch to main (this is actually in the interrupt vector) local_loop: B local_loop
; ; ZX Spectrum specific routines ; by Stefano Bodrato, 29/06/2006 ; Fixed by Antonio Schifano, Dec 2008 ; ; Copy a string to a BASIC variable ; ; int __CALLEE__ zx_setstr_callee(char variable, char *value); ; ; CPIR, debugged version by Antonio Schifano, 29/12/2008 ; ; $Id: zx_setstr_callee.asm,v 1.2 2008/12/31 13:58:11 stefano Exp $ ; XLIB zx_setstr_callee XDEF ASMDISP_ZX_SETSTR_CALLEE zx_setstr_callee: pop bc pop hl pop de push bc ; enter : hl = char *value ; e = char variable .asmentry ld a,e and 95 ld d,a push hl push de ld hl,($5c4b) ; VARS loop: ld a,(hl) cp 128 jr z,store ; variable not found morevar: cp d jr z,found call $19b8 ;get next variable start ex de,hl pop de push de jr loop found: call $19b8 ; get next variable start call $19e8 ; reclaim space (delete) store: pop af ; swap var name and str. ptr into stack pop de push af push de xor a ld b,a ld c,a ex de,hl cpir ; scan for zero ex de,hl ld a,b cpl ld b,a ld a,c cpl ld c,a ; bc=str len push hl push bc inc bc inc bc inc bc call $1655 ; MAKE-ROOM pop bc pop hl pop de ; get back str. ptr pop af ; and var name ld (hl),a inc hl ld (hl),c inc hl ld (hl),b ld a,b ; handle 0 lenght strings or c ret z inc hl ex de,hl ldir ret DEFC ASMDISP_ZX_SETSTR_CALLEE = asmentry - zx_setstr_callee
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "attribute_spec.h" namespace proton { AttributeSpec::AttributeSpec(const vespalib::string &name, const search::attribute::Config &cfg) : _name(name), _cfg(cfg) { } AttributeSpec::AttributeSpec(const AttributeSpec &) = default; AttributeSpec & AttributeSpec::operator=(const AttributeSpec &) = default; AttributeSpec::AttributeSpec(AttributeSpec &&) noexcept = default; AttributeSpec & AttributeSpec::operator=(AttributeSpec &&) noexcept = default; AttributeSpec::~AttributeSpec() = default; bool AttributeSpec::operator==(const AttributeSpec &rhs) const { return ((_name == rhs._name) && (_cfg == rhs._cfg)); } }
*= $0801 .byte $4c,$16,$08,$00,$97,$32 .byte $2c,$30,$3a,$9e,$32,$30 .byte $37,$30,$00,$00,$00,$a9 .byte $01,$85,$02 jsr print .byte 13 .text "(up)cmpay" .byte 0 lda #%00011011 sta db lda #%11000110 sta ab lda #%10110001 sta xb lda #%01101100 sta yb lda #0 sta pb tsx stx sb lda #0 sta db sta ab sta yb next lda db sta da sta dr lda ab sta ar sec sbc db php pla and #%10000011 sta flags+1 lda pb ora #%00110000 and #%01111100 flags ora #0 sta pr lda xb sta xr lda yb sta yr lda sb sta sr ldx sb txs lda pb pha lda ab ldx xb ldy yb plp cmd cmp da,y php cld sta aa stx xa sty ya pla sta pa tsx stx sa jsr check inc cmd+1 bne noinc inc cmd+2 noinc lda yb bne nodec dec cmd+2 nodec dec yb clc lda db adc #17 sta db bcc jmpnext lda #0 sta db clc lda ab adc #17 sta ab bcc jmpnext lda #0 sta ab inc pb beq nonext jmpnext jmp next nonext jsr print .text " - ok" .byte 13,0 lda 2 beq load wait jsr $ffe4 beq wait jmp $8000 load jsr print name .text "cmpix" namelen = *-name .byte 0 lda #0 sta $0a sta $b9 lda #namelen sta $b7 lda #<name sta $bb lda #>name sta $bc pla pla jmp $e16f db .byte 0 ab .byte 0 xb .byte 0 yb .byte 0 pb .byte 0 sb .byte 0 da .byte 0 aa .byte 0 xa .byte 0 ya .byte 0 pa .byte 0 sa .byte 0 dr .byte 0 ar .byte 0 xr .byte 0 yr .byte 0 pr .byte 0 sr .byte 0 check .block lda da cmp dr bne error lda aa cmp ar bne error lda xa cmp xr bne error lda ya cmp yr bne error lda pa cmp pr bne error lda sa cmp sr bne error rts error jsr print .byte 13 .null "before " ldx #<db ldy #>db jsr showregs jsr print .byte 13 .null "after " ldx #<da ldy #>da jsr showregs jsr print .byte 13 .null "right " ldx #<dr ldy #>dr jsr showregs lda #13 jsr $ffd2 wait jsr $ffe4 beq wait cmp #3 beq stop rts stop lda 2 beq basic jmp $8000 basic jmp ($a002) showregs stx 172 sty 173 ldy #0 lda (172),y jsr hexb lda #32 jsr $ffd2 lda #32 jsr $ffd2 iny lda (172),y jsr hexb lda #32 jsr $ffd2 iny lda (172),y jsr hexb lda #32 jsr $ffd2 iny lda (172),y jsr hexb lda #32 jsr $ffd2 iny lda (172),y ldx #"n" asl a bcc ok7 ldx #"N" ok7 pha txa jsr $ffd2 pla ldx #"v" asl a bcc ok6 ldx #"V" ok6 pha txa jsr $ffd2 pla ldx #"0" asl a bcc ok5 ldx #"1" ok5 pha txa jsr $ffd2 pla ldx #"b" asl a bcc ok4 ldx #"B" ok4 pha txa jsr $ffd2 pla ldx #"d" asl a bcc ok3 ldx #"D" ok3 pha txa jsr $ffd2 pla ldx #"i" asl a bcc ok2 ldx #"I" ok2 pha txa jsr $ffd2 pla ldx #"z" asl a bcc ok1 ldx #"Z" ok1 pha txa jsr $ffd2 pla ldx #"c" asl a bcc ok0 ldx #"C" ok0 pha txa jsr $ffd2 pla lda #32 jsr $ffd2 iny lda (172),y .bend hexb pha lsr a lsr a lsr a lsr a jsr hexn pla and #$0f hexn ora #$30 cmp #$3a bcc hexn0 adc #6 hexn0 jmp $ffd2 print pla .block sta print0+1 pla sta print0+2 ldx #1 print0 lda !*,x beq print1 jsr $ffd2 inx bne print0 print1 sec txa adc print0+1 sta print2+1 lda #0 adc print0+2 sta print2+2 print2 jmp !* .bend
; Test case generated by KLC3 ; This file contains the test input event list. ; Note that this file may contains additional things after the end of event list. ; Please carefully identify the end of the event list. .ORIG x4000 .FILL x0008 ; EVENT1_WEEKDAY_BV .STRINGZ "A" ; EVENT1_NAME .FILL x000E ; EVENT1_SLOT .FILL x0007 ; EVENT2_WEEKDAY_BV .STRINGZ "BBBBBBBBBB" ; EVENT2_NAME .FILL x000E ; EVENT2_SLOT .FILL x001F ; EVENT3_WEEKDAY_BV .STRINGZ "" ; EVENT3_NAME .FILL x0001 ; EVENT3_SLOT .FILL xFFFF .END
// // RSM test client // #include "rsm_protocol.h" #include "rsmtest_client.h" #include "rpc.h" #include <arpa/inet.h> #include <vector> #include <stdlib.h> #include <stdio.h> #include <string> using namespace std; rsmtest_client *lc; int main(int argc, char *argv[]) { int r; if(argc != 4){ fprintf(stderr, "Usage: %s [host:]port [partition] arg\n", argv[0]); exit(1); } lc = new rsmtest_client(argv[1]); string command(argv[2]); if (command == "partition") { r = lc->net_repair(atoi(argv[3])); printf ("net_repair returned %d\n", r); } else if (command == "breakpoint") { int b = atoi(argv[3]); r = lc->breakpoint(b); printf ("breakpoint %d returned %d\n", b, r); } else { fprintf(stderr, "Unknown command %s\n", argv[2]); } exit(0); }
/* * Copyright (C) 2010 - 2012 ProjectSkyfire <http://www.projectskyfire.org/> * * Copyright (C) 2012 - 2012 FrenchCORE <http://www.frcore.com/> * Copyright (C) 2008 - 2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptPCH.h" #include "pit_of_saron.h" // positions for Martin Victus (37591) and Gorkun Ironskull (37592) Position const SlaveLeaderPos = {689.7158f, -104.8736f, 513.7360f, 0.0f}; // position for Jaina and Sylvanas Position const EventLeaderPos2 = {1054.368f, 107.14620f, 628.4467f, 0.0f}; class instance_pit_of_saron : public InstanceMapScript { public: instance_pit_of_saron() : InstanceMapScript(PoSScriptName, 658) { } struct instance_pit_of_saron_InstanceScript : public InstanceScript { instance_pit_of_saron_InstanceScript(Map* map) : InstanceScript(map) { SetBossNumber(MAX_ENCOUNTER); _garfrostGUID = 0; _krickGUID = 0; _ickGUID = 0; _tyrannusGUID = 0; _rimefangGUID = 0; _jainaOrSylvanas1GUID = 0; _jainaOrSylvanas2GUID = 0; _teamInInstance = 0; } void OnPlayerEnter(Player* player) { if (!_teamInInstance) _teamInInstance = player->GetTeam(); } void OnCreatureCreate(Creature* creature) { if (!_teamInInstance) { Map::PlayerList const &players = instance->GetPlayers(); if (!players.isEmpty()) if (Player* player = players.begin()->getSource()) _teamInInstance = player->GetTeam(); } switch(creature->GetEntry()) { case NPC_GARFROST: _garfrostGUID = creature->GetGUID(); break; case NPC_KRICK: _krickGUID = creature->GetGUID(); break; case NPC_ICK: _ickGUID = creature->GetGUID(); break; case NPC_TYRANNUS: _tyrannusGUID = creature->GetGUID(); break; case NPC_RIMEFANG: _rimefangGUID = creature->GetGUID(); break; case NPC_TYRANNUS_EVENTS: _tyrannusEventGUID = creature->GetGUID(); break; case NPC_SYLVANAS_PART1: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_JAINA_PART1, ALLIANCE); _jainaOrSylvanas1GUID = creature->GetGUID(); break; case NPC_SYLVANAS_PART2: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_JAINA_PART2, ALLIANCE); _jainaOrSylvanas2GUID = creature->GetGUID(); break; case NPC_KILARA: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_ELANDRA, ALLIANCE); break; case NPC_KORALEN: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_KORLAEN, ALLIANCE); break; case NPC_CHAMPION_1_HORDE: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_CHAMPION_1_ALLIANCE, ALLIANCE); break; case NPC_CHAMPION_2_HORDE: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_CHAMPION_2_ALLIANCE, ALLIANCE); break; case NPC_CHAMPION_3_HORDE: // No 3rd set for Alliance? if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_CHAMPION_2_ALLIANCE, ALLIANCE); break; case NPC_HORDE_SLAVE_1: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_ALLIANCE_SLAVE_1, ALLIANCE); break; case NPC_HORDE_SLAVE_2: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_ALLIANCE_SLAVE_2, ALLIANCE); break; case NPC_HORDE_SLAVE_3: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_ALLIANCE_SLAVE_3, ALLIANCE); break; case NPC_HORDE_SLAVE_4: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_ALLIANCE_SLAVE_4, ALLIANCE); break; case NPC_FREED_SLAVE_1_HORDE: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_FREED_SLAVE_1_ALLIANCE, ALLIANCE); break; case NPC_FREED_SLAVE_2_HORDE: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_FREED_SLAVE_2_ALLIANCE, ALLIANCE); break; case NPC_FREED_SLAVE_3_HORDE: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_FREED_SLAVE_3_ALLIANCE, ALLIANCE); break; case NPC_RESCUED_SLAVE_HORDE: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_RESCUED_SLAVE_ALLIANCE, ALLIANCE); break; case NPC_MARTIN_VICTUS_1: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_MARTIN_VICTUS_1, ALLIANCE); break; case NPC_MARTIN_VICTUS_2: if (_teamInInstance == ALLIANCE) creature->UpdateEntry(NPC_MARTIN_VICTUS_2, ALLIANCE); break; default: break; } } void OnGameObjectCreate(GameObject* go) { switch (go->GetEntry()) { case GO_ICE_WALL: uiIceWall = go->GetGUID(); if(GetBossState(DATA_GARFROST) == DONE && GetBossState(DATA_ICK) == DONE) HandleGameObject(NULL,true,go); break; } } bool SetBossState(uint32 type, EncounterState state) { if (!InstanceScript::SetBossState(type, state)) return false; switch (type) { case DATA_ICK: switch(state) { case DONE: if(GetBossState(DATA_GARFROST)==DONE) HandleGameObject(uiIceWall,true,NULL); } break; case DATA_GARFROST: if(state == DONE) { { if(GetBossState(DATA_ICK)==DONE) HandleGameObject(uiIceWall,true,NULL); } if (Creature* summoner = instance->GetCreature(_garfrostGUID)) { if (_teamInInstance == ALLIANCE) summoner->SummonCreature(NPC_MARTIN_VICTUS_1, SlaveLeaderPos, TEMPSUMMON_MANUAL_DESPAWN); else summoner->SummonCreature(NPC_GORKUN_IRONSKULL_2, SlaveLeaderPos, TEMPSUMMON_MANUAL_DESPAWN); } } break; case DATA_TYRANNUS: if (state == DONE) { if (Creature* summoner = instance->GetCreature(_tyrannusGUID)) { if (_teamInInstance == ALLIANCE) summoner->SummonCreature(NPC_JAINA_PART2, EventLeaderPos2, TEMPSUMMON_MANUAL_DESPAWN); else summoner->SummonCreature(NPC_SYLVANAS_PART2, EventLeaderPos2, TEMPSUMMON_MANUAL_DESPAWN); } } break; default: break; } return true; } uint32 GetData(uint32 type) { switch(type) { case DATA_TEAM_IN_INSTANCE: return _teamInInstance; default: break; } return 0; } uint64 GetData64(uint32 type) { switch (type) { case DATA_GARFROST: return _garfrostGUID; case DATA_KRICK: return _krickGUID; case DATA_ICK: return _ickGUID; case DATA_TYRANNUS: return _tyrannusGUID; case DATA_RIMEFANG: return _rimefangGUID; case DATA_TYRANNUS_EVENT: return _tyrannusEventGUID; case DATA_JAINA_SYLVANAS_1: return _jainaOrSylvanas1GUID; case DATA_JAINA_SYLVANAS_2: return _jainaOrSylvanas2GUID; default: break; } return 0; } std::string GetSaveData() { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << "P S " << GetBossSaveData(); OUT_SAVE_INST_DATA_COMPLETE; return saveStream.str(); } void Load(const char* in) { if (!in) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(in); char dataHead1, dataHead2; std::istringstream loadStream(in); loadStream >> dataHead1 >> dataHead2; if (dataHead1 == 'P' && dataHead2 == 'S') { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { uint32 tmpState; loadStream >> tmpState; if (tmpState == IN_PROGRESS || tmpState > SPECIAL) tmpState = NOT_STARTED; SetBossState(i, EncounterState(tmpState)); } } else OUT_LOAD_INST_DATA_FAIL; OUT_LOAD_INST_DATA_COMPLETE; } private: uint64 _garfrostGUID; uint64 _krickGUID; uint64 _ickGUID; uint64 _tyrannusGUID; uint64 _rimefangGUID; uint64 _tyrannusEventGUID; uint64 _jainaOrSylvanas1GUID; uint64 _jainaOrSylvanas2GUID; uint64 uiIceWall; uint32 _teamInInstance; }; InstanceScript* GetInstanceScript(InstanceMap* map) const { return new instance_pit_of_saron_InstanceScript(map); } }; void AddSC_instance_pit_of_saron() { new instance_pit_of_saron(); }
#pragma once #include "vfs/platform.hpp" // File interface #include "vfs/directory_interface.hpp" // Platform specific implementations #if VFS_PLATFORM_WIN # include "vfs/win_directory.hpp" #elif VFS_PLATFORM_POSIX # include "vfs/posix_directory.hpp" #else # error No directory implementation defined for the current platform #endif #include "vfs/path.hpp" #include "vfs/file.hpp" namespace vfs { //---------------------------------------------------------------------------------------------- using directory = directory_interface<directory_impl>; //---------------------------------------------------------------------------------------------- inline bool create_path(const path &p) { auto folders = split_string(p.str(), path::separators()); if (folders.empty()) { // Invalid path, either empty or containing only path separators. return false; } size_t i = 0; std::string currentPath; const auto &pathStr = p.str(); // Test for absolute paths. if ((pathStr.length() >= 1) && pathStr[0] == '/') { currentPath = "/"; } // Test for remote location. // Those will look like \\foo\bar\ where foo is the remote computer. else if ((pathStr.length() >= 2) && pathStr[0] == '\\' && pathStr[1] == '\\') { // The first folder will contain the name of the remote computer. currentPath = path::combine(path::separator(), path::separator(), folders[0], path::separator()); ++i; } // Drive included in the path. // e.g. C:\foo\bar else if ((pathStr.length() >= 3) && pathStr[1] == ':' && pathStr[2] == '\\') { // The first folder will contain the name of the drive, e.g. 'C:'. currentPath = path::combine(folders[0], path::separator()); ++i; } // Go through the folders list and create any of them that doesn't exit. for (; i < folders.size(); ++i) { currentPath += path::combine(folders[i], path::separator()); if (!directory::exists(currentPath)) { if (!directory::create_directory(currentPath)) { return false; } } } return true; } //---------------------------------------------------------------------------------------------- inline bool delete_directory(const path &dirPath, bool recursivelyDeleteFiles = false) { auto dir = directory(dirPath); dir.scan(); if (recursivelyDeleteFiles) { for (const auto &f : dir.getFiles()) { file::delete_file(f); } } for (const auto &subDir : dir.getSubDirectories()) { delete_directory(subDir.getPath(), recursivelyDeleteFiles); } return directory::delete_directory(dirPath); } //---------------------------------------------------------------------------------------------- inline bool move_directory(const path &src, const path &dst, bool overwrite = false) { if (!directory::exists(src)) { vfs_errorf("Source directory doesn't exists: %s", src.c_str()); return false; } if (!directory::exists(dst)) { if (!directory::create_directory(dst)) { return false; } } else if (!overwrite) { vfs_errorf("Destination directory already exists: %s", dst.c_str()); return false; } auto dir = directory(src); dir.scan(); // Move all files in the new location. for (const auto &srcPath : dir.getFiles()) { const auto &dstPath = path::combine(dst, extract_file_name(srcPath)); file::move(srcPath, dstPath, overwrite); } // Recursively create the sub directories hierarchy. for (auto &d : dir.getSubDirectories()) { const auto &srcPath = d.getPath(); const auto &dstPath = path::combine(dst, extract_file_name(srcPath)); move_directory(srcPath, dstPath, overwrite); } // Delete the source directory (should be empty by now). return delete_directory(src); } } /*vfs*/
;* ;* CW : Character Windows Drivers ;* ;* fx_csd5.asm : Fixed screen driver, OS/2 (linked in) ;* * DOES NOT INCLUDE "csd_code" ;* * has data in application's data segment ;***************************************************************************** include csd_head.inc include fxdrv.inc DM_NonDefault = 1 SDDATA_NonDefault = 1 include csd_data.inc ;* standard data include scr5.inc include scr5data.inc ;* extra data ;***************************************************************************** include fx_data.asm ;***************************************************************************** sBegin DRV assumes CS,DRV assumes ds,NOTHING assumes ss,NOTHING ;***************************************************************************** ;* * There is no low memory structure for the linked driver OFF_lpwDataCsd DW dataOffset rgwDataCsd ;***************************************************************************** include scr5.asm include csd_std.asm include csd_vram.asm include csd_save.asm ;***************************************************************************** include csd_tail.asm ;* tail file ;***************************************************************************** END
fbl(8) g5<1>UD g5<8,8,1>UD { align1 1Q }; fbl(16) g6<1>UD g8<8,8,1>UD { align1 1H }; fbl(1) g27<1>UD mask0<0,1,0>UD { align1 WE_all 1N };
; A214946: Number of squarefree words of length 7 in an (n+1)-ary alphabet. ; 0,60,1848,15960,80040,292740,868560,2218608,5062320,10575180,20577480,37769160,66015768,110690580,179077920,280842720,428571360,638388828,930657240,1330760760,1869981960,2586474660,3526338288,4744798800,6307501200,8291918700,10788883560,13904244648,17760656760,22499506740,28282981440,35296282560,43749993408,53882602620,65963189880,80294278680,97214861160,117103600068,140382212880,167519043120,199032823920,235496638860,277542085128,325863644040,381223263960,444455160660,516470840160,598264349088,690917757600,795606879900,913607237400,1046300269560,1195179797448,1361858745060,1548076123440,1755704282640,1986756436560,2243394465708,2527937002920,2842867807080,3190844429880,3574707180660,3997488394368,4462422007680,4972953448320,5532749842620,6145710546360,6815978003928,7547948940840,8346285894660,9215929089360,10162108658160,11190357219888,12306522813900,13516782198600,14827654518600,16246015345560,17779111097748,19434573843360,21220436492640,23145148383840,25217591268060,27447095698008,29843457825720,32416956614280,35178371468580,38139000290160,41310677961168,44705795262480,48337318231020,52218807961320,56364440856360,60789029332728,65508042985140,70537630215360,75894640330560,81596646116160,87661966888188,94109692030200,100959705019800 mov $2,$0 mov $3,$0 add $3,2 mul $2,$3 mov $4,$2 mul $2,$3 lpb $0 mov $0,0 add $2,1 mul $2,$4 sub $4,1 mul $4,$2 add $1,$4 lpe div $1,12 mul $1,12 mov $0,$1
; A133823: Triangle whose rows are sequences of increasing and decreasing cubes:1; 1,8,1; 1,8,27,8,1; ... . ; 1,1,8,1,1,8,27,8,1,1,8,27,64,27,8,1,1,8,27,64,125,64,27,8,1,1,8,27,64,125,216,125,64,27,8,1,1,8,27,64,125,216,343,216,125,64,27,8,1,1,8,27,64,125,216,343,512,343,216,125,64,27,8,1,1,8,27,64,125,216,343,512,729,512,343,216,125,64,27,8,1,1,8,27,64,125,216,343,512,729,1000,729,512,343,216,125,64,27,8,1 seq $0,4737 ; Concatenation of sequences (1,2,...,n-1,n,n-1,...,1) for n >= 1. pow $0,3
; A003486: a(n) = (n^2 + 1)*3^n. ; 1,6,45,270,1377,6318,26973,109350,426465,1614006,5963949,21611934,77058945,271034910,942244893,3242852982,11063007297,37450647270,125911658925,420738651054,1398200544801,4623476115726,15219813910365,49895884778310,162961842549537,530402669511318,1720843165778733,5566686164040510,17958282077144385,57786777741231486,185507910017278749,594201807225157014,1899345693573137025,6059376017545520070,19295499226514220333,61338674291373640782,194672741980207859937,616888951070666387310 mov $1,$0 pow $1,2 add $1,1 mov $2,3 pow $2,$0 mul $1,$2 mov $0,$1
;------------------------------------------------------------------------------ ; floppy routines for 8085 CPU, PC8477B FDC ; uses no DMAs, no IRQs and TC pin is not serviced ; all data flow control is done via FDC internal registers ;------------------------------------------------------------------------------ ; symbolic constants FDC_RECALIB equ 0 FDC_SEEK equ 1 FDC_READ equ 2 FDC_WRITE equ 3 ; driver constants READ_RETRY equ 3 ;when read sector fails, retry it n times RST65_ADDR equ 0034h ;6.5 interrupt vector MOTOR_TIMEOUT equ 4 ;seconds motor timeout FDC_BASE equ 50h REG_DOR equ FDC_BASE+02h ;digital output register bits (MTR3 MTR2 MTR1 MTR0 DMAEN RESET DRIVE_SEL_1 DRIVE_SEL_0) REG_MSR equ FDC_BASE+04h ;address of main status register REG_DSR equ FDC_BASE+04h ;address of data rate select register REG_DATA equ FDC_BASE+05h ;floppy data register REG_CCR equ FDC_BASE+07h ;configuration control register ;DRIVE_0_DOR equ 14h ;motor on & drive select, no DMA&INT ;DRIVE_1_DOR equ 25h ;motor on & drive select, no DMA&INT ;DRIVE_2_DOR equ 46h ;motor on & drive select, no DMA&INT ;DRIVE_3_DOR equ 87h ;motor on & drive select, no DMA&INT CNF_250 equ 02h ;250kbps data rate (360kB, 720kB) CNF_300 equ 01h ;300kbps data rate (360kB disk in 1.2MB drive) CNF_500 equ 00h ;500kbps data rate (1.2MB, 1.44MB) ;MODE_BYTE1 equ 0xC6 ;mode2, no NSC imp.seek (better use 82077 method), ISO, auto low pwr MODE_BYTE1 equ 86h ;mode2, no imp.seek, IBM, auto low pwr MODE_BYTE2 equ 00h ;FIFO enabled, few tracks if FloppySpeed == "FAST" MODE_BYTE3 equ 0C1h ;default densel, 1x8ms head settle time SPECIFY_BYTE1 equ 0EAh ;step rate 4ms, motor off 10s elseif FloppySpeed == "MEDIUM" MODE_BYTE3 equ 0C2h ;default densel, 2x8ms head settle time SPECIFY_BYTE1 equ 0CAh ;step rate 8ms, motor off 10s endif MODE_BYTE4 equ 00h ;dskchg default SPECIFY_BYTE2 equ 05h ;2x64ms motor on delay, no DMA ; fdc commands CMD_RESET equ 80h ;reset fdc by pulling bit 7 high CMD_INIT equ 04h ;unset reset bit, no DMA CMD_RECALIB equ 07h ;recalibrate CMD_READ equ 46h ;read command, bit 6 is MFM CMD_WRITE equ 45h ;write command, bit 6 is MFM CMD_SEEK equ 0Fh ;absolute track seek CMD_SENS_INTR equ 08h ;sense interrupt command CMD_FORMAT equ 4Dh ;format command, bit 6 is MFM CMD_CONFIG1 equ 13h ;configure command CMD_CONFIG24 equ 00h ;CMD_CONFIG3 equ 0x14 ;disable polling mode (765), no implied seeks, FIFO thresh 4 CMD_CONFIG3 equ 54h ;disable polling mode (765), implied seeks 82077 method, FIFO thresh 4 CMD_NSC equ 18h ;National PC8477 identifes itself as 73h CMD_MODE equ 01h ;set motor timer mode, implied seek, index address, low power CMD_SPECIFY equ 03h ;set internal timers CMD_SENSE_STAT equ 04h ;sense drive status ; do not change order of following lines ; read/write param table (set at runtime) drive_nr: db 0 ;drive track_nr: db 0 ;track head_nr: db 0 ;head sector_nr: db 1 ;sector NUMBER_OF_BYTES:db 1 ;256 bytes per sector eot_sec_nr: db 0 ;end of track sector number ; config values (changed at runtime when needed) gap_length: db 0Ah ;intersector gap length data_length: db 80h ;data length - don't care (end of table above) number_of_sctrs:db 18 ;18 sectors gap3_length: db 0Ch ;recommended value ccr_dsr_value: db CNF_250 mode3_value: db MODE_BYTE3 ; disk format params ;DATA_PATTERN: db 0E5h ;format pattern ; data buffer ;dbuffer: ds 256 ;sector data buffer ; flag area ;drive_calib_0: ;.db 0 ;0 not calibrated, 1 recalibrated ;drive_calib_1: ;.db 0 ;0 not calibrated, 1 recalibrated ; results area status_reg_0: db 0 ;status register 0 status_reg_1: db 0 ;status register 1 status_reg_2: db 0 ;status register 2 status_reg_3: db 0 ;status register 3, bit 6 - write protect ;bit 4 - track0, bit 2 - head select ;bits 0,1 - drive ds 3 ;placeholder for last 3 bytes fdc_extraloop: db 0 ;used in some time loops ticks: db 0 ;8155/8253 timer ticks seconds: db 0 ;motor time off motor_0_state: db 0 ;motor on flag motor_1_state: db 0 ;motor on flag num_of_tracks: db 0 ;drive param ; ; table with drive type params(density,sectors,tracks,GAP,GAP3,densel) table_drv_typ0: db CNF_250, 18, 40, 0Ah, 0Ch, 0C2h ; 360kB 5.25" DD/40tracks standard drive table_drv_typ1: db CNF_250, 18, 80, 0Ah, 0Ch, 0C2h ; 720kB 5.25" DD/80tracks special drive (TEAC FD-55F) table_drv_typ2: db CNF_500, 26, 80, 0Eh, 36h, 0C2h ; 1.2MB 5.25" HD drive table_drv_typ3: db CNF_500, 32, 80, 0Eh, 36h, 02h ; 1.44MB 3.5" HD drive table_drv_typ4: db CNF_300, 18, 80, 0Ah, 0Ch, 0C2h ; 720kB 5.25" HD drive ; set drive type (0-360kb, 1-720kb, 2-1.2M, 3-1.44M, 4-720kB in HD drive) set_drv_type0: lxi h, table_drv_typ0 set_drv_type: mov a,m sta ccr_dsr_value ;data rate out REG_CCR out REG_DSR inx h ;number of sectors mov a,m sta number_of_sctrs inx h ;tracks mov a,m sta num_of_tracks inx h ;read/write gap value mov a,m sta gap_length inx h ;format gap3 value mov a,m sta gap3_length inx h ;densel pin polarity (3.5 vs 5.25 drives) mov a,m sta mode3_value call fd_mode ;use new value ret set_drv_type1: lxi h, table_drv_typ1 jmp set_drv_type set_drv_type2: lxi h, table_drv_typ2 jmp set_drv_type set_drv_type3: lxi h, table_drv_typ3 jmp set_drv_type set_drv_type4: lxi h, table_drv_typ4 jmp set_drv_type ; ; long delay, cca 3ms long_delay: push b lxi b,0100h ld1: call fd_delay dcx b mov a,b ora c jnz ld1 pop b ret ; ; wait aprox. 25us (42t fixed + 24t x LOOP) ; 5MHz CPU 125 cycles (act.162) ; 8MHz CPU 200 cycles (act.234) fd_delay: push b ;[12] lxi b,CRYSTAL/2 ;[10] dela1: dcx b ;[6] mov a,b ;[4] ora c ;[4] jnz dela1 ;[10] pop b ;[10] ret ;[10] ; ; wait until FDC is ready for new command, C flag set on timeout busy_check: push b mvi b,0FFh busy_check2: dcr b jz busy_err ;something is wrong in REG_MSR ;get FDC status ral ;look for busy bit jnc busy_wait ;wait rar ;remake status byte pop b stc cmc ;ok ret busy_wait: call fd_delay jmp busy_check2 busy_err: pop b stc ret ; ; motor on - start motor (when not already started and selects drive) motor_on: lda drive_nr ora a jz .l1 ;drive 0 cpi 01 jz .l2 ;drive 1 ;lxi h,BAD_DRIVE_NR ;for C programm stc ;error ret .l1 mvi a,MOTOR_TIMEOUT ;timeout sta motor_0_state ;set motor 0 started jmp motor_do .l2 mvi a,MOTOR_TIMEOUT ;timeout sta motor_1_state ;set motor 1 started ;fall through ; ;sets DOR register accordingly to motor flags motor_do: push h ;back up push b ;back up lxi h,motor_0_state ;point to motor 0 xra a ;compute result DOR value mov b,a ;clear a,b regsdir c: ora M ;add motor bit for drive 0 jz .l1 ;zero means motor stopped mvi b,10h ;motor 0 is bit 4 .l1 inx h ;move to drive 1 xra a ora M ;add motor bit for drive 1 jz .l2 ;motor 1 stopped mov a,b ;restore motor 0 ori 20h ;motor 1 is bit 5 mov b,a ;backup motors 0,1 .l2 lda drive_nr ;compute result DOR value (drive bits 0,1) ora b ;add motor bits (7..4) ori 04h ;do not reset FDC :-) out REG_DOR ;set FDC register in REG_MSR ;hmm just needed pop b ;restore pop h ;restore ret ; ; read one byte from data reg read_byte: call busy_check rc ;timeout in REG_MSR ;wants to give us result? ani 40h cpi 40h jz read_byte2 stc ;lxi h,DATA_NOT_READY ret read_byte2: in REG_DATA ;read the byte ora a ;set flags, clear carry ret ; ; write one byte to data reg write_byte: push psw call busy_check jnc .l1 pop psw stc ret ;timeout .l1 ani 0C0h cpi 80h ;ready to accept byte? jz .l2 pop psw stc ;lxi h,FDC_NOT_READY ret .l2 pop psw out REG_DATA ;write the byte stc cmc ;clear carry ret ; ; initialise FDC fd_init: mvi a,CMD_RESET out REG_DSR call long_delay xra a out REG_DOR ;software reset call long_delay mvi a,CMD_INIT ;unset reset bit, no DMA, (stops motor) out REG_DOR xra a ;save 0 sta motor_0_state ;motor stopped sta motor_1_state ;motor stopped call fd_delay lda ccr_dsr_value ;250kbps/300kbps/500kbps out REG_DSR call fd_delay lda ccr_dsr_value ;250kbps/300kbps/500kbps out REG_CCR call fd_configure call fd_specify call fd_mode ret ; ; National Semiconductor PC8477B identifies itself as 73h fd_nsc: mvi a,CMD_NSC call write_byte call read_byte ;should be 73h ret ; configure command - implied seek, disable polling, fifo enable fd_configure: mvi a,CMD_CONFIG1 call write_byte mvi a,CMD_CONFIG24 call write_byte mvi a,CMD_CONFIG3 call write_byte mvi a,CMD_CONFIG24 call write_byte ret ; ; mode command - sets special features of fdc (FIFO, densel, low pwr, ..) fd_mode: mvi a,CMD_MODE call write_byte mvi a,MODE_BYTE1 call write_byte mvi a,MODE_BYTE2 call write_byte lda mode3_value ;DENSEL polarity call write_byte mvi a,MODE_BYTE4 call write_byte ret ; ; mode specify - sets internal timers of fdc (step rate, motor on/of) fd_specify: mvi a,CMD_SPECIFY call write_byte mvi a,SPECIFY_BYTE1 call write_byte mvi a,SPECIFY_BYTE2 call write_byte ret ; ; sense drive status - read status register 3 fd_sensestat: mvi a,CMD_SENSE_STAT call write_byte rc ;without diskette it hangs (TODO init FDC?) lda drive_nr ;2nd byte is drive number call write_byte call read_byte ;result phase, status 3 sta status_reg_3 ;store it ani 10h ;check track 0 flag stc ;not track 0 rz cmc ;track 0 detected ret ; ; recalibrate - move to track 0 fd_recalib: mvi a,CMD_RECALIB ;output recalibrate command call write_byte lda drive_nr ;2nd byte is drive number call write_byte lxi b,0FFFh ;wait limit .l1 call fd_sensestat ;check for track 0 jnc .l2 ;track 0 detected dcx b mov a,b ora c jnz .l1 ;jmp sense_intrpt ;timeout, try sensing now .l2 ;fall through ; ; sense interrupt - clears busy bit in MSR after seek and recalibrate commands sense_intrpt: call long_delay ;give the drive some time in REG_MSR ;sense drive seek bits ani 0Fh ;all four drive bits lxi h,0 ;for C rz call long_delay ;no hurry, mechanics is slow mvi a,CMD_SENS_INTR out REG_DATA sense_stat: call read_byte ;result phase, status0 ani 0F0h ;isolate state bits mov b,a ;backup ani 0C0h ;D7,6 must be 00 for normal termination ;lxi h,SENSE_FAILED ;for C program stc ;error rnz mov a,b ani 10h ;lxi h,EQUIPMENT_CHECK ;track 0 signal failed after recalibrate stc rnz sense_track: call read_byte ;read track_nr (recalibrate sets to 0) sta track_nr ;drive is calibrated sense_exit: ;lxi h,RESULT_OK ;for C programm ;stc optimized ;cmc ;clear carry ret ; ; seek track fd_seek: mvi a,CMD_SEEK call write_byte ;output seek command call send_head_drv ;output head and drive number call send_track ;output track number lxi d,40h ;sense interrupt retries .l1 call sense_intrpt jnc .l2 dcr d jnz .l1 ;lxi h,SEEK_FAILED stc ;error ret .l2 ;lxi h,RESULT_OK ;for C ret ;optimized carry is cleared ; ; status - read result of a command read_status: lxi d,0 ;bytes read read_stl1: lxi b,0 ;timeout loop read_stl2: call fd_delay ;wait in REG_MSR ani 0F0h ;RQM=1, DIO=1, EXEC=0, BUSY=1 cpi 0D0h jz next_status cpi 80h ;command finished jz eval_status dcx b mov a,b ora c jnz read_stl2 ;lxi h,TIMEOUT_WATING ;timeout stc ret next_status: mov a,d cpi 07h ;there are 7 result bytes jz read_sterr ;too many status bytes lxi h,status_reg_0 dad d ;array offset inx d ;move to next array item in REG_DATA mov M,a jmp read_stl1 ;loop read_sterr: ;lxi h,ST_TOO_MANY ;should never happen stc ret ; ; evaluate status bytes eval_status: ;lda status_reg_0 ;process Status 0 lda status_reg_1 ;process Status 1 mov b,a ;backup ;ani 0x80 ;end of track error ;jz 1$ in non DMA transfers without using TC pin ;lxi h,ST1_EOTER it is expected condition. There is no other ;stc way to stop FDC to process next sector ;ret .l1 ;mov a,b ani 37h jz eval_st2 stc ret ;ani 20h ;CRC error ;jz .l2 ;lxi h,ST1_CRCER ;stc ;ret .l2 ;mov a,b ;ani 10h ;overrun, CPU too slow ;jz .l3 ;lxi h,ST1_OVERN ;stc ;ret .l3 ;mov a,b ;ani 04h ;no data ;jz .l4 ;lxi h,ST1_NODAT ;stc ;ret .l4 ;mov a,b ;ani 02h ;write protect ;jz .l5 ;lxi h,ST1_WRTPRT ;stc ;ret .l5 ;mov a,b ;ani 01h ;mising address mark ;jz eval_st2 ;lxi h,ST1_MSADR ;stc ;ret eval_st2: lda status_reg_2 ;process Status 2 mov b,a ani 73h jz read_stok stc ret ;ani 12h ;wrong track detected ;jz .l1 ;lxi h,ST2_BADTRK ;stc ;ret .l1 ;mov a,b ;ani 40h ;scan not satisfied ;jz .l2 ;lxi h,ST2_CRCERR ;stc ;ret .l2 ;mov a,b ;ani 20h ;CRC error ;jz .l3 ;lxi h,ST2_CRCERR ;stc ;ret .l3 ;mov a,b ;ani 01h ;missing address mark in data field ;jz read_stok ;lxi h,ST2_MISADR ;stc ;ret read_stok: ;lxi h,RESULT_OK ;all OK stc cmc ret ; ; output head and drive number send_head_drv: lda head_nr ;head number ral ral mov b,a ;backup lda drive_nr ;drive number ora b ;combine them call write_byte ;output head and drive number ret ; ; output track number send_track: lda track_nr ;get physical track call write_byte ret ; ; command phase, send 7 data fields fd_cmd_pha: lda sector_nr ;load current sector number sta eot_sec_nr ;store it in EOT to stop processing more secs mvi c,7 lxi d,track_nr ;table begin (track, head, sector, bytes, EOT, GAP, len) fd_cmd_l1: call busy_check ani 0F0h ;RQM/DIO cpi 90h ;RQM=1, DIO=0 (fdc ready for a byte), CMD in progress jnz fd_cmd_err ;error .. ldax d ;load data out REG_DATA ;send to fdc inx d dcr c jnz fd_cmd_l1 ;next param ret ;command sent fd_cmd_err: jmp read_status ;jump and return to caller from there ; ; write one sector to diskette fd_write: mvi a, CMD_WRITE ;command phase call write_byte call send_head_drv ;send head << 2 | drive byte call fd_cmd_pha ;send 7 param bytes mvi e,0 ;sector size 256 bytes lxi h,dbuffer ;execution phase fd_write_start: mvi a,(CRYSTAL/2+8)/4 ;start write sta fdc_extraloop fd_write_outlo: mvi c,0 ;outer loop 256x fd_write_inrlo: mvi b,0 ;inner loop 256x fd_write_l1: in REG_MSR cpi 0B0h ;RQM=1,DIO=1,NDM=1,BUSY=1 (ready to receive byte) jnz .l1 ;wait mov a,m ;transfer data to FDC out REG_DATA inx h dcr e jnz fd_write_l1 ;next byte jmp read_status ;result phase .l1 dcr b jnz fd_write_l1 ;quickly poll for next byte cpi 0C0h ;waiting for very first byte to write (or abort) jz fd_cmd_abort ;RQM=1, DIO=1, EXEC=0, BUSY=0 (execution aborted) dcr c jnz fd_write_inrlo ;try again cpi 0D0h ;exec aborted (FDC hanged)? jnz .l2 out REG_DATA ;take FDC out of hung jmp read_status ;and jump to status phase .l2 lda fdc_extraloop dcr a sta fdc_extraloop jnz fd_write_outlo ;lxi h,TIMEOUT_WATING ;timeout stc ret ; ; read one sector from diskette fd_read: mvi a, CMD_READ ;command phase call write_byte call send_head_drv ;send head << 2 | drive byte call fd_cmd_pha ;send 7 param bytes lxi h,dbuffer ;execution phase mvi a,(CRYSTAL/2+8)/4 ; sta fdc_extraloop mvi e,0 ;sector size 256 bytes fd_read_outlo: mvi c,0 ;outer loop 256x fd_read_inrlo: mvi b,0 ;inner loop 256x fd_read_l1: in REG_MSR cpi 0F0h ;RQM/DIO/EXEC/BUSY jnz .l1 ;data from floppy? in REG_DATA ;get it mov m,a ;transfer data to buff inx h dcr e jnz fd_read_l1 ;next byte call read_status ;result phase ret .l1 dcr b jnz fd_read_l1 ;quickly poll for next byte cpi 0C0h ;waiting for first byte (or abort) takes longer jz fd_cmd_abort ;RQM=1, DIO=1, EXEC=0, BUSY=0 (execution aborted) dcr c jnz fd_read_inrlo ;try again cpi 0D0h ;exec aborted (FDC hanged)? jnz .l2 jmp read_status ;and jump to status phase .l2 lda fdc_extraloop dcr a sta fdc_extraloop jnz fd_read_outlo ;lxi h,TIMEOUT_WATING ;timeout stc ret fd_cmd_abort: ;lxi h,CMD_ABORT stc ret ; ; report status register to C fd_msr: mvi h,0 in REG_MSR mov l,a ret ; ; start timer - when it expires motor off will be called timer_motor_off:; pulse frequency 10Hz mvi a,00h ;8155 timer out 04h mvi a,0FCh out 05h mvi a,0CEh out 00h mvi a,34h ;8253 timer 0 out 01Bh mvi a,00h out 18h mvi a,3Ch out 18h ; hook up interrupt handler mvi a,0C3h ;JUMP instruction sta RST65_ADDR ;timer is connected to 6.5 interrupt lxi h,interpt_65 ;routine's address shld RST65_ADDR+1 ret ; ; interrupt 6.5 - the timer interpt_65: di push psw ;backup push b ;backup lda ticks ;load ticks inr a ;increment sta ticks cpi 10 ;10hz signal jc .l3 ;less then second, return xra a ;clear ticks sta ticks in REG_MSR ;flash LEDs lda motor_0_state ;motor 0 time out ora a ;seconds to stop jz .l1 ;time out? lda motor_0_state ;no. only decrement time dcr a sta motor_0_state ;save back .l1 lda motor_1_state ;motor 1 time out ora a ;seconds to stop jz .l2 ;time out? lda motor_1_state ;no. only decrement time dcr a sta motor_1_state ;save back .l2 call motor_do ;set updated motor state to DOR register lda motor_0_state ;motor 0 mov b,a lda motor_1_state ;motor 1 ora b ;both motors stopped? cz disa_65 ;yes,mask out 6.5 (timer) .l3 pop b ;restore pop psw ;restore ei ;done, enable interrupt again ret ; ; execute command - all disk operations should be called from here ; A - operation number (0 - recalibrate, 1 - seek, 2 - read sector, 3 - read sector) fd_exec_cmd: push psw call fd_motor_on ;motor started? pop psw cpi FDC_RECALIB ;recalibrate jnz .l1 call fd_recalib jmp .l8 .l1 cpi FDC_SEEK ;seek track jnz .l2 call fd_seek jmp .l8 .l2 cpi FDC_READ ;read sector jz .l3 cpi FDC_WRITE ;write sector jnz .l8 ;unknown operation .l3 mvi d,READ_RETRY ;3x retry mov e,a ;backup operation .l4 push d mov a,e ;restore operation (what to do, read or write) cpi FDC_READ jz .l5 call fd_write jmp .l6 .l5 call fd_read .l6 pop d jnc .l8 ;success, return dcr d ;no luck retrying jz .l7 lda track_nr ;backup track_nr to read mov c,a push b ;push h ;backup error code (for C program) call fd_recalib ;recalibrate heads (sets track_nr to 0) ;pop h ;restore error code pop b mov a,c ;restore track_nr sta track_nr ;set it to param table jmp .l4 ;try again .l7 stc ;no luck .l8 push psw ;backup push h call fd_motor_off ;begin stop motor count pop h ;restore pop psw ret ; ; start motor (if not already started), disable interrupt from timer fd_motor_on: lda drive_nr ;which drive? cpi 1 ;drive 1? jz .l1 ;yes jump lda motor_0_state ;get motor 0 state ora a ;is it already spinning? jz .l2 ;no. start it and wait for spin up jmp .l4 ;yes, only update drive select bits .l1 lda motor_1_state ;get motor 1 state ora a ;is it already spinning? jz .l2 ;no. start it and wait for spin up jmp .l4 ;yes, only update drive select bits .l2 call disa_65 ;mask out 6.5 (timer) call motor_on ;start motor now mvi b,20h ;wait till it starts, cca 100ms .l3 call long_delay dcr b jnz .l3 ret ; .l4 call motor_on ;restart motor timeout counter ;fall through disa_65: rim ;get interrupt status ori 00001010b ;mask out 6.5 (timer) ani 00001111b ;set interrupt mask sim ret ; ; stop motor (if not needed anymore) fd_motor_off: xra a sta ticks ;clear interval sta seconds call timer_motor_off ;start timer, hook interrupt ei ;enable interrupts rim ;get interrupt status ori 00001000b ;mask out none ani 00001101b ;set interrupt mask, enable 6.5 (timer) sim .l1 ret
; A110185: Coefficients of x in the partial quotients of the continued fraction expansion exp(1/x) = [1, x - 1/2, 12*x, 5*x, 28*x, 9*x, 44*x, 13*x, ...]. The partial quotients all have the form a(n)*x except the constant term of 1 and the initial partial quotient which equals (x - 1/2). ; 0,1,12,5,28,9,44,13,60,17,76,21,92,25,108,29,124,33,140,37,156,41,172,45,188,49,204,53,220,57,236,61,252,65,268,69,284,73,300,77,316,81,332,85,348,89,364,93,380,97,396,101,412,105,428,109,444,113,460,117,476,121,492,125,508,129,524,133,540,137,556,141,572,145,588,149,604,153,620,157,636,161,652,165,668,169,684,173,700,177,716,181,732,185,748,189,764,193,780,197,796,201,812,205,828,209,844,213,860,217,876,221,892,225,908,229,924,233,940,237,956,241,972,245,988,249,1004,253,1020,257,1036,261,1052,265,1068,269,1084,273,1100,277,1116,281,1132,285,1148,289,1164,293,1180,297,1196,301,1212,305,1228,309,1244,313,1260,317,1276,321,1292,325,1308,329,1324,333,1340,337,1356,341,1372,345,1388,349,1404,353,1420,357,1436,361,1452,365,1468,369,1484,373,1500,377,1516,381,1532,385,1548,389,1564,393,1580,397,1596,401,1612,405,1628,409,1644,413,1660,417,1676,421,1692,425,1708,429,1724,433,1740,437,1756,441,1772,445,1788,449,1804,453,1820,457,1836,461,1852,465,1868,469,1884,473,1900,477,1916,481,1932,485,1948,489,1964,493,1980,497 mov $1,$0 pow $1,2 mov $2,$0 trn $2,1 add $0,$2 gcd $1,4 mul $1,$0
; A081019: a(n) = Lucas(4n+3) - 1, or Lucas(2n+1)*Lucas(2n+2). ; 3,28,198,1363,9348,64078,439203,3010348,20633238,141422323,969323028,6643838878,45537549123,312119004988,2139295485798,14662949395603,100501350283428,688846502588398,4721424167835363,32361122672259148,221806434537978678,1520283919093591603,10420180999117162548,71420983074726546238,489526700523968661123,3355265920593054081628,22997334743627409910278,157626077284798815290323,1080385206249964297121988,7405070366464951264563598,50755107359004694554823203,347880681146567910619198828,2384409660666970679779568598,16342986943522226847837781363,112016498943988617255084900948,767772505664398093937756525278,5262391040706798040309210776003,36068964779283188188226718906748,247220362414275519277277821571238,1694473572120645446752718032091923,11614094642430242607991748403072228,79604188924891052809189520789413678,545615227831807127056334897122823523 mul $0,2 mov $1,3 lpb $0 sub $0,1 add $2,$1 add $1,1 add $1,$2 lpe add $1,$2 mov $0,$1
Name: zel_bms1.asm Type: file Size: 119240 Last-Modified: '2016-05-13T04:23:03Z' SHA-1: 86AB349597C3DD78891875E295ADC358314393F8 Description: null
// Copyright 2012 the V8 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. #include "src/execution/isolate.h" #include <stdlib.h> #include <atomic> #include <fstream> // NOLINT(readability/streams) #include <memory> #include <sstream> #include <unordered_map> #include "src/api/api-inl.h" #include "src/ast/ast-value-factory.h" #include "src/ast/scopes.h" #include "src/base/adapters.h" #include "src/base/hashmap.h" #include "src/base/platform/platform.h" #include "src/base/sys-info.h" #include "src/base/utils/random-number-generator.h" #include "src/builtins/builtins-promise.h" #include "src/builtins/constants-table-builder.h" #include "src/codegen/assembler-inl.h" #include "src/codegen/compilation-cache.h" #include "src/common/ptr-compr.h" #include "src/compiler-dispatcher/compiler-dispatcher.h" #include "src/compiler-dispatcher/optimizing-compile-dispatcher.h" #include "src/date/date.h" #include "src/debug/debug-frames.h" #include "src/debug/debug.h" #include "src/deoptimizer/deoptimizer.h" #include "src/diagnostics/compilation-statistics.h" #include "src/execution/frames-inl.h" #include "src/execution/isolate-inl.h" #include "src/execution/messages.h" #include "src/execution/microtask-queue.h" #include "src/execution/runtime-profiler.h" #include "src/execution/simulator.h" #include "src/execution/v8threads.h" #include "src/execution/vm-state-inl.h" #include "src/heap/heap-inl.h" #include "src/heap/read-only-heap.h" #include "src/ic/stub-cache.h" #include "src/init/bootstrapper.h" #include "src/init/setup-isolate.h" #include "src/init/v8.h" #include "src/interpreter/interpreter.h" #include "src/libsampler/sampler.h" #include "src/logging/counters.h" #include "src/logging/log.h" #include "src/numbers/hash-seed-inl.h" #include "src/objects/elements.h" #include "src/objects/frame-array-inl.h" #include "src/objects/hash-table-inl.h" #include "src/objects/js-array-inl.h" #include "src/objects/js-generator-inl.h" #include "src/objects/js-weak-refs-inl.h" #include "src/objects/module-inl.h" #include "src/objects/promise-inl.h" #include "src/objects/prototype.h" #include "src/objects/slots.h" #include "src/objects/smi.h" #include "src/objects/stack-frame-info-inl.h" #include "src/objects/visitors.h" #include "src/profiler/heap-profiler.h" #include "src/profiler/tracing-cpu-profiler.h" #include "src/regexp/regexp-stack.h" #include "src/snapshot/embedded/embedded-data.h" #include "src/snapshot/embedded/embedded-file-writer.h" #include "src/snapshot/read-only-deserializer.h" #include "src/snapshot/startup-deserializer.h" #include "src/strings/string-builder-inl.h" #include "src/strings/string-stream.h" #include "src/tasks/cancelable-task.h" #include "src/tracing/tracing-category-observer.h" #include "src/trap-handler/trap-handler.h" #include "src/utils/ostreams.h" #include "src/utils/version.h" #include "src/wasm/wasm-code-manager.h" #include "src/wasm/wasm-engine.h" #include "src/wasm/wasm-objects.h" #include "src/zone/accounting-allocator.h" #ifdef V8_INTL_SUPPORT #include "unicode/uobject.h" #endif // V8_INTL_SUPPORT #if defined(V8_OS_WIN64) #include "src/diagnostics/unwinding-info-win64.h" #endif // V8_OS_WIN64 extern "C" const uint8_t* v8_Default_embedded_blob_; extern "C" uint32_t v8_Default_embedded_blob_size_; namespace v8 { namespace internal { #ifdef DEBUG #define TRACE_ISOLATE(tag) \ do { \ if (FLAG_trace_isolates) { \ PrintF("Isolate %p (id %d)" #tag "\n", reinterpret_cast<void*>(this), \ id()); \ } \ } while (false) #else #define TRACE_ISOLATE(tag) #endif const uint8_t* DefaultEmbeddedBlob() { return v8_Default_embedded_blob_; } uint32_t DefaultEmbeddedBlobSize() { return v8_Default_embedded_blob_size_; } #ifdef V8_MULTI_SNAPSHOTS extern "C" const uint8_t* v8_Trusted_embedded_blob_; extern "C" uint32_t v8_Trusted_embedded_blob_size_; const uint8_t* TrustedEmbeddedBlob() { return v8_Trusted_embedded_blob_; } uint32_t TrustedEmbeddedBlobSize() { return v8_Trusted_embedded_blob_size_; } #endif namespace { // These variables provide access to the current embedded blob without requiring // an isolate instance. This is needed e.g. by Code::InstructionStart, which may // not have access to an isolate but still needs to access the embedded blob. // The variables are initialized by each isolate in Init(). Writes and reads are // relaxed since we can guarantee that the current thread has initialized these // variables before accessing them. Different threads may race, but this is fine // since they all attempt to set the same values of the blob pointer and size. std::atomic<const uint8_t*> current_embedded_blob_(nullptr); std::atomic<uint32_t> current_embedded_blob_size_(0); // The various workflows around embedded snapshots are fairly complex. We need // to support plain old snapshot builds, nosnap builds, and the requirements of // subtly different serialization tests. There's two related knobs to twiddle: // // - The default embedded blob may be overridden by setting the sticky embedded // blob. This is set automatically whenever we create a new embedded blob. // // - Lifecycle management can be either manual or set to refcounting. // // A few situations to demonstrate their use: // // - A plain old snapshot build neither overrides the default blob nor // refcounts. // // - mksnapshot sets the sticky blob and manually frees the embedded // blob once done. // // - Most serializer tests do the same. // // - Nosnapshot builds set the sticky blob and enable refcounting. // This mutex protects access to the following variables: // - sticky_embedded_blob_ // - sticky_embedded_blob_size_ // - enable_embedded_blob_refcounting_ // - current_embedded_blob_refs_ base::LazyMutex current_embedded_blob_refcount_mutex_ = LAZY_MUTEX_INITIALIZER; const uint8_t* sticky_embedded_blob_ = nullptr; uint32_t sticky_embedded_blob_size_ = 0; bool enable_embedded_blob_refcounting_ = true; int current_embedded_blob_refs_ = 0; const uint8_t* StickyEmbeddedBlob() { return sticky_embedded_blob_; } uint32_t StickyEmbeddedBlobSize() { return sticky_embedded_blob_size_; } void SetStickyEmbeddedBlob(const uint8_t* blob, uint32_t blob_size) { sticky_embedded_blob_ = blob; sticky_embedded_blob_size_ = blob_size; } } // namespace void DisableEmbeddedBlobRefcounting() { base::MutexGuard guard(current_embedded_blob_refcount_mutex_.Pointer()); enable_embedded_blob_refcounting_ = false; } void FreeCurrentEmbeddedBlob() { CHECK(!enable_embedded_blob_refcounting_); base::MutexGuard guard(current_embedded_blob_refcount_mutex_.Pointer()); if (StickyEmbeddedBlob() == nullptr) return; CHECK_EQ(StickyEmbeddedBlob(), Isolate::CurrentEmbeddedBlob()); InstructionStream::FreeOffHeapInstructionStream( const_cast<uint8_t*>(Isolate::CurrentEmbeddedBlob()), Isolate::CurrentEmbeddedBlobSize()); current_embedded_blob_.store(nullptr, std::memory_order_relaxed); current_embedded_blob_size_.store(0, std::memory_order_relaxed); sticky_embedded_blob_ = nullptr; sticky_embedded_blob_size_ = 0; } // static bool Isolate::CurrentEmbeddedBlobIsBinaryEmbedded() { // In some situations, we must be able to rely on the embedded blob being // immortal immovable. This is the case if the blob is binary-embedded. // See blob lifecycle controls above for descriptions of when the current // embedded blob may change (e.g. in tests or mksnapshot). If the blob is // binary-embedded, it is immortal immovable. const uint8_t* blob = current_embedded_blob_.load(std::memory_order::memory_order_relaxed); if (blob == nullptr) return false; #ifdef V8_MULTI_SNAPSHOTS if (blob == TrustedEmbeddedBlob()) return true; #endif return blob == DefaultEmbeddedBlob(); } void Isolate::SetEmbeddedBlob(const uint8_t* blob, uint32_t blob_size) { CHECK_NOT_NULL(blob); embedded_blob_ = blob; embedded_blob_size_ = blob_size; current_embedded_blob_.store(blob, std::memory_order_relaxed); current_embedded_blob_size_.store(blob_size, std::memory_order_relaxed); #ifdef DEBUG // Verify that the contents of the embedded blob are unchanged from // serialization-time, just to ensure the compiler isn't messing with us. EmbeddedData d = EmbeddedData::FromBlob(); if (d.EmbeddedBlobHash() != d.CreateEmbeddedBlobHash()) { FATAL( "Embedded blob checksum verification failed. This indicates that the " "embedded blob has been modified since compilation time. A common " "cause is a debugging breakpoint set within builtin code."); } #endif // DEBUG } void Isolate::ClearEmbeddedBlob() { CHECK(enable_embedded_blob_refcounting_); CHECK_EQ(embedded_blob_, CurrentEmbeddedBlob()); CHECK_EQ(embedded_blob_, StickyEmbeddedBlob()); embedded_blob_ = nullptr; embedded_blob_size_ = 0; current_embedded_blob_.store(nullptr, std::memory_order_relaxed); current_embedded_blob_size_.store(0, std::memory_order_relaxed); sticky_embedded_blob_ = nullptr; sticky_embedded_blob_size_ = 0; } const uint8_t* Isolate::embedded_blob() const { return embedded_blob_; } uint32_t Isolate::embedded_blob_size() const { return embedded_blob_size_; } // static const uint8_t* Isolate::CurrentEmbeddedBlob() { return current_embedded_blob_.load(std::memory_order::memory_order_relaxed); } // static uint32_t Isolate::CurrentEmbeddedBlobSize() { return current_embedded_blob_size_.load( std::memory_order::memory_order_relaxed); } size_t Isolate::HashIsolateForEmbeddedBlob() { DCHECK(builtins_.is_initialized()); DCHECK(FLAG_embedded_builtins); DCHECK(Builtins::AllBuiltinsAreIsolateIndependent()); DisallowHeapAllocation no_gc; static constexpr size_t kSeed = 0; size_t hash = kSeed; // Hash data sections of builtin code objects. for (int i = 0; i < Builtins::builtin_count; i++) { Code code = heap_.builtin(i); DCHECK(Internals::HasHeapObjectTag(code.ptr())); uint8_t* const code_ptr = reinterpret_cast<uint8_t*>(code.ptr() - kHeapObjectTag); // These static asserts ensure we don't miss relevant fields. We don't hash // instruction size and flags since they change when creating the off-heap // trampolines. Other data fields must remain the same. STATIC_ASSERT(Code::kInstructionSizeOffset == Code::kDataStart); STATIC_ASSERT(Code::kFlagsOffset == Code::kInstructionSizeOffsetEnd + 1); STATIC_ASSERT(Code::kSafepointTableOffsetOffset == Code::kFlagsOffsetEnd + 1); static constexpr int kStartOffset = Code::kSafepointTableOffsetOffset; for (int j = kStartOffset; j < Code::kUnalignedHeaderSize; j++) { hash = base::hash_combine(hash, size_t{code_ptr[j]}); } } // The builtins constants table is also tightly tied to embedded builtins. hash = base::hash_combine( hash, static_cast<size_t>(heap_.builtins_constants_table().length())); return hash; } base::Thread::LocalStorageKey Isolate::isolate_key_; base::Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_; #if DEBUG std::atomic<bool> Isolate::isolate_key_created_{false}; #endif namespace { // A global counter for all generated Isolates, might overflow. std::atomic<int> isolate_counter{0}; } // namespace Isolate::PerIsolateThreadData* Isolate::FindOrAllocatePerThreadDataForThisThread() { ThreadId thread_id = ThreadId::Current(); PerIsolateThreadData* per_thread = nullptr; { base::MutexGuard lock_guard(&thread_data_table_mutex_); per_thread = thread_data_table_.Lookup(thread_id); if (per_thread == nullptr) { base::OS::AdjustSchedulingParams(); per_thread = new PerIsolateThreadData(this, thread_id); thread_data_table_.Insert(per_thread); } DCHECK(thread_data_table_.Lookup(thread_id) == per_thread); } return per_thread; } void Isolate::DiscardPerThreadDataForThisThread() { ThreadId thread_id = ThreadId::TryGetCurrent(); if (thread_id.IsValid()) { DCHECK_NE(thread_manager_->mutex_owner_.load(std::memory_order_relaxed), thread_id); base::MutexGuard lock_guard(&thread_data_table_mutex_); PerIsolateThreadData* per_thread = thread_data_table_.Lookup(thread_id); if (per_thread) { DCHECK(!per_thread->thread_state_); thread_data_table_.Remove(per_thread); } } } Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() { ThreadId thread_id = ThreadId::Current(); return FindPerThreadDataForThread(thread_id); } Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread( ThreadId thread_id) { PerIsolateThreadData* per_thread = nullptr; { base::MutexGuard lock_guard(&thread_data_table_mutex_); per_thread = thread_data_table_.Lookup(thread_id); } return per_thread; } void Isolate::InitializeOncePerProcess() { isolate_key_ = base::Thread::CreateThreadLocalKey(); #if DEBUG bool expected = false; DCHECK_EQ(true, isolate_key_created_.compare_exchange_strong( expected, true, std::memory_order_relaxed)); #endif per_isolate_thread_data_key_ = base::Thread::CreateThreadLocalKey(); } Address Isolate::get_address_from_id(IsolateAddressId id) { return isolate_addresses_[id]; } char* Isolate::Iterate(RootVisitor* v, char* thread_storage) { ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage); Iterate(v, thread); return thread_storage + sizeof(ThreadLocalTop); } void Isolate::IterateThread(ThreadVisitor* v, char* t) { ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t); v->VisitThread(this, thread); } void Isolate::Iterate(RootVisitor* v, ThreadLocalTop* thread) { // Visit the roots from the top for a given thread. v->VisitRootPointer(Root::kTop, nullptr, FullObjectSlot(&thread->pending_exception_)); v->VisitRootPointer(Root::kTop, nullptr, FullObjectSlot(&thread->pending_message_obj_)); v->VisitRootPointer(Root::kTop, nullptr, FullObjectSlot(&thread->context_)); v->VisitRootPointer(Root::kTop, nullptr, FullObjectSlot(&thread->scheduled_exception_)); for (v8::TryCatch* block = thread->try_catch_handler_; block != nullptr; block = block->next_) { // TODO(3770): Make TryCatch::exception_ an Address (and message_obj_ too). v->VisitRootPointer( Root::kTop, nullptr, FullObjectSlot(reinterpret_cast<Address>(&(block->exception_)))); v->VisitRootPointer( Root::kTop, nullptr, FullObjectSlot(reinterpret_cast<Address>(&(block->message_obj_)))); } // Iterate over pointers on native execution stack. wasm::WasmCodeRefScope wasm_code_ref_scope; for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) { it.frame()->Iterate(v); } } void Isolate::Iterate(RootVisitor* v) { ThreadLocalTop* current_t = thread_local_top(); Iterate(v, current_t); } void Isolate::IterateDeferredHandles(RootVisitor* visitor) { for (DeferredHandles* deferred = deferred_handles_head_; deferred != nullptr; deferred = deferred->next_) { deferred->Iterate(visitor); } } #ifdef DEBUG bool Isolate::IsDeferredHandle(Address* handle) { // Comparing unrelated pointers (not from the same array) is undefined // behavior, so cast to Address before making arbitrary comparisons. Address handle_as_address = reinterpret_cast<Address>(handle); // Each DeferredHandles instance keeps the handles to one job in the // concurrent recompilation queue, containing a list of blocks. Each block // contains kHandleBlockSize handles except for the first block, which may // not be fully filled. // We iterate through all the blocks to see whether the argument handle // belongs to one of the blocks. If so, it is deferred. for (DeferredHandles* deferred = deferred_handles_head_; deferred != nullptr; deferred = deferred->next_) { std::vector<Address*>* blocks = &deferred->blocks_; for (size_t i = 0; i < blocks->size(); i++) { Address* block_limit = (i == 0) ? deferred->first_block_limit_ : blocks->at(i) + kHandleBlockSize; if (reinterpret_cast<Address>(blocks->at(i)) <= handle_as_address && handle_as_address < reinterpret_cast<Address>(block_limit)) { return true; } } } return false; } #endif // DEBUG void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) { thread_local_top()->try_catch_handler_ = that; } void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) { DCHECK(thread_local_top()->try_catch_handler_ == that); thread_local_top()->try_catch_handler_ = that->next_; } Handle<String> Isolate::StackTraceString() { if (stack_trace_nesting_level_ == 0) { stack_trace_nesting_level_++; HeapStringAllocator allocator; StringStream::ClearMentionedObjectCache(this); StringStream accumulator(&allocator); incomplete_message_ = &accumulator; PrintStack(&accumulator); Handle<String> stack_trace = accumulator.ToString(this); incomplete_message_ = nullptr; stack_trace_nesting_level_ = 0; return stack_trace; } else if (stack_trace_nesting_level_ == 1) { stack_trace_nesting_level_++; base::OS::PrintError( "\n\nAttempt to print stack while printing stack (double fault)\n"); base::OS::PrintError( "If you are lucky you may find a partial stack dump on stdout.\n\n"); incomplete_message_->OutputToStdOut(); return factory()->empty_string(); } else { base::OS::Abort(); // Unreachable return factory()->empty_string(); } } void Isolate::PushStackTraceAndDie(void* ptr1, void* ptr2, void* ptr3, void* ptr4) { StackTraceFailureMessage message(this, ptr1, ptr2, ptr3, ptr4); message.Print(); base::OS::Abort(); } void StackTraceFailureMessage::Print() volatile { // Print the details of this failure message object, including its own address // to force stack allocation. base::OS::PrintError( "Stacktrace:\n ptr1=%p\n ptr2=%p\n ptr3=%p\n ptr4=%p\n " "failure_message_object=%p\n%s", ptr1_, ptr2_, ptr3_, ptr4_, this, &js_stack_trace_[0]); } StackTraceFailureMessage::StackTraceFailureMessage(Isolate* isolate, void* ptr1, void* ptr2, void* ptr3, void* ptr4) { isolate_ = isolate; ptr1_ = ptr1; ptr2_ = ptr2; ptr3_ = ptr3; ptr4_ = ptr4; // Write a stracktrace into the {js_stack_trace_} buffer. const size_t buffer_length = arraysize(js_stack_trace_); memset(&js_stack_trace_, 0, buffer_length); FixedStringAllocator fixed(&js_stack_trace_[0], buffer_length - 1); StringStream accumulator(&fixed, StringStream::kPrintObjectConcise); isolate->PrintStack(&accumulator, Isolate::kPrintStackVerbose); // Keeping a reference to the last code objects to increase likelyhood that // they get included in the minidump. const size_t code_objects_length = arraysize(code_objects_); size_t i = 0; StackFrameIterator it(isolate); for (; !it.done() && i < code_objects_length; it.Advance()) { code_objects_[i++] = reinterpret_cast<void*>(it.frame()->unchecked_code().ptr()); } } namespace { class StackFrameCacheHelper : public AllStatic { public: static MaybeHandle<StackTraceFrame> LookupCachedFrame( Isolate* isolate, Handle<AbstractCode> code, int code_offset) { if (FLAG_optimize_for_size) return MaybeHandle<StackTraceFrame>(); const auto maybe_cache = handle(code->stack_frame_cache(), isolate); if (!maybe_cache->IsSimpleNumberDictionary()) return MaybeHandle<StackTraceFrame>(); const auto cache = Handle<SimpleNumberDictionary>::cast(maybe_cache); const int entry = cache->FindEntry(isolate, code_offset); if (entry != NumberDictionary::kNotFound) { return handle(StackTraceFrame::cast(cache->ValueAt(entry)), isolate); } return MaybeHandle<StackTraceFrame>(); } static void CacheFrameAndUpdateCache(Isolate* isolate, Handle<AbstractCode> code, int code_offset, Handle<StackTraceFrame> frame) { if (FLAG_optimize_for_size) return; const auto maybe_cache = handle(code->stack_frame_cache(), isolate); const auto cache = maybe_cache->IsSimpleNumberDictionary() ? Handle<SimpleNumberDictionary>::cast(maybe_cache) : SimpleNumberDictionary::New(isolate, 1); Handle<SimpleNumberDictionary> new_cache = SimpleNumberDictionary::Set(isolate, cache, code_offset, frame); if (*new_cache != *cache || !maybe_cache->IsSimpleNumberDictionary()) { AbstractCode::SetStackFrameCache(code, new_cache); } } }; } // anonymous namespace class FrameArrayBuilder { public: enum FrameFilterMode { ALL, CURRENT_SECURITY_CONTEXT }; FrameArrayBuilder(Isolate* isolate, FrameSkipMode mode, int limit, Handle<Object> caller, FrameFilterMode filter_mode) : isolate_(isolate), mode_(mode), limit_(limit), caller_(caller), check_security_context_(filter_mode == CURRENT_SECURITY_CONTEXT) { switch (mode_) { case SKIP_FIRST: skip_next_frame_ = true; break; case SKIP_UNTIL_SEEN: DCHECK(caller_->IsJSFunction()); skip_next_frame_ = true; break; case SKIP_NONE: skip_next_frame_ = false; break; } elements_ = isolate->factory()->NewFrameArray(Min(limit, 10)); } void AppendAsyncFrame(Handle<JSGeneratorObject> generator_object) { if (full()) return; Handle<JSFunction> function(generator_object->function(), isolate_); if (!IsVisibleInStackTrace(function)) return; int flags = FrameArray::kIsAsync; if (IsStrictFrame(function)) flags |= FrameArray::kIsStrict; Handle<Object> receiver(generator_object->receiver(), isolate_); Handle<AbstractCode> code( AbstractCode::cast(function->shared().GetBytecodeArray()), isolate_); int offset = Smi::ToInt(generator_object->input_or_debug_pos()); // The stored bytecode offset is relative to a different base than what // is used in the source position table, hence the subtraction. offset -= BytecodeArray::kHeaderSize - kHeapObjectTag; Handle<FixedArray> parameters = isolate_->factory()->empty_fixed_array(); if (V8_UNLIKELY(FLAG_detailed_error_stack_trace)) { int param_count = function->shared().internal_formal_parameter_count(); parameters = isolate_->factory()->NewFixedArray(param_count); for (int i = 0; i < param_count; i++) { parameters->set(i, generator_object->parameters_and_registers().get(i)); } } elements_ = FrameArray::AppendJSFrame(elements_, receiver, function, code, offset, flags, parameters); } void AppendPromiseAllFrame(Handle<Context> context, int offset) { if (full()) return; int flags = FrameArray::kIsAsync | FrameArray::kIsPromiseAll; Handle<Context> native_context(context->native_context(), isolate_); Handle<JSFunction> function(native_context->promise_all(), isolate_); if (!IsVisibleInStackTrace(function)) return; Handle<Object> receiver(native_context->promise_function(), isolate_); Handle<AbstractCode> code(AbstractCode::cast(function->code()), isolate_); // TODO(mmarchini) save Promises list from Promise.all() Handle<FixedArray> parameters = isolate_->factory()->empty_fixed_array(); elements_ = FrameArray::AppendJSFrame(elements_, receiver, function, code, offset, flags, parameters); } void AppendJavaScriptFrame( FrameSummary::JavaScriptFrameSummary const& summary) { // Filter out internal frames that we do not want to show. if (!IsVisibleInStackTrace(summary.function())) return; Handle<AbstractCode> abstract_code = summary.abstract_code(); const int offset = summary.code_offset(); const bool is_constructor = summary.is_constructor(); int flags = 0; Handle<JSFunction> function = summary.function(); if (IsStrictFrame(function)) flags |= FrameArray::kIsStrict; if (is_constructor) flags |= FrameArray::kIsConstructor; Handle<FixedArray> parameters = isolate_->factory()->empty_fixed_array(); if (V8_UNLIKELY(FLAG_detailed_error_stack_trace)) parameters = summary.parameters(); elements_ = FrameArray::AppendJSFrame( elements_, TheHoleToUndefined(isolate_, summary.receiver()), function, abstract_code, offset, flags, parameters); } void AppendWasmCompiledFrame( FrameSummary::WasmCompiledFrameSummary const& summary) { if (summary.code()->kind() != wasm::WasmCode::kFunction) return; Handle<WasmInstanceObject> instance = summary.wasm_instance(); int flags = 0; if (instance->module_object().is_asm_js()) { flags |= FrameArray::kIsAsmJsWasmFrame; if (summary.at_to_number_conversion()) { flags |= FrameArray::kAsmJsAtNumberConversion; } } else { flags |= FrameArray::kIsWasmFrame; } elements_ = FrameArray::AppendWasmFrame( elements_, instance, summary.function_index(), summary.code(), summary.code_offset(), flags); } void AppendWasmInterpretedFrame( FrameSummary::WasmInterpretedFrameSummary const& summary) { Handle<WasmInstanceObject> instance = summary.wasm_instance(); int flags = FrameArray::kIsWasmInterpretedFrame; DCHECK(!instance->module_object().is_asm_js()); elements_ = FrameArray::AppendWasmFrame(elements_, instance, summary.function_index(), {}, summary.byte_offset(), flags); } void AppendBuiltinExitFrame(BuiltinExitFrame* exit_frame) { Handle<JSFunction> function = handle(exit_frame->function(), isolate_); // Filter out internal frames that we do not want to show. if (!IsVisibleInStackTrace(function)) return; // TODO(szuend): Remove this check once the flag is enabled // by default. if (!FLAG_experimental_stack_trace_frames && function->shared().IsApiFunction()) { return; } Handle<Object> receiver(exit_frame->receiver(), isolate_); Handle<Code> code(exit_frame->LookupCode(), isolate_); const int offset = static_cast<int>(exit_frame->pc() - code->InstructionStart()); int flags = 0; if (IsStrictFrame(function)) flags |= FrameArray::kIsStrict; if (exit_frame->IsConstructor()) flags |= FrameArray::kIsConstructor; Handle<FixedArray> parameters = isolate_->factory()->empty_fixed_array(); if (V8_UNLIKELY(FLAG_detailed_error_stack_trace)) { int param_count = exit_frame->ComputeParametersCount(); parameters = isolate_->factory()->NewFixedArray(param_count); for (int i = 0; i < param_count; i++) { parameters->set(i, exit_frame->GetParameter(i)); } } elements_ = FrameArray::AppendJSFrame(elements_, receiver, function, Handle<AbstractCode>::cast(code), offset, flags, parameters); } bool full() { return elements_->FrameCount() >= limit_; } Handle<FrameArray> GetElements() { elements_->ShrinkToFit(isolate_); return elements_; } // Creates a StackTraceFrame object for each frame in the FrameArray. Handle<FixedArray> GetElementsAsStackTraceFrameArray( bool enable_frame_caching) { elements_->ShrinkToFit(isolate_); const int frame_count = elements_->FrameCount(); Handle<FixedArray> stack_trace = isolate_->factory()->NewFixedArray(frame_count); for (int i = 0; i < frame_count; ++i) { // Caching stack frames only happens for user JS frames. const bool cache_frame = enable_frame_caching && !elements_->IsAnyWasmFrame(i) && elements_->Function(i).shared().IsUserJavaScript(); if (cache_frame) { MaybeHandle<StackTraceFrame> maybe_frame = StackFrameCacheHelper::LookupCachedFrame( isolate_, handle(elements_->Code(i), isolate_), Smi::ToInt(elements_->Offset(i))); if (!maybe_frame.is_null()) { Handle<StackTraceFrame> frame = maybe_frame.ToHandleChecked(); stack_trace->set(i, *frame); continue; } } Handle<StackTraceFrame> frame = isolate_->factory()->NewStackTraceFrame(elements_, i); stack_trace->set(i, *frame); if (cache_frame) { StackFrameCacheHelper::CacheFrameAndUpdateCache( isolate_, handle(elements_->Code(i), isolate_), Smi::ToInt(elements_->Offset(i)), frame); } } return stack_trace; } private: // Poison stack frames below the first strict mode frame. // The stack trace API should not expose receivers and function // objects on frames deeper than the top-most one with a strict mode // function. bool IsStrictFrame(Handle<JSFunction> function) { if (!encountered_strict_function_) { encountered_strict_function_ = is_strict(function->shared().language_mode()); } return encountered_strict_function_; } // Determines whether the given stack frame should be displayed in a stack // trace. bool IsVisibleInStackTrace(Handle<JSFunction> function) { return ShouldIncludeFrame(function) && IsNotHidden(function) && IsInSameSecurityContext(function); } // This mechanism excludes a number of uninteresting frames from the stack // trace. This can be be the first frame (which will be a builtin-exit frame // for the error constructor builtin) or every frame until encountering a // user-specified function. bool ShouldIncludeFrame(Handle<JSFunction> function) { switch (mode_) { case SKIP_NONE: return true; case SKIP_FIRST: if (!skip_next_frame_) return true; skip_next_frame_ = false; return false; case SKIP_UNTIL_SEEN: if (skip_next_frame_ && (*function == *caller_)) { skip_next_frame_ = false; return false; } return !skip_next_frame_; } UNREACHABLE(); } bool IsNotHidden(Handle<JSFunction> function) { // Functions defined not in user scripts are not visible unless directly // exposed, in which case the native flag is set. // The --builtins-in-stack-traces command line flag allows including // internal call sites in the stack trace for debugging purposes. if (!FLAG_builtins_in_stack_traces && !function->shared().IsUserJavaScript()) { return function->shared().native() || function->shared().IsApiFunction(); } return true; } bool IsInSameSecurityContext(Handle<JSFunction> function) { if (!check_security_context_) return true; return isolate_->context().HasSameSecurityTokenAs(function->context()); } // TODO(jgruber): Fix all cases in which frames give us a hole value (e.g. the // receiver in RegExp constructor frames. Handle<Object> TheHoleToUndefined(Isolate* isolate, Handle<Object> in) { return (in->IsTheHole(isolate)) ? Handle<Object>::cast(isolate->factory()->undefined_value()) : in; } Isolate* isolate_; const FrameSkipMode mode_; int limit_; const Handle<Object> caller_; bool skip_next_frame_ = true; bool encountered_strict_function_ = false; const bool check_security_context_; Handle<FrameArray> elements_; }; bool GetStackTraceLimit(Isolate* isolate, int* result) { Handle<JSObject> error = isolate->error_function(); Handle<String> key = isolate->factory()->stackTraceLimit_string(); Handle<Object> stack_trace_limit = JSReceiver::GetDataProperty(error, key); if (!stack_trace_limit->IsNumber()) return false; // Ensure that limit is not negative. *result = Max(FastD2IChecked(stack_trace_limit->Number()), 0); if (*result != FLAG_stack_trace_limit) { isolate->CountUsage(v8::Isolate::kErrorStackTraceLimit); } return true; } bool NoExtension(const v8::FunctionCallbackInfo<v8::Value>&) { return false; } bool IsBuiltinFunction(Isolate* isolate, HeapObject object, Builtins::Name builtin_index) { if (!object.IsJSFunction()) return false; JSFunction const function = JSFunction::cast(object); return function.code() == isolate->builtins()->builtin(builtin_index); } void CaptureAsyncStackTrace(Isolate* isolate, Handle<JSPromise> promise, FrameArrayBuilder* builder) { while (!builder->full()) { // Check that the {promise} is not settled. if (promise->status() != Promise::kPending) return; // Check that we have exactly one PromiseReaction on the {promise}. if (!promise->reactions().IsPromiseReaction()) return; Handle<PromiseReaction> reaction( PromiseReaction::cast(promise->reactions()), isolate); if (!reaction->next().IsSmi()) return; // Check if the {reaction} has one of the known async function or // async generator continuations as its fulfill handler. if (IsBuiltinFunction(isolate, reaction->fulfill_handler(), Builtins::kAsyncFunctionAwaitResolveClosure) || IsBuiltinFunction(isolate, reaction->fulfill_handler(), Builtins::kAsyncGeneratorAwaitResolveClosure) || IsBuiltinFunction(isolate, reaction->fulfill_handler(), Builtins::kAsyncGeneratorYieldResolveClosure)) { // Now peak into the handlers' AwaitContext to get to // the JSGeneratorObject for the async function. Handle<Context> context( JSFunction::cast(reaction->fulfill_handler()).context(), isolate); Handle<JSGeneratorObject> generator_object( JSGeneratorObject::cast(context->extension()), isolate); CHECK(generator_object->is_suspended()); // Append async frame corresponding to the {generator_object}. builder->AppendAsyncFrame(generator_object); // Try to continue from here. if (generator_object->IsJSAsyncFunctionObject()) { Handle<JSAsyncFunctionObject> async_function_object = Handle<JSAsyncFunctionObject>::cast(generator_object); promise = handle(async_function_object->promise(), isolate); } else { Handle<JSAsyncGeneratorObject> async_generator_object = Handle<JSAsyncGeneratorObject>::cast(generator_object); if (async_generator_object->queue().IsUndefined(isolate)) return; Handle<AsyncGeneratorRequest> async_generator_request( AsyncGeneratorRequest::cast(async_generator_object->queue()), isolate); promise = handle(JSPromise::cast(async_generator_request->promise()), isolate); } } else if (IsBuiltinFunction(isolate, reaction->fulfill_handler(), Builtins::kPromiseAllResolveElementClosure)) { Handle<JSFunction> function(JSFunction::cast(reaction->fulfill_handler()), isolate); Handle<Context> context(function->context(), isolate); // We store the offset of the promise into the {function}'s // hash field for promise resolve element callbacks. int const offset = Smi::ToInt(Smi::cast(function->GetIdentityHash())) - 1; builder->AppendPromiseAllFrame(context, offset); // Now peak into the Promise.all() resolve element context to // find the promise capability that's being resolved when all // the concurrent promises resolve. int const index = PromiseBuiltins::kPromiseAllResolveElementCapabilitySlot; Handle<PromiseCapability> capability( PromiseCapability::cast(context->get(index)), isolate); if (!capability->promise().IsJSPromise()) return; promise = handle(JSPromise::cast(capability->promise()), isolate); } else if (IsBuiltinFunction(isolate, reaction->fulfill_handler(), Builtins::kPromiseCapabilityDefaultResolve)) { Handle<JSFunction> function(JSFunction::cast(reaction->fulfill_handler()), isolate); Handle<Context> context(function->context(), isolate); promise = handle(JSPromise::cast(context->get(PromiseBuiltins::kPromiseSlot)), isolate); } else { // We have some generic promise chain here, so try to // continue with the chained promise on the reaction // (only works for native promise chains). Handle<HeapObject> promise_or_capability( reaction->promise_or_capability(), isolate); if (promise_or_capability->IsJSPromise()) { promise = Handle<JSPromise>::cast(promise_or_capability); } else if (promise_or_capability->IsPromiseCapability()) { Handle<PromiseCapability> capability = Handle<PromiseCapability>::cast(promise_or_capability); if (!capability->promise().IsJSPromise()) return; promise = handle(JSPromise::cast(capability->promise()), isolate); } else { // Otherwise the {promise_or_capability} must be undefined here. CHECK(promise_or_capability->IsUndefined(isolate)); return; } } } } namespace { struct CaptureStackTraceOptions { int limit; // 'filter_mode' and 'skip_mode' are somewhat orthogonal. 'filter_mode' // specifies whether to capture all frames, or just frames in the same // security context. While 'skip_mode' allows skipping the first frame. FrameSkipMode skip_mode; FrameArrayBuilder::FrameFilterMode filter_mode; bool capture_builtin_exit_frames; bool capture_only_frames_subject_to_debugging; bool async_stack_trace; bool enable_frame_caching; }; Handle<Object> CaptureStackTrace(Isolate* isolate, Handle<Object> caller, CaptureStackTraceOptions options) { DisallowJavascriptExecution no_js(isolate); wasm::WasmCodeRefScope code_ref_scope; FrameArrayBuilder builder(isolate, options.skip_mode, options.limit, caller, options.filter_mode); // Build the regular stack trace, and remember the last relevant // frame ID and inlined index (for the async stack trace handling // below, which starts from this last frame). for (StackFrameIterator it(isolate); !it.done() && !builder.full(); it.Advance()) { StackFrame* const frame = it.frame(); switch (frame->type()) { case StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION: case StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH: case StackFrame::OPTIMIZED: case StackFrame::INTERPRETED: case StackFrame::BUILTIN: case StackFrame::WASM_COMPILED: case StackFrame::WASM_INTERPRETER_ENTRY: { // A standard frame may include many summarized frames (due to // inlining). std::vector<FrameSummary> frames; StandardFrame::cast(frame)->Summarize(&frames); for (size_t i = frames.size(); i-- != 0 && !builder.full();) { auto& summary = frames[i]; if (options.capture_only_frames_subject_to_debugging && !summary.is_subject_to_debugging()) { continue; } if (summary.IsJavaScript()) { //========================================================= // Handle a JavaScript frame. //========================================================= auto const& java_script = summary.AsJavaScript(); builder.AppendJavaScriptFrame(java_script); } else if (summary.IsWasmCompiled()) { //========================================================= // Handle a WASM compiled frame. //========================================================= auto const& wasm_compiled = summary.AsWasmCompiled(); builder.AppendWasmCompiledFrame(wasm_compiled); } else if (summary.IsWasmInterpreted()) { //========================================================= // Handle a WASM interpreted frame. //========================================================= auto const& wasm_interpreted = summary.AsWasmInterpreted(); builder.AppendWasmInterpretedFrame(wasm_interpreted); } } break; } case StackFrame::BUILTIN_EXIT: if (!options.capture_builtin_exit_frames) continue; // BuiltinExitFrames are not standard frames, so they do not have // Summarize(). However, they may have one JS frame worth showing. builder.AppendBuiltinExitFrame(BuiltinExitFrame::cast(frame)); break; default: break; } } // If --async-stack-traces are enabled and the "current microtask" is a // PromiseReactionJobTask, we try to enrich the stack trace with async // frames. if (options.async_stack_trace) { Handle<Object> current_microtask = isolate->factory()->current_microtask(); if (current_microtask->IsPromiseReactionJobTask()) { Handle<PromiseReactionJobTask> promise_reaction_job_task = Handle<PromiseReactionJobTask>::cast(current_microtask); // Check if the {reaction} has one of the known async function or // async generator continuations as its fulfill handler. if (IsBuiltinFunction(isolate, promise_reaction_job_task->handler(), Builtins::kAsyncFunctionAwaitResolveClosure) || IsBuiltinFunction(isolate, promise_reaction_job_task->handler(), Builtins::kAsyncGeneratorAwaitResolveClosure) || IsBuiltinFunction(isolate, promise_reaction_job_task->handler(), Builtins::kAsyncGeneratorYieldResolveClosure)) { // Now peak into the handlers' AwaitContext to get to // the JSGeneratorObject for the async function. Handle<Context> context( JSFunction::cast(promise_reaction_job_task->handler()).context(), isolate); Handle<JSGeneratorObject> generator_object( JSGeneratorObject::cast(context->extension()), isolate); if (generator_object->is_executing()) { if (generator_object->IsJSAsyncFunctionObject()) { Handle<JSAsyncFunctionObject> async_function_object = Handle<JSAsyncFunctionObject>::cast(generator_object); Handle<JSPromise> promise(async_function_object->promise(), isolate); CaptureAsyncStackTrace(isolate, promise, &builder); } else { Handle<JSAsyncGeneratorObject> async_generator_object = Handle<JSAsyncGeneratorObject>::cast(generator_object); Handle<AsyncGeneratorRequest> async_generator_request( AsyncGeneratorRequest::cast(async_generator_object->queue()), isolate); Handle<JSPromise> promise( JSPromise::cast(async_generator_request->promise()), isolate); CaptureAsyncStackTrace(isolate, promise, &builder); } } } else { // The {promise_reaction_job_task} doesn't belong to an await (or // yield inside an async generator), but we might still be able to // find an async frame if we follow along the chain of promises on // the {promise_reaction_job_task}. Handle<HeapObject> promise_or_capability( promise_reaction_job_task->promise_or_capability(), isolate); if (promise_or_capability->IsJSPromise()) { Handle<JSPromise> promise = Handle<JSPromise>::cast(promise_or_capability); CaptureAsyncStackTrace(isolate, promise, &builder); } } } } // TODO(yangguo): Queue this structured stack trace for preprocessing on GC. return builder.GetElementsAsStackTraceFrameArray( options.enable_frame_caching); } } // namespace Handle<Object> Isolate::CaptureSimpleStackTrace(Handle<JSReceiver> error_object, FrameSkipMode mode, Handle<Object> caller) { int limit; if (!GetStackTraceLimit(this, &limit)) return factory()->undefined_value(); CaptureStackTraceOptions options; options.limit = limit; options.skip_mode = mode; options.capture_builtin_exit_frames = true; options.async_stack_trace = FLAG_async_stack_traces; options.filter_mode = FrameArrayBuilder::CURRENT_SECURITY_CONTEXT; options.capture_only_frames_subject_to_debugging = false; options.enable_frame_caching = false; return CaptureStackTrace(this, caller, options); } MaybeHandle<JSReceiver> Isolate::CaptureAndSetDetailedStackTrace( Handle<JSReceiver> error_object) { if (capture_stack_trace_for_uncaught_exceptions_) { // Capture stack trace for a detailed exception message. Handle<Name> key = factory()->detailed_stack_trace_symbol(); Handle<FixedArray> stack_trace = CaptureCurrentStackTrace( stack_trace_for_uncaught_exceptions_frame_limit_, stack_trace_for_uncaught_exceptions_options_); RETURN_ON_EXCEPTION( this, Object::SetProperty(this, error_object, key, stack_trace, StoreOrigin::kMaybeKeyed, Just(ShouldThrow::kThrowOnError)), JSReceiver); } return error_object; } MaybeHandle<JSReceiver> Isolate::CaptureAndSetSimpleStackTrace( Handle<JSReceiver> error_object, FrameSkipMode mode, Handle<Object> caller) { // Capture stack trace for simple stack trace string formatting. Handle<Name> key = factory()->stack_trace_symbol(); Handle<Object> stack_trace = CaptureSimpleStackTrace(error_object, mode, caller); RETURN_ON_EXCEPTION(this, Object::SetProperty(this, error_object, key, stack_trace, StoreOrigin::kMaybeKeyed, Just(ShouldThrow::kThrowOnError)), JSReceiver); return error_object; } Handle<FixedArray> Isolate::GetDetailedStackTrace( Handle<JSObject> error_object) { Handle<Name> key_detailed = factory()->detailed_stack_trace_symbol(); Handle<Object> stack_trace = JSReceiver::GetDataProperty(error_object, key_detailed); if (stack_trace->IsFixedArray()) return Handle<FixedArray>::cast(stack_trace); return Handle<FixedArray>(); } Address Isolate::GetAbstractPC(int* line, int* column) { JavaScriptFrameIterator it(this); if (it.done()) { *line = -1; *column = -1; return kNullAddress; } JavaScriptFrame* frame = it.frame(); DCHECK(!frame->is_builtin()); Handle<SharedFunctionInfo> shared = handle(frame->function().shared(), this); SharedFunctionInfo::EnsureSourcePositionsAvailable(this, shared); int position = frame->position(); Object maybe_script = frame->function().shared().script(); if (maybe_script.IsScript()) { Handle<Script> script(Script::cast(maybe_script), this); Script::PositionInfo info; Script::GetPositionInfo(script, position, &info, Script::WITH_OFFSET); *line = info.line + 1; *column = info.column + 1; } else { *line = position; *column = -1; } if (frame->is_interpreted()) { InterpretedFrame* iframe = static_cast<InterpretedFrame*>(frame); Address bytecode_start = iframe->GetBytecodeArray().GetFirstBytecodeAddress(); return bytecode_start + iframe->GetBytecodeOffset(); } return frame->pc(); } Handle<FixedArray> Isolate::CaptureCurrentStackTrace( int frame_limit, StackTrace::StackTraceOptions stack_trace_options) { CaptureStackTraceOptions options; options.limit = Max(frame_limit, 0); // Ensure no negative values. options.skip_mode = SKIP_NONE; options.capture_builtin_exit_frames = false; options.async_stack_trace = false; options.filter_mode = (stack_trace_options & StackTrace::kExposeFramesAcrossSecurityOrigins) ? FrameArrayBuilder::ALL : FrameArrayBuilder::CURRENT_SECURITY_CONTEXT; options.capture_only_frames_subject_to_debugging = true; options.enable_frame_caching = true; return Handle<FixedArray>::cast( CaptureStackTrace(this, factory()->undefined_value(), options)); } void Isolate::PrintStack(FILE* out, PrintStackMode mode) { if (stack_trace_nesting_level_ == 0) { stack_trace_nesting_level_++; StringStream::ClearMentionedObjectCache(this); HeapStringAllocator allocator; StringStream accumulator(&allocator); incomplete_message_ = &accumulator; PrintStack(&accumulator, mode); accumulator.OutputToFile(out); InitializeLoggingAndCounters(); accumulator.Log(this); incomplete_message_ = nullptr; stack_trace_nesting_level_ = 0; } else if (stack_trace_nesting_level_ == 1) { stack_trace_nesting_level_++; base::OS::PrintError( "\n\nAttempt to print stack while printing stack (double fault)\n"); base::OS::PrintError( "If you are lucky you may find a partial stack dump on stdout.\n\n"); incomplete_message_->OutputToFile(out); } } static void PrintFrames(Isolate* isolate, StringStream* accumulator, StackFrame::PrintMode mode) { StackFrameIterator it(isolate); for (int i = 0; !it.done(); it.Advance()) { it.frame()->Print(accumulator, mode, i++); } } void Isolate::PrintStack(StringStream* accumulator, PrintStackMode mode) { HandleScope scope(this); wasm::WasmCodeRefScope wasm_code_ref_scope; DCHECK(accumulator->IsMentionedObjectCacheClear(this)); // Avoid printing anything if there are no frames. if (c_entry_fp(thread_local_top()) == 0) return; accumulator->Add( "\n==== JS stack trace =========================================\n\n"); PrintFrames(this, accumulator, StackFrame::OVERVIEW); if (mode == kPrintStackVerbose) { accumulator->Add( "\n==== Details ================================================\n\n"); PrintFrames(this, accumulator, StackFrame::DETAILS); accumulator->PrintMentionedObjectCache(this); } accumulator->Add("=====================\n\n"); } void Isolate::SetFailedAccessCheckCallback( v8::FailedAccessCheckCallback callback) { thread_local_top()->failed_access_check_callback_ = callback; } void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver) { if (!thread_local_top()->failed_access_check_callback_) { return ScheduleThrow(*factory()->NewTypeError(MessageTemplate::kNoAccess)); } DCHECK(receiver->IsAccessCheckNeeded()); DCHECK(!context().is_null()); // Get the data object from access check info. HandleScope scope(this); Handle<Object> data; { DisallowHeapAllocation no_gc; AccessCheckInfo access_check_info = AccessCheckInfo::Get(this, receiver); if (access_check_info.is_null()) { AllowHeapAllocation doesnt_matter_anymore; return ScheduleThrow( *factory()->NewTypeError(MessageTemplate::kNoAccess)); } data = handle(access_check_info.data(), this); } // Leaving JavaScript. VMState<EXTERNAL> state(this); thread_local_top()->failed_access_check_callback_( v8::Utils::ToLocal(receiver), v8::ACCESS_HAS, v8::Utils::ToLocal(data)); } bool Isolate::MayAccess(Handle<Context> accessing_context, Handle<JSObject> receiver) { DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded()); // Check for compatibility between the security tokens in the // current lexical context and the accessed object. // During bootstrapping, callback functions are not enabled yet. if (bootstrapper()->IsActive()) return true; { DisallowHeapAllocation no_gc; if (receiver->IsJSGlobalProxy()) { Object receiver_context = JSGlobalProxy::cast(*receiver).native_context(); if (!receiver_context.IsContext()) return false; // Get the native context of current top context. // avoid using Isolate::native_context() because it uses Handle. Context native_context = accessing_context->global_object().native_context(); if (receiver_context == native_context) return true; if (Context::cast(receiver_context).security_token() == native_context.security_token()) return true; } } HandleScope scope(this); Handle<Object> data; v8::AccessCheckCallback callback = nullptr; { DisallowHeapAllocation no_gc; AccessCheckInfo access_check_info = AccessCheckInfo::Get(this, receiver); if (access_check_info.is_null()) return false; Object fun_obj = access_check_info.callback(); callback = v8::ToCData<v8::AccessCheckCallback>(fun_obj); data = handle(access_check_info.data(), this); } LOG(this, ApiSecurityCheck()); { // Leaving JavaScript. VMState<EXTERNAL> state(this); return callback(v8::Utils::ToLocal(accessing_context), v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(data)); } } Object Isolate::StackOverflow() { if (FLAG_correctness_fuzzer_suppressions) { FATAL("Aborting on stack overflow"); } DisallowJavascriptExecution no_js(this); HandleScope scope(this); Handle<JSFunction> fun = range_error_function(); Handle<Object> msg = factory()->NewStringFromAsciiChecked( MessageFormatter::TemplateString(MessageTemplate::kStackOverflow)); Handle<Object> no_caller; Handle<Object> exception; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( this, exception, ErrorUtils::Construct(this, fun, fun, msg, SKIP_NONE, no_caller, ErrorUtils::StackTraceCollection::kSimple)); Throw(*exception, nullptr); #ifdef VERIFY_HEAP if (FLAG_verify_heap && FLAG_stress_compaction) { heap()->CollectAllGarbage(Heap::kNoGCFlags, GarbageCollectionReason::kTesting); } #endif // VERIFY_HEAP return ReadOnlyRoots(heap()).exception(); } Object Isolate::TerminateExecution() { return Throw(ReadOnlyRoots(this).termination_exception(), nullptr); } void Isolate::CancelTerminateExecution() { if (try_catch_handler()) { try_catch_handler()->has_terminated_ = false; } if (has_pending_exception() && pending_exception() == ReadOnlyRoots(this).termination_exception()) { thread_local_top()->external_caught_exception_ = false; clear_pending_exception(); } if (has_scheduled_exception() && scheduled_exception() == ReadOnlyRoots(this).termination_exception()) { thread_local_top()->external_caught_exception_ = false; clear_scheduled_exception(); } } void Isolate::RequestInterrupt(InterruptCallback callback, void* data) { ExecutionAccess access(this); api_interrupts_queue_.push(InterruptEntry(callback, data)); stack_guard()->RequestApiInterrupt(); } void Isolate::InvokeApiInterruptCallbacks() { RuntimeCallTimerScope runtimeTimer( this, RuntimeCallCounterId::kInvokeApiInterruptCallbacks); // Note: callback below should be called outside of execution access lock. while (true) { InterruptEntry entry; { ExecutionAccess access(this); if (api_interrupts_queue_.empty()) return; entry = api_interrupts_queue_.front(); api_interrupts_queue_.pop(); } VMState<EXTERNAL> state(this); HandleScope handle_scope(this); entry.first(reinterpret_cast<v8::Isolate*>(this), entry.second); } } void ReportBootstrappingException(Handle<Object> exception, MessageLocation* location) { base::OS::PrintError("Exception thrown during bootstrapping\n"); if (location == nullptr || location->script().is_null()) return; // We are bootstrapping and caught an error where the location is set // and we have a script for the location. // In this case we could have an extension (or an internal error // somewhere) and we print out the line number at which the error occurred // to the console for easier debugging. int line_number = location->script()->GetLineNumber(location->start_pos()) + 1; if (exception->IsString() && location->script()->name().IsString()) { base::OS::PrintError( "Extension or internal compilation error: %s in %s at line %d.\n", String::cast(*exception).ToCString().get(), String::cast(location->script()->name()).ToCString().get(), line_number); } else if (location->script()->name().IsString()) { base::OS::PrintError( "Extension or internal compilation error in %s at line %d.\n", String::cast(location->script()->name()).ToCString().get(), line_number); } else if (exception->IsString()) { base::OS::PrintError("Extension or internal compilation error: %s.\n", String::cast(*exception).ToCString().get()); } else { base::OS::PrintError("Extension or internal compilation error.\n"); } #ifdef OBJECT_PRINT // Since comments and empty lines have been stripped from the source of // builtins, print the actual source here so that line numbers match. if (location->script()->source().IsString()) { Handle<String> src(String::cast(location->script()->source()), location->script()->GetIsolate()); PrintF("Failing script:"); int len = src->length(); if (len == 0) { PrintF(" <not available>\n"); } else { PrintF("\n"); int line_number = 1; PrintF("%5d: ", line_number); for (int i = 0; i < len; i++) { uint16_t character = src->Get(i); PrintF("%c", character); if (character == '\n' && i < len - 2) { PrintF("%5d: ", ++line_number); } } PrintF("\n"); } } #endif } Object Isolate::Throw(Object raw_exception, MessageLocation* location) { DCHECK(!has_pending_exception()); HandleScope scope(this); Handle<Object> exception(raw_exception, this); if (FLAG_print_all_exceptions) { printf("=========================================================\n"); printf("Exception thrown:\n"); if (location) { Handle<Script> script = location->script(); Handle<Object> name(script->GetNameOrSourceURL(), this); printf("at "); if (name->IsString() && String::cast(*name).length() > 0) String::cast(*name).PrintOn(stdout); else printf("<anonymous>"); // Script::GetLineNumber and Script::GetColumnNumber can allocate on the heap to // initialize the line_ends array, so be careful when calling them. #ifdef DEBUG if (AllowHeapAllocation::IsAllowed()) { #else if ((false)) { #endif printf(", %d:%d - %d:%d\n", Script::GetLineNumber(script, location->start_pos()) + 1, Script::GetColumnNumber(script, location->start_pos()), Script::GetLineNumber(script, location->end_pos()) + 1, Script::GetColumnNumber(script, location->end_pos())); // Make sure to update the raw exception pointer in case it moved. raw_exception = *exception; } else { printf(", line %d\n", script->GetLineNumber(location->start_pos()) + 1); } } raw_exception.Print(); printf("Stack Trace:\n"); PrintStack(stdout); printf("=========================================================\n"); } // Determine whether a message needs to be created for the given exception // depending on the following criteria: // 1) External v8::TryCatch missing: Always create a message because any // JavaScript handler for a finally-block might re-throw to top-level. // 2) External v8::TryCatch exists: Only create a message if the handler // captures messages or is verbose (which reports despite the catch). // 3) ReThrow from v8::TryCatch: The message from a previous throw still // exists and we preserve it instead of creating a new message. bool requires_message = try_catch_handler() == nullptr || try_catch_handler()->is_verbose_ || try_catch_handler()->capture_message_; bool rethrowing_message = thread_local_top()->rethrowing_message_; thread_local_top()->rethrowing_message_ = false; // Notify debugger of exception. if (is_catchable_by_javascript(raw_exception)) { debug()->OnThrow(exception); } // Generate the message if required. if (requires_message && !rethrowing_message) { MessageLocation computed_location; // If no location was specified we try to use a computed one instead. if (location == nullptr && ComputeLocation(&computed_location)) { location = &computed_location; } if (bootstrapper()->IsActive()) { // It's not safe to try to make message objects or collect stack traces // while the bootstrapper is active since the infrastructure may not have // been properly initialized. ReportBootstrappingException(exception, location); } else { Handle<Object> message_obj = CreateMessage(exception, location); thread_local_top()->pending_message_obj_ = *message_obj; // For any exception not caught by JavaScript, even when an external // handler is present: // If the abort-on-uncaught-exception flag is specified, and if the // embedder didn't specify a custom uncaught exception callback, // or if the custom callback determined that V8 should abort, then // abort. if (FLAG_abort_on_uncaught_exception) { CatchType prediction = PredictExceptionCatcher(); if ((prediction == NOT_CAUGHT || prediction == CAUGHT_BY_EXTERNAL) && (!abort_on_uncaught_exception_callback_ || abort_on_uncaught_exception_callback_( reinterpret_cast<v8::Isolate*>(this)))) { // Prevent endless recursion. FLAG_abort_on_uncaught_exception = false; // This flag is intended for use by JavaScript developers, so // print a user-friendly stack trace (not an internal one). PrintF(stderr, "%s\n\nFROM\n", MessageHandler::GetLocalizedMessage(this, message_obj).get()); PrintCurrentStackTrace(stderr); base::OS::Abort(); } } } } // Set the exception being thrown. set_pending_exception(*exception); return ReadOnlyRoots(heap()).exception(); } Object Isolate::ReThrow(Object exception) { DCHECK(!has_pending_exception()); // Set the exception being re-thrown. set_pending_exception(exception); return ReadOnlyRoots(heap()).exception(); } Object Isolate::UnwindAndFindHandler() { Object exception = pending_exception(); auto FoundHandler = [&](Context context, Address instruction_start, intptr_t handler_offset, Address constant_pool_address, Address handler_sp, Address handler_fp) { // Store information to be consumed by the CEntry. thread_local_top()->pending_handler_context_ = context; thread_local_top()->pending_handler_entrypoint_ = instruction_start + handler_offset; thread_local_top()->pending_handler_constant_pool_ = constant_pool_address; thread_local_top()->pending_handler_fp_ = handler_fp; thread_local_top()->pending_handler_sp_ = handler_sp; // Return and clear pending exception. The contract is that: // (1) the pending exception is stored in one place (no duplication), and // (2) within generated-code land, that one place is the return register. // If/when we unwind back into C++ (returning to the JSEntry stub, // or to Execution::CallWasm), the returned exception will be sent // back to isolate->set_pending_exception(...). clear_pending_exception(); return exception; }; // Special handling of termination exceptions, uncatchable by JavaScript and // Wasm code, we unwind the handlers until the top ENTRY handler is found. bool catchable_by_js = is_catchable_by_javascript(exception); // Compute handler and stack unwinding information by performing a full walk // over the stack and dispatching according to the frame type. for (StackFrameIterator iter(this);; iter.Advance()) { // Handler must exist. DCHECK(!iter.done()); StackFrame* frame = iter.frame(); switch (frame->type()) { case StackFrame::ENTRY: case StackFrame::CONSTRUCT_ENTRY: { // For JSEntry frames we always have a handler. StackHandler* handler = frame->top_handler(); // Restore the next handler. thread_local_top()->handler_ = handler->next_address(); // Gather information from the handler. Code code = frame->LookupCode(); HandlerTable table(code); return FoundHandler(Context(), code.InstructionStart(), table.LookupReturn(0), code.constant_pool(), handler->address() + StackHandlerConstants::kSize, 0); } case StackFrame::C_WASM_ENTRY: { StackHandler* handler = frame->top_handler(); thread_local_top()->handler_ = handler->next_address(); Code code = frame->LookupCode(); HandlerTable table(code); Address instruction_start = code.InstructionStart(); int return_offset = static_cast<int>(frame->pc() - instruction_start); int handler_offset = table.LookupReturn(return_offset); DCHECK_NE(-1, handler_offset); return FoundHandler(Context(), instruction_start, handler_offset, code.constant_pool(), frame->sp(), frame->fp()); } case StackFrame::WASM_COMPILED: { if (trap_handler::IsThreadInWasm()) { trap_handler::ClearThreadInWasm(); } // For WebAssembly frames we perform a lookup in the handler table. if (!catchable_by_js) break; // This code ref scope is here to avoid a check failure when looking up // the code. It's not actually necessary to keep the code alive as it's // currently being executed. wasm::WasmCodeRefScope code_ref_scope; WasmCompiledFrame* wasm_frame = static_cast<WasmCompiledFrame*>(frame); int stack_slots = 0; // Will contain stack slot count of frame. int offset = wasm_frame->LookupExceptionHandlerInTable(&stack_slots); if (offset < 0) break; // Compute the stack pointer from the frame pointer. This ensures that // argument slots on the stack are dropped as returning would. Address return_sp = frame->fp() + StandardFrameConstants::kFixedFrameSizeAboveFp - stack_slots * kSystemPointerSize; // This is going to be handled by Wasm, so we need to set the TLS flag // again. It was cleared above assuming the frame would be unwound. trap_handler::SetThreadInWasm(); // Gather information from the frame. wasm::WasmCode* wasm_code = wasm_engine()->code_manager()->LookupCode(frame->pc()); return FoundHandler(Context(), wasm_code->instruction_start(), offset, wasm_code->constant_pool(), return_sp, frame->fp()); } case StackFrame::WASM_COMPILE_LAZY: { // Can only fail directly on invocation. This happens if an invalid // function was validated lazily. DCHECK_IMPLIES(trap_handler::IsTrapHandlerEnabled(), trap_handler::IsThreadInWasm()); DCHECK(FLAG_wasm_lazy_validation); trap_handler::ClearThreadInWasm(); break; } case StackFrame::OPTIMIZED: { // For optimized frames we perform a lookup in the handler table. if (!catchable_by_js) break; OptimizedFrame* js_frame = static_cast<OptimizedFrame*>(frame); int stack_slots = 0; // Will contain stack slot count of frame. int offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, nullptr); if (offset < 0) break; // Compute the stack pointer from the frame pointer. This ensures // that argument slots on the stack are dropped as returning would. Address return_sp = frame->fp() + StandardFrameConstants::kFixedFrameSizeAboveFp - stack_slots * kSystemPointerSize; // Gather information from the frame. Code code = frame->LookupCode(); // TODO(bmeurer): Turbofanned BUILTIN frames appear as OPTIMIZED, // but do not have a code kind of OPTIMIZED_FUNCTION. if (code.kind() == Code::OPTIMIZED_FUNCTION && code.marked_for_deoptimization()) { // If the target code is lazy deoptimized, we jump to the original // return address, but we make a note that we are throwing, so // that the deoptimizer can do the right thing. offset = static_cast<int>(frame->pc() - code.entry()); set_deoptimizer_lazy_throw(true); } return FoundHandler(Context(), code.InstructionStart(), offset, code.constant_pool(), return_sp, frame->fp()); } case StackFrame::STUB: { // Some stubs are able to handle exceptions. if (!catchable_by_js) break; StubFrame* stub_frame = static_cast<StubFrame*>(frame); wasm::WasmCodeRefScope code_ref_scope; wasm::WasmCode* wasm_code = wasm_engine()->code_manager()->LookupCode(frame->pc()); if (wasm_code != nullptr) { // It is safe to skip Wasm runtime stubs as none of them contain local // exception handlers. CHECK_EQ(wasm::WasmCode::kRuntimeStub, wasm_code->kind()); CHECK_EQ(0, wasm_code->handler_table_size()); break; } Code code = stub_frame->LookupCode(); if (!code.IsCode() || code.kind() != Code::BUILTIN || !code.has_handler_table() || !code.is_turbofanned()) { break; } int stack_slots = 0; // Will contain stack slot count of frame. int offset = stub_frame->LookupExceptionHandlerInTable(&stack_slots); if (offset < 0) break; // Compute the stack pointer from the frame pointer. This ensures // that argument slots on the stack are dropped as returning would. Address return_sp = frame->fp() + StandardFrameConstants::kFixedFrameSizeAboveFp - stack_slots * kSystemPointerSize; return FoundHandler(Context(), code.InstructionStart(), offset, code.constant_pool(), return_sp, frame->fp()); } case StackFrame::INTERPRETED: { // For interpreted frame we perform a range lookup in the handler table. if (!catchable_by_js) break; InterpretedFrame* js_frame = static_cast<InterpretedFrame*>(frame); int register_slots = InterpreterFrameConstants::RegisterStackSlotCount( js_frame->GetBytecodeArray().register_count()); int context_reg = 0; // Will contain register index holding context. int offset = js_frame->LookupExceptionHandlerInTable(&context_reg, nullptr); if (offset < 0) break; // Compute the stack pointer from the frame pointer. This ensures that // argument slots on the stack are dropped as returning would. // Note: This is only needed for interpreted frames that have been // materialized by the deoptimizer. If there is a handler frame // in between then {frame->sp()} would already be correct. Address return_sp = frame->fp() - InterpreterFrameConstants::kFixedFrameSizeFromFp - register_slots * kSystemPointerSize; // Patch the bytecode offset in the interpreted frame to reflect the // position of the exception handler. The special builtin below will // take care of continuing to dispatch at that position. Also restore // the correct context for the handler from the interpreter register. Context context = Context::cast(js_frame->ReadInterpreterRegister(context_reg)); js_frame->PatchBytecodeOffset(static_cast<int>(offset)); Code code = builtins()->builtin(Builtins::kInterpreterEnterBytecodeDispatch); return FoundHandler(context, code.InstructionStart(), 0, code.constant_pool(), return_sp, frame->fp()); } case StackFrame::BUILTIN: // For builtin frames we are guaranteed not to find a handler. if (catchable_by_js) { CHECK_EQ(-1, JavaScriptFrame::cast(frame)->LookupExceptionHandlerInTable( nullptr, nullptr)); } break; case StackFrame::WASM_INTERPRETER_ENTRY: { if (trap_handler::IsThreadInWasm()) { trap_handler::ClearThreadInWasm(); } } break; case StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH: { // Builtin continuation frames with catch can handle exceptions. if (!catchable_by_js) break; JavaScriptBuiltinContinuationWithCatchFrame* js_frame = JavaScriptBuiltinContinuationWithCatchFrame::cast(frame); js_frame->SetException(exception); // Reconstruct the stack pointer from the frame pointer. Address return_sp = js_frame->fp() - js_frame->GetSPToFPDelta(); Code code = js_frame->LookupCode(); return FoundHandler(Context(), code.InstructionStart(), 0, code.constant_pool(), return_sp, frame->fp()); } break; default: // All other types can not handle exception. break; } if (frame->is_optimized()) { // Remove per-frame stored materialized objects. bool removed = materialized_object_store_->Remove(frame->fp()); USE(removed); // If there were any materialized objects, the code should be // marked for deopt. DCHECK_IMPLIES(removed, frame->LookupCode().marked_for_deoptimization()); } } UNREACHABLE(); } namespace { HandlerTable::CatchPrediction PredictException(JavaScriptFrame* frame) { HandlerTable::CatchPrediction prediction; if (frame->is_optimized()) { if (frame->LookupExceptionHandlerInTable(nullptr, nullptr) > 0) { // This optimized frame will catch. It's handler table does not include // exception prediction, and we need to use the corresponding handler // tables on the unoptimized code objects. std::vector<FrameSummary> summaries; frame->Summarize(&summaries); for (size_t i = summaries.size(); i != 0; i--) { const FrameSummary& summary = summaries[i - 1]; Handle<AbstractCode> code = summary.AsJavaScript().abstract_code(); if (code->IsCode() && code->kind() == AbstractCode::BUILTIN) { prediction = code->GetCode().GetBuiltinCatchPrediction(); if (prediction == HandlerTable::UNCAUGHT) continue; return prediction; } // Must have been constructed from a bytecode array. CHECK_EQ(AbstractCode::INTERPRETED_FUNCTION, code->kind()); int code_offset = summary.code_offset(); HandlerTable table(code->GetBytecodeArray()); int index = table.LookupRange(code_offset, nullptr, &prediction); if (index <= 0) continue; if (prediction == HandlerTable::UNCAUGHT) continue; return prediction; } } } else if (frame->LookupExceptionHandlerInTable(nullptr, &prediction) > 0) { return prediction; } return HandlerTable::UNCAUGHT; } Isolate::CatchType ToCatchType(HandlerTable::CatchPrediction prediction) { switch (prediction) { case HandlerTable::UNCAUGHT: return Isolate::NOT_CAUGHT; case HandlerTable::CAUGHT: return Isolate::CAUGHT_BY_JAVASCRIPT; case HandlerTable::PROMISE: return Isolate::CAUGHT_BY_PROMISE; case HandlerTable::DESUGARING: return Isolate::CAUGHT_BY_DESUGARING; case HandlerTable::ASYNC_AWAIT: return Isolate::CAUGHT_BY_ASYNC_AWAIT; default: UNREACHABLE(); } } } // anonymous namespace Isolate::CatchType Isolate::PredictExceptionCatcher() { Address external_handler = thread_local_top()->try_catch_handler_address(); if (IsExternalHandlerOnTop(Object())) return CAUGHT_BY_EXTERNAL; // Search for an exception handler by performing a full walk over the stack. for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) { StackFrame* frame = iter.frame(); switch (frame->type()) { case StackFrame::ENTRY: case StackFrame::CONSTRUCT_ENTRY: { Address entry_handler = frame->top_handler()->next_address(); // The exception has been externally caught if and only if there is an // external handler which is on top of the top-most JS_ENTRY handler. if (external_handler != kNullAddress && !try_catch_handler()->is_verbose_) { if (entry_handler == kNullAddress || entry_handler > external_handler) { return CAUGHT_BY_EXTERNAL; } } } break; // For JavaScript frames we perform a lookup in the handler table. case StackFrame::OPTIMIZED: case StackFrame::INTERPRETED: case StackFrame::BUILTIN: { JavaScriptFrame* js_frame = JavaScriptFrame::cast(frame); Isolate::CatchType prediction = ToCatchType(PredictException(js_frame)); if (prediction == NOT_CAUGHT) break; return prediction; } break; case StackFrame::STUB: { Handle<Code> code(frame->LookupCode(), this); if (!code->IsCode() || code->kind() != Code::BUILTIN || !code->has_handler_table() || !code->is_turbofanned()) { break; } CatchType prediction = ToCatchType(code->GetBuiltinCatchPrediction()); if (prediction != NOT_CAUGHT) return prediction; } break; case StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH: { Handle<Code> code(frame->LookupCode(), this); CatchType prediction = ToCatchType(code->GetBuiltinCatchPrediction()); if (prediction != NOT_CAUGHT) return prediction; } break; default: // All other types can not handle exception. break; } } // Handler not found. return NOT_CAUGHT; } Object Isolate::ThrowIllegalOperation() { if (FLAG_stack_trace_on_illegal) PrintStack(stdout); return Throw(ReadOnlyRoots(heap()).illegal_access_string()); } void Isolate::ScheduleThrow(Object exception) { // When scheduling a throw we first throw the exception to get the // error reporting if it is uncaught before rescheduling it. Throw(exception); PropagatePendingExceptionToExternalTryCatch(); if (has_pending_exception()) { thread_local_top()->scheduled_exception_ = pending_exception(); thread_local_top()->external_caught_exception_ = false; clear_pending_exception(); } } void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) { DCHECK(handler == try_catch_handler()); DCHECK(handler->HasCaught()); DCHECK(handler->rethrow_); DCHECK(handler->capture_message_); Object message(reinterpret_cast<Address>(handler->message_obj_)); DCHECK(message.IsJSMessageObject() || message.IsTheHole(this)); thread_local_top()->pending_message_obj_ = message; } void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) { DCHECK(has_scheduled_exception()); if (reinterpret_cast<void*>(scheduled_exception().ptr()) == handler->exception_) { DCHECK_NE(scheduled_exception(), ReadOnlyRoots(heap()).termination_exception()); clear_scheduled_exception(); } else { DCHECK_EQ(scheduled_exception(), ReadOnlyRoots(heap()).termination_exception()); // Clear termination once we returned from all V8 frames. if (handle_scope_implementer()->CallDepthIsZero()) { thread_local_top()->external_caught_exception_ = false; clear_scheduled_exception(); } } if (reinterpret_cast<void*>(thread_local_top()->pending_message_obj_.ptr()) == handler->message_obj_) { clear_pending_message(); } } Object Isolate::PromoteScheduledException() { Object thrown = scheduled_exception(); clear_scheduled_exception(); // Re-throw the exception to avoid getting repeated error reporting. return ReThrow(thrown); } void Isolate::PrintCurrentStackTrace(FILE* out) { CaptureStackTraceOptions options; options.limit = 0; options.skip_mode = SKIP_NONE; options.capture_builtin_exit_frames = true; options.async_stack_trace = FLAG_async_stack_traces; options.filter_mode = FrameArrayBuilder::CURRENT_SECURITY_CONTEXT; options.capture_only_frames_subject_to_debugging = false; options.enable_frame_caching = false; Handle<FixedArray> frames = Handle<FixedArray>::cast( CaptureStackTrace(this, this->factory()->undefined_value(), options)); IncrementalStringBuilder builder(this); for (int i = 0; i < frames->length(); ++i) { Handle<StackTraceFrame> frame(StackTraceFrame::cast(frames->get(i)), this); SerializeStackTraceFrame(this, frame, builder); } Handle<String> stack_trace = builder.Finish().ToHandleChecked(); stack_trace->PrintOn(out); } bool Isolate::ComputeLocation(MessageLocation* target) { StackTraceFrameIterator it(this); if (it.done()) return false; StandardFrame* frame = it.frame(); // Compute the location from the function and the relocation info of the // baseline code. For optimized code this will use the deoptimization // information to get canonical location information. std::vector<FrameSummary> frames; wasm::WasmCodeRefScope code_ref_scope; frame->Summarize(&frames); FrameSummary& summary = frames.back(); Handle<SharedFunctionInfo> shared; Handle<Object> script = summary.script(); if (!script->IsScript() || (Script::cast(*script).source().IsUndefined(this))) { return false; } if (summary.IsJavaScript()) { shared = handle(summary.AsJavaScript().function()->shared(), this); } if (summary.AreSourcePositionsAvailable()) { int pos = summary.SourcePosition(); *target = MessageLocation(Handle<Script>::cast(script), pos, pos + 1, shared); } else { *target = MessageLocation(Handle<Script>::cast(script), shared, summary.code_offset()); } return true; } bool Isolate::ComputeLocationFromException(MessageLocation* target, Handle<Object> exception) { if (!exception->IsJSObject()) return false; Handle<Name> start_pos_symbol = factory()->error_start_pos_symbol(); Handle<Object> start_pos = JSReceiver::GetDataProperty( Handle<JSObject>::cast(exception), start_pos_symbol); if (!start_pos->IsSmi()) return false; int start_pos_value = Handle<Smi>::cast(start_pos)->value(); Handle<Name> end_pos_symbol = factory()->error_end_pos_symbol(); Handle<Object> end_pos = JSReceiver::GetDataProperty( Handle<JSObject>::cast(exception), end_pos_symbol); if (!end_pos->IsSmi()) return false; int end_pos_value = Handle<Smi>::cast(end_pos)->value(); Handle<Name> script_symbol = factory()->error_script_symbol(); Handle<Object> script = JSReceiver::GetDataProperty( Handle<JSObject>::cast(exception), script_symbol); if (!script->IsScript()) return false; Handle<Script> cast_script(Script::cast(*script), this); *target = MessageLocation(cast_script, start_pos_value, end_pos_value); return true; } bool Isolate::ComputeLocationFromStackTrace(MessageLocation* target, Handle<Object> exception) { if (!exception->IsJSObject()) return false; Handle<Name> key = factory()->stack_trace_symbol(); Handle<Object> property = JSReceiver::GetDataProperty(Handle<JSObject>::cast(exception), key); if (!property->IsFixedArray()) return false; Handle<FrameArray> elements = GetFrameArrayFromStackTrace(this, Handle<FixedArray>::cast(property)); const int frame_count = elements->FrameCount(); for (int i = 0; i < frame_count; i++) { if (elements->IsWasmFrame(i) || elements->IsAsmJsWasmFrame(i)) { Handle<WasmInstanceObject> instance(elements->WasmInstance(i), this); uint32_t func_index = static_cast<uint32_t>(elements->WasmFunctionIndex(i).value()); int code_offset = elements->Offset(i).value(); bool is_at_number_conversion = elements->IsAsmJsWasmFrame(i) && elements->Flags(i).value() & FrameArray::kAsmJsAtNumberConversion; // WasmCode* held alive by the {GlobalWasmCodeRef}. wasm::WasmCode* code = Managed<wasm::GlobalWasmCodeRef>::cast(elements->WasmCodeObject(i)) .get() ->code(); int byte_offset = FrameSummary::WasmCompiledFrameSummary::GetWasmSourcePosition( code, code_offset); int pos = WasmModuleObject::GetSourcePosition( handle(instance->module_object(), this), func_index, byte_offset, is_at_number_conversion); Handle<Script> script(instance->module_object().script(), this); *target = MessageLocation(script, pos, pos + 1); return true; } Handle<JSFunction> fun = handle(elements->Function(i), this); if (!fun->shared().IsSubjectToDebugging()) continue; Object script = fun->shared().script(); if (script.IsScript() && !(Script::cast(script).source().IsUndefined(this))) { Handle<SharedFunctionInfo> shared = handle(fun->shared(), this); AbstractCode abstract_code = elements->Code(i); const int code_offset = elements->Offset(i).value(); Handle<Script> casted_script(Script::cast(script), this); if (shared->HasBytecodeArray() && shared->GetBytecodeArray().HasSourcePositionTable()) { int pos = abstract_code.SourcePosition(code_offset); *target = MessageLocation(casted_script, pos, pos + 1, shared); } else { *target = MessageLocation(casted_script, shared, code_offset); } return true; } } return false; } Handle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception, MessageLocation* location) { Handle<FixedArray> stack_trace_object; if (capture_stack_trace_for_uncaught_exceptions_) { if (exception->IsJSError()) { // We fetch the stack trace that corresponds to this error object. // If the lookup fails, the exception is probably not a valid Error // object. In that case, we fall through and capture the stack trace // at this throw site. stack_trace_object = GetDetailedStackTrace(Handle<JSObject>::cast(exception)); } if (stack_trace_object.is_null()) { // Not an error object, we capture stack and location at throw site. stack_trace_object = CaptureCurrentStackTrace( stack_trace_for_uncaught_exceptions_frame_limit_, stack_trace_for_uncaught_exceptions_options_); } } MessageLocation computed_location; if (location == nullptr && (ComputeLocationFromException(&computed_location, exception) || ComputeLocationFromStackTrace(&computed_location, exception) || ComputeLocation(&computed_location))) { location = &computed_location; } return MessageHandler::MakeMessageObject( this, MessageTemplate::kUncaughtException, location, exception, stack_trace_object); } bool Isolate::IsJavaScriptHandlerOnTop(Object exception) { DCHECK_NE(ReadOnlyRoots(heap()).the_hole_value(), exception); // For uncatchable exceptions, the JavaScript handler cannot be on top. if (!is_catchable_by_javascript(exception)) return false; // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist. Address entry_handler = Isolate::handler(thread_local_top()); if (entry_handler == kNullAddress) return false; // Get the address of the external handler so we can compare the address to // determine which one is closer to the top of the stack. Address external_handler = thread_local_top()->try_catch_handler_address(); if (external_handler == kNullAddress) return true; // The exception has been externally caught if and only if there is an // external handler which is on top of the top-most JS_ENTRY handler. // // Note, that finally clauses would re-throw an exception unless it's aborted // by jumps in control flow (like return, break, etc.) and we'll have another // chance to set proper v8::TryCatch later. return (entry_handler < external_handler); } bool Isolate::IsExternalHandlerOnTop(Object exception) { DCHECK_NE(ReadOnlyRoots(heap()).the_hole_value(), exception); // Get the address of the external handler so we can compare the address to // determine which one is closer to the top of the stack. Address external_handler = thread_local_top()->try_catch_handler_address(); if (external_handler == kNullAddress) return false; // For uncatchable exceptions, the external handler is always on top. if (!is_catchable_by_javascript(exception)) return true; // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist. Address entry_handler = Isolate::handler(thread_local_top()); if (entry_handler == kNullAddress) return true; // The exception has been externally caught if and only if there is an // external handler which is on top of the top-most JS_ENTRY handler. // // Note, that finally clauses would re-throw an exception unless it's aborted // by jumps in control flow (like return, break, etc.) and we'll have another // chance to set proper v8::TryCatch later. return (entry_handler > external_handler); } void Isolate::ReportPendingMessagesImpl(bool report_externally) { Object exception_obj = pending_exception(); // Clear the pending message object early to avoid endless recursion. Object message_obj = thread_local_top()->pending_message_obj_; clear_pending_message(); // For uncatchable exceptions we do nothing. If needed, the exception and the // message have already been propagated to v8::TryCatch. if (!is_catchable_by_javascript(exception_obj)) return; // Determine whether the message needs to be reported to all message handlers // depending on whether and external v8::TryCatch or an internal JavaScript // handler is on top. bool should_report_exception; if (report_externally) { // Only report the exception if the external handler is verbose. should_report_exception = try_catch_handler()->is_verbose_; } else { // Report the exception if it isn't caught by JavaScript code. should_report_exception = !IsJavaScriptHandlerOnTop(exception_obj); } // Actually report the pending message to all message handlers. if (!message_obj.IsTheHole(this) && should_report_exception) { HandleScope scope(this); Handle<JSMessageObject> message(JSMessageObject::cast(message_obj), this); Handle<Object> exception(exception_obj, this); Handle<Script> script(message->script(), this); // Clear the exception and restore it afterwards, otherwise // CollectSourcePositions will abort. clear_pending_exception(); JSMessageObject::EnsureSourcePositionsAvailable(this, message); set_pending_exception(*exception); int start_pos = message->GetStartPosition(); int end_pos = message->GetEndPosition(); MessageLocation location(script, start_pos, end_pos); MessageHandler::ReportMessage(this, &location, message); } } void Isolate::ReportPendingMessages() { DCHECK(AllowExceptions::IsAllowed(this)); // The embedder might run script in response to an exception. AllowJavascriptExecutionDebugOnly allow_script(this); Object exception = pending_exception(); // Try to propagate the exception to an external v8::TryCatch handler. If // propagation was unsuccessful, then we will get another chance at reporting // the pending message if the exception is re-thrown. bool has_been_propagated = PropagatePendingExceptionToExternalTryCatch(); if (!has_been_propagated) return; ReportPendingMessagesImpl(IsExternalHandlerOnTop(exception)); } void Isolate::ReportPendingMessagesFromJavaScript() { DCHECK(AllowExceptions::IsAllowed(this)); auto IsHandledByJavaScript = [=]() { // In this situation, the exception is always a non-terminating exception. // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist. Address entry_handler = Isolate::handler(thread_local_top()); DCHECK_NE(entry_handler, kNullAddress); entry_handler = StackHandler::FromAddress(entry_handler)->next_address(); // Get the address of the external handler so we can compare the address to // determine which one is closer to the top of the stack. Address external_handler = thread_local_top()->try_catch_handler_address(); if (external_handler == kNullAddress) return true; return (entry_handler < external_handler); }; auto IsHandledExternally = [=]() { Address external_handler = thread_local_top()->try_catch_handler_address(); if (external_handler == kNullAddress) return false; // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist. Address entry_handler = Isolate::handler(thread_local_top()); DCHECK_NE(entry_handler, kNullAddress); entry_handler = StackHandler::FromAddress(entry_handler)->next_address(); return (entry_handler > external_handler); }; auto PropagateToExternalHandler = [=]() { if (IsHandledByJavaScript()) { thread_local_top()->external_caught_exception_ = false; return false; } if (!IsHandledExternally()) { thread_local_top()->external_caught_exception_ = false; return true; } thread_local_top()->external_caught_exception_ = true; v8::TryCatch* handler = try_catch_handler(); DCHECK(thread_local_top()->pending_message_obj_.IsJSMessageObject() || thread_local_top()->pending_message_obj_.IsTheHole(this)); handler->can_continue_ = true; handler->has_terminated_ = false; handler->exception_ = reinterpret_cast<void*>(pending_exception().ptr()); // Propagate to the external try-catch only if we got an actual message. if (thread_local_top()->pending_message_obj_.IsTheHole(this)) return true; handler->message_obj_ = reinterpret_cast<void*>(thread_local_top()->pending_message_obj_.ptr()); return true; }; // Try to propagate to an external v8::TryCatch handler. if (!PropagateToExternalHandler()) return; ReportPendingMessagesImpl(true); } bool Isolate::OptionalRescheduleException(bool clear_exception) { DCHECK(has_pending_exception()); PropagatePendingExceptionToExternalTryCatch(); bool is_termination_exception = pending_exception() == ReadOnlyRoots(this).termination_exception(); if (is_termination_exception) { if (clear_exception) { thread_local_top()->external_caught_exception_ = false; clear_pending_exception(); return false; } } else if (thread_local_top()->external_caught_exception_) { // If the exception is externally caught, clear it if there are no // JavaScript frames on the way to the C++ frame that has the // external handler. DCHECK_NE(thread_local_top()->try_catch_handler_address(), kNullAddress); Address external_handler_address = thread_local_top()->try_catch_handler_address(); JavaScriptFrameIterator it(this); if (it.done() || (it.frame()->sp() > external_handler_address)) { clear_exception = true; } } // Clear the exception if needed. if (clear_exception) { thread_local_top()->external_caught_exception_ = false; clear_pending_exception(); return false; } // Reschedule the exception. thread_local_top()->scheduled_exception_ = pending_exception(); clear_pending_exception(); return true; } void Isolate::PushPromise(Handle<JSObject> promise) { ThreadLocalTop* tltop = thread_local_top(); PromiseOnStack* prev = tltop->promise_on_stack_; Handle<JSObject> global_promise = global_handles()->Create(*promise); tltop->promise_on_stack_ = new PromiseOnStack(global_promise, prev); } void Isolate::PopPromise() { ThreadLocalTop* tltop = thread_local_top(); if (tltop->promise_on_stack_ == nullptr) return; PromiseOnStack* prev = tltop->promise_on_stack_->prev(); Handle<Object> global_promise = tltop->promise_on_stack_->promise(); delete tltop->promise_on_stack_; tltop->promise_on_stack_ = prev; global_handles()->Destroy(global_promise.location()); } namespace { bool InternalPromiseHasUserDefinedRejectHandler(Isolate* isolate, Handle<JSPromise> promise); bool PromiseHandlerCheck(Isolate* isolate, Handle<JSReceiver> handler, Handle<JSReceiver> deferred_promise) { // Recurse to the forwarding Promise, if any. This may be due to // - await reaction forwarding to the throwaway Promise, which has // a dependency edge to the outer Promise. // - PromiseIdResolveHandler forwarding to the output of .then // - Promise.all/Promise.race forwarding to a throwaway Promise, which // has a dependency edge to the generated outer Promise. // Otherwise, this is a real reject handler for the Promise. Handle<Symbol> key = isolate->factory()->promise_forwarding_handler_symbol(); Handle<Object> forwarding_handler = JSReceiver::GetDataProperty(handler, key); if (forwarding_handler->IsUndefined(isolate)) { return true; } if (!deferred_promise->IsJSPromise()) { return true; } return InternalPromiseHasUserDefinedRejectHandler( isolate, Handle<JSPromise>::cast(deferred_promise)); } bool InternalPromiseHasUserDefinedRejectHandler(Isolate* isolate, Handle<JSPromise> promise) { // If this promise was marked as being handled by a catch block // in an async function, then it has a user-defined reject handler. if (promise->handled_hint()) return true; // If this Promise is subsumed by another Promise (a Promise resolved // with another Promise, or an intermediate, hidden, throwaway Promise // within async/await), then recurse on the outer Promise. // In this case, the dependency is one possible way that the Promise // could be resolved, so it does not subsume the other following cases. Handle<Symbol> key = isolate->factory()->promise_handled_by_symbol(); Handle<Object> outer_promise_obj = JSObject::GetDataProperty(promise, key); if (outer_promise_obj->IsJSPromise() && InternalPromiseHasUserDefinedRejectHandler( isolate, Handle<JSPromise>::cast(outer_promise_obj))) { return true; } if (promise->status() == Promise::kPending) { for (Handle<Object> current(promise->reactions(), isolate); !current->IsSmi();) { Handle<PromiseReaction> reaction = Handle<PromiseReaction>::cast(current); Handle<HeapObject> promise_or_capability( reaction->promise_or_capability(), isolate); if (!promise_or_capability->IsUndefined(isolate)) { Handle<JSPromise> promise = Handle<JSPromise>::cast( promise_or_capability->IsJSPromise() ? promise_or_capability : handle(Handle<PromiseCapability>::cast(promise_or_capability) ->promise(), isolate)); if (reaction->reject_handler().IsUndefined(isolate)) { if (InternalPromiseHasUserDefinedRejectHandler(isolate, promise)) { return true; } } else { Handle<JSReceiver> current_handler( JSReceiver::cast(reaction->reject_handler()), isolate); if (PromiseHandlerCheck(isolate, current_handler, promise)) { return true; } } } current = handle(reaction->next(), isolate); } } return false; } } // namespace bool Isolate::PromiseHasUserDefinedRejectHandler(Handle<Object> promise) { if (!promise->IsJSPromise()) return false; return InternalPromiseHasUserDefinedRejectHandler( this, Handle<JSPromise>::cast(promise)); } Handle<Object> Isolate::GetPromiseOnStackOnThrow() { Handle<Object> undefined = factory()->undefined_value(); ThreadLocalTop* tltop = thread_local_top(); if (tltop->promise_on_stack_ == nullptr) return undefined; // Find the top-most try-catch or try-finally handler. CatchType prediction = PredictExceptionCatcher(); if (prediction == NOT_CAUGHT || prediction == CAUGHT_BY_EXTERNAL) { return undefined; } Handle<Object> retval = undefined; PromiseOnStack* promise_on_stack = tltop->promise_on_stack_; for (StackFrameIterator it(this); !it.done(); it.Advance()) { StackFrame* frame = it.frame(); HandlerTable::CatchPrediction catch_prediction; if (frame->is_java_script()) { catch_prediction = PredictException(JavaScriptFrame::cast(frame)); } else if (frame->type() == StackFrame::STUB) { Code code = frame->LookupCode(); if (!code.IsCode() || code.kind() != Code::BUILTIN || !code.has_handler_table() || !code.is_turbofanned()) { continue; } catch_prediction = code.GetBuiltinCatchPrediction(); } else { continue; } switch (catch_prediction) { case HandlerTable::UNCAUGHT: continue; case HandlerTable::CAUGHT: case HandlerTable::DESUGARING: if (retval->IsJSPromise()) { // Caught the result of an inner async/await invocation. // Mark the inner promise as caught in the "synchronous case" so // that Debug::OnException will see. In the synchronous case, // namely in the code in an async function before the first // await, the function which has this exception event has not yet // returned, so the generated Promise has not yet been marked // by AsyncFunctionAwaitCaught with promiseHandledHintSymbol. Handle<JSPromise>::cast(retval)->set_handled_hint(true); } return retval; case HandlerTable::PROMISE: return promise_on_stack ? Handle<Object>::cast(promise_on_stack->promise()) : undefined; case HandlerTable::ASYNC_AWAIT: { // If in the initial portion of async/await, continue the loop to pop up // successive async/await stack frames until an asynchronous one with // dependents is found, or a non-async stack frame is encountered, in // order to handle the synchronous async/await catch prediction case: // assume that async function calls are awaited. if (!promise_on_stack) return retval; retval = promise_on_stack->promise(); if (PromiseHasUserDefinedRejectHandler(retval)) { return retval; } promise_on_stack = promise_on_stack->prev(); continue; } } } return retval; } void Isolate::SetCaptureStackTraceForUncaughtExceptions( bool capture, int frame_limit, StackTrace::StackTraceOptions options) { capture_stack_trace_for_uncaught_exceptions_ = capture; stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit; stack_trace_for_uncaught_exceptions_options_ = options; } void Isolate::SetAbortOnUncaughtExceptionCallback( v8::Isolate::AbortOnUncaughtExceptionCallback callback) { abort_on_uncaught_exception_callback_ = callback; } bool Isolate::AreWasmThreadsEnabled(Handle<Context> context) { if (wasm_threads_enabled_callback()) { v8::Local<v8::Context> api_context = v8::Utils::ToLocal(context); return wasm_threads_enabled_callback()(api_context); } return FLAG_experimental_wasm_threads; } Handle<Context> Isolate::GetIncumbentContext() { JavaScriptFrameIterator it(this); // 1st candidate: most-recently-entered author function's context // if it's newer than the last Context::BackupIncumbentScope entry. // // NOTE: This code assumes that the stack grows downward. Address top_backup_incumbent = top_backup_incumbent_scope() ? top_backup_incumbent_scope()->JSStackComparableAddress() : 0; if (!it.done() && (!top_backup_incumbent || it.frame()->sp() < top_backup_incumbent)) { Context context = Context::cast(it.frame()->context()); return Handle<Context>(context.native_context(), this); } // 2nd candidate: the last Context::Scope's incumbent context if any. if (top_backup_incumbent_scope()) { return Utils::OpenHandle( *top_backup_incumbent_scope()->backup_incumbent_context_); } // Last candidate: the entered context or microtask context. // Given that there is no other author function is running, there must be // no cross-context function running, then the incumbent realm must match // the entry realm. v8::Local<v8::Context> entered_context = reinterpret_cast<v8::Isolate*>(this)->GetEnteredOrMicrotaskContext(); return Utils::OpenHandle(*entered_context); } char* Isolate::ArchiveThread(char* to) { MemCopy(to, reinterpret_cast<char*>(thread_local_top()), sizeof(ThreadLocalTop)); InitializeThreadLocal(); clear_pending_exception(); clear_pending_message(); clear_scheduled_exception(); return to + sizeof(ThreadLocalTop); } char* Isolate::RestoreThread(char* from) { MemCopy(reinterpret_cast<char*>(thread_local_top()), from, sizeof(ThreadLocalTop)); // This might be just paranoia, but it seems to be needed in case a // thread_local_top_ is restored on a separate OS thread. #ifdef USE_SIMULATOR thread_local_top()->simulator_ = Simulator::current(this); #endif DCHECK(context().is_null() || context().IsContext()); return from + sizeof(ThreadLocalTop); } void Isolate::ReleaseSharedPtrs() { base::MutexGuard lock(&managed_ptr_destructors_mutex_); while (managed_ptr_destructors_head_) { ManagedPtrDestructor* l = managed_ptr_destructors_head_; ManagedPtrDestructor* n = nullptr; managed_ptr_destructors_head_ = nullptr; for (; l != nullptr; l = n) { l->destructor_(l->shared_ptr_ptr_); n = l->next_; delete l; } } } void Isolate::RegisterManagedPtrDestructor(ManagedPtrDestructor* destructor) { base::MutexGuard lock(&managed_ptr_destructors_mutex_); DCHECK_NULL(destructor->prev_); DCHECK_NULL(destructor->next_); if (managed_ptr_destructors_head_) { managed_ptr_destructors_head_->prev_ = destructor; } destructor->next_ = managed_ptr_destructors_head_; managed_ptr_destructors_head_ = destructor; } void Isolate::UnregisterManagedPtrDestructor(ManagedPtrDestructor* destructor) { base::MutexGuard lock(&managed_ptr_destructors_mutex_); if (destructor->prev_) { destructor->prev_->next_ = destructor->next_; } else { DCHECK_EQ(destructor, managed_ptr_destructors_head_); managed_ptr_destructors_head_ = destructor->next_; } if (destructor->next_) destructor->next_->prev_ = destructor->prev_; destructor->prev_ = nullptr; destructor->next_ = nullptr; } void Isolate::SetWasmEngine(std::shared_ptr<wasm::WasmEngine> engine) { DCHECK_NULL(wasm_engine_); // Only call once before {Init}. wasm_engine_ = std::move(engine); wasm_engine_->AddIsolate(this); } // NOLINTNEXTLINE Isolate::PerIsolateThreadData::~PerIsolateThreadData() { #if defined(USE_SIMULATOR) delete simulator_; #endif } Isolate::PerIsolateThreadData* Isolate::ThreadDataTable::Lookup( ThreadId thread_id) { auto t = table_.find(thread_id); if (t == table_.end()) return nullptr; return t->second; } void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) { bool inserted = table_.insert(std::make_pair(data->thread_id_, data)).second; CHECK(inserted); } void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) { table_.erase(data->thread_id_); delete data; } void Isolate::ThreadDataTable::RemoveAllThreads() { for (auto& x : table_) { delete x.second; } table_.clear(); } class VerboseAccountingAllocator : public AccountingAllocator { public: VerboseAccountingAllocator(Heap* heap, size_t allocation_sample_bytes) : heap_(heap), allocation_sample_bytes_(allocation_sample_bytes) {} v8::internal::Segment* AllocateSegment(size_t size) override { v8::internal::Segment* memory = AccountingAllocator::AllocateSegment(size); if (!memory) return nullptr; size_t malloced_current = GetCurrentMemoryUsage(); if (last_memory_usage_ + allocation_sample_bytes_ < malloced_current) { PrintMemoryJSON(malloced_current); last_memory_usage_ = malloced_current; } return memory; } void ReturnSegment(v8::internal::Segment* memory) override { AccountingAllocator::ReturnSegment(memory); size_t malloced_current = GetCurrentMemoryUsage(); if (malloced_current + allocation_sample_bytes_ < last_memory_usage_) { PrintMemoryJSON(malloced_current); last_memory_usage_ = malloced_current; } } void ZoneCreation(const Zone* zone) override { PrintZoneModificationSample(zone, "zonecreation"); nesting_deepth_++; } void ZoneDestruction(const Zone* zone) override { nesting_deepth_--; PrintZoneModificationSample(zone, "zonedestruction"); } private: void PrintZoneModificationSample(const Zone* zone, const char* type) { PrintF( "{" "\"type\": \"%s\", " "\"isolate\": \"%p\", " "\"time\": %f, " "\"ptr\": \"%p\", " "\"name\": \"%s\", " "\"size\": %zu," "\"nesting\": %zu}\n", type, reinterpret_cast<void*>(heap_->isolate()), heap_->isolate()->time_millis_since_init(), reinterpret_cast<const void*>(zone), zone->name(), zone->allocation_size(), nesting_deepth_.load()); } void PrintMemoryJSON(size_t malloced) { // Note: Neither isolate, nor heap is locked, so be careful with accesses // as the allocator is potentially used on a concurrent thread. double time = heap_->isolate()->time_millis_since_init(); PrintF( "{" "\"type\": \"zone\", " "\"isolate\": \"%p\", " "\"time\": %f, " "\"allocated\": %zu}\n", reinterpret_cast<void*>(heap_->isolate()), time, malloced); } Heap* heap_; std::atomic<size_t> last_memory_usage_{0}; std::atomic<size_t> nesting_deepth_{0}; size_t allocation_sample_bytes_; }; #ifdef DEBUG std::atomic<size_t> Isolate::non_disposed_isolates_; #endif // DEBUG // static Isolate* Isolate::New(IsolateAllocationMode mode) { // IsolateAllocator allocates the memory for the Isolate object according to // the given allocation mode. std::unique_ptr<IsolateAllocator> isolate_allocator = base::make_unique<IsolateAllocator>(mode); // Construct Isolate object in the allocated memory. void* isolate_ptr = isolate_allocator->isolate_memory(); Isolate* isolate = new (isolate_ptr) Isolate(std::move(isolate_allocator)); #if V8_TARGET_ARCH_64_BIT DCHECK_IMPLIES( mode == IsolateAllocationMode::kInV8Heap, IsAligned(isolate->isolate_root(), kPtrComprIsolateRootAlignment)); #endif #ifdef DEBUG non_disposed_isolates_++; #endif // DEBUG return isolate; } // static void Isolate::Delete(Isolate* isolate) { DCHECK_NOT_NULL(isolate); // Temporarily set this isolate as current so that various parts of // the isolate can access it in their destructors without having a // direct pointer. We don't use Enter/Exit here to avoid // initializing the thread data. PerIsolateThreadData* saved_data = isolate->CurrentPerIsolateThreadData(); DCHECK_EQ(true, isolate_key_created_.load(std::memory_order_relaxed)); Isolate* saved_isolate = reinterpret_cast<Isolate*>( base::Thread::GetThreadLocal(isolate->isolate_key_)); SetIsolateThreadLocals(isolate, nullptr); isolate->Deinit(); #ifdef DEBUG non_disposed_isolates_--; #endif // DEBUG // Take ownership of the IsolateAllocator to ensure the Isolate memory will // be available during Isolate descructor call. std::unique_ptr<IsolateAllocator> isolate_allocator = std::move(isolate->isolate_allocator_); isolate->~Isolate(); // Now free the memory owned by the allocator. isolate_allocator.reset(); // Restore the previous current isolate. SetIsolateThreadLocals(saved_isolate, saved_data); } void Isolate::SetUpFromReadOnlyHeap(ReadOnlyHeap* ro_heap) { DCHECK_NOT_NULL(ro_heap); DCHECK_IMPLIES(read_only_heap_ != nullptr, read_only_heap_ == ro_heap); read_only_heap_ = ro_heap; heap_.SetUpFromReadOnlyHeap(ro_heap); } v8::PageAllocator* Isolate::page_allocator() { return isolate_allocator_->page_allocator(); } Isolate::Isolate(std::unique_ptr<i::IsolateAllocator> isolate_allocator) : isolate_data_(this), isolate_allocator_(std::move(isolate_allocator)), id_(isolate_counter.fetch_add(1, std::memory_order_relaxed)), allocator_(FLAG_trace_zone_stats ? new VerboseAccountingAllocator(&heap_, 256 * KB) : new AccountingAllocator()), builtins_(this), rail_mode_(PERFORMANCE_ANIMATION), code_event_dispatcher_(new CodeEventDispatcher()), cancelable_task_manager_(new CancelableTaskManager()) { TRACE_ISOLATE(constructor); CheckIsolateLayout(); // ThreadManager is initialized early to support locking an isolate // before it is entered. thread_manager_ = new ThreadManager(this); handle_scope_data_.Initialize(); #define ISOLATE_INIT_EXECUTE(type, name, initial_value) \ name##_ = (initial_value); ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE) #undef ISOLATE_INIT_EXECUTE #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \ memset(name##_, 0, sizeof(type) * length); ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE) #undef ISOLATE_INIT_ARRAY_EXECUTE InitializeLoggingAndCounters(); debug_ = new Debug(this); InitializeDefaultEmbeddedBlob(); MicrotaskQueue::SetUpDefaultMicrotaskQueue(this); } void Isolate::CheckIsolateLayout() { CHECK_EQ(OFFSET_OF(Isolate, isolate_data_), 0); CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, isolate_data_.embedder_data_)), Internals::kIsolateEmbedderDataOffset); CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, isolate_data_.roots_)), Internals::kIsolateRootsOffset); CHECK_EQ(Internals::kExternalMemoryOffset % 8, 0); CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, isolate_data_.external_memory_)), Internals::kExternalMemoryOffset); CHECK_EQ(Internals::kExternalMemoryLimitOffset % 8, 0); CHECK_EQ(static_cast<int>( OFFSET_OF(Isolate, isolate_data_.external_memory_limit_)), Internals::kExternalMemoryLimitOffset); CHECK_EQ(Internals::kExternalMemoryAtLastMarkCompactOffset % 8, 0); CHECK_EQ(static_cast<int>(OFFSET_OF( Isolate, isolate_data_.external_memory_at_last_mark_compact_)), Internals::kExternalMemoryAtLastMarkCompactOffset); } void Isolate::ClearSerializerData() { delete external_reference_map_; external_reference_map_ = nullptr; } bool Isolate::LogObjectRelocation() { return FLAG_verify_predictable || logger()->is_logging() || is_profiling() || heap()->isolate()->logger()->is_listening_to_code_events() || (heap_profiler() != nullptr && heap_profiler()->is_tracking_object_moves()) || heap()->has_heap_object_allocation_tracker(); } void Isolate::Deinit() { TRACE_ISOLATE(deinit); tracing_cpu_profiler_.reset(); if (FLAG_stress_sampling_allocation_profiler > 0) { heap_profiler()->StopSamplingHeapProfiler(); } #if defined(V8_OS_WIN64) if (win64_unwindinfo::CanRegisterUnwindInfoForNonABICompliantCodeRange() && heap()->memory_allocator()) { const base::AddressRegion& code_range = heap()->memory_allocator()->code_range(); void* start = reinterpret_cast<void*>(code_range.begin()); win64_unwindinfo::UnregisterNonABICompliantCodeRange(start); } #endif // V8_OS_WIN64 debug()->Unload(); wasm_engine()->DeleteCompileJobsOnIsolate(this); if (concurrent_recompilation_enabled()) { optimizing_compile_dispatcher_->Stop(); delete optimizing_compile_dispatcher_; optimizing_compile_dispatcher_ = nullptr; } wasm_engine()->memory_tracker()->DeleteSharedMemoryObjectsOnIsolate(this); heap_.mark_compact_collector()->EnsureSweepingCompleted(); heap_.memory_allocator()->unmapper()->EnsureUnmappingCompleted(); DumpAndResetStats(); if (FLAG_print_deopt_stress) { PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_); } // We must stop the logger before we tear down other components. sampler::Sampler* sampler = logger_->sampler(); if (sampler && sampler->IsActive()) sampler->Stop(); FreeThreadResources(); logger_->StopProfilerThread(); // We start with the heap tear down so that releasing managed objects does // not cause a GC. heap_.StartTearDown(); ReleaseSharedPtrs(); delete deoptimizer_data_; deoptimizer_data_ = nullptr; builtins_.TearDown(); bootstrapper_->TearDown(); if (runtime_profiler_ != nullptr) { delete runtime_profiler_; runtime_profiler_ = nullptr; } delete heap_profiler_; heap_profiler_ = nullptr; compiler_dispatcher_->AbortAll(); delete compiler_dispatcher_; compiler_dispatcher_ = nullptr; // This stops cancelable tasks (i.e. concurrent marking tasks) cancelable_task_manager()->CancelAndWait(); heap_.TearDown(); logger_->TearDown(); if (wasm_engine_) { wasm_engine_->RemoveIsolate(this); wasm_engine_.reset(); } TearDownEmbeddedBlob(); delete interpreter_; interpreter_ = nullptr; delete ast_string_constants_; ast_string_constants_ = nullptr; code_event_dispatcher_.reset(); delete root_index_map_; root_index_map_ = nullptr; delete compiler_zone_; compiler_zone_ = nullptr; compiler_cache_ = nullptr; ClearSerializerData(); { base::MutexGuard lock_guard(&thread_data_table_mutex_); thread_data_table_.RemoveAllThreads(); } } void Isolate::SetIsolateThreadLocals(Isolate* isolate, PerIsolateThreadData* data) { base::Thread::SetThreadLocal(isolate_key_, isolate); base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data); } Isolate::~Isolate() { TRACE_ISOLATE(destructor); // The entry stack must be empty when we get here. DCHECK(entry_stack_ == nullptr || entry_stack_->previous_item == nullptr); delete entry_stack_; entry_stack_ = nullptr; delete date_cache_; date_cache_ = nullptr; delete regexp_stack_; regexp_stack_ = nullptr; delete descriptor_lookup_cache_; descriptor_lookup_cache_ = nullptr; delete load_stub_cache_; load_stub_cache_ = nullptr; delete store_stub_cache_; store_stub_cache_ = nullptr; delete materialized_object_store_; materialized_object_store_ = nullptr; delete logger_; logger_ = nullptr; delete handle_scope_implementer_; handle_scope_implementer_ = nullptr; delete code_tracer(); set_code_tracer(nullptr); delete compilation_cache_; compilation_cache_ = nullptr; delete bootstrapper_; bootstrapper_ = nullptr; delete inner_pointer_to_code_cache_; inner_pointer_to_code_cache_ = nullptr; delete thread_manager_; thread_manager_ = nullptr; delete global_handles_; global_handles_ = nullptr; delete eternal_handles_; eternal_handles_ = nullptr; delete string_stream_debug_object_cache_; string_stream_debug_object_cache_ = nullptr; delete random_number_generator_; random_number_generator_ = nullptr; delete fuzzer_rng_; fuzzer_rng_ = nullptr; delete debug_; debug_ = nullptr; delete cancelable_task_manager_; cancelable_task_manager_ = nullptr; delete allocator_; allocator_ = nullptr; // Assert that |default_microtask_queue_| is the last MicrotaskQueue instance. DCHECK_IMPLIES(default_microtask_queue_, default_microtask_queue_ == default_microtask_queue_->next()); delete default_microtask_queue_; default_microtask_queue_ = nullptr; } void Isolate::InitializeThreadLocal() { thread_local_top()->Initialize(this); } void Isolate::SetTerminationOnExternalTryCatch() { if (try_catch_handler() == nullptr) return; try_catch_handler()->can_continue_ = false; try_catch_handler()->has_terminated_ = true; try_catch_handler()->exception_ = reinterpret_cast<void*>(ReadOnlyRoots(heap()).null_value().ptr()); } bool Isolate::PropagatePendingExceptionToExternalTryCatch() { Object exception = pending_exception(); if (IsJavaScriptHandlerOnTop(exception)) { thread_local_top()->external_caught_exception_ = false; return false; } if (!IsExternalHandlerOnTop(exception)) { thread_local_top()->external_caught_exception_ = false; return true; } thread_local_top()->external_caught_exception_ = true; if (!is_catchable_by_javascript(exception)) { SetTerminationOnExternalTryCatch(); } else { v8::TryCatch* handler = try_catch_handler(); DCHECK(thread_local_top()->pending_message_obj_.IsJSMessageObject() || thread_local_top()->pending_message_obj_.IsTheHole(this)); handler->can_continue_ = true; handler->has_terminated_ = false; handler->exception_ = reinterpret_cast<void*>(pending_exception().ptr()); // Propagate to the external try-catch only if we got an actual message. if (thread_local_top()->pending_message_obj_.IsTheHole(this)) return true; handler->message_obj_ = reinterpret_cast<void*>(thread_local_top()->pending_message_obj_.ptr()); } return true; } bool Isolate::InitializeCounters() { if (async_counters_) return false; async_counters_ = std::make_shared<Counters>(this); return true; } void Isolate::InitializeLoggingAndCounters() { if (logger_ == nullptr) { logger_ = new Logger(this); } InitializeCounters(); } namespace { void CreateOffHeapTrampolines(Isolate* isolate) { DCHECK_NOT_NULL(isolate->embedded_blob()); DCHECK_NE(0, isolate->embedded_blob_size()); HandleScope scope(isolate); Builtins* builtins = isolate->builtins(); EmbeddedData d = EmbeddedData::FromBlob(); for (int i = 0; i < Builtins::builtin_count; i++) { if (!Builtins::IsIsolateIndependent(i)) continue; Address instruction_start = d.InstructionStartOfBuiltin(i); Handle<Code> trampoline = isolate->factory()->NewOffHeapTrampolineFor( builtins->builtin_handle(i), instruction_start); // From this point onwards, the old builtin code object is unreachable and // will be collected by the next GC. builtins->set_builtin(i, *trampoline); } } #ifdef DEBUG bool IsolateIsCompatibleWithEmbeddedBlob(Isolate* isolate) { if (!FLAG_embedded_builtins) return true; EmbeddedData d = EmbeddedData::FromBlob(isolate); return (d.IsolateHash() == isolate->HashIsolateForEmbeddedBlob()); } #endif // DEBUG } // namespace void Isolate::InitializeDefaultEmbeddedBlob() { const uint8_t* blob = DefaultEmbeddedBlob(); uint32_t size = DefaultEmbeddedBlobSize(); #ifdef V8_MULTI_SNAPSHOTS if (!FLAG_untrusted_code_mitigations) { blob = TrustedEmbeddedBlob(); size = TrustedEmbeddedBlobSize(); } #endif if (StickyEmbeddedBlob() != nullptr) { base::MutexGuard guard(current_embedded_blob_refcount_mutex_.Pointer()); // Check again now that we hold the lock. if (StickyEmbeddedBlob() != nullptr) { blob = StickyEmbeddedBlob(); size = StickyEmbeddedBlobSize(); current_embedded_blob_refs_++; } } if (blob == nullptr) { CHECK_EQ(0, size); } else { SetEmbeddedBlob(blob, size); } } void Isolate::CreateAndSetEmbeddedBlob() { base::MutexGuard guard(current_embedded_blob_refcount_mutex_.Pointer()); PrepareBuiltinSourcePositionMap(); // If a sticky blob has been set, we reuse it. if (StickyEmbeddedBlob() != nullptr) { CHECK_EQ(embedded_blob(), StickyEmbeddedBlob()); CHECK_EQ(CurrentEmbeddedBlob(), StickyEmbeddedBlob()); } else { // Create and set a new embedded blob. uint8_t* data; uint32_t size; InstructionStream::CreateOffHeapInstructionStream(this, &data, &size); CHECK_EQ(0, current_embedded_blob_refs_); const uint8_t* const_data = const_cast<const uint8_t*>(data); SetEmbeddedBlob(const_data, size); current_embedded_blob_refs_++; SetStickyEmbeddedBlob(const_data, size); } CreateOffHeapTrampolines(this); } void Isolate::TearDownEmbeddedBlob() { // Nothing to do in case the blob is embedded into the binary or unset. if (StickyEmbeddedBlob() == nullptr) return; CHECK_EQ(embedded_blob(), StickyEmbeddedBlob()); CHECK_EQ(CurrentEmbeddedBlob(), StickyEmbeddedBlob()); base::MutexGuard guard(current_embedded_blob_refcount_mutex_.Pointer()); current_embedded_blob_refs_--; if (current_embedded_blob_refs_ == 0 && enable_embedded_blob_refcounting_) { // We own the embedded blob and are the last holder. Free it. InstructionStream::FreeOffHeapInstructionStream( const_cast<uint8_t*>(embedded_blob()), embedded_blob_size()); ClearEmbeddedBlob(); } } bool Isolate::InitWithoutSnapshot() { return Init(nullptr, nullptr); } bool Isolate::InitWithSnapshot(ReadOnlyDeserializer* read_only_deserializer, StartupDeserializer* startup_deserializer) { DCHECK_NOT_NULL(read_only_deserializer); DCHECK_NOT_NULL(startup_deserializer); return Init(read_only_deserializer, startup_deserializer); } static std::string AddressToString(uintptr_t address) { std::stringstream stream_address; stream_address << "0x" << std::hex << address; return stream_address.str(); } void Isolate::AddCrashKeysForIsolateAndHeapPointers() { DCHECK_NOT_NULL(add_crash_key_callback_); const uintptr_t isolate_address = reinterpret_cast<uintptr_t>(this); add_crash_key_callback_(v8::CrashKeyId::kIsolateAddress, AddressToString(isolate_address)); const uintptr_t ro_space_firstpage_address = reinterpret_cast<uintptr_t>(heap()->read_only_space()->first_page()); add_crash_key_callback_(v8::CrashKeyId::kReadonlySpaceFirstPageAddress, AddressToString(ro_space_firstpage_address)); const uintptr_t map_space_firstpage_address = reinterpret_cast<uintptr_t>(heap()->map_space()->first_page()); add_crash_key_callback_(v8::CrashKeyId::kMapSpaceFirstPageAddress, AddressToString(map_space_firstpage_address)); const uintptr_t code_space_firstpage_address = reinterpret_cast<uintptr_t>(heap()->code_space()->first_page()); add_crash_key_callback_(v8::CrashKeyId::kCodeSpaceFirstPageAddress, AddressToString(code_space_firstpage_address)); } bool Isolate::Init(ReadOnlyDeserializer* read_only_deserializer, StartupDeserializer* startup_deserializer) { TRACE_ISOLATE(init); const bool create_heap_objects = (read_only_deserializer == nullptr); // We either have both or neither. DCHECK_EQ(create_heap_objects, startup_deserializer == nullptr); base::ElapsedTimer timer; if (create_heap_objects && FLAG_profile_deserialization) timer.Start(); time_millis_at_init_ = heap_.MonotonicallyIncreasingTimeInMs(); stress_deopt_count_ = FLAG_deopt_every_n_times; force_slow_path_ = FLAG_force_slow_path; has_fatal_error_ = false; // The initialization process does not handle memory exhaustion. AlwaysAllocateScope always_allocate(this); // Safe after setting Heap::isolate_, and initializing StackGuard heap_.SetStackLimits(); #define ASSIGN_ELEMENT(CamelName, hacker_name) \ isolate_addresses_[IsolateAddressId::k##CamelName##Address] = \ reinterpret_cast<Address>(hacker_name##_address()); FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT) #undef ASSIGN_ELEMENT compilation_cache_ = new CompilationCache(this); descriptor_lookup_cache_ = new DescriptorLookupCache(); inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this); global_handles_ = new GlobalHandles(this); eternal_handles_ = new EternalHandles(); bootstrapper_ = new Bootstrapper(this); handle_scope_implementer_ = new HandleScopeImplementer(this); load_stub_cache_ = new StubCache(this); store_stub_cache_ = new StubCache(this); materialized_object_store_ = new MaterializedObjectStore(this); regexp_stack_ = new RegExpStack(); regexp_stack_->isolate_ = this; date_cache_ = new DateCache(); heap_profiler_ = new HeapProfiler(heap()); interpreter_ = new interpreter::Interpreter(this); compiler_dispatcher_ = new CompilerDispatcher(this, V8::GetCurrentPlatform(), FLAG_stack_size); // Enable logging before setting up the heap logger_->SetUp(this); { // NOLINT // Ensure that the thread has a valid stack guard. The v8::Locker object // will ensure this too, but we don't have to use lockers if we are only // using one thread. ExecutionAccess lock(this); stack_guard()->InitThread(lock); } // SetUp the object heap. DCHECK(!heap_.HasBeenSetUp()); heap_.SetUp(); ReadOnlyHeap::SetUp(this, read_only_deserializer); heap_.SetUpSpaces(); isolate_data_.external_reference_table()->Init(this); // Setup the wasm engine. if (wasm_engine_ == nullptr) { SetWasmEngine(wasm::WasmEngine::GetWasmEngine()); } DCHECK_NOT_NULL(wasm_engine_); deoptimizer_data_ = new DeoptimizerData(heap()); if (setup_delegate_ == nullptr) { setup_delegate_ = new SetupIsolateDelegate(create_heap_objects); } if (!FLAG_inline_new) heap_.DisableInlineAllocation(); if (!setup_delegate_->SetupHeap(&heap_)) { V8::FatalProcessOutOfMemory(this, "heap object creation"); return false; } if (create_heap_objects) { // Terminate the partial snapshot cache so we can iterate. partial_snapshot_cache_.push_back(ReadOnlyRoots(this).undefined_value()); } InitializeThreadLocal(); // Profiler has to be created after ThreadLocal is initialized // because it makes use of interrupts. tracing_cpu_profiler_.reset(new TracingCpuProfilerImpl(this)); bootstrapper_->Initialize(create_heap_objects); if (FLAG_embedded_builtins && create_heap_objects) { builtins_constants_table_builder_ = new BuiltinsConstantsTableBuilder(this); } setup_delegate_->SetupBuiltins(this); #ifndef V8_TARGET_ARCH_ARM if (create_heap_objects) { // Store the interpreter entry trampoline on the root list. It is used as a // template for further copies that may later be created to help profile // interpreted code. // We currently cannot do this on arm due to RELATIVE_CODE_TARGETs // assuming that all possible Code targets may be addressed with an int24 // offset, effectively limiting code space size to 32MB. We can guarantee // this at mksnapshot-time, but not at runtime. // See also: https://crbug.com/v8/8713. heap_.SetInterpreterEntryTrampolineForProfiling( heap_.builtin(Builtins::kInterpreterEntryTrampoline)); } #endif if (FLAG_embedded_builtins && create_heap_objects) { builtins_constants_table_builder_->Finalize(); delete builtins_constants_table_builder_; builtins_constants_table_builder_ = nullptr; CreateAndSetEmbeddedBlob(); } // Initialize custom memcopy and memmove functions (must happen after // embedded blob setup). init_memcopy_functions(); if (FLAG_log_internal_timer_events) { set_event_logger(Logger::DefaultEventLoggerSentinel); } if (FLAG_trace_turbo || FLAG_trace_turbo_graph || FLAG_turbo_profiling) { PrintF("Concurrent recompilation has been disabled for tracing.\n"); } else if (OptimizingCompileDispatcher::Enabled()) { optimizing_compile_dispatcher_ = new OptimizingCompileDispatcher(this); } // Initialize runtime profiler before deserialization, because collections may // occur, clearing/updating ICs. runtime_profiler_ = new RuntimeProfiler(this); // If we are deserializing, read the state into the now-empty heap. { AlwaysAllocateScope always_allocate(this); CodeSpaceMemoryModificationScope modification_scope(&heap_); if (create_heap_objects) { heap_.read_only_space()->ClearStringPaddingIfNeeded(); read_only_heap_->OnCreateHeapObjectsComplete(this); } else { startup_deserializer->DeserializeInto(this); } load_stub_cache_->Initialize(); store_stub_cache_->Initialize(); interpreter_->Initialize(); heap_.NotifyDeserializationComplete(); } #ifdef VERIFY_HEAP if (FLAG_verify_heap) { heap_.VerifyReadOnlyHeap(); } #endif delete setup_delegate_; setup_delegate_ = nullptr; Builtins::UpdateBuiltinEntryTable(this); Builtins::EmitCodeCreateEvents(this); #ifdef DEBUG // Verify that the current heap state (usually deserialized from the snapshot) // is compatible with the embedded blob. If this DCHECK fails, we've likely // loaded a snapshot generated by a different V8 version or build-time // configuration. if (!IsolateIsCompatibleWithEmbeddedBlob(this)) { FATAL( "The Isolate is incompatible with the embedded blob. This is usually " "caused by incorrect usage of mksnapshot. When generating custom " "snapshots, embedders must ensure they pass the same flags as during " "the V8 build process (e.g.: --turbo-instruction-scheduling)."); } DCHECK_IMPLIES(FLAG_jitless, FLAG_embedded_builtins); #endif // DEBUG #ifndef V8_TARGET_ARCH_ARM // The IET for profiling should always be a full on-heap Code object. DCHECK(!Code::cast(heap_.interpreter_entry_trampoline_for_profiling()) .is_off_heap_trampoline()); #endif // V8_TARGET_ARCH_ARM if (FLAG_print_builtin_code) builtins()->PrintBuiltinCode(); if (FLAG_print_builtin_size) builtins()->PrintBuiltinSize(); // Finish initialization of ThreadLocal after deserialization is done. clear_pending_exception(); clear_pending_message(); clear_scheduled_exception(); // Deserializing may put strange things in the root array's copy of the // stack guard. heap_.SetStackLimits(); // Quiet the heap NaN if needed on target platform. if (!create_heap_objects) Assembler::QuietNaN(ReadOnlyRoots(this).nan_value()); if (FLAG_trace_turbo) { // Create an empty file. std::ofstream(GetTurboCfgFileName(this).c_str(), std::ios_base::trunc); } { HandleScope scope(this); ast_string_constants_ = new AstStringConstants(this, HashSeed(this)); } initialized_from_snapshot_ = !create_heap_objects; if (FLAG_stress_sampling_allocation_profiler > 0) { uint64_t sample_interval = FLAG_stress_sampling_allocation_profiler; int stack_depth = 128; v8::HeapProfiler::SamplingFlags sampling_flags = v8::HeapProfiler::SamplingFlags::kSamplingForceGC; heap_profiler()->StartSamplingHeapProfiler(sample_interval, stack_depth, sampling_flags); } #if defined(V8_OS_WIN64) if (win64_unwindinfo::CanRegisterUnwindInfoForNonABICompliantCodeRange()) { const base::AddressRegion& code_range = heap()->memory_allocator()->code_range(); void* start = reinterpret_cast<void*>(code_range.begin()); size_t size_in_bytes = code_range.size(); win64_unwindinfo::RegisterNonABICompliantCodeRange(start, size_in_bytes); } #endif // V8_OS_WIN64 if (create_heap_objects && FLAG_profile_deserialization) { double ms = timer.Elapsed().InMillisecondsF(); PrintF("[Initializing isolate from scratch took %0.3f ms]\n", ms); } return true; } void Isolate::Enter() { Isolate* current_isolate = nullptr; PerIsolateThreadData* current_data = CurrentPerIsolateThreadData(); if (current_data != nullptr) { current_isolate = current_data->isolate_; DCHECK_NOT_NULL(current_isolate); if (current_isolate == this) { DCHECK(Current() == this); DCHECK_NOT_NULL(entry_stack_); DCHECK(entry_stack_->previous_thread_data == nullptr || entry_stack_->previous_thread_data->thread_id() == ThreadId::Current()); // Same thread re-enters the isolate, no need to re-init anything. entry_stack_->entry_count++; return; } } PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread(); DCHECK_NOT_NULL(data); DCHECK(data->isolate_ == this); EntryStackItem* item = new EntryStackItem(current_data, current_isolate, entry_stack_); entry_stack_ = item; SetIsolateThreadLocals(this, data); // In case it's the first time some thread enters the isolate. set_thread_id(data->thread_id()); } void Isolate::Exit() { DCHECK_NOT_NULL(entry_stack_); DCHECK(entry_stack_->previous_thread_data == nullptr || entry_stack_->previous_thread_data->thread_id() == ThreadId::Current()); if (--entry_stack_->entry_count > 0) return; DCHECK_NOT_NULL(CurrentPerIsolateThreadData()); DCHECK(CurrentPerIsolateThreadData()->isolate_ == this); // Pop the stack. EntryStackItem* item = entry_stack_; entry_stack_ = item->previous_item; PerIsolateThreadData* previous_thread_data = item->previous_thread_data; Isolate* previous_isolate = item->previous_isolate; delete item; // Reinit the current thread for the isolate it was running before this one. SetIsolateThreadLocals(previous_isolate, previous_thread_data); } void Isolate::LinkDeferredHandles(DeferredHandles* deferred) { deferred->next_ = deferred_handles_head_; if (deferred_handles_head_ != nullptr) { deferred_handles_head_->previous_ = deferred; } deferred_handles_head_ = deferred; } void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) { #ifdef DEBUG // In debug mode assert that the linked list is well-formed. DeferredHandles* deferred_iterator = deferred; while (deferred_iterator->previous_ != nullptr) { deferred_iterator = deferred_iterator->previous_; } DCHECK(deferred_handles_head_ == deferred_iterator); #endif if (deferred_handles_head_ == deferred) { deferred_handles_head_ = deferred_handles_head_->next_; } if (deferred->next_ != nullptr) { deferred->next_->previous_ = deferred->previous_; } if (deferred->previous_ != nullptr) { deferred->previous_->next_ = deferred->next_; } } void Isolate::DumpAndResetStats() { if (turbo_statistics() != nullptr) { DCHECK(FLAG_turbo_stats || FLAG_turbo_stats_nvp); StdoutStream os; if (FLAG_turbo_stats) { AsPrintableStatistics ps = {*turbo_statistics(), false}; os << ps << std::endl; } if (FLAG_turbo_stats_nvp) { AsPrintableStatistics ps = {*turbo_statistics(), true}; os << ps << std::endl; } delete turbo_statistics_; turbo_statistics_ = nullptr; } // TODO(7424): There is no public API for the {WasmEngine} yet. So for now we // just dump and reset the engines statistics together with the Isolate. if (FLAG_turbo_stats_wasm) { wasm_engine()->DumpAndResetTurboStatistics(); } if (V8_UNLIKELY(TracingFlags::runtime_stats.load(std::memory_order_relaxed) == v8::tracing::TracingCategoryObserver::ENABLED_BY_NATIVE)) { counters()->worker_thread_runtime_call_stats()->AddToMainTable( counters()->runtime_call_stats()); counters()->runtime_call_stats()->Print(); counters()->runtime_call_stats()->Reset(); } } void Isolate::AbortConcurrentOptimization(BlockingBehavior behavior) { if (concurrent_recompilation_enabled()) { DisallowHeapAllocation no_recursive_gc; optimizing_compile_dispatcher()->Flush(behavior); } } CompilationStatistics* Isolate::GetTurboStatistics() { if (turbo_statistics() == nullptr) set_turbo_statistics(new CompilationStatistics()); return turbo_statistics(); } CodeTracer* Isolate::GetCodeTracer() { if (code_tracer() == nullptr) set_code_tracer(new CodeTracer(id())); return code_tracer(); } bool Isolate::use_optimizer() { return FLAG_opt && !serializer_enabled_ && CpuFeatures::SupportsOptimizer() && !is_precise_count_code_coverage(); } bool Isolate::NeedsDetailedOptimizedCodeLineInfo() const { return NeedsSourcePositionsForProfiling() || detailed_source_positions_for_profiling(); } bool Isolate::NeedsSourcePositionsForProfiling() const { return FLAG_trace_deopt || FLAG_trace_turbo || FLAG_trace_turbo_graph || FLAG_turbo_profiling || FLAG_perf_prof || is_profiling() || debug_->is_active() || logger_->is_logging() || FLAG_trace_maps; } void Isolate::SetFeedbackVectorsForProfilingTools(Object value) { DCHECK(value.IsUndefined(this) || value.IsArrayList()); heap()->set_feedback_vectors_for_profiling_tools(value); } void Isolate::MaybeInitializeVectorListFromHeap() { if (!heap()->feedback_vectors_for_profiling_tools().IsUndefined(this)) { // Already initialized, return early. DCHECK(heap()->feedback_vectors_for_profiling_tools().IsArrayList()); return; } // Collect existing feedback vectors. std::vector<Handle<FeedbackVector>> vectors; { HeapObjectIterator heap_iterator(heap()); for (HeapObject current_obj = heap_iterator.Next(); !current_obj.is_null(); current_obj = heap_iterator.Next()) { if (!current_obj.IsFeedbackVector()) continue; FeedbackVector vector = FeedbackVector::cast(current_obj); SharedFunctionInfo shared = vector.shared_function_info(); // No need to preserve the feedback vector for non-user-visible functions. if (!shared.IsSubjectToDebugging()) continue; vectors.emplace_back(vector, this); } } // Add collected feedback vectors to the root list lest we lose them to GC. Handle<ArrayList> list = ArrayList::New(this, static_cast<int>(vectors.size())); for (const auto& vector : vectors) list = ArrayList::Add(this, list, vector); SetFeedbackVectorsForProfilingTools(*list); } void Isolate::set_date_cache(DateCache* date_cache) { if (date_cache != date_cache_) { delete date_cache_; } date_cache_ = date_cache; } bool Isolate::IsArrayOrObjectOrStringPrototype(Object object) { Object context = heap()->native_contexts_list(); while (!context.IsUndefined(this)) { Context current_context = Context::cast(context); if (current_context.initial_object_prototype() == object || current_context.initial_array_prototype() == object || current_context.initial_string_prototype() == object) { return true; } context = current_context.next_context_link(); } return false; } bool Isolate::IsInAnyContext(Object object, uint32_t index) { DisallowHeapAllocation no_gc; Object context = heap()->native_contexts_list(); while (!context.IsUndefined(this)) { Context current_context = Context::cast(context); if (current_context.get(index) == object) { return true; } context = current_context.next_context_link(); } return false; } bool Isolate::IsNoElementsProtectorIntact(Context context) { PropertyCell no_elements_cell = heap()->no_elements_protector(); bool cell_reports_intact = no_elements_cell.value().IsSmi() && Smi::ToInt(no_elements_cell.value()) == kProtectorValid; #ifdef DEBUG Context native_context = context.native_context(); Map root_array_map = native_context.GetInitialJSArrayMap(GetInitialFastElementsKind()); JSObject initial_array_proto = JSObject::cast( native_context.get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX)); JSObject initial_object_proto = JSObject::cast( native_context.get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX)); JSObject initial_string_proto = JSObject::cast( native_context.get(Context::INITIAL_STRING_PROTOTYPE_INDEX)); if (root_array_map.is_null() || initial_array_proto == initial_object_proto) { // We are in the bootstrapping process, and the entire check sequence // shouldn't be performed. return cell_reports_intact; } // Check that the array prototype hasn't been altered WRT empty elements. if (root_array_map.prototype() != initial_array_proto) { DCHECK_EQ(false, cell_reports_intact); return cell_reports_intact; } FixedArrayBase elements = initial_array_proto.elements(); ReadOnlyRoots roots(heap()); if (elements != roots.empty_fixed_array() && elements != roots.empty_slow_element_dictionary()) { DCHECK_EQ(false, cell_reports_intact); return cell_reports_intact; } // Check that the Object.prototype hasn't been altered WRT empty elements. elements = initial_object_proto.elements(); if (elements != roots.empty_fixed_array() && elements != roots.empty_slow_element_dictionary()) { DCHECK_EQ(false, cell_reports_intact); return cell_reports_intact; } // Check that the Array.prototype has the Object.prototype as its // [[Prototype]] and that the Object.prototype has a null [[Prototype]]. PrototypeIterator iter(this, initial_array_proto); if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) { DCHECK_EQ(false, cell_reports_intact); DCHECK(!has_pending_exception()); return cell_reports_intact; } iter.Advance(); if (!iter.IsAtEnd()) { DCHECK_EQ(false, cell_reports_intact); DCHECK(!has_pending_exception()); return cell_reports_intact; } DCHECK(!has_pending_exception()); // Check that the String.prototype hasn't been altered WRT empty elements. elements = initial_string_proto.elements(); if (elements != roots.empty_fixed_array() && elements != roots.empty_slow_element_dictionary()) { DCHECK_EQ(false, cell_reports_intact); return cell_reports_intact; } // Check that the String.prototype has the Object.prototype // as its [[Prototype]] still. if (initial_string_proto.map().prototype() != initial_object_proto) { DCHECK_EQ(false, cell_reports_intact); return cell_reports_intact; } #endif return cell_reports_intact; } bool Isolate::IsNoElementsProtectorIntact() { return Isolate::IsNoElementsProtectorIntact(context()); } bool Isolate::IsIsConcatSpreadableLookupChainIntact() { Cell is_concat_spreadable_cell = heap()->is_concat_spreadable_protector(); bool is_is_concat_spreadable_set = Smi::ToInt(is_concat_spreadable_cell.value()) == kProtectorInvalid; #ifdef DEBUG Map root_array_map = raw_native_context().GetInitialJSArrayMap(GetInitialFastElementsKind()); if (root_array_map.is_null()) { // Ignore the value of is_concat_spreadable during bootstrap. return !is_is_concat_spreadable_set; } Handle<Object> array_prototype(array_function()->prototype(), this); Handle<Symbol> key = factory()->is_concat_spreadable_symbol(); Handle<Object> value; LookupIterator it(this, array_prototype, key); if (it.IsFound() && !JSReceiver::GetDataProperty(&it)->IsUndefined(this)) { // TODO(cbruni): Currently we do not revert if we unset the // @@isConcatSpreadable property on Array.prototype or Object.prototype // hence the reverse implication doesn't hold. DCHECK(is_is_concat_spreadable_set); return false; } #endif // DEBUG return !is_is_concat_spreadable_set; } bool Isolate::IsIsConcatSpreadableLookupChainIntact(JSReceiver receiver) { if (!IsIsConcatSpreadableLookupChainIntact()) return false; return !receiver.HasProxyInPrototype(this); } bool Isolate::IsPromiseHookProtectorIntact() { PropertyCell promise_hook_cell = heap()->promise_hook_protector(); bool is_promise_hook_protector_intact = Smi::ToInt(promise_hook_cell.value()) == kProtectorValid; DCHECK_IMPLIES(is_promise_hook_protector_intact, !promise_hook_or_async_event_delegate_); DCHECK_IMPLIES(is_promise_hook_protector_intact, !promise_hook_or_debug_is_active_or_async_event_delegate_); return is_promise_hook_protector_intact; } bool Isolate::IsPromiseResolveLookupChainIntact() { Cell promise_resolve_cell = heap()->promise_resolve_protector(); bool is_promise_resolve_protector_intact = Smi::ToInt(promise_resolve_cell.value()) == kProtectorValid; return is_promise_resolve_protector_intact; } bool Isolate::IsPromiseThenLookupChainIntact() { PropertyCell promise_then_cell = heap()->promise_then_protector(); bool is_promise_then_protector_intact = Smi::ToInt(promise_then_cell.value()) == kProtectorValid; return is_promise_then_protector_intact; } bool Isolate::IsPromiseThenLookupChainIntact(Handle<JSReceiver> receiver) { DisallowHeapAllocation no_gc; if (!receiver->IsJSPromise()) return false; if (!IsInAnyContext(receiver->map().prototype(), Context::PROMISE_PROTOTYPE_INDEX)) { return false; } return IsPromiseThenLookupChainIntact(); } void Isolate::UpdateNoElementsProtectorOnSetElement(Handle<JSObject> object) { DisallowHeapAllocation no_gc; if (!object->map().is_prototype_map()) return; if (!IsNoElementsProtectorIntact()) return; if (!IsArrayOrObjectOrStringPrototype(*object)) return; PropertyCell::SetValueWithInvalidation( this, "no_elements_protector", factory()->no_elements_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); } void Isolate::TraceProtectorInvalidation(const char* protector_name) { static constexpr char kInvalidateProtectorTracingCategory[] = "V8.InvalidateProtector"; static constexpr char kInvalidateProtectorTracingArg[] = "protector-name"; DCHECK(FLAG_trace_protector_invalidation); // TODO(jgruber): Remove the PrintF once tracing can output to stdout. i::PrintF("Invalidating protector cell %s in isolate %p\n", protector_name, this); TRACE_EVENT_INSTANT1("v8", kInvalidateProtectorTracingCategory, TRACE_EVENT_SCOPE_THREAD, kInvalidateProtectorTracingArg, protector_name); } void Isolate::InvalidateIsConcatSpreadableProtector() { DCHECK(factory()->is_concat_spreadable_protector()->value().IsSmi()); DCHECK(IsIsConcatSpreadableLookupChainIntact()); if (FLAG_trace_protector_invalidation) { TraceProtectorInvalidation("is_concat_spreadable_protector"); } factory()->is_concat_spreadable_protector()->set_value( Smi::FromInt(kProtectorInvalid)); DCHECK(!IsIsConcatSpreadableLookupChainIntact()); } void Isolate::InvalidateArrayConstructorProtector() { DCHECK(factory()->array_constructor_protector()->value().IsSmi()); DCHECK(IsArrayConstructorIntact()); if (FLAG_trace_protector_invalidation) { TraceProtectorInvalidation("array_constructor_protector"); } factory()->array_constructor_protector()->set_value( Smi::FromInt(kProtectorInvalid)); DCHECK(!IsArrayConstructorIntact()); } void Isolate::InvalidateArraySpeciesProtector() { DCHECK(factory()->array_species_protector()->value().IsSmi()); DCHECK(IsArraySpeciesLookupChainIntact()); PropertyCell::SetValueWithInvalidation( this, "array_species_protector", factory()->array_species_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsArraySpeciesLookupChainIntact()); } void Isolate::InvalidateTypedArraySpeciesProtector() { DCHECK(factory()->typed_array_species_protector()->value().IsSmi()); DCHECK(IsTypedArraySpeciesLookupChainIntact()); PropertyCell::SetValueWithInvalidation( this, "typed_array_species_protector", factory()->typed_array_species_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsTypedArraySpeciesLookupChainIntact()); } void Isolate::InvalidateRegExpSpeciesProtector( Handle<NativeContext> native_context) { DCHECK_EQ(*native_context, this->raw_native_context()); DCHECK(native_context->regexp_species_protector().value().IsSmi()); DCHECK(IsRegExpSpeciesLookupChainIntact(native_context)); Handle<PropertyCell> species_cell(native_context->regexp_species_protector(), this); PropertyCell::SetValueWithInvalidation( this, "regexp_species_protector", species_cell, handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsRegExpSpeciesLookupChainIntact(native_context)); } void Isolate::InvalidatePromiseSpeciesProtector() { DCHECK(factory()->promise_species_protector()->value().IsSmi()); DCHECK(IsPromiseSpeciesLookupChainIntact()); PropertyCell::SetValueWithInvalidation( this, "promise_species_protector", factory()->promise_species_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsPromiseSpeciesLookupChainIntact()); } void Isolate::InvalidateStringLengthOverflowProtector() { DCHECK(factory()->string_length_protector()->value().IsSmi()); DCHECK(IsStringLengthOverflowIntact()); if (FLAG_trace_protector_invalidation) { TraceProtectorInvalidation("string_length_protector"); } factory()->string_length_protector()->set_value( Smi::FromInt(kProtectorInvalid)); DCHECK(!IsStringLengthOverflowIntact()); } void Isolate::InvalidateArrayIteratorProtector() { DCHECK(factory()->array_iterator_protector()->value().IsSmi()); DCHECK(IsArrayIteratorLookupChainIntact()); PropertyCell::SetValueWithInvalidation( this, "array_iterator_protector", factory()->array_iterator_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsArrayIteratorLookupChainIntact()); } void Isolate::InvalidateMapIteratorProtector() { DCHECK(factory()->map_iterator_protector()->value().IsSmi()); DCHECK(IsMapIteratorLookupChainIntact()); PropertyCell::SetValueWithInvalidation( this, "map_iterator_protector", factory()->map_iterator_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsMapIteratorLookupChainIntact()); } void Isolate::InvalidateSetIteratorProtector() { DCHECK(factory()->set_iterator_protector()->value().IsSmi()); DCHECK(IsSetIteratorLookupChainIntact()); PropertyCell::SetValueWithInvalidation( this, "set_iterator_protector", factory()->set_iterator_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsSetIteratorLookupChainIntact()); } void Isolate::InvalidateStringIteratorProtector() { DCHECK(factory()->string_iterator_protector()->value().IsSmi()); DCHECK(IsStringIteratorLookupChainIntact()); PropertyCell::SetValueWithInvalidation( this, "string_iterator_protector", factory()->string_iterator_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsStringIteratorLookupChainIntact()); } void Isolate::InvalidateArrayBufferDetachingProtector() { DCHECK(factory()->array_buffer_detaching_protector()->value().IsSmi()); DCHECK(IsArrayBufferDetachingIntact()); PropertyCell::SetValueWithInvalidation( this, "array_buffer_detaching_protector", factory()->array_buffer_detaching_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsArrayBufferDetachingIntact()); } void Isolate::InvalidatePromiseHookProtector() { DCHECK(factory()->promise_hook_protector()->value().IsSmi()); DCHECK(IsPromiseHookProtectorIntact()); PropertyCell::SetValueWithInvalidation( this, "promise_hook_protector", factory()->promise_hook_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsPromiseHookProtectorIntact()); } void Isolate::InvalidatePromiseResolveProtector() { DCHECK(factory()->promise_resolve_protector()->value().IsSmi()); DCHECK(IsPromiseResolveLookupChainIntact()); if (FLAG_trace_protector_invalidation) { TraceProtectorInvalidation("promise_resolve_protector"); } factory()->promise_resolve_protector()->set_value( Smi::FromInt(kProtectorInvalid)); DCHECK(!IsPromiseResolveLookupChainIntact()); } void Isolate::InvalidatePromiseThenProtector() { DCHECK(factory()->promise_then_protector()->value().IsSmi()); DCHECK(IsPromiseThenLookupChainIntact()); PropertyCell::SetValueWithInvalidation( this, "promise_then_protector", factory()->promise_then_protector(), handle(Smi::FromInt(kProtectorInvalid), this)); DCHECK(!IsPromiseThenLookupChainIntact()); } bool Isolate::IsAnyInitialArrayPrototype(Handle<JSArray> array) { DisallowHeapAllocation no_gc; return IsInAnyContext(*array, Context::INITIAL_ARRAY_PROTOTYPE_INDEX); } static base::RandomNumberGenerator* ensure_rng_exists( base::RandomNumberGenerator** rng, int seed) { if (*rng == nullptr) { if (seed != 0) { *rng = new base::RandomNumberGenerator(seed); } else { *rng = new base::RandomNumberGenerator(); } } return *rng; } base::RandomNumberGenerator* Isolate::random_number_generator() { // TODO(bmeurer) Initialized lazily because it depends on flags; can // be fixed once the default isolate cleanup is done. return ensure_rng_exists(&random_number_generator_, FLAG_random_seed); } base::RandomNumberGenerator* Isolate::fuzzer_rng() { if (fuzzer_rng_ == nullptr) { int64_t seed = FLAG_fuzzer_random_seed; if (seed == 0) { seed = random_number_generator()->initial_seed(); } fuzzer_rng_ = new base::RandomNumberGenerator(seed); } return fuzzer_rng_; } int Isolate::GenerateIdentityHash(uint32_t mask) { int hash; int attempts = 0; do { hash = random_number_generator()->NextInt() & mask; } while (hash == 0 && attempts++ < 30); return hash != 0 ? hash : 1; } Code Isolate::FindCodeObject(Address a) { return heap()->GcSafeFindCodeForInnerPointer(a); } #ifdef DEBUG #define ISOLATE_FIELD_OFFSET(type, name, ignored) \ const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_); ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET) ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET) #undef ISOLATE_FIELD_OFFSET #endif Handle<Symbol> Isolate::SymbolFor(RootIndex dictionary_index, Handle<String> name, bool private_symbol) { Handle<String> key = factory()->InternalizeString(name); Handle<NameDictionary> dictionary = Handle<NameDictionary>::cast(root_handle(dictionary_index)); int entry = dictionary->FindEntry(this, key); Handle<Symbol> symbol; if (entry == NameDictionary::kNotFound) { symbol = private_symbol ? factory()->NewPrivateSymbol() : factory()->NewSymbol(); symbol->set_name(*key); dictionary = NameDictionary::Add(this, dictionary, key, symbol, PropertyDetails::Empty(), &entry); switch (dictionary_index) { case RootIndex::kPublicSymbolTable: symbol->set_is_in_public_symbol_table(true); heap()->set_public_symbol_table(*dictionary); break; case RootIndex::kApiSymbolTable: heap()->set_api_symbol_table(*dictionary); break; case RootIndex::kApiPrivateSymbolTable: heap()->set_api_private_symbol_table(*dictionary); break; default: UNREACHABLE(); } } else { symbol = Handle<Symbol>(Symbol::cast(dictionary->ValueAt(entry)), this); } return symbol; } void Isolate::AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback) { auto pos = std::find(before_call_entered_callbacks_.begin(), before_call_entered_callbacks_.end(), callback); if (pos != before_call_entered_callbacks_.end()) return; before_call_entered_callbacks_.push_back(callback); } void Isolate::RemoveBeforeCallEnteredCallback( BeforeCallEnteredCallback callback) { auto pos = std::find(before_call_entered_callbacks_.begin(), before_call_entered_callbacks_.end(), callback); if (pos == before_call_entered_callbacks_.end()) return; before_call_entered_callbacks_.erase(pos); } void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) { auto pos = std::find(call_completed_callbacks_.begin(), call_completed_callbacks_.end(), callback); if (pos != call_completed_callbacks_.end()) return; call_completed_callbacks_.push_back(callback); } void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) { auto pos = std::find(call_completed_callbacks_.begin(), call_completed_callbacks_.end(), callback); if (pos == call_completed_callbacks_.end()) return; call_completed_callbacks_.erase(pos); } void Isolate::FireCallCompletedCallback(MicrotaskQueue* microtask_queue) { if (!handle_scope_implementer()->CallDepthIsZero()) return; bool run_microtasks = microtask_queue && microtask_queue->size() && !microtask_queue->HasMicrotasksSuppressions() && microtask_queue->microtasks_policy() == v8::MicrotasksPolicy::kAuto; if (run_microtasks) { microtask_queue->RunMicrotasks(this); } if (call_completed_callbacks_.empty()) return; // Fire callbacks. Increase call depth to prevent recursive callbacks. v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this); v8::Isolate::SuppressMicrotaskExecutionScope suppress(isolate); std::vector<CallCompletedCallback> callbacks(call_completed_callbacks_); for (auto& callback : callbacks) { callback(reinterpret_cast<v8::Isolate*>(this)); } } void Isolate::PromiseHookStateUpdated() { bool promise_hook_or_async_event_delegate = promise_hook_ || async_event_delegate_; bool promise_hook_or_debug_is_active_or_async_event_delegate = promise_hook_or_async_event_delegate || debug()->is_active(); if (promise_hook_or_debug_is_active_or_async_event_delegate && IsPromiseHookProtectorIntact()) { HandleScope scope(this); InvalidatePromiseHookProtector(); } promise_hook_or_async_event_delegate_ = promise_hook_or_async_event_delegate; promise_hook_or_debug_is_active_or_async_event_delegate_ = promise_hook_or_debug_is_active_or_async_event_delegate; } namespace { MaybeHandle<JSPromise> NewRejectedPromise(Isolate* isolate, v8::Local<v8::Context> api_context, Handle<Object> exception) { v8::Local<v8::Promise::Resolver> resolver; ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE( isolate, resolver, v8::Promise::Resolver::New(api_context), MaybeHandle<JSPromise>()); RETURN_ON_SCHEDULED_EXCEPTION_VALUE( isolate, resolver->Reject(api_context, v8::Utils::ToLocal(exception)), MaybeHandle<JSPromise>()); v8::Local<v8::Promise> promise = resolver->GetPromise(); return v8::Utils::OpenHandle(*promise); } } // namespace MaybeHandle<JSPromise> Isolate::RunHostImportModuleDynamicallyCallback( Handle<Script> referrer, Handle<Object> specifier) { v8::Local<v8::Context> api_context = v8::Utils::ToLocal(Handle<Context>(native_context())); if (host_import_module_dynamically_callback_ == nullptr) { Handle<Object> exception = factory()->NewError(error_function(), MessageTemplate::kUnsupported); return NewRejectedPromise(this, api_context, exception); } Handle<String> specifier_str; MaybeHandle<String> maybe_specifier = Object::ToString(this, specifier); if (!maybe_specifier.ToHandle(&specifier_str)) { Handle<Object> exception(pending_exception(), this); clear_pending_exception(); return NewRejectedPromise(this, api_context, exception); } DCHECK(!has_pending_exception()); v8::Local<v8::Promise> promise; ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE( this, promise, host_import_module_dynamically_callback_( api_context, v8::Utils::ScriptOrModuleToLocal(referrer), v8::Utils::ToLocal(specifier_str)), MaybeHandle<JSPromise>()); return v8::Utils::OpenHandle(*promise); } void Isolate::ClearKeptObjects() { heap()->ClearKeptObjects(); } void Isolate::SetHostCleanupFinalizationGroupCallback( HostCleanupFinalizationGroupCallback callback) { host_cleanup_finalization_group_callback_ = callback; } void Isolate::RunHostCleanupFinalizationGroupCallback( Handle<JSFinalizationGroup> fg) { if (host_cleanup_finalization_group_callback_ != nullptr) { v8::Local<v8::Context> api_context = v8::Utils::ToLocal(handle(Context::cast(fg->native_context()), this)); host_cleanup_finalization_group_callback_(api_context, v8::Utils::ToLocal(fg)); } } void Isolate::SetHostImportModuleDynamicallyCallback( HostImportModuleDynamicallyCallback callback) { host_import_module_dynamically_callback_ = callback; } Handle<JSObject> Isolate::RunHostInitializeImportMetaObjectCallback( Handle<SourceTextModule> module) { Handle<Object> host_meta(module->import_meta(), this); if (host_meta->IsTheHole(this)) { host_meta = factory()->NewJSObjectWithNullProto(); if (host_initialize_import_meta_object_callback_ != nullptr) { v8::Local<v8::Context> api_context = v8::Utils::ToLocal(Handle<Context>(native_context())); host_initialize_import_meta_object_callback_( api_context, Utils::ToLocal(Handle<Module>::cast(module)), v8::Local<v8::Object>::Cast(v8::Utils::ToLocal(host_meta))); } module->set_import_meta(*host_meta); } return Handle<JSObject>::cast(host_meta); } void Isolate::SetHostInitializeImportMetaObjectCallback( HostInitializeImportMetaObjectCallback callback) { host_initialize_import_meta_object_callback_ = callback; } MaybeHandle<Object> Isolate::RunPrepareStackTraceCallback( Handle<Context> context, Handle<JSObject> error, Handle<JSArray> sites) { v8::Local<v8::Context> api_context = Utils::ToLocal(context); v8::Local<v8::Value> stack; ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE( this, stack, prepare_stack_trace_callback_(api_context, Utils::ToLocal(error), Utils::ToLocal(sites)), MaybeHandle<Object>()); return Utils::OpenHandle(*stack); } int Isolate::LookupOrAddExternallyCompiledFilename(const char* filename) { if (embedded_file_writer_ != nullptr) { return embedded_file_writer_->LookupOrAddExternallyCompiledFilename( filename); } return 0; } const char* Isolate::GetExternallyCompiledFilename(int index) const { if (embedded_file_writer_ != nullptr) { return embedded_file_writer_->GetExternallyCompiledFilename(index); } return ""; } int Isolate::GetExternallyCompiledFilenameCount() const { if (embedded_file_writer_ != nullptr) { return embedded_file_writer_->GetExternallyCompiledFilenameCount(); } return 0; } void Isolate::PrepareBuiltinSourcePositionMap() { if (embedded_file_writer_ != nullptr) { return embedded_file_writer_->PrepareBuiltinSourcePositionMap( this->builtins()); } } #if defined(V8_OS_WIN64) void Isolate::SetBuiltinUnwindData( int builtin_index, const win64_unwindinfo::BuiltinUnwindInfo& unwinding_info) { if (embedded_file_writer_ != nullptr) { embedded_file_writer_->SetBuiltinUnwindData(builtin_index, unwinding_info); } } #endif // V8_OS_WIN64 void Isolate::SetPrepareStackTraceCallback(PrepareStackTraceCallback callback) { prepare_stack_trace_callback_ = callback; } bool Isolate::HasPrepareStackTraceCallback() const { return prepare_stack_trace_callback_ != nullptr; } void Isolate::SetAddCrashKeyCallback(AddCrashKeyCallback callback) { add_crash_key_callback_ = callback; // Log the initial set of data. AddCrashKeysForIsolateAndHeapPointers(); } void Isolate::SetAtomicsWaitCallback(v8::Isolate::AtomicsWaitCallback callback, void* data) { atomics_wait_callback_ = callback; atomics_wait_callback_data_ = data; } void Isolate::RunAtomicsWaitCallback(v8::Isolate::AtomicsWaitEvent event, Handle<JSArrayBuffer> array_buffer, size_t offset_in_bytes, int64_t value, double timeout_in_ms, AtomicsWaitWakeHandle* stop_handle) { DCHECK(array_buffer->is_shared()); if (atomics_wait_callback_ == nullptr) return; HandleScope handle_scope(this); atomics_wait_callback_( event, v8::Utils::ToLocalShared(array_buffer), offset_in_bytes, value, timeout_in_ms, reinterpret_cast<v8::Isolate::AtomicsWaitWakeHandle*>(stop_handle), atomics_wait_callback_data_); } void Isolate::SetPromiseHook(PromiseHook hook) { promise_hook_ = hook; PromiseHookStateUpdated(); } void Isolate::RunPromiseHook(PromiseHookType type, Handle<JSPromise> promise, Handle<Object> parent) { RunPromiseHookForAsyncEventDelegate(type, promise); if (promise_hook_ == nullptr) return; promise_hook_(type, v8::Utils::PromiseToLocal(promise), v8::Utils::ToLocal(parent)); } void Isolate::RunPromiseHookForAsyncEventDelegate(PromiseHookType type, Handle<JSPromise> promise) { if (!async_event_delegate_) return; if (type == PromiseHookType::kResolve) return; if (type == PromiseHookType::kBefore) { if (!promise->async_task_id()) return; async_event_delegate_->AsyncEventOccurred(debug::kDebugWillHandle, promise->async_task_id(), false); } else if (type == PromiseHookType::kAfter) { if (!promise->async_task_id()) return; async_event_delegate_->AsyncEventOccurred(debug::kDebugDidHandle, promise->async_task_id(), false); } else { DCHECK(type == PromiseHookType::kInit); debug::DebugAsyncActionType type = debug::kDebugPromiseThen; bool last_frame_was_promise_builtin = false; JavaScriptFrameIterator it(this); while (!it.done()) { std::vector<Handle<SharedFunctionInfo>> infos; it.frame()->GetFunctions(&infos); for (size_t i = 1; i <= infos.size(); ++i) { Handle<SharedFunctionInfo> info = infos[infos.size() - i]; if (info->IsUserJavaScript()) { // We should not report PromiseThen and PromiseCatch which is called // indirectly, e.g. Promise.all calls Promise.then internally. if (last_frame_was_promise_builtin) { if (!promise->async_task_id()) { promise->set_async_task_id(++async_task_count_); } async_event_delegate_->AsyncEventOccurred( type, promise->async_task_id(), debug()->IsBlackboxed(info)); } return; } last_frame_was_promise_builtin = false; if (info->HasBuiltinId()) { if (info->builtin_id() == Builtins::kPromisePrototypeThen) { type = debug::kDebugPromiseThen; last_frame_was_promise_builtin = true; } else if (info->builtin_id() == Builtins::kPromisePrototypeCatch) { type = debug::kDebugPromiseCatch; last_frame_was_promise_builtin = true; } else if (info->builtin_id() == Builtins::kPromisePrototypeFinally) { type = debug::kDebugPromiseFinally; last_frame_was_promise_builtin = true; } } } it.Advance(); } } } void Isolate::OnAsyncFunctionStateChanged(Handle<JSPromise> promise, debug::DebugAsyncActionType event) { if (!async_event_delegate_) return; if (!promise->async_task_id()) { promise->set_async_task_id(++async_task_count_); } async_event_delegate_->AsyncEventOccurred(event, promise->async_task_id(), false); } void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) { promise_reject_callback_ = callback; } void Isolate::ReportPromiseReject(Handle<JSPromise> promise, Handle<Object> value, v8::PromiseRejectEvent event) { if (promise_reject_callback_ == nullptr) return; promise_reject_callback_(v8::PromiseRejectMessage( v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value))); } void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) { DCHECK(!use_counter_callback_); use_counter_callback_ = callback; } void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) { // The counter callback may cause the embedder to call into V8, which is not // generally possible during GC. if (heap_.gc_state() == Heap::NOT_IN_GC) { if (use_counter_callback_) { HandleScope handle_scope(this); use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature); } } else { heap_.IncrementDeferredCount(feature); } } // static std::string Isolate::GetTurboCfgFileName(Isolate* isolate) { if (FLAG_trace_turbo_cfg_file == nullptr) { std::ostringstream os; os << "turbo-" << base::OS::GetCurrentProcessId() << "-"; if (isolate != nullptr) { os << isolate->id(); } else { os << "any"; } os << ".cfg"; return os.str(); } else { return FLAG_trace_turbo_cfg_file; } } // Heap::detached_contexts tracks detached contexts as pairs // (number of GC since the context was detached, the context). void Isolate::AddDetachedContext(Handle<Context> context) { HandleScope scope(this); Handle<WeakArrayList> detached_contexts = factory()->detached_contexts(); detached_contexts = WeakArrayList::AddToEnd( this, detached_contexts, MaybeObjectHandle(Smi::kZero, this)); detached_contexts = WeakArrayList::AddToEnd(this, detached_contexts, MaybeObjectHandle::Weak(context)); heap()->set_detached_contexts(*detached_contexts); } void Isolate::CheckDetachedContextsAfterGC() { HandleScope scope(this); Handle<WeakArrayList> detached_contexts = factory()->detached_contexts(); int length = detached_contexts->length(); if (length == 0) return; int new_length = 0; for (int i = 0; i < length; i += 2) { int mark_sweeps = detached_contexts->Get(i).ToSmi().value(); MaybeObject context = detached_contexts->Get(i + 1); DCHECK(context->IsWeakOrCleared()); if (!context->IsCleared()) { detached_contexts->Set( new_length, MaybeObject::FromSmi(Smi::FromInt(mark_sweeps + 1))); detached_contexts->Set(new_length + 1, context); new_length += 2; } } detached_contexts->set_length(new_length); while (new_length < length) { detached_contexts->Set(new_length, MaybeObject::FromSmi(Smi::zero())); ++new_length; } if (FLAG_trace_detached_contexts) { PrintF("%d detached contexts are collected out of %d\n", length - new_length, length); for (int i = 0; i < new_length; i += 2) { int mark_sweeps = detached_contexts->Get(i).ToSmi().value(); MaybeObject context = detached_contexts->Get(i + 1); DCHECK(context->IsWeakOrCleared()); if (mark_sweeps > 3) { PrintF("detached context %p\n survived %d GCs (leak?)\n", reinterpret_cast<void*>(context.ptr()), mark_sweeps); } } } } double Isolate::LoadStartTimeMs() { base::MutexGuard guard(&rail_mutex_); return load_start_time_ms_; } void Isolate::SetRAILMode(RAILMode rail_mode) { RAILMode old_rail_mode = rail_mode_.load(); if (old_rail_mode != PERFORMANCE_LOAD && rail_mode == PERFORMANCE_LOAD) { base::MutexGuard guard(&rail_mutex_); load_start_time_ms_ = heap()->MonotonicallyIncreasingTimeInMs(); } rail_mode_.store(rail_mode); if (old_rail_mode == PERFORMANCE_LOAD && rail_mode != PERFORMANCE_LOAD) { heap()->incremental_marking()->incremental_marking_job()->ScheduleTask( heap()); } if (FLAG_trace_rail) { PrintIsolate(this, "RAIL mode: %s\n", RAILModeName(rail_mode)); } } void Isolate::IsolateInBackgroundNotification() { is_isolate_in_background_ = true; heap()->ActivateMemoryReducerIfNeeded(); } void Isolate::IsolateInForegroundNotification() { is_isolate_in_background_ = false; } void Isolate::PrintWithTimestamp(const char* format, ...) { base::OS::Print("[%d:%p] %8.0f ms: ", base::OS::GetCurrentProcessId(), static_cast<void*>(this), time_millis_since_init()); va_list arguments; va_start(arguments, format); base::OS::VPrint(format, arguments); va_end(arguments); } void Isolate::SetIdle(bool is_idle) { if (!is_profiling()) return; StateTag state = current_vm_state(); DCHECK(state == EXTERNAL || state == IDLE); if (js_entry_sp() != kNullAddress) return; if (is_idle) { set_current_vm_state(IDLE); } else if (state == IDLE) { set_current_vm_state(EXTERNAL); } } #ifdef V8_INTL_SUPPORT icu::UMemory* Isolate::get_cached_icu_object(ICUObjectCacheType cache_type) { return icu_object_cache_[cache_type].get(); } void Isolate::set_icu_object_in_cache(ICUObjectCacheType cache_type, std::shared_ptr<icu::UMemory> obj) { icu_object_cache_[cache_type] = obj; } void Isolate::clear_cached_icu_object(ICUObjectCacheType cache_type) { icu_object_cache_.erase(cache_type); } #endif // V8_INTL_SUPPORT bool StackLimitCheck::JsHasOverflowed(uintptr_t gap) const { StackGuard* stack_guard = isolate_->stack_guard(); #ifdef USE_SIMULATOR // The simulator uses a separate JS stack. Address jssp_address = Simulator::current(isolate_)->get_sp(); uintptr_t jssp = static_cast<uintptr_t>(jssp_address); if (jssp - gap < stack_guard->real_jslimit()) return true; #endif // USE_SIMULATOR return GetCurrentStackPosition() - gap < stack_guard->real_climit(); } SaveContext::SaveContext(Isolate* isolate) : isolate_(isolate) { if (!isolate->context().is_null()) { context_ = Handle<Context>(isolate->context(), isolate); } c_entry_fp_ = isolate->c_entry_fp(isolate->thread_local_top()); } SaveContext::~SaveContext() { isolate_->set_context(context_.is_null() ? Context() : *context_); } bool SaveContext::IsBelowFrame(StandardFrame* frame) { return (c_entry_fp_ == 0) || (c_entry_fp_ > frame->sp()); } SaveAndSwitchContext::SaveAndSwitchContext(Isolate* isolate, Context new_context) : SaveContext(isolate) { isolate->set_context(new_context); } #ifdef DEBUG AssertNoContextChange::AssertNoContextChange(Isolate* isolate) : isolate_(isolate), context_(isolate->context(), isolate) {} #endif // DEBUG #undef TRACE_ISOLATE } // namespace internal } // namespace v8
; A086729: Decimal expansion of Sum_{m=0..infinity} 1/(6*m+3)^2. ; Submitted by Jon Maiga ; 1,3,7,0,7,7,8,3,8,9,0,4,0,1,8,8,6,9,7,0,6,0,3,4,5,9,7,2,2,0,5,0,2,0,9,9,1,0,1,5,7,9,1,5,8,4,3,3,8,9,9,8,6,9,8,1,1,2,9,6,5,1,9,1,1,4,1,6,7,2,8,9,2,0,0,2,6,6,7,3,9,4,8,6,1,3,5,7,4,1,7,1,8,3,1,3,2,2,5 add $0,1 mov $2,1 mov $3,$0 mul $3,4 sub $3,1 lpb $3 mul $1,$3 mov $5,$3 mul $5,2 add $5,1 mul $2,$5 add $1,$2 div $1,$0 div $2,$0 sub $3,1 lpe pow $1,2 div $1,3 pow $2,2 mul $2,6 mov $4,10 pow $4,$0 div $2,$4 div $1,$2 mov $0,$1 mod $0,10
; A004689: Fibonacci numbers written in base 6. ; 0,1,1,2,3,5,12,21,33,54,131,225,400,1025,1425,2454,4323,11221,15544,31205,51153,122402,213555,340401,554400,1335201,2334001,4113202,10451203,15004405,25500012,44504421,114404433,203313254,322122131,525435425,1252002000,2221441425,3513443425,10135325254,14053213123,24232542421,42330155544,111003142405,153333342353,304340525202,502114311555,1210455241201,2113013553200,3323513234401,5440531232001,13204444510402,23045420142403,40254305053205,103344125240012,144042434333221,251431004013233 seq $0,45 ; Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. seq $0,7092 ; Numbers in base 6.
; A219085: Floor((n + 1/2)^3). ; 0,3,15,42,91,166,274,421,614,857,1157,1520,1953,2460,3048,3723,4492,5359,6331,7414,8615,9938,11390,12977,14706,16581,18609,20796,23149,25672,28372,31255,34328,37595,41063,44738,48627,52734,57066,61629,66430,71473,76765,82312,88121,94196,100544,107171,114084,121287,128787,136590,144703,153130,161878,170953,180362,190109,200201,210644,221445,232608,244140,256047,268336,281011,294079,307546,321419,335702,350402,365525,381078,397065,413493,430368,447697,465484,483736,502459,521660,541343,561515,582182,603351,625026,647214,669921,693154,716917,741217,766060,791453,817400,843908,870983,898632,926859,955671,985074 mul $0,2 add $0,1 pow $0,3 div $0,8
; A278816: Numbers that can be produced from their own digits by applying one or more of the eight operations {+, -, *, /, sqrt(), ^, !, concat11()}, with no operation used more than once, where "concat11()" means the operation of concatenating two single digits. ; 0,1,2,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84 mov $1,2 bin $1,$0 cmp $1,0 mul $1,7 add $1,$0
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11, c++14, c++17 // UNSUPPORTED: libcpp-no-concepts // template<class F, class... Args> // concept equivalence_relation; #include <concepts> // clang-format off template<class F, class T, class U> requires std::relation<F, T, U> constexpr bool check_subsumption() { return false; } template<class F, class T> requires std::equivalence_relation<F, T, T> && true constexpr bool check_subsumption() { return false; } template<class F, class T, class U> requires std::equivalence_relation<F, T, U> && true constexpr bool check_subsumption() { return true; } // clang-format on static_assert(check_subsumption<int (*)(int, int), int, int>()); static_assert(check_subsumption<int (*)(int, double), int, double>()); struct S1 {}; struct S2 {}; struct R { bool operator()(S1, S1) const; bool operator()(S1, S2) const; bool operator()(S2, S1) const; bool operator()(S2, S2) const; }; static_assert(check_subsumption<R, S1, S1>()); static_assert(check_subsumption<R, S1, S2>()); // clang-format off template<class F, class T, class U> requires std::relation<F, T, U> && true constexpr bool check_reverse_subsumption() { return true; } template<class F, class T, class U> requires std::equivalence_relation<F, T, U> constexpr bool check_no_subsumption() { return false; } // clang-format on static_assert(check_reverse_subsumption<int (*)(int, int), int, int>()); static_assert(check_reverse_subsumption<int (*)(int, double), int, double>()); static_assert(check_reverse_subsumption<R, S1, S1>()); static_assert(check_reverse_subsumption<R, S1, S2>()); int main(int, char**) { return 0; }
#include "hphp/runtime/ext/extension.h" #include "hphp/runtime/base/execution-context.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/tv-refcount.h" #include "hphp/runtime/vm/native-data.h" #include "hphp/runtime/ext/asio/asio-external-thread-event.h" #include <memory> #include <folly/Memory.h> #include <folly/Range.h> #include "mcrouter/McrouterClient.h" // @nolint #include "mcrouter/McrouterInstance.h" // @nolint #include "mcrouter/config.h" // @nolint #include "mcrouter/lib/McOperation.h" // @nolint #include "mcrouter/lib/McResUtil.h" // @nolint #include "mcrouter/lib/network/CarbonMessageList.h" // @nolint #include "mcrouter/lib/network/gen/Memcache.h" // @nolint #include "mcrouter/options.h" // @nolint namespace mc = facebook::memcache; namespace mcr = facebook::memcache::mcrouter; namespace HPHP { ///////////////////////////////////////////////////////////////////////////// struct MCRouterResult; const StaticString s_MCRouter("MCRouter"), s_MCRouterException("MCRouterException"), s_MCRouterOptionException("MCRouterOptionException"), s_option("option"), s_error("error"), s_value("value"), s_cas("cas"), s_flags("flags"); static Class* c_MCRouterException = nullptr; [[noreturn]] static void mcr_throwException(const std::string& message, mc_op_t op = mc_op_unknown, mc_res_t result = mc_res_unknown, const std::string& key = "") { if (!c_MCRouterException) { c_MCRouterException = Unit::lookupClass(s_MCRouterException.get()); assert(c_MCRouterException); } Object obj{c_MCRouterException}; tvDecRefGen( g_context->invokeFunc(c_MCRouterException->getCtor(), make_packed_array(message, (int64_t)op, (int64_t)result, key), obj.get()) ); throw_object(obj); } static Class* c_MCRouterOptionException = nullptr; [[noreturn]] static void mcr_throwOptionException( const std::vector<mc::McrouterOptionError>& errors) { if (!c_MCRouterOptionException) { c_MCRouterOptionException = Unit::lookupClass(s_MCRouterOptionException.get()); assert(c_MCRouterOptionException); } Array errorArray = Array::Create(); for (auto err : errors) { Array e; e.set(s_option, String(err.requestedName)); e.set(s_value, String(err.requestedValue)); e.set(s_error, String(err.errorMsg)); errorArray.append(e); } Object obj{c_MCRouterOptionException}; tvDecRefGen( g_context->invokeFunc( c_MCRouterOptionException->getCtor(), make_packed_array(errorArray), obj.get() ) ); throw_object(obj); } namespace { // Helpers for retrieving 'delta' field template <class Reply> uint64_t getDelta(const Reply& reply) { mcr_throwException( "getDelta expected arithmetic reply type", mc::McOperation<mc::OpFromType<Reply, mc::ReplyOpMapping>::value>::mc_op); } uint64_t getDelta(const mc::McIncrReply& reply) { return reply.delta(); } uint64_t getDelta(const mc::McDecrReply& reply) { return reply.delta(); } // Helpers for retrieving 'casToken' field template <class Reply> uint64_t getCasToken(const Reply& reply) { mcr_throwException( "getCasToken expected reply type McGetsReply", mc::McOperation<mc::OpFromType<Reply, mc::ReplyOpMapping>::value>::mc_op); } uint64_t getCasToken(const mc::McGetsReply& reply) { return reply.casToken(); } } // anonymous ///////////////////////////////////////////////////////////////////////////// struct MCRouter { MCRouter() = default; MCRouter& operator=(const MCRouter& str) = delete; template <class Request> void send(std::unique_ptr<const Request> request, MCRouterResult* res); void init(const Array& options, const String& pid) { mc::McrouterOptions opts; parseOptions(opts, options); mcr::McrouterInstance* router; if (pid.empty()) { m_transientRouter = mcr::McrouterInstance::create(opts.clone()); router = m_transientRouter.get(); } else { router = mcr::McrouterInstance::init(pid.toCppString(), opts); } if (!router) { mcr_throwException("Unable to initialize MCRouter instance"); } m_client = router->createClient(0 /* disable max_outstanding_requests */); if (!m_client) { mcr_throwException("Unable to initialize MCRouterClient instance"); } } template <class Request> Object issue(std::unique_ptr<const Request> request); private: std::shared_ptr<mcr::McrouterInstance> m_transientRouter; mcr::McrouterClient::Pointer m_client; void parseOptions(mc::McrouterOptions& opts, const Array& options) { #ifdef HPHP_OSS // Change defaults for these since they make assumptions about the system opts.asynclog_disable = true; opts.async_spool = ""; opts.stats_logging_interval = 0; opts.stats_root = ""; #endif std::unordered_map<std::string, std::string> dict; for (ArrayIter iter(options); iter; ++iter) { auto key = iter.first().toString().toCppString(); auto val = iter.second(); if (val.isBoolean()) { // false -> toString() == "" which will fail foll::to<bool> dict[key] = val.toBoolean() ? "1" : "0"; } else { dict[key] = val.toString().toCppString(); } } auto errors = opts.updateFromDict(dict); if (!errors.empty()) { mcr_throwOptionException(errors); } } }; struct MCRouterResult : AsioExternalThreadEvent { template <class Request> MCRouterResult(MCRouter* router, std::unique_ptr<const Request> request) { m_result.m_type = KindOfNull; router->send(std::move(request), this); } /** * Unserialize happens in the request thread where we can allocate smart * pointers. Use this opportunity to marshal the saved data from persistent * data structures into per-request data. */ void unserialize(Cell& c) override { if (!m_exception.empty()) { mcr_throwException(m_exception, m_op, m_replyCode, m_key); } if ((m_result.m_type == KindOfString) && !m_result.m_data.pstr) { // Deferred string init, see below m_result.m_data.pstr = StringData::Make( m_stringResult.c_str(), m_stringResult.size(), CopyString); m_stringResult.clear(); } else if ((m_result.m_type == KindOfArray) && !m_result.m_data.parr) { // Deferred string value and cas, see below Array ret = Array::Create(); ret.set(s_value, String(m_stringResult.c_str(), m_stringResult.size(), CopyString)); ret.set(s_cas, (int64_t)m_cas); ret.set(s_flags, (int64_t)m_flags); m_result.m_data.parr = ret.detach(); m_stringResult.clear(); } cellDup(m_result, c); } /* Callback invoked by libmcrouter on the receipt of a reply. * We're in the worker thread here, so we can't do any request * allocations or the memory manager will get confused. * We also can't store `msg' directly on the object as it'll be * freed after the result() method returns. * * Marshal the data we actually care about into fields on this * object, then remarshal them into smart_ptr structures during unserialize() */ template <class Request> void result(const Request& request, mc::ReplyT<Request>&& reply) { if (mc::isErrorResult(reply.result())) { setResultException(request, reply); } else { const auto mc_op = mc::McOperation< mc::OpFromType<Request, mc::RequestOpMapping>::value>::mc_op; switch (mc_op) { case mc_op_add: case mc_op_cas: case mc_op_set: case mc_op_replace: case mc_op_prepend: case mc_op_append: if (!mc::isStoredResult(reply.result())) { setResultException(request, reply); break; } break; case mc_op_flushall: if (reply.result() != mc_res_ok) { setResultException(request, reply); break; } break; case mc_op_delete: if (reply.result() != mc_res_deleted) { setResultException(request, reply); break; } break; case mc_op_incr: case mc_op_decr: if (!mc::isStoredResult(reply.result())) { setResultException(request, reply); break; } m_result.m_type = KindOfInt64; m_result.m_data.num = getDelta(reply); break; case mc_op_gets: m_cas = getCasToken(reply); /* fallthrough */ case mc_op_get: m_flags = reply.flags(); if (mc::isMissResult(reply.result())) { setResultException(request, reply); break; } /* fallthrough */ case mc_op_version: m_result.m_type = mc_op == mc_op_gets ? KindOfArray : KindOfString; m_result.m_data.pstr = nullptr; // We're in the wrong thread for making a StringData // so stash it in a std::string until we get to unserialize m_stringResult = carbon::valueRangeSlow(reply).str(); break; default: always_assert(false); } } markAsFinished(); } private: // Store the important parts of the exception in non-thread vars // to bubble up during unserialize template <class Request> void setResultException(const Request& request, const mc::ReplyT<Request>& reply) { m_op = mc::McOperation< mc::OpFromType<Request, mc::RequestOpMapping>::value>::mc_op; m_replyCode = reply.result(); m_exception = mc_op_to_string(m_op); m_exception += " failed with result "; m_exception += mc_res_to_string(m_replyCode); if (!reply.message().empty()) { m_exception += ": "; m_exception += reply.message(); } m_key = request.key().fullKey().str(); } Cell m_result; // Deferred string result and metadata std::string m_stringResult; uint64_t m_cas{0}; uint64_t m_flags{0}; // Deferred exception data mc_op_t m_op; mc_res_t m_replyCode; std::string m_exception, m_key; }; template <class Request> void MCRouter::send(std::unique_ptr<const Request> request, MCRouterResult* res) { auto requestPtr = request.get(); m_client->send( *requestPtr, [res, request = std::move(request)](const Request& req, mc::ReplyT<Request>&& reply) { if (reply.result() == mc_res_unknown) { // McrouterClient has signaled this request is cancelled res->cancel(); } else { res->result(req, std::move(reply)); } }); } template <class Request> Object MCRouter::issue(std::unique_ptr<const Request> request) { auto ev = new MCRouterResult(this, std::move(request)); try { return Object{ev->getWaitHandle()}; } catch (...) { assert(false); ev->abandon(); throw; } } ///////////////////////////////////////////////////////////////////////////// static void HHVM_METHOD(MCRouter, __construct, const Array& opts, const String& pid) { Native::data<MCRouter>(this_)->init(opts, pid); } template <class M> static Object mcr_str(ObjectData* this_, const String& key) { return Native::data<MCRouter>(this_)->issue( std::make_unique<const M>(folly::StringPiece(key.c_str(), key.size()))); } template <class Request> static Object mcr_set(ObjectData* this_, const String& key, const String& val, int64_t flags, int64_t expiration) { auto request = std::make_unique<Request>(folly::StringPiece(key.c_str(), key.size())); request->value() = folly::IOBuf( folly::IOBuf::COPY_BUFFER, folly::StringPiece(val.c_str(), val.size())); request->flags() = flags; request->exptime() = expiration; return Native::data<MCRouter>(this_)->issue<Request>(std::move(request)); } template <class Request> static Object mcr_aprepend(ObjectData* this_, const String& key, const String& val) { auto request = std::make_unique<Request>(folly::StringPiece(key.c_str(), key.size())); request->value() = folly::IOBuf( folly::IOBuf::COPY_BUFFER, folly::StringPiece(val.c_str(), val.size())); return Native::data<MCRouter>(this_)->issue<Request>(std::move(request)); } template <class Request> static Object mcr_str_delta(ObjectData* this_, const String& key, int64_t val) { auto request = std::make_unique<Request>(folly::StringPiece(key.c_str(), key.size())); request->delta() = val; return Native::data<MCRouter>(this_)->issue<Request>(std::move(request)); } static Object mcr_flushall(ObjectData* this_, int64_t val) { using Request = mc::McFlushAllRequest; auto request = std::make_unique<Request>("unused"); request->delay() = val; return Native::data<MCRouter>(this_)->issue<Request>(std::move(request)); } static Object mcr_version(ObjectData* this_) { return Native::data<MCRouter>(this_)->issue( std::make_unique<const mc::McVersionRequest>("unused")); } static Object HHVM_METHOD(MCRouter, cas, int64_t cas, const String& key, const String& val, int64_t expiration /*=0*/) { using Request = mc::McCasRequest; auto request = std::make_unique<Request>( folly::StringPiece(key.c_str(), key.size())); request->value() = folly::IOBuf( folly::IOBuf::COPY_BUFFER, folly::StringPiece(val.c_str(), val.size())); request->exptime() = expiration; request->casToken() = cas; return Native::data<MCRouter>(this_)->issue<Request>(std::move(request)); } ///////////////////////////////////////////////////////////////////////////// static String HHVM_STATIC_METHOD(MCRouter, getOpName, int64_t op) { auto name = mc_op_to_string((mc_op_t)op); if (!name) { std::string msg = "Unknown mc_op_* value: "; msg += op; mcr_throwException(msg, (mc_op_t)op); } return name; } static String HHVM_STATIC_METHOD(MCRouter, getResultName, int64_t res) { auto name = mc_res_to_string((mc_res_t)res); if (!name) { std::string msg = "Unknown mc_res_* value: "; msg += res; mcr_throwException(msg, mc_op_unknown, (mc_res_t)res); } return name; } ///////////////////////////////////////////////////////////////////////////// struct MCRouterExtension : Extension { MCRouterExtension(): Extension("mcrouter", "1.0.0") {} void moduleInit() override { HHVM_ME(MCRouter, __construct); HHVM_NAMED_ME(MCRouter, get, mcr_str<mc::McGetRequest>); HHVM_NAMED_ME(MCRouter, gets, mcr_str<mc::McGetsRequest>); HHVM_NAMED_ME(MCRouter, add, mcr_set<mc::McAddRequest>); HHVM_NAMED_ME(MCRouter, set, mcr_set<mc::McSetRequest>); HHVM_NAMED_ME(MCRouter, replace, mcr_set<mc::McReplaceRequest>); HHVM_NAMED_ME(MCRouter, prepend, mcr_aprepend<mc::McPrependRequest>); HHVM_NAMED_ME(MCRouter, append, mcr_aprepend<mc::McAppendRequest>); HHVM_NAMED_ME(MCRouter, incr, mcr_str_delta<mc::McIncrRequest>); HHVM_NAMED_ME(MCRouter, decr, mcr_str_delta<mc::McDecrRequest>); HHVM_NAMED_ME(MCRouter, del, mcr_str<mc::McDeleteRequest>); HHVM_NAMED_ME(MCRouter, flushAll, mcr_flushall); HHVM_NAMED_ME(MCRouter, version, mcr_version); HHVM_ME(MCRouter, cas); Native::registerNativeDataInfo<MCRouter>(s_MCRouter.get()); HHVM_STATIC_ME(MCRouter, getOpName); HHVM_STATIC_ME(MCRouter, getResultName); std::string opname("mc_op_"); for (int i = 0; i < mc_nops; ++i) { std::string name; name = opname + mc_op_to_string((mc_op_t)i); // mcrouter defines op names as foo-bar, // but PHP wants constants like foo_bar for (int j = opname.size(); j < name.size(); ++j) { if (name[j] == '-') { name[j] = '_'; } } Native::registerClassConstant<KindOfInt64>( s_MCRouter.get(), makeStaticString(name), i); } for (int i = 0; i < mc_nres; ++i) { Native::registerClassConstant<KindOfInt64>( s_MCRouter.get(), makeStaticString(mc_res_to_string((mc_res_t)i)), i); } loadSystemlib(); } } s_mcrouter_extension; ///////////////////////////////////////////////////////////////////////////// } // namespace HPHP
db 0 ; 282 DEX NO db 68, 65, 65, 80, 125, 115 ; hp atk def spd sat sdf db PSYCHIC, PSYCHIC ; type db 45 ; catch rate db 208 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F50 ; gender ratio db 100 ; unknown 1 db 20 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/hoenn/gardevoir/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_SLOW ; growth rate dn EGG_HUMANSHAPE, EGG_INDETERMINATE ; egg groups ; tm/hm learnset tmhm ; end
; ; Sharp OZ family port (graphics routines) ; Stefano Bodrato - Aug 2002 ; ; Page the graphics bank in/out - used by all gfx functions ; Simply does a swap... ; ; ; $Id: swapgfxbk.asm,v 1.3 2015/01/19 01:32:50 pauloscustodio Exp $ ; PUBLIC swapgfxbk PUBLIC swapgfxbk1 EXTERN ozactivepage ;.iysave defw 0 .swapgfxbk push bc ld bc,(ozactivepage) ld a,c out (3),a ld a,b out (4),a pop bc ; ld (iysave),iy ret .swapgfxbk1 ld a,7 out (3),a ld a,4 out (4),a ;; page in proper second page ; ld iy,(iysave) ret
// 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 "ui/compositor/callback_layer_animation_observer.h" #include <memory> #include "base/bind.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/compositor/layer_animation_sequence.h" #include "ui/compositor/test/layer_animation_observer_test_api.h" namespace ui { namespace test { // Simple class that tracks whether callbacks were invoked and when. class TestCallbacks { public: TestCallbacks(); TestCallbacks(const TestCallbacks&) = delete; TestCallbacks& operator=(const TestCallbacks&) = delete; virtual ~TestCallbacks(); void ResetCallbackObservations(); void set_should_delete_observer_on_animations_ended( bool should_delete_observer_on_animations_ended) { should_delete_observer_on_animations_ended_ = should_delete_observer_on_animations_ended; } bool animations_started() const { return animations_started_; } bool animations_ended() const { return animations_ended_; } virtual void AnimationsStarted(const CallbackLayerAnimationObserver&); virtual bool AnimationsEnded(const CallbackLayerAnimationObserver&); testing::AssertionResult StartedEpochIsBeforeEndedEpoch(); private: // Monotonic counter that tracks the next time snapshot. int next_epoch_ = 0; // Is true when AnimationsStarted() has been called. bool animations_started_ = false; // Relative time snapshot of when AnimationsStarted() was last called. int animations_started_epoch_ = -1; // Is true when AnimationsEnded() has been called. bool animations_ended_ = false; // Relative time snapshot of when AnimationsEnded() was last called. int animations_ended_epoch_ = -1; // The return value for AnimationsEnded(). bool should_delete_observer_on_animations_ended_ = false; }; TestCallbacks::TestCallbacks() {} TestCallbacks::~TestCallbacks() {} void TestCallbacks::ResetCallbackObservations() { next_epoch_ = 0; animations_started_ = false; animations_started_epoch_ = -1; animations_ended_ = false; animations_ended_epoch_ = -1; should_delete_observer_on_animations_ended_ = false; } void TestCallbacks::AnimationsStarted(const CallbackLayerAnimationObserver&) { animations_started_ = true; animations_started_epoch_ = next_epoch_++; } bool TestCallbacks::AnimationsEnded(const CallbackLayerAnimationObserver&) { animations_ended_ = true; animations_ended_epoch_ = next_epoch_++; return should_delete_observer_on_animations_ended_; } testing::AssertionResult TestCallbacks::StartedEpochIsBeforeEndedEpoch() { if (animations_started_epoch_ < animations_ended_epoch_) { return testing::AssertionSuccess(); } else { return testing::AssertionFailure() << "The started epoch=" << animations_started_epoch_ << " is NOT before the ended epoch=" << animations_ended_epoch_; } } // A child of TestCallbacks that can explicitly delete a // CallbackLayerAnimationObserver in the AnimationsStarted() or // AnimationsEnded() callback. class TestCallbacksThatExplicitlyDeletesObserver : public TestCallbacks { public: TestCallbacksThatExplicitlyDeletesObserver(); TestCallbacksThatExplicitlyDeletesObserver( const TestCallbacksThatExplicitlyDeletesObserver&) = delete; TestCallbacksThatExplicitlyDeletesObserver& operator=( const TestCallbacksThatExplicitlyDeletesObserver&) = delete; void set_observer_to_delete_in_animation_started( CallbackLayerAnimationObserver* observer) { observer_to_delete_in_animation_started_ = observer; } void set_observer_to_delete_in_animation_ended( CallbackLayerAnimationObserver* observer) { observer_to_delete_in_animation_ended_ = observer; } // TestCallbacks: void AnimationsStarted( const CallbackLayerAnimationObserver& observer) override; bool AnimationsEnded(const CallbackLayerAnimationObserver& observer) override; private: // The observer to delete, if non-NULL, in AnimationsStarted(). CallbackLayerAnimationObserver* observer_to_delete_in_animation_started_ = nullptr; // The observer to delete, if non-NULL, in AnimationsEnded(). CallbackLayerAnimationObserver* observer_to_delete_in_animation_ended_ = nullptr; }; TestCallbacksThatExplicitlyDeletesObserver:: TestCallbacksThatExplicitlyDeletesObserver() {} void TestCallbacksThatExplicitlyDeletesObserver::AnimationsStarted( const CallbackLayerAnimationObserver& observer) { if (observer_to_delete_in_animation_started_) delete observer_to_delete_in_animation_started_; TestCallbacks::AnimationsStarted(observer); } bool TestCallbacksThatExplicitlyDeletesObserver::AnimationsEnded( const CallbackLayerAnimationObserver& observer) { if (observer_to_delete_in_animation_ended_) delete observer_to_delete_in_animation_ended_; return TestCallbacks::AnimationsEnded(observer); } // A test specific CallbackLayerAnimationObserver that will set a bool when // destroyed. class TestCallbackLayerAnimationObserver : public CallbackLayerAnimationObserver { public: TestCallbackLayerAnimationObserver( AnimationStartedCallback animation_started_callback, AnimationEndedCallback animation_ended_callback, bool* destroyed); TestCallbackLayerAnimationObserver( AnimationStartedCallback animation_started_callback, bool should_delete_observer, bool* destroyed); TestCallbackLayerAnimationObserver( AnimationEndedCallback animation_ended_callback, bool* destroyed); TestCallbackLayerAnimationObserver( const TestCallbackLayerAnimationObserver&) = delete; TestCallbackLayerAnimationObserver& operator=( const TestCallbackLayerAnimationObserver&) = delete; ~TestCallbackLayerAnimationObserver() override; private: bool* destroyed_; }; TestCallbackLayerAnimationObserver::TestCallbackLayerAnimationObserver( AnimationStartedCallback animation_started_callback, AnimationEndedCallback animation_ended_callback, bool* destroyed) : CallbackLayerAnimationObserver(animation_started_callback, animation_ended_callback), destroyed_(destroyed) { if (destroyed_) (*destroyed_) = false; } TestCallbackLayerAnimationObserver::TestCallbackLayerAnimationObserver( AnimationStartedCallback animation_started_callback, bool should_delete_observer, bool* destroyed) : CallbackLayerAnimationObserver(animation_started_callback, should_delete_observer), destroyed_(destroyed) { if (destroyed_) (*destroyed_) = false; } TestCallbackLayerAnimationObserver::TestCallbackLayerAnimationObserver( AnimationEndedCallback animation_ended_callback, bool* destroyed) : CallbackLayerAnimationObserver(animation_ended_callback), destroyed_(destroyed) { if (destroyed_) (*destroyed_) = false; } TestCallbackLayerAnimationObserver::~TestCallbackLayerAnimationObserver() { if (destroyed_) (*destroyed_) = true; } class CallbackLayerAnimationObserverTest : public testing::Test { public: CallbackLayerAnimationObserverTest(); CallbackLayerAnimationObserverTest( const CallbackLayerAnimationObserverTest&) = delete; CallbackLayerAnimationObserverTest& operator=( const CallbackLayerAnimationObserverTest&) = delete; ~CallbackLayerAnimationObserverTest() override; protected: // Creates a LayerAnimationSequence. The lifetime of the sequence will be // managed by this. LayerAnimationSequence* CreateLayerAnimationSequence(); std::unique_ptr<TestCallbacks> callbacks_; std::unique_ptr<CallbackLayerAnimationObserver> observer_; std::unique_ptr<LayerAnimationObserverTestApi> observer_test_api_; // List of managaged sequences created by CreateLayerAnimationSequence() that // need to be destroyed. std::vector<std::unique_ptr<LayerAnimationSequence>> sequences_; }; CallbackLayerAnimationObserverTest::CallbackLayerAnimationObserverTest() : callbacks_(new TestCallbacks()), observer_(new CallbackLayerAnimationObserver( base::BindRepeating(&TestCallbacks::AnimationsStarted, base::Unretained(callbacks_.get())), base::BindRepeating(&TestCallbacks::AnimationsEnded, base::Unretained(callbacks_.get())))), observer_test_api_(new LayerAnimationObserverTestApi(observer_.get())) {} CallbackLayerAnimationObserverTest::~CallbackLayerAnimationObserverTest() { observer_test_api_.reset(); // The |observer_| will detach from all attached sequences upon destruction so // we need to explicitly delete the |observer_| before the |sequences_| and // |callbacks_|. observer_.reset(); } LayerAnimationSequence* CallbackLayerAnimationObserverTest::CreateLayerAnimationSequence() { sequences_.emplace_back(new LayerAnimationSequence); return sequences_.back().get(); } class CallbackLayerAnimationObserverTestOverwrite : public CallbackLayerAnimationObserverTest { public: CallbackLayerAnimationObserverTestOverwrite(); CallbackLayerAnimationObserverTestOverwrite( const CallbackLayerAnimationObserverTestOverwrite&) = delete; CallbackLayerAnimationObserverTestOverwrite& operator=( const CallbackLayerAnimationObserverTestOverwrite&) = delete; protected: void AnimationStarted(const CallbackLayerAnimationObserver& observer); std::unique_ptr<CallbackLayerAnimationObserver> CreateAnimationObserver(); }; CallbackLayerAnimationObserverTestOverwrite:: CallbackLayerAnimationObserverTestOverwrite() { observer_ = CreateAnimationObserver(); observer_test_api_ = std::make_unique<LayerAnimationObserverTestApi>(observer_.get()); } void CallbackLayerAnimationObserverTestOverwrite::AnimationStarted( const CallbackLayerAnimationObserver& observer) { observer_->OnLayerAnimationAborted(sequences_.front().get()); observer_test_api_.reset(); // Replace the current observer with a new observer so that the destructor // gets called on the current observer. observer_ = CreateAnimationObserver(); } std::unique_ptr<CallbackLayerAnimationObserver> CallbackLayerAnimationObserverTestOverwrite::CreateAnimationObserver() { return std::make_unique<CallbackLayerAnimationObserver>( base::BindRepeating( &CallbackLayerAnimationObserverTestOverwrite::AnimationStarted, base::Unretained(this)), base::BindRepeating([](const CallbackLayerAnimationObserver& observer) { return false; })); } TEST(CallbackLayerAnimationObserverDestructionTest, VerifyFalseAutoDelete) { TestCallbacks callbacks; callbacks.set_should_delete_observer_on_animations_ended(false); bool is_destroyed = false; TestCallbackLayerAnimationObserver* observer = new TestCallbackLayerAnimationObserver( base::BindRepeating(&TestCallbacks::AnimationsStarted, base::Unretained(&callbacks)), false, &is_destroyed); observer->SetActive(); EXPECT_FALSE(is_destroyed); delete observer; } TEST(CallbackLayerAnimationObserverDestructionTest, VerifyTrueAutoDelete) { TestCallbacks callbacks; callbacks.set_should_delete_observer_on_animations_ended(false); bool is_destroyed = false; TestCallbackLayerAnimationObserver* observer = new TestCallbackLayerAnimationObserver( base::BindRepeating(&TestCallbacks::AnimationsStarted, base::Unretained(&callbacks)), true, &is_destroyed); observer->SetActive(); EXPECT_TRUE(is_destroyed); } TEST(CallbackLayerAnimationObserverDestructionTest, AnimationEndedReturnsFalse) { TestCallbacks callbacks; callbacks.set_should_delete_observer_on_animations_ended(false); bool is_destroyed = false; TestCallbackLayerAnimationObserver* observer = new TestCallbackLayerAnimationObserver( base::BindRepeating(&TestCallbacks::AnimationsStarted, base::Unretained(&callbacks)), base::BindRepeating(&TestCallbacks::AnimationsEnded, base::Unretained(&callbacks)), &is_destroyed); observer->SetActive(); EXPECT_FALSE(is_destroyed); delete observer; } TEST(CallbackLayerAnimationObserverDestructionTest, AnimationEndedReturnsTrue) { TestCallbacks callbacks; callbacks.set_should_delete_observer_on_animations_ended(true); bool is_destroyed = false; TestCallbackLayerAnimationObserver* observer = new TestCallbackLayerAnimationObserver( base::BindRepeating(&TestCallbacks::AnimationsStarted, base::Unretained(&callbacks)), base::BindRepeating(&TestCallbacks::AnimationsEnded, base::Unretained(&callbacks)), &is_destroyed); observer->SetActive(); EXPECT_TRUE(is_destroyed); } // Verifies that there are not heap-use-after-free errors when an observer has // its animation aborted and it gets destroyed due to a // unique_ptr<CallbackLayerAnimationObserver> being assigned a new value. TEST_F(CallbackLayerAnimationObserverTestOverwrite, VerifyOverwriteOnAnimationStart) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->OnLayerAnimationStarted(sequence_1); observer_->OnLayerAnimationStarted(sequence_2); observer_->OnLayerAnimationEnded(sequence_1); observer_->SetActive(); EXPECT_FALSE(observer_->active()); } TEST_F(CallbackLayerAnimationObserverTest, VerifyInitialState) { EXPECT_FALSE(observer_->active()); EXPECT_EQ(0, observer_->aborted_count()); EXPECT_EQ(0, observer_->successful_count()); EXPECT_FALSE(callbacks_->animations_started()); EXPECT_FALSE(callbacks_->animations_ended()); } // Verifies that the CallbackLayerAnimationObserver is robust to explicit // deletes caused as a side effect of calling the AnimationsStartedCallback() // when there are no animation sequences attached. This test also guards against // heap-use-after-free errors. TEST_F( CallbackLayerAnimationObserverTest, ExplicitlyDeleteObserverInAnimationStartedCallbackWithNoSequencesAttached) { TestCallbacksThatExplicitlyDeletesObserver callbacks; callbacks.set_should_delete_observer_on_animations_ended(true); bool is_destroyed = false; TestCallbackLayerAnimationObserver* observer = new TestCallbackLayerAnimationObserver( base::BindRepeating(&TestCallbacks::AnimationsStarted, base::Unretained(&callbacks)), base::BindRepeating(&TestCallbacks::AnimationsEnded, base::Unretained(&callbacks)), &is_destroyed); callbacks.set_observer_to_delete_in_animation_started(observer); observer->SetActive(); EXPECT_TRUE(is_destroyed); } // Verifies that the CallbackLayerAnimationObserver is robust to explicit // deletes caused as a side effect of calling the AnimationsStartedCallback() // when there are some animation sequences attached. This test also guards // against heap-use-after-free errors. TEST_F( CallbackLayerAnimationObserverTest, ExplicitlyDeleteObserverInAnimationStartedCallbackWithSomeSequencesAttached) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); TestCallbacksThatExplicitlyDeletesObserver callbacks; callbacks.set_should_delete_observer_on_animations_ended(true); bool is_destroyed = false; TestCallbackLayerAnimationObserver* observer = new TestCallbackLayerAnimationObserver( base::BindRepeating(&TestCallbacks::AnimationsStarted, base::Unretained(&callbacks)), base::BindRepeating(&TestCallbacks::AnimationsEnded, base::Unretained(&callbacks)), &is_destroyed); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->OnLayerAnimationStarted(sequence_1); observer_->OnLayerAnimationStarted(sequence_2); callbacks.set_observer_to_delete_in_animation_started(observer); observer->SetActive(); EXPECT_TRUE(is_destroyed); } // Verifies that a 'true' return value for AnimationEndedCallback is ignored if // the CallbackLayerAnimationObserver is explicitly deleted as a side effect of // calling the AnimationEndedCallback. This test also guards against // heap-use-after-free errors. TEST_F(CallbackLayerAnimationObserverTest, IgnoreTrueReturnValueForAnimationEndedCallbackIfExplicitlyDeleted) { TestCallbacksThatExplicitlyDeletesObserver callbacks; callbacks.set_should_delete_observer_on_animations_ended(true); bool is_destroyed = false; TestCallbackLayerAnimationObserver* observer = new TestCallbackLayerAnimationObserver( base::BindRepeating(&TestCallbacks::AnimationsStarted, base::Unretained(&callbacks)), base::BindRepeating(&TestCallbacks::AnimationsEnded, base::Unretained(&callbacks)), &is_destroyed); callbacks.set_observer_to_delete_in_animation_ended(observer); observer->SetActive(); EXPECT_TRUE(is_destroyed); } TEST_F(CallbackLayerAnimationObserverTest, SetActiveWhenNoSequencesWereAttached) { observer_->SetActive(); EXPECT_FALSE(observer_->active()); EXPECT_TRUE(callbacks_->animations_started()); EXPECT_TRUE(callbacks_->animations_ended()); EXPECT_TRUE(callbacks_->StartedEpochIsBeforeEndedEpoch()); } TEST_F(CallbackLayerAnimationObserverTest, SetActiveWhenAllSequencesAreAttachedButNoneWereStarted) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->SetActive(); EXPECT_TRUE(observer_->active()); EXPECT_FALSE(callbacks_->animations_started()); EXPECT_FALSE(callbacks_->animations_ended()); } TEST_F(CallbackLayerAnimationObserverTest, SetActiveWhenAllSequencesAreAttachedAndOnlySomeWereStarted) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->OnLayerAnimationStarted(sequence_1); observer_->SetActive(); EXPECT_TRUE(observer_->active()); EXPECT_FALSE(callbacks_->animations_started()); EXPECT_FALSE(callbacks_->animations_ended()); } TEST_F(CallbackLayerAnimationObserverTest, SetActiveWhenAllSequencesAreAttachedAndOnlySomeWereCompleted) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->OnLayerAnimationStarted(sequence_1); observer_->OnLayerAnimationEnded(sequence_1); observer_->SetActive(); EXPECT_TRUE(observer_->active()); EXPECT_FALSE(callbacks_->animations_started()); EXPECT_FALSE(callbacks_->animations_ended()); } TEST_F(CallbackLayerAnimationObserverTest, SetActiveAfterAllSequencesWereStartedButNoneWereCompleted) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->OnLayerAnimationStarted(sequence_1); observer_->OnLayerAnimationStarted(sequence_2); observer_->SetActive(); EXPECT_TRUE(observer_->active()); EXPECT_TRUE(callbacks_->animations_started()); EXPECT_FALSE(callbacks_->animations_ended()); } TEST_F(CallbackLayerAnimationObserverTest, SetActiveWhenAllSequencesAreStartedAndOnlySomeWereCompleted) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->OnLayerAnimationStarted(sequence_1); observer_->OnLayerAnimationStarted(sequence_2); observer_->OnLayerAnimationEnded(sequence_1); observer_->SetActive(); EXPECT_TRUE(observer_->active()); EXPECT_TRUE(callbacks_->animations_started()); EXPECT_FALSE(callbacks_->animations_ended()); } TEST_F(CallbackLayerAnimationObserverTest, SetActiveWhenAllSequencesWereCompleted) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->OnLayerAnimationStarted(sequence_1); observer_->OnLayerAnimationStarted(sequence_2); observer_->OnLayerAnimationEnded(sequence_1); observer_->OnLayerAnimationEnded(sequence_2); observer_->SetActive(); EXPECT_FALSE(observer_->active()); EXPECT_TRUE(callbacks_->animations_started()); EXPECT_TRUE(callbacks_->animations_ended()); } TEST_F(CallbackLayerAnimationObserverTest, SetActiveAgainAfterAllSequencesWereCompleted) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_3 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_4 = CreateLayerAnimationSequence(); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->OnLayerAnimationStarted(sequence_1); observer_->OnLayerAnimationStarted(sequence_2); observer_->OnLayerAnimationEnded(sequence_1); observer_->OnLayerAnimationEnded(sequence_2); observer_->SetActive(); EXPECT_FALSE(observer_->active()); observer_test_api_->AttachedToSequence(sequence_3); observer_test_api_->AttachedToSequence(sequence_4); callbacks_->ResetCallbackObservations(); observer_->SetActive(); EXPECT_TRUE(observer_->active()); EXPECT_FALSE(callbacks_->animations_started()); EXPECT_FALSE(callbacks_->animations_ended()); EXPECT_EQ(2, observer_->successful_count()); observer_->OnLayerAnimationStarted(sequence_3); observer_->OnLayerAnimationStarted(sequence_4); EXPECT_TRUE(observer_->active()); EXPECT_TRUE(callbacks_->animations_started()); EXPECT_FALSE(callbacks_->animations_ended()); EXPECT_EQ(2, observer_->successful_count()); observer_->OnLayerAnimationEnded(sequence_3); observer_->OnLayerAnimationEnded(sequence_4); EXPECT_FALSE(observer_->active()); EXPECT_TRUE(callbacks_->animations_started()); EXPECT_TRUE(callbacks_->animations_ended()); EXPECT_EQ(4, observer_->successful_count()); } TEST_F(CallbackLayerAnimationObserverTest, DetachBeforeActive) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->OnLayerAnimationStarted(sequence_1); observer_->OnLayerAnimationEnded(sequence_1); observer_test_api_->DetachedFromSequence(sequence_1, true); observer_test_api_->DetachedFromSequence(sequence_2, true); observer_->SetActive(); EXPECT_FALSE(observer_->active()); EXPECT_TRUE(callbacks_->animations_started()); EXPECT_TRUE(callbacks_->animations_ended()); } TEST_F(CallbackLayerAnimationObserverTest, DetachAfterActive) { LayerAnimationSequence* sequence_1 = CreateLayerAnimationSequence(); LayerAnimationSequence* sequence_2 = CreateLayerAnimationSequence(); observer_test_api_->AttachedToSequence(sequence_1); observer_test_api_->AttachedToSequence(sequence_2); observer_->SetActive(); observer_->OnLayerAnimationStarted(sequence_1); observer_->OnLayerAnimationEnded(sequence_1); observer_test_api_->DetachedFromSequence(sequence_1, true); observer_test_api_->DetachedFromSequence(sequence_2, true); EXPECT_FALSE(observer_->active()); EXPECT_TRUE(callbacks_->animations_started()); EXPECT_TRUE(callbacks_->animations_ended()); } } // namespace test } // namespace ui
; ; ; Copyright (C) Microsoft Corporation, 1986 ; ; This Module contains Proprietary Information of Microsoft ; Corporation and should be treated as Confidential. ; subttl emxenix.asm - XENIX function jump tables and Initialization page public __eminit, __emulate, __87exception org 10h __eminit: ; UNDONE - not used any more org 15h __emulate: jmp protemulation ; protect mode emulation org 1Ah __87exception: pop eax ; eax = error code int 0FFh page ;------------------------------------------------------------------------------ ; ; install emulator (initial all data elements ; ; This routine is executed once for the 1st emulated instruction ; ;------------------------------------------------------------------------------ pub installemulator mov [Einstall],1 ; mark emulator as initialized mov eax,offset BEGstk ; pointer to beginning of stack mov [BASstk],eax ; set base of stack mov [CURstk],eax ; set current stack element mov eax,offset ENDstk-Reg87Len mov [LIMstk],eax ; set end of stack mov ax,InitControlWord mov [UserControlWord],ax ; initialize control words mov [ControlWord],ax xor eax,eax mov [UserStatusWord],ax ; initialize status words mov [StatusWord],ax jmp protemcont ; continue emulating 1st instruction
; Stub for the TI 86 calculator ; ; Stefano Bodrato - Dec 2000 ; ; $Id: ti86_crt0.asm,v 1.34 2016-07-11 05:58:34 stefano Exp $ ; ; startup = ; n - Primary shell(s); compatible shell(s) ; (Primary shell merely means it's the smallest implementation ; for that shell, that uses full capabilities of the shell) ; ; 1 - LASM (default) ; 2 - ASE, Rascal, emanon, etc. ; 3 - zap2000 ; 4 - emanon ; 5 - Embedded LargeLd - !!!EXPERIMENTAL!!! ; 10 - asm() executable ; ;----------------------------------------------------- ; Some general PUBLICs and EXTERNs needed by the assembler ;----------------------------------------------------- MODULE Ti86_crt0 EXTERN _main ; No matter what set up we have, main is ; always, always external to this file. PUBLIC cleanup ; used by exit() PUBLIC l_dcal ; used by calculated calls = "call (hl)" PUBLIC cpygraph ; TI calc specific stuff PUBLIC tidi ; PUBLIC tiei ; ;------------------------- ; Begin of (shell) headers ;------------------------- INCLUDE "Ti86.def" ; ROM / RAM adresses on Ti86 defc crt0 = 1 INCLUDE "zcc_opt.def" ; Receive all compiler-defines ;----------------------------- ;2 - ASE, Rascal, emanon, etc. ;----------------------------- IF (startup=2) DEFINE ASE DEFINE NOT_DEFAULT_SHELL org _asm_exec_ram-2 ;TI 86 standard asm() entry point. defb $8e, $28 nop ;identifier of table jp start defw $0000 ;version number of table defw description ;pointer to the description description: DEFINE NEED_name INCLUDE "zcc_opt.def" UNDEFINE NEED_name IF !DEFINED_NEED_name defm "Z88DK Small C+ Program" ENDIF defb $0 ; Termination zero ENDIF ;----------- ;3 - zap2000 ;----------- IF (startup=3) DEFINE ZAP2000 DEFINE NOT_DEFAULT_SHELL org _asm_exec_ram-2 defb $8e, $28 nop jp start defw description defw icon description: DEFINE NEED_name INCLUDE "zcc_opt.def" UNDEFINE NEED_name IF !DEFINED_NEED_name defm "Z88DK Small C+ Program" ENDIF defb $0 ; Termination zero icon: DEFINE NEED_icon INCLUDE "zcc_opt.def" UNDEFINE NEED_icon IF !DEFINED_NEED_icon defb @00000000 ; 8x8 icon defb @00110010 ; C with a small '+' defb @01000111 defb @01000010 defb @01000000 defb @00110000 defb @00000000 defb @00000000 ENDIF ENDIF ;---------- ;4 - emanon ;---------- IF (startup=4) DEFINE EMANON DEFINE NOT_DEFAULT_SHELL org _asm_exec_ram-2 ;TI 86 standard asm() entry point. defb $8e, $28 nop ;identifier of table jp start defw $0001 ;version number of table defw description ;pointer to description defw icon ;pointer to icon description: DEFINE NEED_name INCLUDE "zcc_opt.def" UNDEFINE NEED_name IF !DEFINED_NEED_name defm "Z88DK Small C+ Program" ENDIF defb $0 ; Termination zero icon: DEFINE NEED_icon INCLUDE "zcc_opt.def" ; Get icon from zcc_opt.def UNDEFINE NEED_icon IF !DEFINED_NEED_icon defb @00000000 ; 7x7 icon defb @00110010 defb @01000111 defb @01000010 defb @01000000 defb @00110000 defb @00000000 ENDIF ENDIF ;---------------------- ; 10 - asm() executable ;---------------------- IF (startup=10) DEFINE STDASM DEFINE NOT_DEFAULT_SHELL org _asm_exec_ram - 2 defb $8e, $28 ENDIF ;-------------------------------------------------- ; 5 - Embedded LargeLd - !!!EXPERIMENTAL!!! ; - The calculator needs to be reset (memory clean) ; - This has to be the first program in memory ;-------------------------------------------------- IF (startup=5) DEFINE NOT_DEFAULT_SHELL org $8000+14 ld a,$42 ; (RAM_PAGE_1) out (6),a jp start ENDIF ;------------------ ;1 - LASM (default) ;------------------ IF !NOT_DEFAULT_SHELL DEFINE LASM org $801D ; "Large asm block". To be loaded with "LASM" ; You need LASM 0.8 Beta by Patrick Wong for this (www.ticalc.org) ; - First wipe TI86 RAM (InstLASM is simply a memory cleaner) ; - Load LargeLd ; - Load your compiled and converted .86p code ; - run asm(LargeLd ; It will run your program. Loading order is important. defb $8e, $28 ;org $801F ; Start from here if you want to use PRGM86 ret nop ;Identifies the table jp start defw 1 ;Version # of Table. Release 0 has no icon (Title only) defw description ;Absolute pointer to program description defw icon ;foo pointer to icon description: DEFINE NEED_name INCLUDE "zcc_opt.def" UNDEFINE NEED_name IF !DEFINED_NEED_name defm "Z88DK Small C+ Program" ENDIF icon: defb $0 ; Termination zero ENDIF ;------------------------------------- ; End of header, begin of startup part ;------------------------------------- start: IF STDASM | LASM ; asm( executable call _runindicoff ; stop anoing run-indicator ENDIF ld hl,0 add hl,sp ld (start1+1),hl IF !DEFINED_atexit ; Less stack use ld hl,-6 ; 3 pointers (more likely value) add hl,sp ld sp,hl call crt0_init_bss ld (exitsp),sp ELSE ld hl,-64 ; 32 pointers (ANSI standard) add hl,sp ld sp,hl call crt0_init_bss ld (exitsp),sp ENDIF ; Optional definition for auto MALLOC init ; it assumes we have free space between the end of ; the compiled program and the stack pointer IF DEFINED_USING_amalloc INCLUDE "amalloc.def" ENDIF ; IF NONANSI call _homeup ; Set text cursor at (0,0) ld a,8 ; Set _winBtm back to 8, so we ld (_winBtm),a ; can print on the last line ; ELSE EXTERN fputc_cons ld hl,12 push hl call fputc_cons pop hl IF DEFINED_GRAYlib INCLUDE "gray86.asm" ENDIF ;im 2 call tidi call _flushallmenus call _main cleanup: ; exit() jumps to this point start1: ld sp,0 IF DEFINED_GRAYlib ld a,$3C ; Make sure video mem is active out (0),a ENDIF tiei: ld IY,_Flags exx ld hl,(hl1save) ld bc,(bc1save) ld de,(de1save) exx IF DEFINED_GRAYlib im 1 ELSE ei ENDIF ret tidi: IF DEFINED_GRAYlib im 2 ELSE di ENDIF exx ld (hl1save),hl ld (bc1save),bc ld (de1save),de exx ret cpygraph: ret ;---------------------------------------- ; End of startup part, routines following ;---------------------------------------- l_dcal: jp (hl) defc ansipixels = 128 IF !DEFINED_ansicolumns defc DEFINED_ansicolumns = 1 defc ansicolumns = 32 ENDIF INCLUDE "crt0_runtime_selection.asm" INCLUDE "crt0_section.asm" SECTION bss_crt hl1save: defw 0 de1save: defw 0 bc1save: defw 0 SECTION code_crt_init ld hl,$FC00 ld (base_graphics),hl
BITS 32 ;TEST_FILE_META_BEGIN ;TEST_TYPE=TEST_F ;TEST_IGNOREFLAGS=FLAG_AF|FLAG_OF ;TEST_FILE_META_END ; SHL8rCL mov bh, 0xa mov cl, 0x3 ;TEST_BEGIN_RECORDING shl bh, cl ;TEST_END_RECORDING
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r9 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_WT_ht+0x23bf, %rsi lea addresses_UC_ht+0x97f5, %rdi clflush (%rdi) nop nop mfence mov $106, %rcx rep movsw nop nop nop nop cmp $44618, %r13 lea addresses_D_ht+0x5165, %rdi clflush (%rdi) nop nop nop nop nop cmp $51897, %rbx movups (%rdi), %xmm3 vpextrq $0, %xmm3, %rsi nop nop nop dec %rcx lea addresses_A_ht+0x15fb5, %r13 nop nop inc %rax and $0xffffffffffffffc0, %r13 movaps (%r13), %xmm7 vpextrq $1, %xmm7, %rbx nop nop dec %rcx lea addresses_normal_ht+0x1abf5, %rsi lea addresses_WT_ht+0x11c29, %rdi nop nop nop nop add %r11, %r11 mov $62, %rcx rep movsw nop nop nop nop nop dec %rbx lea addresses_D_ht+0x7df5, %rax nop nop nop nop nop add $569, %rdi movups (%rax), %xmm7 vpextrq $0, %xmm7, %rbx nop nop nop nop nop and %r11, %r11 lea addresses_A_ht+0xa3f5, %rbx nop nop cmp $43180, %rcx mov $0x6162636465666768, %r11 movq %r11, %xmm3 and $0xffffffffffffffc0, %rbx vmovaps %ymm3, (%rbx) nop nop cmp %r11, %r11 lea addresses_UC_ht+0xdabf, %rsi lea addresses_WT_ht+0x1d9d5, %rdi clflush (%rdi) xor $28899, %r13 mov $4, %rcx rep movsl and %rax, %rax lea addresses_A_ht+0x1a115, %rsi nop nop nop nop nop sub %rdi, %rdi mov $0x6162636465666768, %r9 movq %r9, %xmm7 vmovups %ymm7, (%rsi) nop nop xor %r9, %r9 pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r9 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r9 push %rax push %rcx push %rdi push %rsi // REPMOV lea addresses_RW+0x4015, %rsi lea addresses_UC+0x153f5, %rdi nop nop nop sub $55130, %r9 mov $15, %rcx rep movsq nop nop nop and $49983, %r12 // Store lea addresses_PSE+0x19b27, %rdi nop sub %rax, %rax mov $0x5152535455565758, %r11 movq %r11, %xmm0 movups %xmm0, (%rdi) nop nop nop and $46031, %r12 // Store lea addresses_UC+0x2f9d, %rax sub %rsi, %rsi mov $0x5152535455565758, %r12 movq %r12, %xmm1 vmovups %ymm1, (%rax) nop add $52898, %r9 // Faulty Load lea addresses_RW+0x2bf5, %r9 nop nop nop xor %rcx, %rcx movb (%r9), %al lea oracles, %r9 and $0xff, %rax shlq $12, %rax mov (%r9,%rax,1), %rax pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 4, 'type': 'addresses_RW', 'congruent': 0}} {'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_RW'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_PSE', 'congruent': 0}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_UC', 'congruent': 2}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_RW', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'congruent': 10, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_WT_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D_ht', 'congruent': 4}} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': True, 'size': 16, 'type': 'addresses_A_ht', 'congruent': 6}} {'dst': {'same': False, 'congruent': 2, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 11, 'type': 'addresses_normal_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D_ht', 'congruent': 5}} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 32, 'type': 'addresses_A_ht', 'congruent': 11}, 'OP': 'STOR'} {'dst': {'same': False, 'congruent': 3, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_UC_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_A_ht', 'congruent': 5}, 'OP': 'STOR'} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ABI32_0_0AttributedString.h" #include <ABI32_0_0fabric/ABI32_0_0debug/DebugStringConvertibleItem.h> namespace facebook { namespace ReactABI32_0_0 { using Fragment = AttributedString::Fragment; using Fragments = AttributedString::Fragments; void AttributedString::appendFragment(const Fragment &fragment) { ensureUnsealed(); fragments_.push_back(fragment); } void AttributedString::prependFragment(const Fragment &fragment) { ensureUnsealed(); fragments_.insert(fragments_.begin(), fragment); } void AttributedString::appendAttributedString(const AttributedString &attributedString) { ensureUnsealed(); fragments_.insert(fragments_.end(), attributedString.fragments_.begin(), attributedString.fragments_.end()); } void AttributedString::prependAttributedString(const AttributedString &attributedString) { ensureUnsealed(); fragments_.insert(fragments_.begin(), attributedString.fragments_.begin(), attributedString.fragments_.end()); } const std::vector<Fragment> &AttributedString::getFragments() const { return fragments_; } std::string AttributedString::getString() const { std::string string; for (const auto &fragment : fragments_) { string += fragment.string; } return string; } #pragma mark - DebugStringConvertible SharedDebugStringConvertibleList AttributedString::getDebugChildren() const { SharedDebugStringConvertibleList list = {}; for (auto &&fragment : fragments_) { auto propsList = fragment.textAttributes.DebugStringConvertible::getDebugProps(); if (fragment.shadowNode) { propsList.push_back(std::make_shared<DebugStringConvertibleItem>("shadowNode", fragment.shadowNode->getDebugDescription())); } list.push_back( std::make_shared<DebugStringConvertibleItem>( "Fragment", fragment.string, SharedDebugStringConvertibleList(), propsList ) ); } return list; } } // namespace ReactABI32_0_0 } // namespace facebook
.text li $s0 0x00000010 li $s1 0x12345678 sw $s1 0($s0) sw $s1 4($s0) lh $t1 2($s0) sh $t1 4($s0) lb $t2 1($s0) sb $t2 7($s0)
.global s_prepare_buffers s_prepare_buffers: push %r8 push %rax push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_D_ht+0x4199, %rbp nop nop nop nop add %rbx, %rbx movb $0x61, (%rbp) nop nop add %rbx, %rbx lea addresses_UC_ht+0x16193, %rbp nop nop nop nop cmp %rdx, %rdx mov $0x6162636465666768, %rax movq %rax, %xmm6 vmovups %ymm6, (%rbp) nop nop nop nop sub %r8, %r8 lea addresses_UC_ht+0x2ea3, %r8 clflush (%r8) nop nop nop dec %rdx mov (%r8), %ebp nop xor %r8, %r8 lea addresses_normal_ht+0x10419, %rsi lea addresses_normal_ht+0x3b93, %rdi nop nop nop cmp %r8, %r8 mov $66, %rcx rep movsw nop nop nop nop and %rdx, %rdx lea addresses_WT_ht+0xecef, %rcx nop nop nop cmp %rbp, %rbp movups (%rcx), %xmm4 vpextrq $0, %xmm4, %rdi nop nop nop xor $22317, %rbx lea addresses_normal_ht+0x16213, %rsi lea addresses_normal_ht+0x1ae93, %rdi nop cmp %r8, %r8 mov $100, %rcx rep movsl nop nop nop nop sub %rdx, %rdx lea addresses_normal_ht+0x5667, %rsi lea addresses_D_ht+0x3b93, %rdi nop nop nop nop add %rax, %rax mov $111, %rcx rep movsb nop nop nop nop nop add $59404, %rbx lea addresses_WT_ht+0x14a8b, %rsi nop nop nop nop nop and $39898, %r8 movups (%rsi), %xmm2 vpextrq $0, %xmm2, %rbx nop nop nop sub $7787, %rbp lea addresses_UC_ht+0x12fcb, %rdx xor $18109, %r8 mov (%rdx), %ebp nop nop nop nop nop inc %rdi lea addresses_D_ht+0xe87a, %rsi lea addresses_WT_ht+0x12293, %rdi nop nop nop nop add %rbp, %rbp mov $67, %rcx rep movsw xor $17932, %rsi lea addresses_UC_ht+0x10ad3, %rdx nop xor $2039, %r8 movl $0x61626364, (%rdx) nop nop dec %rbp lea addresses_UC_ht+0x19913, %r8 clflush (%r8) nop nop nop add %rax, %rax mov $0x6162636465666768, %rdi movq %rdi, (%r8) nop nop nop nop add %r8, %r8 lea addresses_WC_ht+0x5f93, %rsi lea addresses_normal_ht+0x1e793, %rdi nop nop sub %rdx, %rdx mov $31, %rcx rep movsl nop nop cmp %rbx, %rbx lea addresses_UC_ht+0x2793, %rsi lea addresses_normal_ht+0x19c43, %rdi nop nop nop sub $9811, %rdx mov $42, %rcx rep movsl nop cmp $31772, %rbx lea addresses_D_ht+0xc093, %rsi lea addresses_A_ht+0x1ea23, %rdi nop nop add %rbx, %rbx mov $122, %rcx rep movsb nop nop nop nop xor $56661, %rcx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r8 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r13 push %r15 push %r8 push %rax push %rcx push %rdi push %rsi // Store lea addresses_PSE+0x14313, %r12 nop nop nop nop nop dec %r8 movb $0x51, (%r12) nop nop cmp $13292, %r8 // Store lea addresses_PSE+0xd123, %r11 nop nop nop nop xor $46081, %rax mov $0x5152535455565758, %r12 movq %r12, (%r11) nop nop nop nop inc %rax // Store lea addresses_A+0x14824, %r15 nop nop cmp $42124, %rax movb $0x51, (%r15) nop nop nop nop dec %r11 // Store mov $0x2af8f50000000e6b, %r15 nop nop nop dec %rdi movl $0x51525354, (%r15) nop nop cmp %rdi, %rdi // Store lea addresses_D+0x13393, %r8 clflush (%r8) nop and %r13, %r13 movb $0x51, (%r8) nop nop inc %rdi // Store lea addresses_US+0x50af, %rax add $38060, %r12 mov $0x5152535455565758, %r8 movq %r8, (%rax) // Exception!!! nop nop nop nop xor %r8, %r8 div %r8 nop nop nop nop nop sub $41763, %r15 // Store lea addresses_UC+0x104b, %r15 nop nop nop nop nop xor %r8, %r8 mov $0x5152535455565758, %r11 movq %r11, %xmm2 vmovups %ymm2, (%r15) nop sub $11208, %r13 // Store lea addresses_UC+0x5793, %r8 nop nop cmp $15980, %rax movw $0x5152, (%r8) // Exception!!! nop nop nop xor %rax, %rax div %rax nop nop cmp $29882, %r11 // REPMOV lea addresses_normal+0x1908f, %rsi mov $0x683, %rdi nop nop nop nop xor %r15, %r15 mov $113, %rcx rep movsl // Exception!!! nop nop nop nop mov (0), %r11 nop nop nop nop cmp $47924, %rdi // Store lea addresses_UC+0x1bf3, %r15 nop nop nop nop and $59094, %r11 mov $0x5152535455565758, %rsi movq %rsi, %xmm2 vmovups %ymm2, (%r15) nop nop dec %rax // Faulty Load lea addresses_RW+0x1793, %r13 clflush (%r13) cmp %rax, %rax mov (%r13), %esi lea oracles, %r11 and $0xff, %rsi shlq $12, %rsi mov (%r11,%rsi,1), %rsi pop %rsi pop %rdi pop %rcx pop %rax pop %r8 pop %r15 pop %r13 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_RW', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 1}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_A', 'AVXalign': True, 'size': 1}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_NC', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 10, 'type': 'addresses_D', 'AVXalign': False, 'size': 1}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_US', 'AVXalign': False, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_UC', 'AVXalign': False, 'size': 32}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_UC', 'AVXalign': False, 'size': 2}} {'src': {'same': False, 'congruent': 2, 'type': 'addresses_normal'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_P'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_UC', 'AVXalign': False, 'size': 32}} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_RW', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32}} {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_UC_ht', 'AVXalign': True, 'size': 4}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 1, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_normal_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 5, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_normal_ht'}} {'src': {'same': False, 'congruent': 0, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'same': True, 'congruent': 10, 'type': 'addresses_D_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': True, 'congruent': 2, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 0, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 4}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8}} {'src': {'same': False, 'congruent': 11, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_normal_ht'}} {'src': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_normal_ht'}} {'src': {'same': False, 'congruent': 6, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_A_ht'}} {'7d': 1} 7d */
; A266252: Total number of OFF (white) cells after n iterations of the "Rule 9" elementary cellular automaton starting with a single ON (black) cell. ; 0,3,6,11,16,22,31,37,50,56,73,79,100,106,131,137,166,172,205,211,248,254,295,301,346,352,401,407,460,466,523,529,590,596,661,667,736,742,815,821,898,904,985,991,1076,1082,1171,1177,1270,1276,1373,1379,1480,1486,1591,1597,1706,1712,1825,1831,1948,1954,2075,2081,2206,2212,2341,2347,2480,2486,2623,2629,2770,2776,2921,2927,3076,3082,3235,3241,3398,3404,3565,3571,3736,3742,3911,3917,4090,4096,4273,4279,4460,4466,4651,4657,4846,4852,5045,5051 mov $2,$0 mov $4,$0 sub $0,2 mov $3,$2 sub $3,1 lpb $0 sub $0,1 add $2,1 mov $1,$2 add $3,$0 mov $2,$3 add $2,$0 mov $3,$1 lpe trn $3,2 add $3,1 mov $1,$3 lpb $4 add $1,3 sub $4,1 lpe sub $1,1 mov $0,$1
; A054087: s(3n-2), s=A054086; also a bisection of A003511. ; 1,4,6,9,12,15,17,20,23,25,28,31,34,36,39,42,45,47,50,53,56,58,61,64,66,69,72,75,77,80,83,86,88,91,94,96,99,102,105,107,110,113,116,118,121,124,127,129,132,135,137,140,143,146,148,151 mov $2,$0 mov $4,3 lpb $4 lpb $0 mov $5,$0 add $5,$0 add $3,$5 add $3,$0 sub $0,1 lpe lpb $3 add $1,1 sub $3,$1 trn $3,1 lpe mov $4,1 lpe lpb $2 add $1,1 sub $2,1 lpe add $1,1
;-------------------------------------------------------------------------------- ; OnLoadOW ;-------------------------------------------------------------------------------- ;OnLoadMap: ; LDA $7EF2DB ; thing we wrote over ;RTL ;-------------------------------------------------------------------------------- OnPrepFileSelect: LDA $11 : CMP.b #$03 : BNE + LDA.b #$06 : STA $14 ; thing we wrote over RTL + JSL.l LoadAlphabetTilemap JSL.l LoadFullItemTiles RTL ;-------------------------------------------------------------------------------- OnDrawHud: JSL.l DrawChallengeTimer ; this has to come before NewDrawHud because the timer overwrites the compass counter .DrHudOverride print "DrHudOverride: ", pc JSL.l NewDrawHud ;JSL.l SwapSpriteIfNecissary JSL.l PollService JML.l ReturnFromOnDrawHud ;-------------------------------------------------------------------------------- ;OnDungeonEntrance: ; STA $7EC172 ; thing we wrote over ;RTL ;-------------------------------------------------------------------------------- OnPlayerDead: PHA JSL.l SetDeathWorldChecked JSL.l SetSilverBowMode JSL.l RefreshRainAmmo PLA RTL ;-------------------------------------------------------------------------------- OnDungeonExit: PHA : PHP SEP #$20 ; set 8-bit accumulator JSL.l PodEGFix PLP : PLA STA $040C : STZ $04AC ; thing we wrote over PHA : PHP JSL.l HUD_RebuildLong JSL.l FloodGateResetInner JSL.l SetSilverBowMode PLP : PLA RTL ;-------------------------------------------------------------------------------- OnQuit: JSL.l PodEGFix LDA.b #$10 : STA $1C ; thing we wrote over RTL ;-------------------------------------------------------------------------------- OnUncleItemGet: PHA LDA.l EscapeAssist BIT.b #$04 : BEQ + : STA !INFINITE_MAGIC : + BIT.b #$02 : BEQ + : STA !INFINITE_BOMBS : + BIT.b #$01 : BEQ + : STA !INFINITE_ARROWS : + %GetPossiblyEncryptedItem(UncleItem, SpriteItemValues) : TAY %GetPossiblyEncryptedPlayerID(UncleItem_Player) : STA !MULTIWORLD_ITEM_PLAYER_ID PLA JSL Link_ReceiveItem LDA.l UncleRefill : BIT.b #$04 : BEQ + : LDA.b #$80 : STA $7EF373 : + ; refill magic LDA.l UncleRefill : BIT.b #$02 : BEQ + : LDA.b #50 : STA $7EF375 : + ; refill bombs LDA.l UncleRefill : BIT.b #$01 : BEQ + ; refill arrows LDA.b #70 : STA $7EF376 LDA.l ArrowMode : BEQ + LDA !INVENTORY_SWAP_2 : ORA #$80 : STA !INVENTORY_SWAP_2 ; enable bow toggle REP #$20 ; set 16-bit accumulator LDA $7EF360 : !ADD.l FreeUncleItemAmount : STA $7EF360 ; rupee arrows, so also give the player some money to start SEP #$20 ; set 8-bit accumulator + RTL ;-------------------------------------------------------------------------------- OnAga2Defeated: JSL.l Dungeon_SaveRoomData_justKeys ; thing we wrote over, make sure this is first JSL.l IncrementAgahnim2Sword RTL ;-------------------------------------------------------------------------------- !RNG_ITEM_LOCK_IN = "$7F5090" OnFileLoad: REP #$10 ; set 16 bit index registers JSL.l EnableForceBlank ; what we wrote over LDA.b #$07 : STA $210c ; Restore screen 3 to normal tile area LDA !FRESH_FILE_MARKER : BNE + JSL.l OnNewFile LDA.b #$FF : STA !FRESH_FILE_MARKER + LDA.w $010A : BNE + ; don't adjust the worlds for "continue" or "save-continue" LDA.l $7EC011 : BNE + ; don't adjust worlds if mosiac is enabled (Read: mirroring in dungeon) JSL.l DoWorldFix + JSL.l MasterSwordFollowerClear JSL.l InitOpenMode LDA #$FF : STA !RNG_ITEM_LOCK_IN ; reset rng item lock-in LDA #$00 : STA $7F5001 ; mark fake flipper softlock as impossible LDA.l GenericKeys : BEQ + LDA $7EF38B : STA $7EF36F ; copy generic keys to key counter + JSL.l SetSilverBowMode JSL.l RefreshRainAmmo JSL.l SetEscapeAssist LDA.l IsEncrypted : CMP.b #01 : BNE + JSL LoadStaticDecryptionKey + SEP #$10 ; restore 8 bit index registers RTL ;-------------------------------------------------------------------------------- !RNG_ITEM_LOCK_IN = "$7F5090" OnNewFile: PHX : PHP REP #$20 ; set 16-bit accumulator LDA.l LinkStartingRupees : STA $7EF362 : STA $7EF360 LDA.l StartingTime : STA $7EF454 LDA.l StartingTime+2 : STA $7EF454+2 LDX.w #$004E : - ; copy over starting equipment LDA StartingEquipment, X : STA $7EF340, X DEX : DEX BPL - LDX #$000E : - LDA $7EF37C, X : STA $7EF4E0, X DEX : DEX BPL - SEP #$20 ; set 8-bit accumulator ;LDA #$FF : STA !RNG_ITEM_LOCK_IN ; reset rng item lock-in LDA.l PreopenCurtains : BEQ + LDA.b #$80 : STA $7EF061 ; open aga tower curtain LDA.b #$80 : STA $7EF093 ; open skull woods curtain + LDA.l PreopenPyramid : BEQ + LDA.b #$20 : STA $7EF2DB ; pyramid hole already open + LDA.l PreopenGanonsTower : BEQ + LDA.b #$20 : STA $7EF2C3 ; Ganons Tower already open + LDA StartingSword : STA $7EF359 ; set starting sword type LDA !INVENTORY_SWAP : STA $70038C ; copy starting equipment swaps to file select screen LDA !INVENTORY_SWAP_2 : STA $70038E PLP : PLX RTL ;-------------------------------------------------------------------------------- OnInitFileSelect: ; LDA.b #$10 : STA $BC ; init sprite pointer - does nothing unless spriteswap.asm is included ; JSL.l SpriteSwap_SetSprite LDA.b #$51 : STA $0AA2 ;<-- Line missing from JP1.0, needed to ensure "extra" copy of naming screen graphics are loaded. JSL.l EnableForceBlank RTL ;-------------------------------------------------------------------------------- OnLinkDamaged: JSL.l FlipperKill JSL.l OHKOTimer RTL ;-------------------------------------------------------------------------------- OnEnterWater: JSL.l RegisterWaterEntryScreen JSL.l MysteryWaterFunction LDX.b #$04 RTL ;-------------------------------------------------------------------------------- OnLinkDamagedFromPit: JSL.l OHKOTimer LDA.b #$14 : STA $11 ; thing we wrote over RTL ;-------------------------------------------------------------------------------- OnLinkDamagedFromPitOutdoors: JSL.l OHKOTimer ; make sure this is last RTL ;-------------------------------------------------------------------------------- !RNG_ITEM_LOCK_IN = "$7F5090" OnOWTransition: JSL.l FloodGateReset JSL.l FlipperFlag JSL.l StatTransitionCounter PHP SEP #$20 ; set 8-bit accumulator LDA.b #$FF : STA !RNG_ITEM_LOCK_IN ; clear lock-in PLP RTL ;-------------------------------------------------------------------------------- !DARK_DUCK_TEMP = "$7F509C" OnLoadDuckMap: LDA !DARK_DUCK_TEMP BNE + INC : STA !DARK_DUCK_TEMP JSL OverworldMap_InitGfx : DEC $0200 RTL + LDA.b #$00 : STA !DARK_DUCK_TEMP JSL OverworldMap_DarkWorldTilemap RTL ;-------------------------------------------------------------------------------- PreItemGet: LDA.b #$01 : STA !ITEM_BUSY ; mark item as busy RTL ;-------------------------------------------------------------------------------- PostItemGet: JSL.l MaybeWriteSRAMTrace RTL ;-------------------------------------------------------------------------------- PostItemAnimation: LDA.b #$00 : STA !ITEM_BUSY ; mark item as finished LDA $7F509F : BEQ + STZ $1CF0 : STZ $1CF1 ; reset decompression buffer JSL.l Main_ShowTextMessage_Alt LDA.b #$00 : STA $7F509F + LDA $1B : BEQ + REP #$20 : LDA $A0 : STA !MULTIWORLD_ROOMID : SEP #$20 LDA $0403 : STA !MULTIWORLD_ROOMDATA + LDA !MULTIWORLD_ITEM_PLAYER_ID : BEQ + STZ $02E9 LDA #$00 : STA !MULTIWORLD_ITEM_PLAYER_ID JML.l Ancilla_ReceiveItem_objectFinished + STZ $02E9 : LDA $0C5E, X ; thing we wrote over to get here JML.l Ancilla_ReceiveItem_optimus+6 ;--------------------------------------------------------------------------------
{ let r := 0 for { let i := 0 } lt(i, 1048576) { i := add(i, 1) } { 0x51022b6317003a9d 0xa20456c62e00753a 0x51022b6317003a9d dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub pop dup2 dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub pop dup2 dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub pop dup2 dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub pop dup2 dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub pop dup2 dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub pop dup2 dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub pop dup2 dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub dup2 sub =: r pop pop } switch r case 0x51022b6317003a9d { stop } default { 0 0 revert } }
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2018 The Traff developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "guiutil.h" #include "optionsmodel.h" #include "walletmodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget* parent) : QStackedWidget(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); setCurrentWidget(ui->SendCoins); #ifdef Q_OS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); #endif // normal traff address field GUIUtil::setupAddressWidget(ui->payTo, this); // just a label for displaying traff address(es) ui->payTo_is->setFont(GUIUtil::bitcoinAddressFont()); // Connect signals connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged())); connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked())); connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked())); connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked())); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if (!model) return; AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString& address) { updateLabel(address); } void SendCoinsEntry::setModel(WalletModel* model) { this->model = model; if (model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); clear(); } void SendCoinsEntry::clear() { // clear UI elements for normal payment ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->messageTextLabel->clear(); ui->messageTextLabel->hide(); ui->messageLabel->hide(); // clear UI elements for insecure payment request ui->payTo_is->clear(); ui->memoTextLabel_is->clear(); ui->payAmount_is->clear(); // clear UI elements for secure payment request ui->payTo_s->clear(); ui->memoTextLabel_s->clear(); ui->payAmount_s->clear(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::deleteClicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { if (!model) return false; // Check input validity bool retval = true; // Skip checks for payment request if (recipient.paymentRequest.IsInitialized()) return retval; if (!model->validateAddress(ui->payTo->text())) { ui->payTo->setValid(false); retval = false; } if (!ui->payAmount->validate()) { retval = false; } // Sending a zero amount is invalid if (ui->payAmount->value(0) <= 0) { ui->payAmount->setValid(false); retval = false; } // Reject dust outputs: if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) { ui->payAmount->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { // Payment request if (recipient.paymentRequest.IsInitialized()) return recipient; // Normal payment recipient.address = ui->payTo->text(); recipient.label = ui->addAsLabel->text(); recipient.amount = ui->payAmount->value(); recipient.message = ui->messageTextLabel->text(); return recipient; } QWidget* SendCoinsEntry::setupTabChain(QWidget* prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addAsLabel); QWidget* w = ui->payAmount->setupTabChain(ui->addAsLabel); QWidget::setTabOrder(w, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); return ui->deleteButton; } void SendCoinsEntry::setValue(const SendCoinsRecipient& value) { recipient = value; if (recipient.paymentRequest.IsInitialized()) // payment request { if (recipient.authenticatedMerchant.isEmpty()) // insecure { ui->payTo_is->setText(recipient.address); ui->memoTextLabel_is->setText(recipient.message); ui->payAmount_is->setValue(recipient.amount); ui->payAmount_is->setReadOnly(true); setCurrentWidget(ui->SendCoins_InsecurePaymentRequest); } else // secure { ui->payTo_s->setText(recipient.authenticatedMerchant); ui->memoTextLabel_s->setText(recipient.message); ui->payAmount_s->setValue(recipient.amount); ui->payAmount_s->setReadOnly(true); setCurrentWidget(ui->SendCoins_SecurePaymentRequest); } } else // normal payment { // message ui->messageTextLabel->setText(recipient.message); ui->messageTextLabel->setVisible(!recipient.message.isEmpty()); ui->messageLabel->setVisible(!recipient.message.isEmpty()); ui->addAsLabel->clear(); ui->payTo->setText(recipient.address); // this may set a label from addressbook if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, dont overwrite with an empty label ui->addAsLabel->setText(recipient.label); ui->payAmount->setValue(recipient.amount); } } void SendCoinsEntry::setAddress(const QString& address) { ui->payTo->setText(address); ui->payAmount->setFocus(); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if (model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } bool SendCoinsEntry::updateLabel(const QString& address) { if (!model) return false; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if (!associatedLabel.isEmpty()) { ui->addAsLabel->setText(associatedLabel); return true; } return false; }
; A096977: a(n) = 4*a(n-1) + 3*a(n-2) - 14*a(n-3) + 8*a(n-4). ; 0,1,2,11,36,157,598,2447,9672,38913,155194,621683,2484908,9943269,39765790,159077719,636281744,2545185225,10180624386,40722730555,162890456180,651562756781,2606249162982,10425000380191,41699994064216,166799991169937,667199934853578,2668799799066627,10675199076961852,42700796546456693,170803185708608174,683212743788869863,2732850973246605088,10931403896804169049,43725615579581178770,174902462333595709899,699609849303840849924,2798439397276447379005,11193757588983621557366,44775030356178822146735 lpb $0 mov $2,$0 sub $0,1 seq $2,139818 ; Squares of Jacobsthal numbers. add $1,$2 lpe mov $0,$1
.text .globl _start _start: /* Set pin 47 as an output */ mov r0, #1 lsl r0, r0, #21 /* 4th GPIO register, FSEL47 */ ldr r1, =0x20200010 str r0, [r1] /* Set pin 47 to on */ mov r0, #1 lsl r0, r0, #16 /* GPIO output set register 1 */ ldr r1, =0x20200020 str r0, [r1]
/*++ Copyright (c) Microsoft Corporation. Licensed under the MIT License. Abstract: QUIC Interop Test Client. It tests all the major QUIC features of known public QUIC endpoints. --*/ #include "interop.h" #ifdef QUIC_CLOG #include "interop.cpp.clog.h" #endif #define VERIFY_QUIC_SUCCESS(X) { \ QUIC_STATUS s = X; \ if (QUIC_FAILED(s)) { printf(#X " FAILURE: 0x%x!!\n", s); } \ } #define HTTP_NO_ERROR 0 #define HTTP_INTERNAL_ERROR 3 const QUIC_API_TABLE* MsQuic; HQUIC Registration; uint32_t TestCases = QuicTestFeatureAll; uint32_t WaitTimeoutMs = 10000; uint32_t InitialVersion = 0; bool RunSerially = false; bool TestFailed = false; // True if any test failed const uint32_t RandomReservedVersion = 168430090ul; // Random reserved version to force VN. const uint8_t RandomTransportParameterPayload[2345] = {0}; QUIC_PRIVATE_TRANSPORT_PARAMETER RandomTransportParameter = { 77, sizeof(RandomTransportParameterPayload), RandomTransportParameterPayload }; const QUIC_BUFFER HandshakeAlpns[] = { { sizeof("hq-interop") - 1, (uint8_t*)"hq-interop" }, { sizeof("h3") - 1, (uint8_t*)"h3" }, { sizeof("hq-29") - 1, (uint8_t*)"hq-29" }, { sizeof("h3-29") - 1, (uint8_t*)"h3-29" }, }; const QUIC_BUFFER DatapathAlpns[] = { { sizeof("hq-interop") - 1, (uint8_t*)"hq-interop" }, { sizeof("hq-29") - 1, (uint8_t*)"hq-29" }, }; const QUIC_BUFFER DatagramAlpns[] = { { sizeof("siduck") - 1, (uint8_t*)"siduck" }, { sizeof("siduck-00") - 1, (uint8_t*)"siduck-00" }, }; const uint16_t PublicPorts[] = { 443, 4433, 4434 }; const uint32_t PublicPortsCount = ARRAYSIZE(PublicPorts); const QUIC_BUFFER QuackBuffer = { sizeof("quack") - 1, (uint8_t*)"quack" }; const QUIC_BUFFER QuackAckBuffer = { sizeof("quack-ack") - 1, (uint8_t*)"quack-ack" }; // // Represents the information of a well-known public QUIC endpoint. // struct QuicPublicEndpoint { const char* ImplementationName; const char* ServerName; }; QuicPublicEndpoint PublicEndpoints[] = { { "aioquic", "quic.aiortc.org" }, { "akamaiquic", "ietf.akaquic.com" }, { "applequic", "71.202.41.169" }, { "ats", "quic.ogre.com" }, { "f5", "f5quic.com" }, { "gquic", "quic.rocks" }, { "haskell", "mew.org" }, { "lsquic", "http3-test.litespeedtech.com" }, { "mvfst", "fb.mvfst.net" }, { "msquic", "msquic.net" }, { "ngtcp2", "nghttp2.org" }, { "ngx_quic", "cloudflare-quic.com" }, { "Pandora", "pandora.cm.in.tum.de" }, { "picoquic", "test.privateoctopus.com" }, { "quant", "quant.eggert.org" }, { "quinn", "h3.stammw.eu" }, { "quic-go", "quic.seemann.io" }, { "quiche", "quic.tech" }, { "quicker", "quicker.edm.uhasselt.be" }, { "quicly-quic", "quic.examp1e.net" }, { "quicly-h20", "h2o.examp1e.net" }, { nullptr, nullptr }, // Used for -custom cmd arg }; const uint32_t PublicEndpointsCount = ARRAYSIZE(PublicEndpoints) - 1; struct QuicTestResults { const char* Alpn; uint32_t QuicVersion; uint32_t Features; }; QuicTestResults TestResults[ARRAYSIZE(PublicEndpoints)]; CXPLAT_LOCK TestResultsLock; const uint32_t MaxThreadCount = PublicPortsCount * PublicEndpointsCount * QuicTestFeatureCount; CXPLAT_THREAD Threads[MaxThreadCount]; uint32_t CurrentThreadCount; uint16_t CustomPort = 0; bool CustomUrlPath = false; std::vector<std::string> Urls; const char* SslKeyLogFileParam = nullptr; void PrintUsage() { printf("\nquicinterop tests all the major QUIC features of an endpoint.\n\n"); printf("Usage:\n"); printf(" quicinterop.exe -help\n"); printf(" quicinterop.exe -list\n"); printf(" quicinterop.exe [-target:<implementation> | -custom:<hostname>] [-port:<####>] [-test:<test case>] [-timeout:<milliseconds>] [-version:<####>]\n\n"); printf("Examples:\n"); printf(" quicinterop.exe\n"); printf(" quicinterop.exe -test:H\n"); printf(" quicinterop.exe -target:msquic\n"); printf(" quicinterop.exe -custom:localhost -test:16\n"); } class GetRequest : public QUIC_BUFFER { uint8_t RawBuffer[512]; public: GetRequest(const char *Request, bool Http1_1 = false) { Buffer = RawBuffer; if (Http1_1) { Length = (uint32_t)sprintf_s((char*)RawBuffer, sizeof(RawBuffer), "GET %s HTTP/1.1\r\n", Request); } else { Length = (uint32_t)sprintf_s((char*)RawBuffer, sizeof(RawBuffer), "GET %s\r\n", Request); } } }; class InteropStream { HQUIC Stream; CXPLAT_EVENT RequestComplete; GetRequest SendRequest; const char* RequestPath; const char* FileName; FILE* File; uint64_t DownloadStartTime; uint64_t LastReceiveTime; int64_t LastReceiveDuration; public: bool ReceivedResponse : 1; bool UsedZeroRtt : 1; InteropStream(HQUIC Connection, const char* Request) : Stream(nullptr), SendRequest(Request), RequestPath(Request), FileName(nullptr), File(nullptr), DownloadStartTime(0), LastReceiveTime(0), LastReceiveDuration(0), ReceivedResponse(false), UsedZeroRtt(false) { CxPlatEventInitialize(&RequestComplete, TRUE, FALSE); VERIFY_QUIC_SUCCESS( MsQuic->StreamOpen( Connection, QUIC_STREAM_OPEN_FLAG_NONE, InteropStream::StreamCallback, this, &Stream)); } ~InteropStream() { MsQuic->StreamClose(Stream); CxPlatEventUninitialize(RequestComplete); } bool SendHttpRequest(bool WaitForResponse = true) { CxPlatEventReset(RequestComplete); if (QUIC_FAILED( MsQuic->StreamStart( Stream, QUIC_STREAM_START_FLAG_IMMEDIATE))) { MsQuic->StreamClose(Stream); return false; } if (CustomUrlPath) { printf("Sending request: %s", SendRequest.Buffer); } if (QUIC_FAILED( MsQuic->StreamSend( Stream, &SendRequest, 1, QUIC_SEND_FLAG_ALLOW_0_RTT | QUIC_SEND_FLAG_FIN, nullptr))) { MsQuic->StreamShutdown( Stream, QUIC_STREAM_SHUTDOWN_FLAG_ABORT | QUIC_STREAM_SHUTDOWN_FLAG_IMMEDIATE, 0); return false; } return !WaitForResponse || WaitForHttpResponse(); } bool WaitForHttpResponse() { return CxPlatEventWaitWithTimeout(RequestComplete, WaitTimeoutMs) && ReceivedResponse; } static _IRQL_requires_max_(DISPATCH_LEVEL) _Function_class_(QUIC_STREAM_CALLBACK) QUIC_STATUS QUIC_API StreamCallback( _In_ HQUIC Stream, _In_opt_ void* Context, _Inout_ QUIC_STREAM_EVENT* Event ) { InteropStream* pThis = (InteropStream*)Context; int64_t Now = CxPlatTimeMs64(); switch (Event->Type) { case QUIC_STREAM_EVENT_RECEIVE: if (CustomUrlPath) { if (pThis->File == nullptr) { pThis->DownloadStartTime = Now; pThis->FileName = strrchr(pThis->RequestPath, '/') + 1; pThis->File = fopen(pThis->FileName, "wb"); if (pThis->File == nullptr) { printf("Failed to open file %s\n", pThis->FileName); break; } } uint64_t TotalBytesWritten = 0; for (uint32_t i = 0; i < Event->RECEIVE.BufferCount; ++i) { uint32_t DataLength = Event->RECEIVE.Buffers[i].Length; if (fwrite( Event->RECEIVE.Buffers[i].Buffer, 1, DataLength, pThis->File) < DataLength) { printf("Failed to write to file!\n"); break; } TotalBytesWritten += DataLength; } int64_t ReceiveDuration = (int64_t)(pThis->LastReceiveTime == 0) ? 0 : CxPlatTimeDiff64(pThis->LastReceiveTime, Now); int64_t ReceiveTimeDiff = (int64_t)CxPlatTimeDiff64(pThis->LastReceiveDuration, ReceiveDuration); printf( "%s: Wrote %llu bytes.(%llu ms/%lld ms/%lld ms)\n", pThis->FileName, (unsigned long long)TotalBytesWritten, (unsigned long long)CxPlatTimeDiff64(pThis->DownloadStartTime, Now), (long long)ReceiveDuration, (long long)ReceiveTimeDiff); pThis->LastReceiveTime = Now; pThis->LastReceiveDuration = ReceiveDuration; } break; case QUIC_STREAM_EVENT_SEND_COMPLETE: break; case QUIC_STREAM_EVENT_PEER_SEND_ABORTED: if (CustomUrlPath) { printf("%s: Peer aborted send! (%llu ms)\n", pThis->FileName, (unsigned long long)CxPlatTimeDiff64(pThis->DownloadStartTime, Now)); } CxPlatEventSet(pThis->RequestComplete); break; case QUIC_STREAM_EVENT_PEER_SEND_SHUTDOWN: if (pThis->File) { fflush(pThis->File); fclose(pThis->File); pThis->File = nullptr; printf("%s: Completed download! (%llu ms)\n", pThis->FileName, (unsigned long long)CxPlatTimeDiff64(pThis->DownloadStartTime, Now)); } pThis->ReceivedResponse = true; break; case QUIC_STREAM_EVENT_SHUTDOWN_COMPLETE: { if (pThis->File) { printf("%s: Request closed incomplete. (%llu ms)\n", pThis->FileName, (unsigned long long)CxPlatTimeDiff64(pThis->DownloadStartTime, Now)); fclose(pThis->File); // Didn't get closed properly. pThis->File = nullptr; } uint64_t Length = 0; uint32_t LengthLength = sizeof(Length); if (QUIC_SUCCEEDED( MsQuic->GetParam( Stream, QUIC_PARAM_STREAM_0RTT_LENGTH, &LengthLength, &Length)) && Length > 0) { pThis->UsedZeroRtt = true; } CxPlatEventSet(pThis->RequestComplete); break; } default: break; } return QUIC_STATUS_SUCCESS; } }; class InteropConnection { HQUIC Configuration; HQUIC Connection; std::vector<InteropStream*> Streams; CXPLAT_EVENT ConnectionComplete; CXPLAT_EVENT RequestComplete; CXPLAT_EVENT QuackAckReceived; CXPLAT_EVENT ShutdownComplete; CXPLAT_EVENT TicketReceived; char* NegotiatedAlpn; const uint8_t* ResumptionTicket; uint32_t ResumptionTicketLength; QUIC_TLS_SECRETS TlsSecrets; const char* SslKeyLogFile; public: bool VersionUnsupported : 1; bool Connected : 1; bool Resumed : 1; bool ReceivedQuackAck : 1; InteropConnection(HQUIC Configuration, bool VerNeg = false, bool LargeTP = false) : Configuration(Configuration), Connection(nullptr), NegotiatedAlpn(nullptr), ResumptionTicket(nullptr), ResumptionTicketLength(0), TlsSecrets({}), SslKeyLogFile(SslKeyLogFileParam), VersionUnsupported(false), Connected(false), Resumed(false), ReceivedQuackAck(false) { CxPlatEventInitialize(&ConnectionComplete, TRUE, FALSE); CxPlatEventInitialize(&RequestComplete, TRUE, FALSE); CxPlatEventInitialize(&QuackAckReceived, TRUE, FALSE); CxPlatEventInitialize(&ShutdownComplete, TRUE, FALSE); CxPlatEventInitialize(&TicketReceived, TRUE, FALSE); VERIFY_QUIC_SUCCESS( MsQuic->ConnectionOpen( Registration, InteropConnection::ConnectionCallback, this, &Connection)); if (VerNeg) { uint32_t SupportedVersions[] = { RandomReservedVersion, 0x709a50c4U, 0x00000001U, 0xff00001dU }; QUIC_VERSION_SETTINGS Settings = { 0 }; Settings.AcceptableVersions = SupportedVersions; Settings.AcceptableVersionsLength = ARRAYSIZE(SupportedVersions); Settings.OfferedVersions = SupportedVersions; Settings.OfferedVersionsLength = ARRAYSIZE(SupportedVersions); Settings.FullyDeployedVersions = SupportedVersions; Settings.FullyDeployedVersionsLength = ARRAYSIZE(SupportedVersions); VERIFY_QUIC_SUCCESS( MsQuic->SetParam( Connection, QUIC_PARAM_CONN_VERSION_SETTINGS, sizeof(Settings), &Settings)); } else if (InitialVersion != 0) { uint32_t SupportedVersions[] = { InitialVersion, 0x709a50c4U, 0x00000001U, 0xff00001dU }; QUIC_VERSION_SETTINGS Settings = { 0 }; Settings.AcceptableVersions = SupportedVersions; Settings.AcceptableVersionsLength = ARRAYSIZE(SupportedVersions); Settings.OfferedVersions = SupportedVersions; Settings.OfferedVersionsLength = ARRAYSIZE(SupportedVersions); Settings.FullyDeployedVersions = SupportedVersions; Settings.FullyDeployedVersionsLength = ARRAYSIZE(SupportedVersions); VERIFY_QUIC_SUCCESS( MsQuic->SetParam( Connection, QUIC_PARAM_CONN_VERSION_SETTINGS, sizeof(Settings), &Settings)); } if (LargeTP) { VERIFY_QUIC_SUCCESS( MsQuic->SetParam( Connection, QUIC_PARAM_CONN_TEST_TRANSPORT_PARAMETER, sizeof(RandomTransportParameter), &RandomTransportParameter)); } if (SslKeyLogFile != nullptr) { QUIC_STATUS Status = MsQuic->SetParam( Connection, QUIC_PARAM_CONN_TLS_SECRETS, sizeof(TlsSecrets), (uint8_t*)&TlsSecrets); if (QUIC_FAILED(Status)) { SslKeyLogFile = nullptr; VERIFY_QUIC_SUCCESS(Status); } } } ~InteropConnection() { if (SslKeyLogFile != nullptr) { WriteSslKeyLogFile(SslKeyLogFile, TlsSecrets); } for (InteropStream* Stream : Streams) { delete Stream; } Streams.clear(); Shutdown(); MsQuic->ConnectionClose(Connection); CxPlatEventUninitialize(TicketReceived); CxPlatEventUninitialize(ShutdownComplete); CxPlatEventUninitialize(RequestComplete); CxPlatEventUninitialize(QuackAckReceived); CxPlatEventUninitialize(ConnectionComplete); delete [] NegotiatedAlpn; delete [] ResumptionTicket; } bool SetKeepAlive(uint32_t KeepAliveMs) { QUIC_SETTINGS Settings{0}; Settings.KeepAliveIntervalMs = KeepAliveMs; Settings.IsSet.KeepAliveIntervalMs = TRUE; return QUIC_SUCCEEDED( MsQuic->SetParam( Connection, QUIC_PARAM_CONN_SETTINGS, sizeof(Settings), &Settings)); } bool SetDisconnectTimeout(uint32_t TimeoutMs) { QUIC_SETTINGS Settings{0}; Settings.DisconnectTimeoutMs = TimeoutMs; Settings.IsSet.DisconnectTimeoutMs = TRUE; return QUIC_SUCCEEDED( MsQuic->SetParam( Connection, QUIC_PARAM_CONN_SETTINGS, sizeof(Settings), &Settings)); } bool SetResumptionTicket(const uint8_t* Ticket, uint32_t TicketLength) { return QUIC_SUCCEEDED( MsQuic->SetParam( Connection, QUIC_PARAM_CONN_RESUMPTION_TICKET, TicketLength, Ticket)); } bool ConnectToServer(const char* ServerName, uint16_t ServerPort) { if (QUIC_SUCCEEDED( MsQuic->ConnectionStart( Connection, Configuration, QUIC_ADDRESS_FAMILY_UNSPEC, ServerName, ServerPort))) { CxPlatEventWaitWithTimeout(ConnectionComplete, WaitTimeoutMs); } return Connected; } bool Shutdown() { MsQuic->ConnectionShutdown( Connection, QUIC_CONNECTION_SHUTDOWN_FLAG_NONE, Connected ? HTTP_NO_ERROR : HTTP_INTERNAL_ERROR); return WaitForShutdownComplete(); } bool WaitForShutdownComplete() { return CxPlatEventWaitWithTimeout(ShutdownComplete, WaitTimeoutMs); } bool SendHttpRequests(bool WaitForResponse = true) { for (auto& Url : Urls) { InteropStream* Stream = new InteropStream(Connection, Url.c_str()); Streams.push_back(Stream); if (!Stream->SendHttpRequest(WaitForResponse)) { return false; } } return !WaitForResponse || WaitForHttpResponses(); } bool WaitForHttpResponses() { bool Result = true; for (InteropStream* Stream : Streams) { Result &= Stream->WaitForHttpResponse(); } return Result; } bool SendQuack() { BOOLEAN DatagramEnabled = TRUE; VERIFY_QUIC_SUCCESS( MsQuic->SetParam( Connection, QUIC_PARAM_CONN_DATAGRAM_RECEIVE_ENABLED, sizeof(DatagramEnabled), &DatagramEnabled)); if (QUIC_FAILED( MsQuic->DatagramSend( Connection, &QuackBuffer, 1, QUIC_SEND_FLAG_NONE, nullptr))) { return false; } return true; } bool WaitForQuackAck() { return CxPlatEventWaitWithTimeout(QuackAckReceived, WaitTimeoutMs) && ReceivedQuackAck; } bool WaitForTicket() { return CxPlatEventWaitWithTimeout(TicketReceived, WaitTimeoutMs); } bool UsedZeroRtt() { bool Result = true; for (InteropStream* Stream : Streams) { Result &= Stream->UsedZeroRtt; } return Result; } bool ForceCidUpdate() { return QUIC_SUCCEEDED( MsQuic->SetParam( Connection, QUIC_PARAM_CONN_FORCE_CID_UPDATE, 0, nullptr)); } bool SimulateNatRebinding() { QUIC_ADDR LocalAddress = {0}; // Unspecified uint32_t LocalAddrSize = sizeof(LocalAddress); if (!QUIC_SUCCEEDED( MsQuic->GetParam( Connection, QUIC_PARAM_CONN_LOCAL_ADDRESS, &LocalAddrSize, &LocalAddress))) { return FALSE; } uint16_t PrevPort = QuicAddrGetPort(&LocalAddress); for (uint16_t i = 1236; i <= 1246; ++i) { QuicAddrSetPort(&LocalAddress, PrevPort + i); if (QUIC_SUCCEEDED( MsQuic->SetParam( Connection, QUIC_PARAM_CONN_LOCAL_ADDRESS, sizeof(LocalAddress), &LocalAddress))) { return TRUE; } } return FALSE; } bool GetQuicVersion(uint32_t& QuicVersion) { uint32_t Buffer = UINT32_MAX; uint32_t BufferLength = sizeof(Buffer); if (QUIC_SUCCEEDED( MsQuic->GetParam( Connection, QUIC_PARAM_CONN_QUIC_VERSION, &BufferLength, &Buffer)) && BufferLength == sizeof(Buffer) && Buffer != UINT32_MAX) { QuicVersion = Buffer; return true; } return false; } bool GetNegotiatedAlpn(const char* &Alpn) { if (NegotiatedAlpn == nullptr) return false; Alpn = strdup(NegotiatedAlpn); return true; } bool GetStatistics(QUIC_STATISTICS_V2& Stats) { uint32_t BufferLength = sizeof(Stats); if (QUIC_SUCCEEDED( MsQuic->GetParam( Connection, QUIC_PARAM_CONN_STATISTICS_V2, &BufferLength, &Stats)) && BufferLength == sizeof(Stats)) { return true; } return false; } bool GetResumptionTicket(const uint8_t*& Ticket, uint32_t& TicketLength) { if (!WaitForTicket() || ResumptionTicket == nullptr) { return false; } Ticket = ResumptionTicket; TicketLength = ResumptionTicketLength; ResumptionTicket = nullptr; return true; } private: static _IRQL_requires_max_(DISPATCH_LEVEL) _Function_class_(QUIC_CONNECTION_CALLBACK) QUIC_STATUS QUIC_API ConnectionCallback( _In_ HQUIC /* Connection */, _In_opt_ void* Context, _Inout_ QUIC_CONNECTION_EVENT* Event ) { InteropConnection* pThis = (InteropConnection*)Context; switch (Event->Type) { case QUIC_CONNECTION_EVENT_CONNECTED: pThis->Connected = true; pThis->NegotiatedAlpn = new char[Event->CONNECTED.NegotiatedAlpnLength + 1]; memcpy(pThis->NegotiatedAlpn, Event->CONNECTED.NegotiatedAlpn, Event->CONNECTED.NegotiatedAlpnLength); pThis->NegotiatedAlpn[Event->CONNECTED.NegotiatedAlpnLength] = 0; if (Event->CONNECTED.SessionResumed) { pThis->Resumed = true; } CxPlatEventSet(pThis->ConnectionComplete); break; case QUIC_CONNECTION_EVENT_SHUTDOWN_INITIATED_BY_TRANSPORT: if (Event->SHUTDOWN_INITIATED_BY_TRANSPORT.Status == QUIC_STATUS_VER_NEG_ERROR) { pThis->VersionUnsupported = TRUE; } __fallthrough; case QUIC_CONNECTION_EVENT_SHUTDOWN_INITIATED_BY_PEER: CxPlatEventSet(pThis->RequestComplete); CxPlatEventSet(pThis->QuackAckReceived); CxPlatEventSet(pThis->ConnectionComplete); break; case QUIC_CONNECTION_EVENT_SHUTDOWN_COMPLETE: CxPlatEventSet(pThis->RequestComplete); CxPlatEventSet(pThis->QuackAckReceived); CxPlatEventSet(pThis->ConnectionComplete); CxPlatEventSet(pThis->ShutdownComplete); break; case QUIC_CONNECTION_EVENT_PEER_STREAM_STARTED: MsQuic->SetCallbackHandler( Event->PEER_STREAM_STARTED.Stream, (void*)NoOpStreamCallback, pThis); break; case QUIC_CONNECTION_EVENT_DATAGRAM_RECEIVED: if (Event->DATAGRAM_RECEIVED.Buffer->Length == QuackAckBuffer.Length && !memcmp(Event->DATAGRAM_RECEIVED.Buffer->Buffer, QuackAckBuffer.Buffer, QuackAckBuffer.Length)) { pThis->ReceivedQuackAck = true; CxPlatEventSet(pThis->QuackAckReceived); } break; case QUIC_CONNECTION_EVENT_RESUMPTION_TICKET_RECEIVED: pThis->ResumptionTicketLength = Event->RESUMPTION_TICKET_RECEIVED.ResumptionTicketLength; pThis->ResumptionTicket = new uint8_t[pThis->ResumptionTicketLength]; memcpy( (uint8_t*)pThis->ResumptionTicket, Event->RESUMPTION_TICKET_RECEIVED.ResumptionTicket, Event->RESUMPTION_TICKET_RECEIVED.ResumptionTicketLength); CxPlatEventSet(pThis->TicketReceived); break; default: break; } return QUIC_STATUS_SUCCESS; } static _IRQL_requires_max_(DISPATCH_LEVEL) _Function_class_(QUIC_STREAM_CALLBACK) QUIC_STATUS QUIC_API NoOpStreamCallback( _In_ HQUIC Stream, _In_opt_ void* /* Context */, _Inout_ QUIC_STREAM_EVENT* Event ) { switch (Event->Type) { case QUIC_STREAM_EVENT_SHUTDOWN_COMPLETE: { MsQuic->StreamClose(Stream); break; default: break; } } return QUIC_STATUS_SUCCESS; } }; bool RunInteropTest( const QuicPublicEndpoint& Endpoint, uint16_t Port, QuicTestFeature Feature, uint32_t& QuicVersionUsed, const char* &NegotiatedAlpn ) { bool Success = false; QUIC_SETTINGS Settings{0}; Settings.PeerUnidiStreamCount = 3; Settings.IsSet.PeerUnidiStreamCount = TRUE; Settings.InitialRttMs = 50; // Be more aggressive with RTT for interop testing Settings.IsSet.InitialRttMs = TRUE; Settings.SendBufferingEnabled = FALSE; Settings.IsSet.SendBufferingEnabled = TRUE; Settings.IdleTimeoutMs = WaitTimeoutMs; Settings.IsSet.IdleTimeoutMs = TRUE; if (Feature == KeyUpdate) { Settings.MaxBytesPerKey = 10; // Force a key update after every 10 bytes sent Settings.IsSet.MaxBytesPerKey = TRUE; } const QUIC_BUFFER* Alpns; uint32_t AlpnCount; if (Feature & QuicTestFeatureDataPath) { Alpns = DatapathAlpns; AlpnCount = ARRAYSIZE(DatapathAlpns); } else if (Feature == Datagram) { Alpns = DatagramAlpns; AlpnCount = ARRAYSIZE(DatagramAlpns); } else { Alpns = HandshakeAlpns; AlpnCount = ARRAYSIZE(HandshakeAlpns); } HQUIC Configuration; VERIFY_QUIC_SUCCESS( MsQuic->ConfigurationOpen( Registration, Alpns, AlpnCount, &Settings, sizeof(Settings), nullptr, &Configuration)); QUIC_CREDENTIAL_CONFIG CredConfig; CxPlatZeroMemory(&CredConfig, sizeof(CredConfig)); CredConfig.Flags = QUIC_CREDENTIAL_FLAG_CLIENT | QUIC_CREDENTIAL_FLAG_NO_CERTIFICATE_VALIDATION; if (Feature == ChaCha20) { CredConfig.Flags |= QUIC_CREDENTIAL_FLAG_SET_ALLOWED_CIPHER_SUITES; CredConfig.AllowedCipherSuites = QUIC_ALLOWED_CIPHER_SUITE_CHACHA20_POLY1305_SHA256; } VERIFY_QUIC_SUCCESS( MsQuic->ConfigurationLoadCredential( Configuration, &CredConfig)); switch (Feature) { case VersionNegotiation: { InteropConnection Connection(Configuration, true); if (Connection.ConnectToServer(Endpoint.ServerName, Port)) { Connection.GetQuicVersion(QuicVersionUsed); Connection.GetNegotiatedAlpn(NegotiatedAlpn); QUIC_STATISTICS_V2 Stats; if (Connection.GetStatistics(Stats)) { Success = Stats.VersionNegotiation != 0; } if (Success && CustomUrlPath) { Success = Connection.SendHttpRequests(); } } else if (Connection.VersionUnsupported) { Success = Connection.VersionUnsupported; } break; } case Handshake: case ConnectionClose: case Resumption: case StatelessRetry: case PostQuantum: case ChaCha20: { const uint8_t* ResumptionTicket = nullptr; uint32_t ResumptionTicketLength = 0; if (Feature == Resumption) { InteropConnection Connection(Configuration); if (!Connection.ConnectToServer(Endpoint.ServerName, Port) || !Connection.WaitForTicket() || !Connection.GetResumptionTicket(ResumptionTicket, ResumptionTicketLength)) { break; } } InteropConnection Connection(Configuration, false, Feature == PostQuantum); if (Feature == Resumption) { Connection.SetResumptionTicket(ResumptionTicket, ResumptionTicketLength); } if (Connection.ConnectToServer(Endpoint.ServerName, Port)) { Connection.GetQuicVersion(QuicVersionUsed); Connection.GetNegotiatedAlpn(NegotiatedAlpn); if (Feature == StatelessRetry) { QUIC_STATISTICS_V2 Stats; if (Connection.GetStatistics(Stats)) { Success = Stats.StatelessRetry != 0; } } else if (Feature == ConnectionClose) { Success = Connection.Shutdown(); } else if (Feature == Resumption) { Success = Connection.Resumed; } else { Success = true; } if (Success && CustomUrlPath) { Success = Connection.SendHttpRequests(); } } delete [] ResumptionTicket; break; } case StreamData: case ZeroRtt: { const uint8_t* ResumptionTicket = nullptr; uint32_t ResumptionTicketLength = 0; if (Feature == ZeroRtt) { InteropConnection Connection(Configuration); if (!Connection.ConnectToServer(Endpoint.ServerName, Port) || !Connection.WaitForTicket() || !Connection.GetResumptionTicket(ResumptionTicket, ResumptionTicketLength)) { break; } } InteropConnection Connection(Configuration, false); if (Feature == ZeroRtt) { Connection.SetResumptionTicket(ResumptionTicket, ResumptionTicketLength); } if (Connection.SendHttpRequests(false) && Connection.ConnectToServer(Endpoint.ServerName, Port) && Connection.WaitForHttpResponses()) { Connection.GetQuicVersion(QuicVersionUsed); Connection.GetNegotiatedAlpn(NegotiatedAlpn); if (Feature == ZeroRtt) { Success = Connection.UsedZeroRtt(); } else { Success = true; } } delete [] ResumptionTicket; break; } case KeyUpdate: { InteropConnection Connection(Configuration); if (Connection.SetKeepAlive(50) && Connection.ConnectToServer(Endpoint.ServerName, Port)) { Connection.GetQuicVersion(QuicVersionUsed); Connection.GetNegotiatedAlpn(NegotiatedAlpn); CxPlatSleep(2000); // Allow keep alive packets to trigger key updates. QUIC_STATISTICS_V2 Stats; if (Connection.GetStatistics(Stats)) { Success = Stats.KeyUpdateCount > 1; } if (Success && CustomUrlPath) { Success = Connection.SendHttpRequests(); } } break; } case CidUpdate: { InteropConnection Connection(Configuration); if (Connection.ConnectToServer(Endpoint.ServerName, Port)) { Connection.GetQuicVersion(QuicVersionUsed); Connection.GetNegotiatedAlpn(NegotiatedAlpn); CxPlatSleep(250); if (Connection.SetDisconnectTimeout(1000) && Connection.ForceCidUpdate() && Connection.SetKeepAlive(50) && !Connection.WaitForShutdownComplete()) { Success = true; } if (Success && CustomUrlPath) { Success = Connection.SendHttpRequests(); } } break; } case NatRebinding: { InteropConnection Connection(Configuration); if (Connection.ConnectToServer(Endpoint.ServerName, Port)) { Connection.GetQuicVersion(QuicVersionUsed); Connection.GetNegotiatedAlpn(NegotiatedAlpn); CxPlatSleep(250); if (Connection.SetDisconnectTimeout(1000) && Connection.SimulateNatRebinding() && Connection.SetKeepAlive(50) && !Connection.WaitForShutdownComplete()) { Success = true; } if (Success && CustomUrlPath) { Success = Connection.SendHttpRequests(); } } break; } case Datagram: { InteropConnection Connection(Configuration, false); if (Connection.SendQuack() && Connection.ConnectToServer(Endpoint.ServerName, Port) && Connection.WaitForQuackAck()) { Connection.GetQuicVersion(QuicVersionUsed); Connection.GetNegotiatedAlpn(NegotiatedAlpn); Success = true; } } } MsQuic->ConfigurationClose(Configuration); // TODO - Wait on connection if (CustomUrlPath && !Success) { // // Delete any file we might have downloaded, because the test didn't // actually succeed. // for (auto& Url : Urls) { const char* FileName = strrchr(Url.c_str(), '/') + 1; (void)remove(FileName); } } return Success; } struct InteropTestContext { uint32_t EndpointIndex; uint16_t Port; QuicTestFeature Feature; }; CXPLAT_THREAD_CALLBACK(InteropTestCallback, Context) { auto TestContext = (InteropTestContext*)Context; QuicTraceLogInfo( InteropTestStart, "[ntrp] Test Start, Server: %s, Port: %hu, Tests: 0x%x.", PublicEndpoints[TestContext->EndpointIndex].ServerName, TestContext->Port, (uint32_t)TestContext->Feature); uint32_t QuicVersion = 0; const char* Alpn = nullptr; bool ThisTestFailed = false; if (RunInteropTest( PublicEndpoints[TestContext->EndpointIndex], TestContext->Port, TestContext->Feature, QuicVersion, Alpn)) { CxPlatLockAcquire(&TestResultsLock); TestResults[TestContext->EndpointIndex].Features |= TestContext->Feature; if (TestResults[TestContext->EndpointIndex].QuicVersion == 0) { TestResults[TestContext->EndpointIndex].QuicVersion = QuicVersion; } if (TestResults[TestContext->EndpointIndex].Alpn == nullptr) { TestResults[TestContext->EndpointIndex].Alpn = Alpn; } CxPlatLockRelease(&TestResultsLock); } else { TestFailed = true; ThisTestFailed = true; } QuicTraceLogInfo( InteropTestStop, "[ntrp] Test Stop, Server: %s, Port: %hu, Tests: 0x%x, Negotiated Alpn: %s, Passed: %s.", PublicEndpoints[TestContext->EndpointIndex].ServerName, TestContext->Port, (uint32_t)TestContext->Feature, Alpn, ThisTestFailed ? "false" : "true"); if (ThisTestFailed) { free((void*)Alpn); } delete TestContext; CXPLAT_THREAD_RETURN(0); } void StartTest( _In_ uint32_t EndpointIdx, _In_ uint16_t Port, _In_ QuicTestFeature Feature ) { auto TestContext = new InteropTestContext; TestContext->EndpointIndex = EndpointIdx; TestContext->Port = Port; TestContext->Feature = Feature; CXPLAT_THREAD_CONFIG ThreadConfig = { 0, 0, "QuicInterop", InteropTestCallback, TestContext }; VERIFY_QUIC_SUCCESS( CxPlatThreadCreate(&ThreadConfig, &Threads[CurrentThreadCount++])); if (RunSerially) { CxPlatThreadWait(&Threads[CurrentThreadCount-1]); } } void PrintTestResults( uint32_t Endpoint ) { char ResultCodes[] = QuicTestFeatureCodes; for (uint32_t i = 0; i < QuicTestFeatureCount; ++i) { if (!(TestResults[Endpoint].Features & (1 << i))) { ResultCodes[i] = '-'; } } if (TestResults[Endpoint].QuicVersion == 0) { printf("%12s %s\n", PublicEndpoints[Endpoint].ImplementationName, ResultCodes); } else { printf("%12s %s 0x%08X %s\n", PublicEndpoints[Endpoint].ImplementationName, ResultCodes, TestResults[Endpoint].QuicVersion, TestResults[Endpoint].Alpn); } } void RunInteropTests(int EndpointIndex) { const uint16_t* Ports = CustomPort == 0 ? PublicPorts : &CustomPort; const uint32_t PortsCount = CustomPort == 0 ? PublicPortsCount : 1; uint32_t StartTime = 0, StopTime = 0; StartTime = CxPlatTimeMs32(); for (uint32_t b = 0; b < PortsCount; ++b) { for (uint32_t c = 0; c < QuicTestFeatureCount; ++c) { if (TestCases & (1 << c)) { if (EndpointIndex == -1) { for (uint32_t d = 0; d < PublicEndpointsCount; ++d) { StartTest(d, Ports[b], (QuicTestFeature)(1 << c)); } } else { StartTest((uint32_t)EndpointIndex, Ports[b], (QuicTestFeature)(1 << c)); } } } } for (uint32_t i = 0; i < CurrentThreadCount; ++i) { CxPlatThreadWait(&Threads[i]); CxPlatThreadDelete(&Threads[i]); } StopTime = CxPlatTimeMs32(); printf("\n%12s %s %s %s\n", "TARGET", QuicTestFeatureCodes, "VERSION", "ALPN"); printf(" ============================================\n"); if (EndpointIndex == -1) { for (uint32_t i = 0; i < PublicEndpointsCount; ++i) { PrintTestResults(i); } } else { PrintTestResults((uint32_t)EndpointIndex); } printf("\n"); printf( "Total execution time: %u.%03us\n", (StopTime - StartTime) / 1000, (StopTime - StartTime) % 1000); printf("\n"); } bool ParseCommandLineUrls( _In_ int argc, _In_reads_(argc) _Null_terminated_ char* argv[] ) { bool ProcessingUrls = false; for (int i = 0; i < argc; ++i) { if (_strnicmp(argv[i] + 1, "urls", 4) == 0) { if (argv[i][1 + 4] != ':') { printf("Invalid URLs! First URL needs a : between the parameter name and it.\n"); return false; } CustomUrlPath = true; ProcessingUrls = true; argv[i] += 5; // Advance beyond the parameter name. } if (ProcessingUrls) { if (argv[i][0] == '-') { ProcessingUrls = false; continue; } const char* Url = argv[i]; for (int j = 0; j < 3; ++j) { Url = strchr(Url, '/'); if (Url == nullptr) { printf("Invalid URL provided! Must match 'http[s]://server[:port]/\n"); return false; } if (j < 2) { ++Url; } } Urls.push_back(Url); } } return true; } int QUIC_MAIN_EXPORT main( _In_ int argc, _In_reads_(argc) _Null_terminated_ char* argv[] ) { int EndpointIndex = -1; if (GetFlag(argc, argv, "help") || GetFlag(argc, argv, "?")) { PrintUsage(); return 0; } if (GetFlag(argc, argv, "list")) { printf("\nKnown implementations and servers:\n"); for (uint32_t i = 0; i < PublicEndpointsCount; ++i) { printf(" %12s\t%s\n", PublicEndpoints[i].ImplementationName, PublicEndpoints[i].ServerName); } return 0; } const char* TestCaseStr = GetValue(argc, argv, "test"); if (TestCaseStr) { TestCases = 0; const uint32_t Len = (uint32_t)strlen(TestCaseStr); for (uint32_t i = 0; i < QuicTestFeatureCount; ++i) { for (uint32_t j = 0; j < Len; ++j) { if (QuicTestFeatureCodes[i] == TestCaseStr[j]) { TestCases |= (1 << i); } } } if (TestCases == 0) { TestCases = QuicTestFeatureAll & (uint32_t)atoi(TestCaseStr); if (TestCases == 0) { printf("Invalid test cases!\n"); return 0; } } } RunSerially = GetFlag(argc, argv, "serial"); CxPlatSystemLoad(); QUIC_STATUS Status; const QUIC_REGISTRATION_CONFIG RegConfig = { "quicinterop", QUIC_EXECUTION_PROFILE_LOW_LATENCY }; if (QUIC_FAILED(Status = CxPlatInitialize())) { printf("CxPlatInitialize failed, 0x%x!\n", Status); CxPlatSystemUnload(); return Status; } CxPlatLockInitialize(&TestResultsLock); if (QUIC_FAILED(Status = MsQuicOpen2(&MsQuic))) { printf("MsQuicOpen2 failed, 0x%x!\n", Status); goto Error; } if (QUIC_FAILED(Status = MsQuic->RegistrationOpen(&RegConfig, &Registration))) { printf("RegistrationOpen failed, 0x%x!\n", Status); goto Error; } TryGetValue(argc, argv, "timeout", &WaitTimeoutMs); TryGetValue(argc, argv, "version", &InitialVersion); TryGetValue(argc, argv, "port", &CustomPort); if (!ParseCommandLineUrls(argc, argv)) { Status = QUIC_STATUS_INVALID_PARAMETER; goto Error; } if (!CustomUrlPath) { Urls.push_back("/"); } TryGetValue(argc, argv, "sslkeylogfile", &SslKeyLogFileParam); const char* Target, *Custom; if (TryGetValue(argc, argv, "target", &Target)) { bool Found = false; for (uint32_t i = 0; i < PublicEndpointsCount; ++i) { if (strcmp(Target, PublicEndpoints[i].ImplementationName) == 0) { EndpointIndex = (int)i; Found = true; break; } } if (!Found) { printf("Unknown implementation '%s'\n", Target); goto Error; } } else if (TryGetValue(argc, argv, "custom", &Custom)) { PublicEndpoints[PublicEndpointsCount].ImplementationName = Custom; PublicEndpoints[PublicEndpointsCount].ServerName = Custom; EndpointIndex = (int)PublicEndpointsCount; } RunInteropTests(EndpointIndex); if (CustomUrlPath && TestFailed) { Status = QUIC_STATUS_ABORTED; } Error: if (MsQuic != nullptr) { if (Registration != nullptr) { MsQuic->RegistrationClose(Registration); } MsQuicClose(MsQuic); } CxPlatLockUninitialize(&TestResultsLock); CxPlatUninitialize(); CxPlatSystemUnload(); return (int)Status; }
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.16.27026.1 TITLE Z:\Sources\Lunor\Repos\rougemeilland\Palmtree.Math.Core.Sint\Palmtree.Math.Core.Sint\TEST_op_Clone.c .686P .XMM include listing.inc .model flat INCLUDELIB MSVCRTD INCLUDELIB OLDNAMES _DATA SEGMENT COMM _uint_number_zero:DWORD COMM _uint_number_one:DWORD _DATA ENDS msvcjmc SEGMENT __7B7A869E_ctype@h DB 01H __457DD326_basetsd@h DB 01H __4384A2D9_corecrt_memcpy_s@h DB 01H __4E51A221_corecrt_wstring@h DB 01H __2140C079_string@h DB 01H __1887E595_winnt@h DB 01H __9FC7C64B_processthreadsapi@h DB 01H __FA470AEC_memoryapi@h DB 01H __F37DAFF1_winerror@h DB 01H __7A450CCC_winbase@h DB 01H __B4B40122_winioctl@h DB 01H __86261D59_stralign@h DB 01H __059414E1_pmc_sint_debug@h DB 01H __07425A21_test_op_clone@c DB 01H msvcjmc ENDS PUBLIC _TEST_Clone_X PUBLIC __JustMyCode_Default PUBLIC ??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ ; `string' PUBLIC ??_C@_1CA@CLLGGBHI@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4?$AA?$CF?$AAd?$AA?$CJ@ ; `string' PUBLIC ??_C@_1DG@CCIPFPD@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM?$PP?I?$AAL?$AA?$BP@ ; `string' PUBLIC ??_C@_1DO@DOHJEMND@?$AAT?$AAo?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ?$AA0?$PP?$LD@ ; `string' PUBLIC ??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ ; `string' EXTRN _TEST_Assert:PROC EXTRN _FormatTestLabel:PROC EXTRN _FormatTestMesssage:PROC EXTRN @_RTC_CheckStackVars@8:PROC EXTRN @__CheckForDebuggerJustMyCode@4:PROC EXTRN @__security_check_cookie@4:PROC EXTRN __RTC_CheckEsp:PROC EXTRN __RTC_InitBase:PROC EXTRN __RTC_Shutdown:PROC EXTRN ___security_cookie:DWORD ; COMDAT rtc$TMZ rtc$TMZ SEGMENT __RTC_Shutdown.rtc$TMZ DD FLAT:__RTC_Shutdown rtc$TMZ ENDS ; COMDAT rtc$IMZ rtc$IMZ SEGMENT __RTC_InitBase.rtc$IMZ DD FLAT:__RTC_InitBase rtc$IMZ ENDS ; COMDAT ??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ CONST SEGMENT ??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ DB 0c7H DB '0', 0fcH, '0', 0bfH, '0n0', 085H, 'Q', 0b9H, '[L0', 00H, 'N', 0f4H DB 081H, 'W0j0D0', 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1DO@DOHJEMND@?$AAT?$AAo?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ?$AA0?$PP?$LD@ CONST SEGMENT ??_C@_1DO@DOHJEMND@?$AAT?$AAo?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ?$AA0?$PP?$LD@ DB 'T' DB 00H, 'o', 00H, 'B', 00H, 'y', 00H, 't', 00H, 'e', 00H, 'A', 00H DB 'r', 00H, 'r', 00H, 'a', 00H, 'y', 00H, 'n0', 0a9H, '_0^', 0b3H DB '0', 0fcH, '0', 0c9H, '0L0', 01fH, 'g', 085H, '_', 01aH, 090H, 08aH DB '0g0o0j0D0(', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1DG@CCIPFPD@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM?$PP?I?$AAL?$AA?$BP@ CONST SEGMENT ??_C@_1DG@CCIPFPD@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM?$PP?I?$AAL?$AA?$BP@ DB 'C' DB 00H, 'l', 00H, 'o', 00H, 'n', 00H, 'e', 00H, '_', 00H, 'X', 00H DB 'n0', 0a9H, '_0^', 0b3H, '0', 0fcH, '0', 0c9H, '0L0', 01fH, 'g' DB 085H, '_', 01aH, 090H, 08aH, '0g0o0j0D0(', 00H, '%', 00H, 'd', 00H DB ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1CA@CLLGGBHI@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4?$AA?$CF?$AAd?$AA?$CJ@ CONST SEGMENT ??_C@_1CA@CLLGGBHI@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4?$AA?$CF?$AAd?$AA?$CJ@ DB 'C' DB 00H, 'l', 00H, 'o', 00H, 'n', 00H, 'e', 00H, '_', 00H, 'X', 00H DB ' ', 00H, '(', 00H, '%', 00H, 'd', 00H, '.', 00H, '%', 00H, 'd' DB 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ CONST SEGMENT ??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ DB 'F' DB 00H, 'r', 00H, 'o', 00H, 'm', 00H, 'B', 00H, 'y', 00H, 't', 00H DB 'e', 00H, 'A', 00H, 'r', 00H, 'r', 00H, 'a', 00H, 'y', 00H, 'n' DB '0', 0a9H, '_0^', 0b3H, '0', 0fcH, '0', 0c9H, '0L0', 01fH, 'g', 085H DB '_', 01aH, 090H, 08aH, '0g0o0j0D0(', 00H, '%', 00H, 'd', 00H, ')' DB 00H, 00H, 00H ; `string' CONST ENDS ; Function compile flags: /Odt ; COMDAT __JustMyCode_Default _TEXT SEGMENT __JustMyCode_Default PROC ; COMDAT push ebp mov ebp, esp pop ebp ret 0 __JustMyCode_Default ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu /ZI ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.sint\palmtree.math.core.sint\pmc_sint_debug.h ; COMDAT __EQUALS_MEMORY _TEXT SEGMENT _buffer1$ = 8 ; size = 4 _count1$ = 12 ; size = 4 _buffer2$ = 16 ; size = 4 _count2$ = 20 ; size = 4 __EQUALS_MEMORY PROC ; COMDAT ; 140 : { push ebp mov ebp, esp sub esp, 192 ; 000000c0H push ebx push esi push edi lea edi, DWORD PTR [ebp-192] mov ecx, 48 ; 00000030H mov eax, -858993460 ; ccccccccH rep stosd mov ecx, OFFSET __059414E1_pmc_sint_debug@h call @__CheckForDebuggerJustMyCode@4 ; 141 : if (count1 != count2) mov eax, DWORD PTR _count1$[ebp] cmp eax, DWORD PTR _count2$[ebp] je SHORT $LN2@EQUALS_MEM ; 142 : return (-1); or eax, -1 jmp SHORT $LN1@EQUALS_MEM $LN2@EQUALS_MEM: ; 143 : while (count1 > 0) cmp DWORD PTR _count1$[ebp], 0 jbe SHORT $LN3@EQUALS_MEM ; 144 : { ; 145 : if (*buffer1 != *buffer2) mov eax, DWORD PTR _buffer1$[ebp] movzx ecx, BYTE PTR [eax] mov edx, DWORD PTR _buffer2$[ebp] movzx eax, BYTE PTR [edx] cmp ecx, eax je SHORT $LN5@EQUALS_MEM ; 146 : return (-1); or eax, -1 jmp SHORT $LN1@EQUALS_MEM $LN5@EQUALS_MEM: ; 147 : ++buffer1; mov eax, DWORD PTR _buffer1$[ebp] add eax, 1 mov DWORD PTR _buffer1$[ebp], eax ; 148 : ++buffer2; mov eax, DWORD PTR _buffer2$[ebp] add eax, 1 mov DWORD PTR _buffer2$[ebp], eax ; 149 : --count1; mov eax, DWORD PTR _count1$[ebp] sub eax, 1 mov DWORD PTR _count1$[ebp], eax ; 150 : } jmp SHORT $LN2@EQUALS_MEM $LN3@EQUALS_MEM: ; 151 : return (0); xor eax, eax $LN1@EQUALS_MEM: ; 152 : } pop edi pop esi pop ebx add esp, 192 ; 000000c0H cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 0 __EQUALS_MEMORY ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu /ZI ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.sint\palmtree.math.core.sint\test_op_clone.c ; COMDAT _TEST_Clone_X _TEXT SEGMENT tv157 = -536 ; size = 4 tv142 = -536 ; size = 4 tv91 = -536 ; size = 4 tv74 = -536 ; size = 4 _o_result$ = -336 ; size = 4 _x_result$ = -324 ; size = 4 _result$ = -312 ; size = 4 _actual_o_buf_size$ = -300 ; size = 4 _actual_o_buf$ = -288 ; size = 256 _o$ = -24 ; size = 4 _x$ = -12 ; size = 4 __$ArrayPad$ = -4 ; size = 4 _env$ = 8 ; size = 4 _ep$ = 12 ; size = 4 _no$ = 16 ; size = 4 _x_buf$ = 20 ; size = 4 _x_buf_size$ = 24 ; size = 4 _desired_o_buf$ = 28 ; size = 4 _desired_o_buf_size$ = 32 ; size = 4 _TEST_Clone_X PROC ; COMDAT ; 32 : { push ebp mov ebp, esp sub esp, 536 ; 00000218H push ebx push esi push edi lea edi, DWORD PTR [ebp-536] mov ecx, 134 ; 00000086H mov eax, -858993460 ; ccccccccH rep stosd mov eax, DWORD PTR ___security_cookie xor eax, ebp mov DWORD PTR __$ArrayPad$[ebp], eax mov ecx, OFFSET __07425A21_test_op_clone@c call @__CheckForDebuggerJustMyCode@4 ; 33 : PMC_HANDLE_SINT x; ; 34 : PMC_HANDLE_SINT o; ; 35 : unsigned char actual_o_buf[256]; ; 36 : size_t actual_o_buf_size; ; 37 : PMC_STATUS_CODE result; ; 38 : PMC_STATUS_CODE x_result; ; 39 : PMC_STATUS_CODE o_result; ; 40 : TEST_Assert(env, FormatTestLabel(L"Clone_X (%d.%d)", no, 1), (x_result = ep->FromByteArray(x_buf, x_buf_size, &x)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", x_result)); mov esi, esp lea eax, DWORD PTR _x$[ebp] push eax mov ecx, DWORD PTR _x_buf_size$[ebp] push ecx mov edx, DWORD PTR _x_buf$[ebp] push edx mov eax, DWORD PTR _ep$[ebp] mov ecx, DWORD PTR [eax+304] call ecx cmp esi, esp call __RTC_CheckEsp mov DWORD PTR _x_result$[ebp], eax cmp DWORD PTR _x_result$[ebp], 0 jne SHORT $LN5@TEST_Clone mov DWORD PTR tv74[ebp], 1 jmp SHORT $LN6@TEST_Clone $LN5@TEST_Clone: mov DWORD PTR tv74[ebp], 0 $LN6@TEST_Clone: mov edx, DWORD PTR _x_result$[ebp] push edx push OFFSET ??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call _FormatTestMesssage add esp, 8 push eax mov eax, DWORD PTR tv74[ebp] push eax push 1 mov ecx, DWORD PTR _no$[ebp] push ecx push OFFSET ??_C@_1CA@CLLGGBHI@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4?$AA?$CF?$AAd?$AA?$CJ@ call _FormatTestLabel add esp, 12 ; 0000000cH push eax mov edx, DWORD PTR _env$[ebp] push edx call _TEST_Assert add esp, 16 ; 00000010H ; 41 : TEST_Assert(env, FormatTestLabel(L"Clone_X (%d.%d)", no, 2), (o_result = ep->Clone_X(x, &o)) == PMC_STATUS_OK, FormatTestMesssage(L"Clone_Xの復帰コードが期待通りではない(%d)", o_result)); mov esi, esp lea eax, DWORD PTR _o$[ebp] push eax mov ecx, DWORD PTR _x$[ebp] push ecx mov edx, DWORD PTR _ep$[ebp] mov eax, DWORD PTR [edx+312] call eax cmp esi, esp call __RTC_CheckEsp mov DWORD PTR _o_result$[ebp], eax cmp DWORD PTR _o_result$[ebp], 0 jne SHORT $LN7@TEST_Clone mov DWORD PTR tv91[ebp], 1 jmp SHORT $LN8@TEST_Clone $LN7@TEST_Clone: mov DWORD PTR tv91[ebp], 0 $LN8@TEST_Clone: mov ecx, DWORD PTR _o_result$[ebp] push ecx push OFFSET ??_C@_1DG@CCIPFPD@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM?$PP?I?$AAL?$AA?$BP@ call _FormatTestMesssage add esp, 8 push eax mov edx, DWORD PTR tv91[ebp] push edx push 2 mov eax, DWORD PTR _no$[ebp] push eax push OFFSET ??_C@_1CA@CLLGGBHI@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4?$AA?$CF?$AAd?$AA?$CJ@ call _FormatTestLabel add esp, 12 ; 0000000cH push eax mov ecx, DWORD PTR _env$[ebp] push ecx call _TEST_Assert add esp, 16 ; 00000010H ; 42 : TEST_Assert(env, FormatTestLabel(L"Clone_X (%d.%d)", no, 3), (result = ep->ToByteArray(o, actual_o_buf, sizeof(actual_o_buf), &actual_o_buf_size)) == PMC_STATUS_OK, FormatTestMesssage(L"ToByteArrayの復帰コードが期待通りではない(%d)", result)); mov esi, esp lea eax, DWORD PTR _actual_o_buf_size$[ebp] push eax push 256 ; 00000100H lea ecx, DWORD PTR _actual_o_buf$[ebp] push ecx mov edx, DWORD PTR _o$[ebp] push edx mov eax, DWORD PTR _ep$[ebp] mov ecx, DWORD PTR [eax+308] call ecx cmp esi, esp call __RTC_CheckEsp mov DWORD PTR _result$[ebp], eax cmp DWORD PTR _result$[ebp], 0 jne SHORT $LN9@TEST_Clone mov DWORD PTR tv142[ebp], 1 jmp SHORT $LN10@TEST_Clone $LN9@TEST_Clone: mov DWORD PTR tv142[ebp], 0 $LN10@TEST_Clone: mov edx, DWORD PTR _result$[ebp] push edx push OFFSET ??_C@_1DO@DOHJEMND@?$AAT?$AAo?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ?$AA0?$PP?$LD@ call _FormatTestMesssage add esp, 8 push eax mov eax, DWORD PTR tv142[ebp] push eax push 3 mov ecx, DWORD PTR _no$[ebp] push ecx push OFFSET ??_C@_1CA@CLLGGBHI@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4?$AA?$CF?$AAd?$AA?$CJ@ call _FormatTestLabel add esp, 12 ; 0000000cH push eax mov edx, DWORD PTR _env$[ebp] push edx call _TEST_Assert add esp, 16 ; 00000010H ; 43 : TEST_Assert(env, FormatTestLabel(L"Clone_X (%d.%d)", no, 4), _EQUALS_MEMORY(actual_o_buf, actual_o_buf_size, desired_o_buf, desired_o_buf_size) == 0, L"データの内容が一致しない"); mov eax, DWORD PTR _desired_o_buf_size$[ebp] push eax mov ecx, DWORD PTR _desired_o_buf$[ebp] push ecx mov edx, DWORD PTR _actual_o_buf_size$[ebp] push edx lea eax, DWORD PTR _actual_o_buf$[ebp] push eax call __EQUALS_MEMORY add esp, 16 ; 00000010H test eax, eax jne SHORT $LN11@TEST_Clone mov DWORD PTR tv157[ebp], 1 jmp SHORT $LN12@TEST_Clone $LN11@TEST_Clone: mov DWORD PTR tv157[ebp], 0 $LN12@TEST_Clone: push OFFSET ??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ mov ecx, DWORD PTR tv157[ebp] push ecx push 4 mov edx, DWORD PTR _no$[ebp] push edx push OFFSET ??_C@_1CA@CLLGGBHI@?$AAC?$AAl?$AAo?$AAn?$AAe?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4?$AA?$CF?$AAd?$AA?$CJ@ call _FormatTestLabel add esp, 12 ; 0000000cH push eax mov eax, DWORD PTR _env$[ebp] push eax call _TEST_Assert add esp, 16 ; 00000010H ; 44 : if (o_result == PMC_STATUS_OK) cmp DWORD PTR _o_result$[ebp], 0 jne SHORT $LN2@TEST_Clone ; 45 : ep->Dispose(o); mov esi, esp mov eax, DWORD PTR _o$[ebp] push eax mov ecx, DWORD PTR _ep$[ebp] mov edx, DWORD PTR [ecx+296] call edx cmp esi, esp call __RTC_CheckEsp $LN2@TEST_Clone: ; 46 : if (x_result == PMC_STATUS_OK) cmp DWORD PTR _x_result$[ebp], 0 jne SHORT $LN1@TEST_Clone ; 47 : ep->Dispose(x); mov esi, esp mov eax, DWORD PTR _x$[ebp] push eax mov ecx, DWORD PTR _ep$[ebp] mov edx, DWORD PTR [ecx+296] call edx cmp esi, esp call __RTC_CheckEsp $LN1@TEST_Clone: ; 48 : } push edx mov ecx, ebp push eax lea edx, DWORD PTR $LN18@TEST_Clone call @_RTC_CheckStackVars@8 pop eax pop edx pop edi pop esi pop ebx mov ecx, DWORD PTR __$ArrayPad$[ebp] xor ecx, ebp call @__security_check_cookie@4 add esp, 536 ; 00000218H cmp ebp, esp call __RTC_CheckEsp mov esp, ebp pop ebp ret 0 npad 3 $LN18@TEST_Clone: DD 4 DD $LN17@TEST_Clone $LN17@TEST_Clone: DD -12 ; fffffff4H DD 4 DD $LN13@TEST_Clone DD -24 ; ffffffe8H DD 4 DD $LN14@TEST_Clone DD -288 ; fffffee0H DD 256 ; 00000100H DD $LN15@TEST_Clone DD -300 ; fffffed4H DD 4 DD $LN16@TEST_Clone $LN16@TEST_Clone: DB 97 ; 00000061H DB 99 ; 00000063H DB 116 ; 00000074H DB 117 ; 00000075H DB 97 ; 00000061H DB 108 ; 0000006cH DB 95 ; 0000005fH DB 111 ; 0000006fH DB 95 ; 0000005fH DB 98 ; 00000062H DB 117 ; 00000075H DB 102 ; 00000066H DB 95 ; 0000005fH DB 115 ; 00000073H DB 105 ; 00000069H DB 122 ; 0000007aH DB 101 ; 00000065H DB 0 $LN15@TEST_Clone: DB 97 ; 00000061H DB 99 ; 00000063H DB 116 ; 00000074H DB 117 ; 00000075H DB 97 ; 00000061H DB 108 ; 0000006cH DB 95 ; 0000005fH DB 111 ; 0000006fH DB 95 ; 0000005fH DB 98 ; 00000062H DB 117 ; 00000075H DB 102 ; 00000066H DB 0 $LN14@TEST_Clone: DB 111 ; 0000006fH DB 0 $LN13@TEST_Clone: DB 120 ; 00000078H DB 0 _TEST_Clone_X ENDP _TEXT ENDS END
/* SPDX-License-Identifier: BSD-2-Clause */ /* * Copyright (C) 2020, Raspberry Pi (Trading) Ltd. * * h264_encoder.cpp - h264 video encoder. */ #include <fcntl.h> #include <poll.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <linux/videodev2.h> #include <chrono> #include <iostream> #include "h264_encoder.hpp" static int xioctl(int fd, int ctl, void *arg) { int ret, num_tries = 10; do { ret = ioctl(fd, ctl, arg); } while (ret == -1 && errno == EINTR && num_tries-- > 0); return ret; } H264Encoder::H264Encoder(VideoOptions const &options) : Encoder(options), abort_(false) { // First open the encoder device. Maybe we should double-check its "caps". const char device_name[] = "/dev/video11"; fd_ = open(device_name, O_RDWR, 0); if (fd_ < 0) throw std::runtime_error("failed to open V4L2 H264 encoder"); if (options.verbose) std::cout << "Opened H264Encoder on " << device_name << " as fd " << fd_ << std::endl; // Apply any options. v4l2_control ctrl = {}; if (options.bitrate) { ctrl.id = V4L2_CID_MPEG_VIDEO_BITRATE; ctrl.value = options.bitrate; if (xioctl(fd_, VIDIOC_S_CTRL, &ctrl) < 0) throw std::runtime_error("failed to set bitrate"); } if (!options.profile.empty()) { static const std::map<std::string, int> profile_map = { { "baseline", V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE }, { "main", V4L2_MPEG_VIDEO_H264_PROFILE_MAIN }, { "high", V4L2_MPEG_VIDEO_H264_PROFILE_HIGH } }; auto it = profile_map.find(options.profile); if (it == profile_map.end()) throw std::runtime_error("no such profile " + options.profile); ctrl.id = V4L2_CID_MPEG_VIDEO_H264_PROFILE; ctrl.value = it->second; if (xioctl(fd_, VIDIOC_S_CTRL, &ctrl) < 0) throw std::runtime_error("failed to set profile"); } if (!options.level.empty()) { static const std::map<std::string, int> level_map = { { "4", V4L2_MPEG_VIDEO_H264_LEVEL_4_0 }, { "4.1", V4L2_MPEG_VIDEO_H264_LEVEL_4_1 }, { "4.2", V4L2_MPEG_VIDEO_H264_LEVEL_4_2 } }; auto it = level_map.find(options.level); if (it == level_map.end()) throw std::runtime_error("no such level " + options.level); ctrl.id = V4L2_CID_MPEG_VIDEO_H264_LEVEL; ctrl.value = it->second; if (xioctl(fd_, VIDIOC_S_CTRL, &ctrl) < 0) throw std::runtime_error("failed to set level"); } if (options.intra) { ctrl.id = V4L2_CID_MPEG_VIDEO_H264_I_PERIOD; ctrl.value = options.intra; if (xioctl(fd_, VIDIOC_S_CTRL, &ctrl) < 0) throw std::runtime_error("failed to set intra period"); } if (options.inline_headers) { ctrl.id = V4L2_CID_MPEG_VIDEO_REPEAT_SEQ_HEADER; ctrl.value = 1; if (xioctl(fd_, VIDIOC_S_CTRL, &ctrl) < 0) throw std::runtime_error("failed to set inline headers"); } // Set the output and capture formats. We know exactly what they will be. v4l2_format fmt = {}; fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; fmt.fmt.pix_mp.width = options.width; fmt.fmt.pix_mp.height = options.height; fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_YUV420; fmt.fmt.pix_mp.field = V4L2_FIELD_ANY; // libcamera currently has no means to request the right colour space, hence: fmt.fmt.pix_mp.colorspace = V4L2_COLORSPACE_JPEG; fmt.fmt.pix_mp.num_planes = 1; fmt.fmt.pix_mp.plane_fmt[0].bytesperline = ((options.width + 31) & ~31); fmt.fmt.pix_mp.plane_fmt[0].sizeimage = fmt.fmt.pix_mp.plane_fmt[0].bytesperline * fmt.fmt.pix_mp.height * 3 / 2; if (xioctl(fd_, VIDIOC_S_FMT, &fmt) < 0) throw std::runtime_error("failed to set output format"); fmt = {}; fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; fmt.fmt.pix_mp.width = options.width; fmt.fmt.pix_mp.height = options.height; fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_H264; fmt.fmt.pix_mp.field = V4L2_FIELD_ANY; fmt.fmt.pix_mp.colorspace = V4L2_COLORSPACE_DEFAULT; fmt.fmt.pix_mp.num_planes = 1; fmt.fmt.pix_mp.plane_fmt[0].bytesperline = 0; fmt.fmt.pix_mp.plane_fmt[0].sizeimage = 512<<10; if (xioctl(fd_, VIDIOC_S_FMT, &fmt) < 0) throw std::runtime_error("failed to set capture format"); // Request that the necessary buffers are allocated. The output queue // (input to the encoder) shares buffers from our caller, these must be // DMABUFs. Buffers for the encoded bitstream must be allocated and // m-mapped. v4l2_requestbuffers reqbufs = {}; reqbufs.count = NUM_OUTPUT_BUFFERS; reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; reqbufs.memory = V4L2_MEMORY_DMABUF; if (xioctl(fd_, VIDIOC_REQBUFS, &reqbufs) < 0) throw std::runtime_error("request for output buffers failed"); if (options.verbose) std::cout << "Got " << reqbufs.count << " output buffers" << std::endl; // We have to maintain a list of the buffers we can use when our caller gives // us another frame to encode. for (int i = 0; i < reqbufs.count; i++) input_buffers_available_.push(i); reqbufs = {}; reqbufs.count = NUM_CAPTURE_BUFFERS; reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; reqbufs.memory = V4L2_MEMORY_MMAP; if (xioctl(fd_, VIDIOC_REQBUFS, &reqbufs) < 0) throw std::runtime_error("request for capture buffers failed"); if (options.verbose) std::cout << "Got " << reqbufs.count << " capture buffers" << std::endl; for (int i = 0; i < reqbufs.count; i++) { v4l2_plane planes[VIDEO_MAX_PLANES]; v4l2_buffer buffer = {}; buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; buffer.memory = V4L2_MEMORY_MMAP; buffer.index = i; buffer.length = 1; buffer.m.planes = planes; if (xioctl(fd_, VIDIOC_QUERYBUF, &buffer) < 0) throw std::runtime_error("failed to capture query buffer " + std::to_string(i)); buffers_[i].mem = mmap(0, buffer.m.planes[0].length, PROT_READ|PROT_WRITE, MAP_SHARED, fd_, buffer.m.planes[0].m.mem_offset); if (buffers_[i].mem == MAP_FAILED) throw std::runtime_error("failed to mmap capture buffer " + std::to_string(i)); buffers_[i].size = buffer.m.planes[0].length; // Whilst we're going through all the capture buffers, we may as well queue // them ready for the encoder to write into. if (xioctl(fd_, VIDIOC_QBUF, &buffer) < 0) throw std::runtime_error("failed to queue capture buffer " + std::to_string(i)); } // Enable streaming and we're done. v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; if (xioctl(fd_, VIDIOC_STREAMON, &type) < 0) throw std::runtime_error("failed to start output streaming"); type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; if (xioctl(fd_, VIDIOC_STREAMON, &type) < 0) throw std::runtime_error("failed to start capture streaming"); if (options.verbose) std::cout << "Codec streaming started" << std::endl; output_thread_ = std::thread(&H264Encoder::outputThread, this); poll_thread_ = std::thread(&H264Encoder::pollThread, this); } H264Encoder::~H264Encoder() { abort_ = true; output_thread_.join(); poll_thread_.join(); if (options_.verbose) std::cout << "H264Encoder closed" << std::endl; // Other stuff will mostly get hoovered up with the process quits. } int H264Encoder::EncodeBuffer(int fd, size_t size, void *mem, int width, int height, int stride, int64_t timestamp_us) { int index; { // We need to find an available output buffer (input to the codec) to // "wrap" the DMABUF. std::lock_guard<std::mutex> lock(input_buffers_available_mutex_); if (input_buffers_available_.empty()) throw std::runtime_error("no buffers available to queue codec input"); index = input_buffers_available_.front(); input_buffers_available_.pop(); } v4l2_buffer buf = {}; v4l2_plane planes[VIDEO_MAX_PLANES] = {}; buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; buf.index = index; buf.field = V4L2_FIELD_NONE; buf.memory = V4L2_MEMORY_DMABUF; buf.length = 1; buf.timestamp.tv_sec = timestamp_us / 1000000; buf.timestamp.tv_usec = timestamp_us % 1000000; buf.m.planes = planes; buf.m.planes[0].m.fd = fd; buf.m.planes[0].bytesused = size; buf.m.planes[0].length = size; if (xioctl(fd_, VIDIOC_QBUF, &buf) < 0) throw std::runtime_error("failed to queue input to codec"); return index; } void H264Encoder::pollThread() { while (true) { pollfd p = { fd_, POLLIN }; int ret = poll(&p, 1, 200); if (abort_) break; if (ret == -1) { if (errno == EINTR) continue; throw std::runtime_error("unexpected errno " + std::to_string(errno) + " from poll"); } if (p.revents & POLLIN) { v4l2_buffer buf = {}; v4l2_plane planes[VIDEO_MAX_PLANES] = {}; buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; buf.memory = V4L2_MEMORY_DMABUF; buf.length = 1; buf.m.planes = planes; int ret = xioctl(fd_, VIDIOC_DQBUF, &buf); if (ret == 0) { // Return this to the caller, first noting that this buffer, identified // by its index, is available for queueing up another frame. std::lock_guard<std::mutex> lock(input_buffers_available_mutex_); input_buffers_available_.push(buf.index); input_done_callback_(buf.index); } buf = {}; memset(planes, 0, sizeof(planes)); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; buf.memory = V4L2_MEMORY_MMAP; buf.length = 1; buf.m.planes = planes; ret = xioctl(fd_, VIDIOC_DQBUF, &buf); if (ret == 0) { // We push this encoded buffer to another thread so that our // application can take its time with the data without blocking the // encode process. int64_t timestamp_us = (buf.timestamp.tv_sec * (int64_t)1000000) + buf.timestamp.tv_usec; OutputItem item = { buffers_[buf.index].mem, buf.m.planes[0].bytesused, buf.m.planes[0].length, buf.index, buf.flags & V4L2_BUF_FLAG_KEYFRAME, timestamp_us }; std::lock_guard<std::mutex> lock(output_mutex_); output_queue_.push(item); output_cond_var_.notify_one(); } } } } void H264Encoder::outputThread() { OutputItem item; while (true) { { std::unique_lock<std::mutex> lock(output_mutex_); while (true) { using namespace std::chrono_literals; if (!output_queue_.empty()) { item = output_queue_.front(); output_queue_.pop(); break; } else output_cond_var_.wait_for(lock, 200ms); if (abort_) return; } } output_ready_callback_(item.mem, item.bytes_used, item.timestamp_us, item.keyframe); v4l2_buffer buf = {}; v4l2_plane planes[VIDEO_MAX_PLANES] = {}; buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; buf.memory = V4L2_MEMORY_MMAP; buf.index = item.index; buf.length = 1; buf.m.planes = planes; buf.m.planes[0].bytesused = 0; buf.m.planes[0].length = item.length; if (xioctl(fd_, VIDIOC_QBUF, &buf) < 0) throw std::runtime_error("failed to re-queue encoded buffer"); } }
; RUN: llvm-ml -filetype=s %s /Fo - /DT1=test1 /D T2=test2 /Dtest5=def /Dtest6 | FileCheck %s .code t1: ret ; CHECK-NOT: t1: ; CHECK-LABEL: test1: ; CHECK-NOT: t1: t2: ret ; CHECK-NOT: t2: ; CHECK-LABEL: test2: ; CHECK-NOT: t2: t3: ifdef t1 xor eax, eax endif ret ; CHECK-LABEL: t3: ; CHECK: xor eax, eax ; CHECK: ret t4: ifdef undefined xor eax, eax elseifdef t2 xor ebx, ebx endif ret ; CHECK-LABEL: t4: ; CHECK-NOT: xor eax, eax ; CHECK: xor ebx, ebx ; CHECK: ret % t5_original BYTE "&test5" ; CHECK-LABEL: t5_original: ; CHECK-NEXT: .byte 100 ; CHECK-NEXT: .byte 101 ; CHECK-NEXT: .byte 102 test5 textequ <redef> % t5_changed BYTE "&test5" ; CHECK-LABEL: t5_changed: ; CHECK-NEXT: .byte 114 ; CHECK-NEXT: .byte 101 ; CHECK-NEXT: .byte 100 ; CHECK-NEXT: .byte 101 ; CHECK-NEXT: .byte 102 t6: ifdef test6 xor eax, eax endif ret ; CHECK-LABEL: t6: ; CHECK: xor eax, eax ; CHECK: ret end
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 Metrological * * 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 "Module.h" #include "FirmwareControl.h" #include <interfaces/json/JsonData_FirmwareControl.h> namespace WPEFramework { namespace Plugin { using namespace JsonData::FirmwareControl; // Registration // void FirmwareControl::RegisterAll() { Register<UpgradeParamsData,void>(_T("upgrade"), &FirmwareControl::endpoint_upgrade, this); Register<ResumeParamsData,void>(_T("resume"), &FirmwareControl::endpoint_resume, this); Property<Core::JSON::EnumType<StatusType>>(_T("status"), &FirmwareControl::get_status, nullptr, this); Property<Core::JSON::DecUInt64>(_T("downloadsize"), &FirmwareControl::get_downloadsize, nullptr, this); } void FirmwareControl::UnregisterAll() { Unregister(_T("resume")); Unregister(_T("upgrade")); Unregister(_T("downloadsize")); Unregister(_T("status")); } // API implementation // // Method: upgrade - Upgrade the device to the given firmware // Return codes: // - ERROR_NONE: Success // - ERROR_INPROGRESS: Operation in progress // - ERROR_INCORRECT_URL: Invalid location given // - ERROR_UNAVAILABLE: Error in download // - ERROR_BAD_REQUEST: Bad file name given // - ERROR_ILLEGAL_STATE: Invalid state of device // - ERROR_INCORRECT_HASH: Incorrect hash given uint32_t FirmwareControl::endpoint_upgrade(const UpgradeParamsData& params) { TRACE(Trace::Information, (string(__FUNCTION__))); uint32_t result = Core::ERROR_NONE; const string& name = params.Name.Value(); _adminLock.Lock(); UpgradeStatus upgradeStatus = _upgradeStatus; _adminLock.Unlock(); TRACE(Trace::Information, (_T("status = [%s] \n"), Core::EnumerateType<JsonData::FirmwareControl::StatusType>(upgradeStatus).Data())); if (upgradeStatus == UpgradeStatus::NONE) { if (result == Core::ERROR_NONE) { if (name.empty() != true) { _adminLock.Lock(); _upgradeStatus = UPGRADE_STARTED; _adminLock.Unlock(); string locator = _source; if (params.Location.IsSet() == true) { locator = params.Location.Value(); } TRACE(Trace::Information, (_T("Image = [%s/%s]\n"), locator.c_str(), name.c_str())); Type type = IMAGE_TYPE_CDL; if (params.Type.IsSet() == true) { type = static_cast<Type>(params.Type.Value()); } TRACE(Trace::Information, (_T("Image Type = [%d]\n"), type)); uint16_t progressInterval = 0; if (params.Progressinterval.IsSet() == true) { progressInterval = params.Progressinterval.Value(); } TRACE(Trace::Information, (_T("Progress Interval = [%d]\n"), progressInterval)); string hash; if (params.Hmac.IsSet() == true) { if (params.Hmac.Value().size() == (Crypto::HASH_SHA256 * 2)) { hash = params.Hmac.Value(); } else { result = Core::ERROR_INCORRECT_HASH; } TRACE(Trace::Information, (_T("Hash = [%s]\n"), hash.c_str())); } if (result == Core::ERROR_NONE) { TRACE(Trace::Information, (_T("Scheduling the upgrade \n"))); result = Schedule(name, locator, type, progressInterval, hash, false); } } else { result = Core::ERROR_BAD_REQUEST; } } } else { result = Core::ERROR_INPROGRESS; } if ((result != Core::ERROR_NONE) && (result != Core::ERROR_INPROGRESS)) { ResetStatus(); } TRACE(Trace::Information, (_T("Status of upgrade request = %d\n"), result)); return result; } // Method: resume - Resume download from the last paused position" // Return codes: // - ERROR_NONE: Success // - ERROR_INPROGRESS: Operation in progress // - ERROR_INCORRECT_URL: Invalid location given // - ERROR_UNAVAILABLE: Error in download // - ERROR_BAD_REQUEST: Bad file name given // - ERROR_ILLEGAL_STATE: Invalid state of device uint32_t FirmwareControl::endpoint_resume(const ResumeParamsData& params) { TRACE(Trace::Information, (string(__FUNCTION__))); uint32_t result = Core::ERROR_NONE; const string& name = params.Name.Value(); _adminLock.Lock(); UpgradeStatus upgradeStatus = _upgradeStatus; _adminLock.Unlock(); TRACE(Trace::Information, (_T("status = [%s] \n"), Core::EnumerateType<JsonData::FirmwareControl::StatusType>(upgradeStatus).Data())); if (upgradeStatus == UpgradeStatus::NONE) { if (result == Core::ERROR_NONE) { if (name.empty() != true) { _adminLock.Lock(); _upgradeStatus = UPGRADE_STARTED; _adminLock.Unlock(); string locator = _source; if (params.Location.IsSet() == true) { locator = params.Location.Value(); } TRACE(Trace::Information, (_T("Image = [%s/%s]\n"), locator.c_str(), name.c_str())); if (result == Core::ERROR_NONE) { TRACE(Trace::Information, (_T("Scheduling the upgrade \n"))); result = Schedule(name, locator); } } else { result = Core::ERROR_BAD_REQUEST; } } } else { result = Core::ERROR_INPROGRESS; } if ((result != Core::ERROR_NONE) && (result != Core::ERROR_INPROGRESS)) { ResetStatus(); } TRACE(Trace::Information, (_T("Status of resume request = %d\n"), result)); return result; } // Property: status - Current status of a upgrade // Return codes: // - ERROR_NONE: Success uint32_t FirmwareControl::get_status(Core::JSON::EnumType<StatusType>& response) const { _adminLock.Lock(); response = static_cast<JsonData::FirmwareControl::StatusType>(_upgradeStatus); _adminLock.Unlock(); TRACE(Trace::Information, (_T("status = [%s] \n"), Core::EnumerateType<JsonData::FirmwareControl::StatusType>(response).Data())); return Core::ERROR_NONE; } // Property: downloadsize - Max free space available to download image // Return codes: // - ERROR_NONE: Success uint32_t FirmwareControl::get_downloadsize(Core::JSON::DecUInt64& response) const { response = DownloadMaxSize(); return Core::ERROR_NONE; } // Event: upgradeprogress - Notifies progress of upgrade void FirmwareControl::event_upgradeprogress(const StatusType& status, const UpgradeprogressParamsData::ErrorType& error, const uint32_t& progress) { UpgradeprogressParamsData params; params.Status = status; params.Error = error; params.Progress = progress; TRACE(Trace::Information, (_T("status = [%s] error = [%s] progress = [%d]\n"), Core::EnumerateType<JsonData::FirmwareControl::StatusType>(status).Data(), Core::EnumerateType<JsonData::FirmwareControl::UpgradeprogressParamsData::ErrorType>(error).Data(), progress)); Notify(_T("upgradeprogress"), params); } } // namespace Plugin }
assume cs:code code segment start: int 1h mov ax,cs mov ds,ax mov si, offset sqr ;设置ds:si指向源地址 mov ax,0 mov es,ax mov di, 200h ;设置es:di指向目的地址 mov cx, offset sqrend - offset sqr ;设置cx为传输长度 cld ;设置传输方向为正 rep movsb mov ax,0 mov es,ax mov word ptr es:[7ch*4],200h ;设置中断向量表 偏移地址 mov word ptr es:[7ch*4+2],0 ;设置中断向量表,段地址 mov ax,4c00h int 21h sqr: mul ax iret sqrend: nop code ends end start
; ; 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_subtract_b_neon| EXPORT |vp8_subtract_mby_neon| EXPORT |vp8_subtract_mbuv_neon| INCLUDE asm_enc_offsets.asm ARM REQUIRE8 PRESERVE8 AREA ||.text||, CODE, READONLY, ALIGN=2 ;void vp8_subtract_b_neon(BLOCK *be, BLOCKD *bd, int pitch) |vp8_subtract_b_neon| PROC stmfd sp!, {r4-r7} ldr r3, [r0, #vp8_block_base_src] ldr r4, [r0, #vp8_block_src] ldr r5, [r0, #vp8_block_src_diff] ldr r3, [r3] ldr r6, [r0, #vp8_block_src_stride] add r3, r3, r4 ; src = *base_src + src ldr r7, [r1, #vp8_blockd_predictor] vld1.8 {d0}, [r3], r6 ;load src vld1.8 {d1}, [r7], r2 ;load pred vld1.8 {d2}, [r3], r6 vld1.8 {d3}, [r7], r2 vld1.8 {d4}, [r3], r6 vld1.8 {d5}, [r7], r2 vld1.8 {d6}, [r3], r6 vld1.8 {d7}, [r7], r2 vsubl.u8 q10, d0, d1 vsubl.u8 q11, d2, d3 vsubl.u8 q12, d4, d5 vsubl.u8 q13, d6, d7 mov r2, r2, lsl #1 vst1.16 {d20}, [r5], r2 ;store diff vst1.16 {d22}, [r5], r2 vst1.16 {d24}, [r5], r2 vst1.16 {d26}, [r5], r2 ldmfd sp!, {r4-r7} bx lr ENDP ;========================================== ;void vp8_subtract_mby_neon(short *diff, unsigned char *src, int src_stride ; unsigned char *pred, int pred_stride) |vp8_subtract_mby_neon| PROC push {r4-r7} mov r12, #4 ldr r4, [sp, #16] ; pred_stride mov r6, #32 ; "diff" stride x2 add r5, r0, #16 ; second diff pointer subtract_mby_loop vld1.8 {q0}, [r1], r2 ;load src vld1.8 {q1}, [r3], r4 ;load pred vld1.8 {q2}, [r1], r2 vld1.8 {q3}, [r3], r4 vld1.8 {q4}, [r1], r2 vld1.8 {q5}, [r3], r4 vld1.8 {q6}, [r1], r2 vld1.8 {q7}, [r3], r4 vsubl.u8 q8, d0, d2 vsubl.u8 q9, d1, d3 vsubl.u8 q10, d4, d6 vsubl.u8 q11, d5, d7 vsubl.u8 q12, d8, d10 vsubl.u8 q13, d9, d11 vsubl.u8 q14, d12, d14 vsubl.u8 q15, d13, d15 vst1.16 {q8}, [r0], r6 ;store diff vst1.16 {q9}, [r5], r6 vst1.16 {q10}, [r0], r6 vst1.16 {q11}, [r5], r6 vst1.16 {q12}, [r0], r6 vst1.16 {q13}, [r5], r6 vst1.16 {q14}, [r0], r6 vst1.16 {q15}, [r5], r6 subs r12, r12, #1 bne subtract_mby_loop pop {r4-r7} bx lr ENDP ;================================= ;void vp8_subtract_mbuv_c(short *diff, unsigned char *usrc, unsigned char *vsrc, ; int src_stride, unsigned char *upred, ; unsigned char *vpred, int pred_stride) |vp8_subtract_mbuv_neon| PROC push {r4-r7} ldr r4, [sp, #16] ; upred ldr r5, [sp, #20] ; vpred ldr r6, [sp, #24] ; pred_stride add r0, r0, #512 ; short *udiff = diff + 256; mov r12, #32 ; "diff" stride x2 add r7, r0, #16 ; second diff pointer ;u vld1.8 {d0}, [r1], r3 ;load usrc vld1.8 {d1}, [r4], r6 ;load upred vld1.8 {d2}, [r1], r3 vld1.8 {d3}, [r4], r6 vld1.8 {d4}, [r1], r3 vld1.8 {d5}, [r4], r6 vld1.8 {d6}, [r1], r3 vld1.8 {d7}, [r4], r6 vld1.8 {d8}, [r1], r3 vld1.8 {d9}, [r4], r6 vld1.8 {d10}, [r1], r3 vld1.8 {d11}, [r4], r6 vld1.8 {d12}, [r1], r3 vld1.8 {d13}, [r4], r6 vld1.8 {d14}, [r1], r3 vld1.8 {d15}, [r4], r6 vsubl.u8 q8, d0, d1 vsubl.u8 q9, d2, d3 vsubl.u8 q10, d4, d5 vsubl.u8 q11, d6, d7 vsubl.u8 q12, d8, d9 vsubl.u8 q13, d10, d11 vsubl.u8 q14, d12, d13 vsubl.u8 q15, d14, d15 vst1.16 {q8}, [r0], r12 ;store diff vst1.16 {q9}, [r7], r12 vst1.16 {q10}, [r0], r12 vst1.16 {q11}, [r7], r12 vst1.16 {q12}, [r0], r12 vst1.16 {q13}, [r7], r12 vst1.16 {q14}, [r0], r12 vst1.16 {q15}, [r7], r12 ;v vld1.8 {d0}, [r2], r3 ;load vsrc vld1.8 {d1}, [r5], r6 ;load vpred vld1.8 {d2}, [r2], r3 vld1.8 {d3}, [r5], r6 vld1.8 {d4}, [r2], r3 vld1.8 {d5}, [r5], r6 vld1.8 {d6}, [r2], r3 vld1.8 {d7}, [r5], r6 vld1.8 {d8}, [r2], r3 vld1.8 {d9}, [r5], r6 vld1.8 {d10}, [r2], r3 vld1.8 {d11}, [r5], r6 vld1.8 {d12}, [r2], r3 vld1.8 {d13}, [r5], r6 vld1.8 {d14}, [r2], r3 vld1.8 {d15}, [r5], r6 vsubl.u8 q8, d0, d1 vsubl.u8 q9, d2, d3 vsubl.u8 q10, d4, d5 vsubl.u8 q11, d6, d7 vsubl.u8 q12, d8, d9 vsubl.u8 q13, d10, d11 vsubl.u8 q14, d12, d13 vsubl.u8 q15, d14, d15 vst1.16 {q8}, [r0], r12 ;store diff vst1.16 {q9}, [r7], r12 vst1.16 {q10}, [r0], r12 vst1.16 {q11}, [r7], r12 vst1.16 {q12}, [r0], r12 vst1.16 {q13}, [r7], r12 vst1.16 {q14}, [r0], r12 vst1.16 {q15}, [r7], r12 pop {r4-r7} bx lr ENDP END
; ; VGM QSound chip ; QSound: MACRO super: Chip QSound_name, Header.qSoundClock, System_Return ENDM ; ix = this ; iy = header QSound_Construct: equ Chip_Construct ; jp Chip_Construct ; ix = this QSound_Destruct: equ Chip_Destruct ; jp Chip_Destruct ; SECTION RAM QSound_instance: QSound ENDS QSound_name: db "QSound",0
// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // // Test that header file is self-contained. #include <boost/beast/http/serializer.hpp> #include <boost/beast/http/string_body.hpp> #include <boost/beast/unit_test/suite.hpp> namespace boost { namespace beast { namespace http { class serializer_test : public beast::unit_test::suite { public: struct deprecated_body { using value_type = std::string; class writer { public: using const_buffers_type = boost::asio::const_buffer; value_type const& body_; template<bool isRequest, class Fields> explicit writer(message<isRequest, deprecated_body, Fields> const& m): body_{m.body()} { } void init(error_code& ec) { ec.assign(0, ec.category()); } boost::optional<std::pair<const_buffers_type, bool>> get(error_code& ec) { ec.assign(0, ec.category()); return {{const_buffers_type{ body_.data(), body_.size()}, false}}; } }; }; struct const_body { struct value_type{}; struct writer { using const_buffers_type = boost::asio::const_buffer; template<bool isRequest, class Fields> writer(header<isRequest, Fields> const&, value_type const&); void init(error_code& ec); boost::optional<std::pair<const_buffers_type, bool>> get(error_code&); }; }; struct mutable_body { struct value_type{}; struct writer { using const_buffers_type = boost::asio::const_buffer; template<bool isRequest, class Fields> writer(header<isRequest, Fields>&, value_type&); void init(error_code& ec); boost::optional<std::pair<const_buffers_type, bool>> get(error_code&); }; }; BOOST_STATIC_ASSERT(std::is_const< serializer< true, const_body>::value_type>::value); BOOST_STATIC_ASSERT(! std::is_const<serializer< true, mutable_body>::value_type>::value); BOOST_STATIC_ASSERT(std::is_constructible< serializer<true, const_body>, message <true, const_body>&>::value); BOOST_STATIC_ASSERT(std::is_constructible< serializer<true, const_body>, message <true, const_body> const&>::value); BOOST_STATIC_ASSERT(std::is_constructible< serializer<true, mutable_body>, message <true, mutable_body>&>::value); BOOST_STATIC_ASSERT(! std::is_constructible< serializer<true, mutable_body>, message <true, mutable_body> const&>::value); struct lambda { std::size_t size; template<class ConstBufferSequence> void operator()(error_code&, ConstBufferSequence const& buffers) { size = boost::asio::buffer_size(buffers); } }; void testWriteLimit() { auto const limit = 30; lambda visit; error_code ec; response<string_body> res; res.body().append(1000, '*'); serializer<false, string_body> sr{res}; sr.limit(limit); for(;;) { sr.next(ec, visit); BEAST_EXPECT(visit.size <= limit); sr.consume(visit.size); if(sr.is_done()) break; } } void testBodyWriterCtor() { response<deprecated_body> res; request<deprecated_body> req; serializer<false, deprecated_body> sr1{res}; serializer<true, deprecated_body> sr2{req}; boost::ignore_unused(sr1, sr2); } void run() override { testWriteLimit(); testBodyWriterCtor(); } }; BEAST_DEFINE_TESTSUITE(beast,http,serializer); } // http } // beast } // boost
; A000453: Stirling numbers of the second kind, S(n,4). ; 1,10,65,350,1701,7770,34105,145750,611501,2532530,10391745,42355950,171798901,694337290,2798806985,11259666950,45232115901,181509070050,727778623825,2916342574750,11681056634501,46771289738810,187226356946265,749329038535350,2998587019946701,11998160744311570,48004081105038305,192050639071964750,768305500780164501,3073530837671316330,12295049856484723945,49182978947632238950,196740254364198919901,786986033194985441090,3148019180028870787185,12592301861930989693950,50369882873307917364901 add $0,3 mov $1,4 pow $1,$0 seq $0,210448 ; Total number of different letters summed over all ternary words of length n. sub $1,$0 div $1,6 mov $0,$1
;ZXVGS specific functions ;020128 (C) created by Yarek PUBLIC bnkfree ;int bnkfree() ;returns number of free memory banks .bnkfree RST 8 DEFB $BF LD L,A LD H,0 RET
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "catalog/catalog-server.h" #include <gutil/strings/substitute.h> #include <thrift/protocol/TDebugProtocol.h> #include "catalog/catalog-util.h" #include "statestore/statestore-subscriber.h" #include "util/debug-util.h" #include "util/logging-support.h" #include "util/webserver.h" #include "gen-cpp/CatalogInternalService_types.h" #include "gen-cpp/CatalogObjects_types.h" #include "gen-cpp/CatalogService_types.h" #include "common/names.h" using boost::bind; using boost::mem_fn; using namespace apache::thrift; using namespace impala; using namespace rapidjson; using namespace strings; DEFINE_int32(catalog_service_port, 26000, "port where the CatalogService is running"); DECLARE_string(state_store_host); DECLARE_int32(state_store_subscriber_port); DECLARE_int32(state_store_port); DECLARE_string(hostname); DECLARE_bool(compact_catalog_topic); string CatalogServer::IMPALA_CATALOG_TOPIC = "catalog-update"; const string CATALOG_SERVER_TOPIC_PROCESSING_TIMES = "catalog-server.topic-processing-time-s"; const string CATALOG_WEB_PAGE = "/catalog"; const string CATALOG_TEMPLATE = "catalog.tmpl"; const string CATALOG_OBJECT_WEB_PAGE = "/catalog_object"; const string CATALOG_OBJECT_TEMPLATE = "catalog_object.tmpl"; // Implementation for the CatalogService thrift interface. class CatalogServiceThriftIf : public CatalogServiceIf { public: CatalogServiceThriftIf(CatalogServer* catalog_server) : catalog_server_(catalog_server) { } // Executes a TDdlExecRequest and returns details on the result of the operation. virtual void ExecDdl(TDdlExecResponse& resp, const TDdlExecRequest& req) { VLOG_RPC << "ExecDdl(): request=" << ThriftDebugString(req); Status status = catalog_server_->catalog()->ExecDdl(req, &resp); if (!status.ok()) LOG(ERROR) << status.GetDetail(); TStatus thrift_status; status.ToThrift(&thrift_status); resp.result.__set_status(thrift_status); VLOG_RPC << "ExecDdl(): response=" << ThriftDebugString(resp); } // Executes a TResetMetadataRequest and returns details on the result of the operation. virtual void ResetMetadata(TResetMetadataResponse& resp, const TResetMetadataRequest& req) { VLOG_RPC << "ResetMetadata(): request=" << ThriftDebugString(req); Status status = catalog_server_->catalog()->ResetMetadata(req, &resp); if (!status.ok()) LOG(ERROR) << status.GetDetail(); TStatus thrift_status; status.ToThrift(&thrift_status); resp.result.__set_status(thrift_status); VLOG_RPC << "ResetMetadata(): response=" << ThriftDebugString(resp); } // Executes a TUpdateCatalogRequest and returns details on the result of the // operation. virtual void UpdateCatalog(TUpdateCatalogResponse& resp, const TUpdateCatalogRequest& req) { VLOG_RPC << "UpdateCatalog(): request=" << ThriftDebugString(req); Status status = catalog_server_->catalog()->UpdateCatalog(req, &resp); if (!status.ok()) LOG(ERROR) << status.GetDetail(); TStatus thrift_status; status.ToThrift(&thrift_status); resp.result.__set_status(thrift_status); VLOG_RPC << "UpdateCatalog(): response=" << ThriftDebugString(resp); } // Gets functions in the Catalog based on the parameters of the // TGetFunctionsRequest. virtual void GetFunctions(TGetFunctionsResponse& resp, const TGetFunctionsRequest& req) { VLOG_RPC << "GetFunctions(): request=" << ThriftDebugString(req); Status status = catalog_server_->catalog()->GetFunctions(req, &resp); if (!status.ok()) LOG(ERROR) << status.GetDetail(); TStatus thrift_status; status.ToThrift(&thrift_status); resp.__set_status(thrift_status); VLOG_RPC << "GetFunctions(): response=" << ThriftDebugString(resp); } // Gets a TCatalogObject based on the parameters of the TGetCatalogObjectRequest. virtual void GetCatalogObject(TGetCatalogObjectResponse& resp, const TGetCatalogObjectRequest& req) { VLOG_RPC << "GetCatalogObject(): request=" << ThriftDebugString(req); Status status = catalog_server_->catalog()->GetCatalogObject(req.object_desc, &resp.catalog_object); if (!status.ok()) LOG(ERROR) << status.GetDetail(); VLOG_RPC << "GetCatalogObject(): response=" << ThriftDebugString(resp); } // Prioritizes the loading of metadata for one or more catalog objects. Currently only // used for loading tables/views because they are the only type of object that is loaded // lazily. virtual void PrioritizeLoad(TPrioritizeLoadResponse& resp, const TPrioritizeLoadRequest& req) { VLOG_RPC << "PrioritizeLoad(): request=" << ThriftDebugString(req); Status status = catalog_server_->catalog()->PrioritizeLoad(req); if (!status.ok()) LOG(ERROR) << status.GetDetail(); TStatus thrift_status; status.ToThrift(&thrift_status); resp.__set_status(thrift_status); VLOG_RPC << "PrioritizeLoad(): response=" << ThriftDebugString(resp); } virtual void SentryAdminCheck(TSentryAdminCheckResponse& resp, const TSentryAdminCheckRequest& req) { VLOG_RPC << "SentryAdminCheck(): request=" << ThriftDebugString(req); Status status = catalog_server_->catalog()->SentryAdminCheck(req); if (!status.ok()) LOG(ERROR) << status.GetDetail(); TStatus thrift_status; status.ToThrift(&thrift_status); resp.__set_status(thrift_status); VLOG_RPC << "SentryAdminCheck(): response=" << ThriftDebugString(resp); } private: CatalogServer* catalog_server_; }; CatalogServer::CatalogServer(MetricGroup* metrics) : thrift_iface_(new CatalogServiceThriftIf(this)), thrift_serializer_(FLAGS_compact_catalog_topic), metrics_(metrics), topic_updates_ready_(false), last_sent_catalog_version_(0L), catalog_objects_min_version_(0L), catalog_objects_max_version_(0L) { topic_processing_time_metric_ = StatsMetric<double>::CreateAndRegister(metrics, CATALOG_SERVER_TOPIC_PROCESSING_TIMES); } Status CatalogServer::Start() { TNetworkAddress subscriber_address = MakeNetworkAddress(FLAGS_hostname, FLAGS_state_store_subscriber_port); TNetworkAddress statestore_address = MakeNetworkAddress(FLAGS_state_store_host, FLAGS_state_store_port); TNetworkAddress server_address = MakeNetworkAddress(FLAGS_hostname, FLAGS_catalog_service_port); // This will trigger a full Catalog metadata load. catalog_.reset(new Catalog()); catalog_update_gathering_thread_.reset(new Thread("catalog-server", "catalog-update-gathering-thread", &CatalogServer::GatherCatalogUpdatesThread, this)); statestore_subscriber_.reset(new StatestoreSubscriber( Substitute("catalog-server@$0", TNetworkAddressToString(server_address)), subscriber_address, statestore_address, metrics_)); StatestoreSubscriber::UpdateCallback cb = bind<void>(mem_fn(&CatalogServer::UpdateCatalogTopicCallback), this, _1, _2); Status status = statestore_subscriber_->AddTopic(IMPALA_CATALOG_TOPIC, false, cb); if (!status.ok()) { status.AddDetail("CatalogService failed to start"); return status; } RETURN_IF_ERROR(statestore_subscriber_->Start()); // Notify the thread to start for the first time. { lock_guard<mutex> l(catalog_lock_); catalog_update_cv_.notify_one(); } return Status::OK(); } void CatalogServer::RegisterWebpages(Webserver* webserver) { Webserver::UrlCallback catalog_callback = bind<void>(mem_fn(&CatalogServer::CatalogUrlCallback), this, _1, _2); webserver->RegisterUrlCallback(CATALOG_WEB_PAGE, CATALOG_TEMPLATE, catalog_callback); Webserver::UrlCallback catalog_objects_callback = bind<void>(mem_fn(&CatalogServer::CatalogObjectsUrlCallback), this, _1, _2); webserver->RegisterUrlCallback(CATALOG_OBJECT_WEB_PAGE, CATALOG_OBJECT_TEMPLATE, catalog_objects_callback, false); RegisterLogLevelCallbacks(webserver, true); } void CatalogServer::UpdateCatalogTopicCallback( const StatestoreSubscriber::TopicDeltaMap& incoming_topic_deltas, vector<TTopicDelta>* subscriber_topic_updates) { StatestoreSubscriber::TopicDeltaMap::const_iterator topic = incoming_topic_deltas.find(CatalogServer::IMPALA_CATALOG_TOPIC); if (topic == incoming_topic_deltas.end()) return; try_mutex::scoped_try_lock l(catalog_lock_); // Return if unable to acquire the catalog_lock_ or if the topic update data is // not yet ready for processing. This indicates the catalog_update_gathering_thread_ // is still building a topic update. if (!l || !topic_updates_ready_) return; const TTopicDelta& delta = topic->second; // If this is not a delta update, clear all catalog objects and request an update // from version 0 from the local catalog. There is an optimization that checks if // pending_topic_updates_ was just reloaded from version 0, if they have then skip this // step and use that data. if (delta.from_version == 0 && delta.to_version == 0 && catalog_objects_min_version_ != 0) { catalog_topic_entry_keys_.clear(); last_sent_catalog_version_ = 0L; } else { // Process the pending topic update. LOG_EVERY_N(INFO, 300) << "Catalog Version: " << catalog_objects_max_version_ << " Last Catalog Version: " << last_sent_catalog_version_; for (const TTopicItem& catalog_object: pending_topic_updates_) { if (subscriber_topic_updates->size() == 0) { subscriber_topic_updates->push_back(TTopicDelta()); subscriber_topic_updates->back().topic_name = IMPALA_CATALOG_TOPIC; } TTopicDelta& update = subscriber_topic_updates->back(); update.topic_entries.push_back(catalog_object); } // Update the new catalog version and the set of known catalog objects. last_sent_catalog_version_ = catalog_objects_max_version_; } // Signal the catalog update gathering thread to start. topic_updates_ready_ = false; catalog_update_cv_.notify_one(); } [[noreturn]] void CatalogServer::GatherCatalogUpdatesThread() { while (1) { unique_lock<mutex> unique_lock(catalog_lock_); // Protect against spurious wakups by checking the value of topic_updates_ready_. // It is only safe to continue on and update the shared pending_topic_updates_ // when topic_updates_ready_ is false, otherwise we may be in the middle of // processing a heartbeat. while (topic_updates_ready_) { catalog_update_cv_.wait(unique_lock); } MonotonicStopWatch sw; sw.Start(); // Clear any pending topic updates. They will have been processed by the heartbeat // thread by the time we make it here. pending_topic_updates_.clear(); long current_catalog_version; Status status = catalog_->GetCatalogVersion(&current_catalog_version); if (!status.ok()) { LOG(ERROR) << status.GetDetail(); } else if (current_catalog_version != last_sent_catalog_version_) { // If there has been a change since the last time the catalog was queried, // call into the Catalog to find out what has changed. TGetAllCatalogObjectsResponse catalog_objects; status = catalog_->GetAllCatalogObjects(last_sent_catalog_version_, &catalog_objects); if (!status.ok()) { LOG(ERROR) << status.GetDetail(); } else { // Use the catalog objects to build a topic update list. BuildTopicUpdates(catalog_objects.objects); catalog_objects_min_version_ = last_sent_catalog_version_; catalog_objects_max_version_ = catalog_objects.max_catalog_version; } } topic_processing_time_metric_->Update(sw.ElapsedTime() / (1000.0 * 1000.0 * 1000.0)); topic_updates_ready_ = true; } } void CatalogServer::BuildTopicUpdates(const vector<TCatalogObject>& catalog_objects) { unordered_set<string> current_entry_keys; // Add any new/updated catalog objects to the topic. for (const TCatalogObject& catalog_object: catalog_objects) { const string& entry_key = TCatalogObjectToEntryKey(catalog_object); if (entry_key.empty()) { LOG_EVERY_N(WARNING, 60) << "Unable to build topic entry key for TCatalogObject: " << ThriftDebugString(catalog_object); } current_entry_keys.insert(entry_key); // Remove this entry from catalog_topic_entry_keys_. At the end of this loop, we will // be left with the set of keys that were in the last update, but not in this // update, indicating which objects have been removed/dropped. catalog_topic_entry_keys_.erase(entry_key); // This isn't a new or an updated item, skip it. if (catalog_object.catalog_version <= last_sent_catalog_version_) continue; VLOG(1) << "Publishing update: " << entry_key << "@" << catalog_object.catalog_version; pending_topic_updates_.push_back(TTopicItem()); TTopicItem& item = pending_topic_updates_.back(); item.key = entry_key; Status status = thrift_serializer_.Serialize(&catalog_object, &item.value); if (!status.ok()) { LOG(ERROR) << "Error serializing topic value: " << status.GetDetail(); pending_topic_updates_.pop_back(); } } // Any remaining items in catalog_topic_entry_keys_ indicate the object was removed // since the last update. for (const string& key: catalog_topic_entry_keys_) { pending_topic_updates_.push_back(TTopicItem()); TTopicItem& item = pending_topic_updates_.back(); item.key = key; VLOG(1) << "Publishing deletion: " << key; // Don't set a value to mark this item as deleted. } catalog_topic_entry_keys_.swap(current_entry_keys); } void CatalogServer::CatalogUrlCallback(const Webserver::ArgumentMap& args, Document* document) { TGetDbsResult get_dbs_result; Status status = catalog_->GetDbs(NULL, &get_dbs_result); if (!status.ok()) { Value error(status.GetDetail().c_str(), document->GetAllocator()); document->AddMember("error", error, document->GetAllocator()); return; } Value databases(kArrayType); for (const TDatabase& db: get_dbs_result.dbs) { Value database(kObjectType); Value str(db.db_name.c_str(), document->GetAllocator()); database.AddMember("name", str, document->GetAllocator()); TGetTablesResult get_table_results; Status status = catalog_->GetTableNames(db.db_name, NULL, &get_table_results); if (!status.ok()) { Value error(status.GetDetail().c_str(), document->GetAllocator()); database.AddMember("error", error, document->GetAllocator()); continue; } Value table_array(kArrayType); for (const string& table: get_table_results.tables) { Value table_obj(kObjectType); Value fq_name(Substitute("$0.$1", db.db_name, table).c_str(), document->GetAllocator()); table_obj.AddMember("fqtn", fq_name, document->GetAllocator()); Value table_name(table.c_str(), document->GetAllocator()); table_obj.AddMember("name", table_name, document->GetAllocator()); table_array.PushBack(table_obj, document->GetAllocator()); } database.AddMember("num_tables", table_array.Size(), document->GetAllocator()); database.AddMember("tables", table_array, document->GetAllocator()); databases.PushBack(database, document->GetAllocator()); } document->AddMember("databases", databases, document->GetAllocator()); } void CatalogServer::CatalogObjectsUrlCallback(const Webserver::ArgumentMap& args, Document* document) { Webserver::ArgumentMap::const_iterator object_type_arg = args.find("object_type"); Webserver::ArgumentMap::const_iterator object_name_arg = args.find("object_name"); if (object_type_arg != args.end() && object_name_arg != args.end()) { TCatalogObjectType::type object_type = TCatalogObjectTypeFromName(object_type_arg->second); // Get the object type and name from the topic entry key TCatalogObject request; TCatalogObjectFromObjectName(object_type, object_name_arg->second, &request); // Get the object and dump its contents. TCatalogObject result; Status status = catalog_->GetCatalogObject(request, &result); if (status.ok()) { Value debug_string(ThriftDebugString(result).c_str(), document->GetAllocator()); document->AddMember("thrift_string", debug_string, document->GetAllocator()); } else { Value error(status.GetDetail().c_str(), document->GetAllocator()); document->AddMember("error", error, document->GetAllocator()); } } else { Value error("Please specify values for the object_type and object_name parameters.", document->GetAllocator()); document->AddMember("error", error, document->GetAllocator()); } }
<% from pwnlib.shellcraft.thumb.linux import syscall %> <%page args="path, buf, length"/> <%docstring> Invokes the syscall readlink. See 'man 2 readlink' for more information. Arguments: path(char): path buf(char): buf len(size_t): len </%docstring> ${syscall('SYS_readlink', path, buf, length)}
; ; jcgray.asm - grayscale colorspace conversion (64-bit AVX2) ; ; Copyright (C) 2011, 2016, D. R. Commander. ; Copyright (C) 2015, Intel Corporation. ; ; Based on the x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/project/showfiles.php?group_id=6208 %include "jsimdext.inc" ; -------------------------------------------------------------------------- %define SCALEBITS 16 F_0_114 equ 7471 ; FIX(0.11400) F_0_250 equ 16384 ; FIX(0.25000) F_0_299 equ 19595 ; FIX(0.29900) F_0_587 equ 38470 ; FIX(0.58700) F_0_337 equ (F_0_587 - F_0_250) ; FIX(0.58700) - FIX(0.25000) ; -------------------------------------------------------------------------- SECTION SEG_CONST alignz 32 GLOBAL_DATA(jconst_rgb_gray_convert_avx2) EXTN(jconst_rgb_gray_convert_avx2): PW_F0299_F0337 times 8 dw F_0_299, F_0_337 PW_F0114_F0250 times 8 dw F_0_114, F_0_250 PD_ONEHALF times 8 dd (1 << (SCALEBITS - 1)) alignz 32 ; -------------------------------------------------------------------------- SECTION SEG_TEXT BITS 64 %include "jcgryext-avx2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_RGB_RED %define RGB_GREEN EXT_RGB_GREEN %define RGB_BLUE EXT_RGB_BLUE %define RGB_PIXELSIZE EXT_RGB_PIXELSIZE %define jsimd_rgb_gray_convert_avx2 jsimd_extrgb_gray_convert_avx2 %include "jcgryext-avx2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_RGBX_RED %define RGB_GREEN EXT_RGBX_GREEN %define RGB_BLUE EXT_RGBX_BLUE %define RGB_PIXELSIZE EXT_RGBX_PIXELSIZE %define jsimd_rgb_gray_convert_avx2 jsimd_extrgbx_gray_convert_avx2 %include "jcgryext-avx2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_BGR_RED %define RGB_GREEN EXT_BGR_GREEN %define RGB_BLUE EXT_BGR_BLUE %define RGB_PIXELSIZE EXT_BGR_PIXELSIZE %define jsimd_rgb_gray_convert_avx2 jsimd_extbgr_gray_convert_avx2 %include "jcgryext-avx2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_BGRX_RED %define RGB_GREEN EXT_BGRX_GREEN %define RGB_BLUE EXT_BGRX_BLUE %define RGB_PIXELSIZE EXT_BGRX_PIXELSIZE %define jsimd_rgb_gray_convert_avx2 jsimd_extbgrx_gray_convert_avx2 %include "jcgryext-avx2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_XBGR_RED %define RGB_GREEN EXT_XBGR_GREEN %define RGB_BLUE EXT_XBGR_BLUE %define RGB_PIXELSIZE EXT_XBGR_PIXELSIZE %define jsimd_rgb_gray_convert_avx2 jsimd_extxbgr_gray_convert_avx2 %include "jcgryext-avx2.asm" %undef RGB_RED %undef RGB_GREEN %undef RGB_BLUE %undef RGB_PIXELSIZE %define RGB_RED EXT_XRGB_RED %define RGB_GREEN EXT_XRGB_GREEN %define RGB_BLUE EXT_XRGB_BLUE %define RGB_PIXELSIZE EXT_XRGB_PIXELSIZE %define jsimd_rgb_gray_convert_avx2 jsimd_extxrgb_gray_convert_avx2 %include "jcgryext-avx2.asm"
; Arquivo: Abs.nasm ; Curso: Elementos de Sistemas ; Criado por: Luciano Soares ; Data: 27/03/2017 ; Copia o valor de RAM[1] para RAM[0] deixando o valor sempre positivo. leaw $1, %A movw (%A), %D leaw $END, %A jg %D nop negw %D END: leaw $0, %A movw %D, (%A)
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include <niftkLogHelper.h> #include <niftkConversionUtils.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkNifTKImageIOFactory.h> #include <itkCommandLineHelper.h> #include <itkImageRegionIterator.h> #include <itkContinuousIndex.h> #include <itkVector.h> /*! * \file niftkResetVoxelDimensionsField.cxx * \page niftkResetVoxelDimensionsField * \section niftkResetVoxelDimensionsFieldSummary Loads an image in, and sets the voxel size to the ones you specified. */ void Usage(char *exec) { niftk::LogHelper::PrintCommandLineHeader(std::cout); std::cout << " " << std::endl; std::cout << " Loads an image in, and sets the voxel size to the ones you specified." << std::endl; std::cout << " " << std::endl; std::cout << " " << std::endl; std::cout << " " << exec << " -i inputFileName -o outputFileName [options]" << std::endl; std::cout << " " << std::endl; std::cout << "*** [mandatory] ***" << std::endl << std::endl; std::cout << " -i <filename> Input image " << std::endl; std::cout << " -o <filename> Output image" << std::endl << std::endl; std::cout << "*** [options] ***" << std::endl << std::endl; std::cout << " -spacing x y z [1] Set the spacing of the output image" << std::endl; } struct arguments { std::string inputImage; std::string outputImage; float spacing[3]; }; template <int Dimension, class PixelType> int DoMain(arguments args) { typedef typename itk::Image< PixelType, Dimension > InputImageType; typedef typename itk::ImageFileReader< InputImageType > InputImageReaderType; typedef typename itk::ImageFileWriter< InputImageType > OutputImageWriterType; typename InputImageReaderType::Pointer imageReader = InputImageReaderType::New(); imageReader->SetFileName(args.inputImage); try { imageReader->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "Failed: " << err << std::endl; return EXIT_FAILURE; } typename InputImageType::SizeType oldSize; typename InputImageType::SpacingType oldSpacing; typename InputImageType::PointType oldOrigin; typename InputImageType::DirectionType oldDirection; typename InputImageType::Pointer inputImage = imageReader->GetOutput(); oldSize = inputImage->GetLargestPossibleRegion().GetSize(); oldSpacing = inputImage->GetSpacing(); oldOrigin = inputImage->GetOrigin(); oldDirection = inputImage->GetDirection(); typedef itk::ContinuousIndex<double, Dimension> ContinuousIndexType; typedef itk::Vector<double, Dimension> VectorType; typename InputImageType::IndexType cornerOfImageInVoxels; typename InputImageType::PointType cornerOfImageInMillimetres; typename InputImageType::PointType centreOfImageInMillimetres; ContinuousIndexType centreOfImageInVoxels; VectorType directionVector; for (int i = 0; i < Dimension; i++) { cornerOfImageInVoxels[i] = 0; centreOfImageInVoxels[i] = ((oldSize[i]-1)/2.0); } inputImage->TransformIndexToPhysicalPoint(cornerOfImageInVoxels, cornerOfImageInMillimetres); inputImage->TransformContinuousIndexToPhysicalPoint(centreOfImageInVoxels, centreOfImageInMillimetres); for (int i = 0; i < Dimension; i++) { directionVector[i] = centreOfImageInMillimetres[i] - cornerOfImageInMillimetres[i]; } directionVector /= directionVector.GetNorm(); typename InputImageType::SpacingType newSpacing; typename InputImageType::PointType newOrigin; for (int i = 0; i < Dimension; i++) { newSpacing[i] = args.spacing[i]; } double diagonalLength = 0; for (int i = 0; i < Dimension; i++) { diagonalLength += newSpacing[i]*((oldSize[i]-1)/2.0)*newSpacing[i]*((oldSize[i]-1)/2.0); } diagonalLength = sqrt(diagonalLength); for (int i = 0; i < Dimension; i++) { newOrigin[i] = centreOfImageInMillimetres[i] - diagonalLength*directionVector[i]; } // Create new image, as a copy of the input typename InputImageType::Pointer image = InputImageType::New(); image->SetRegions(inputImage->GetLargestPossibleRegion()); image->SetDirection(inputImage->GetDirection()); image->SetOrigin(newOrigin); image->SetSpacing(newSpacing); image->Allocate(); image->FillBuffer(0); itk::ImageRegionIterator<InputImageType> inputIterator(imageReader->GetOutput(), imageReader->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionIterator<InputImageType> outputIterator(image, image->GetLargestPossibleRegion()); for (inputIterator.GoToBegin(), outputIterator.GoToBegin(); !inputIterator.IsAtEnd(); ++inputIterator, ++outputIterator) { outputIterator.Set(inputIterator.Get()); } typename OutputImageWriterType::Pointer imageWriter = OutputImageWriterType::New(); imageWriter->SetFileName(args.outputImage); imageWriter->SetInput(image); try { imageWriter->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "Failed: " << err << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } /** * \brief Takes image and changes voxel sizes in header. */ int main(int argc, char** argv) { itk::NifTKImageIOFactory::Initialize(); // To pass around command line args struct arguments args; // Set defaults for (unsigned int i = 0; i < 3; i++) { args.spacing[i] = 1; } // Parse command line args for image for(int i=1; i < argc; i++){ if(strcmp(argv[i], "-help")==0 || strcmp(argv[i], "-Help")==0 || strcmp(argv[i], "-HELP")==0 || strcmp(argv[i], "-h")==0 || strcmp(argv[i], "--h")==0){ Usage(argv[0]); return -1; } else if(strcmp(argv[i], "-i") == 0){ args.inputImage=argv[++i]; std::cout << "Set -i=" << args.inputImage << std::endl; } else if(strcmp(argv[i], "-o") == 0){ args.outputImage=argv[++i]; std::cout << "Set -o=" << args.outputImage << std::endl; } } // Validate command line args if (args.inputImage.length() == 0 || args.outputImage.length() == 0) { Usage(argv[0]); return EXIT_FAILURE; } int dims = itk::PeekAtImageDimension(args.inputImage); if (dims != 2 && dims != 3) { std::cout << "Unsuported image dimension" << std::endl; return EXIT_FAILURE; } // Now we know we have 3 dimensions, parse the other command line args. for(int i=1; i < argc; i++){ if(strcmp(argv[i], "-spacing") == 0){ for (int j = 0; j < dims; j++) { args.spacing[j]=atof(argv[++i]); std::cout << "Set -spacing[" << niftk::ConvertToString(j) << "]=" << niftk::ConvertToString(args.spacing[j]) << std::endl; } } } int result; // You could template for 2D and 3D, and all datatypes, but 64bit gcc compilers seem // to struggle here, so I've just done the bare minimum for now. switch (itk::PeekAtComponentType(args.inputImage)) { case itk::ImageIOBase::UCHAR: if (dims == 2) { result = DoMain<2, unsigned char>(args); } else { result = DoMain<3, unsigned char>(args); } break; case itk::ImageIOBase::CHAR: if (dims == 2) { result = DoMain<2, char>(args); } else { result = DoMain<3, char>(args); } break; case itk::ImageIOBase::USHORT: if (dims == 2) { result = DoMain<2, unsigned short>(args); } else { result = DoMain<3, unsigned short>(args); } break; case itk::ImageIOBase::SHORT: if (dims == 2) { result = DoMain<2, short>(args); } else { result = DoMain<3, short>(args); } break; case itk::ImageIOBase::UINT: if (dims == 2) { result = DoMain<2, unsigned int>(args); } else { result = DoMain<3, unsigned int>(args); } break; case itk::ImageIOBase::INT: if (dims == 2) { result = DoMain<2, int>(args); } else { result = DoMain<3, int>(args); } break; case itk::ImageIOBase::ULONG: if (dims == 2) { result = DoMain<2, unsigned long>(args); } else { result = DoMain<3, unsigned long>(args); } break; case itk::ImageIOBase::LONG: if (dims == 2) { result = DoMain<2, long>(args); } else { result = DoMain<3, long>(args); } break; case itk::ImageIOBase::FLOAT: if (dims == 2) { result = DoMain<2, float>(args); } else { result = DoMain<3, float>(args); } break; case itk::ImageIOBase::DOUBLE: if (dims == 2) { result = DoMain<2, double>(args); } else { result = DoMain<3, double>(args); } break; default: std::cerr << "non standard pixel format" << std::endl; return EXIT_FAILURE; } return result; }
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r13 push %r8 push %rdi push %rdx // Store lea addresses_D+0xa482, %r13 nop add $12222, %r8 movl $0x51525354, (%r13) nop nop inc %r11 // Store lea addresses_PSE+0x8a86, %rdi nop nop nop sub %r12, %r12 mov $0x5152535455565758, %r8 movq %r8, %xmm1 movups %xmm1, (%rdi) nop nop nop nop and $32019, %r13 // Faulty Load mov $0x1d9200000000286, %r8 clflush (%r8) nop nop nop and %rdx, %rdx mov (%r8), %r11 lea oracles, %rdx and $0xff, %r11 shlq $12, %r11 mov (%rdx,%r11,1), %r11 pop %rdx pop %rdi pop %r8 pop %r13 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_NC', 'same': False, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_D', 'same': False, 'size': 4, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_PSE', 'same': False, 'size': 16, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_NC', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; uint in_Pause(uint ticks) ; 09.2005 aralbrec SECTION code_clib PUBLIC in_Pause PUBLIC _in_Pause EXTERN in_WaitForNoKey, in_WaitForKey, t_delay ; Waits a period of time measured in milliseconds and exits ; early if a key is pressed ; ; enter: HL = time to wait in ms, if 0 waits forever until key pressed ; exit : carry = exit early because of keypress with HL = time remaining ; no carry = exit after time passed ; uses : AF,BC,DE,HL .in_Pause ._in_Pause ld a,h or l jr z, waitforkey .loop ; wait 1ms then sample keyboard, in loop ; at 3.5MHz, 1ms = 3500 T states ex de,hl ld hl,3500 - 78 call t_delay ; wait exactly HL t-states ex de,hl dec hl ld a,h or l ret z xor a in a,($b2) and 127 cp 127 jr z, loop scf ret .waitforkey call in_WaitForNoKey jp in_WaitForKey
; A006046: Total number of odd entries in first n rows of Pascal's triangle: a(0) = 0, a(1) = 1, a(2k) = 3*a(k), a(2k+1) = 2*a(k) + a(k+1). For n>0, a(n) = Sum_{i=0..n-1} 2^wt(i). ; 0,1,3,5,9,11,15,19,27,29,33,37,45,49,57,65,81,83,87,91,99,103,111,119,135,139,147,155,171,179,195,211,243,245,249,253,261,265,273,281,297,301,309,317,333,341,357,373,405,409,417,425,441,449,465,481,513,521,537,553,585,601,633,665,729,731,735,739,747,751,759,767,783,787,795,803,819,827,843,859,891,895,903,911,927,935,951,967,999,1007,1023,1039,1071,1087,1119,1151,1215,1219,1227,1235 sub $0,1 mov $1,$0 add $0,4 max $1,0 seq $1,267700 ; "Tree" sequence in a 90 degree sector of the cellular automaton of A160720. add $1,$0 mov $0,$1 sub $0,3
SFX_Purchase_1_Ch4: duty 2 unknownsfx0x20 4, 225, 0, 7 unknownsfx0x20 8, 242, 224, 7 endchannel SFX_Purchase_1_Ch5: duty 2 unknownsfx0x20 1, 8, 0, 0 unknownsfx0x20 4, 145, 193, 6 unknownsfx0x20 8, 162, 161, 7 endchannel
// Copyright (c) 2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "timedata.h" #include "netbase.h" #include "sync.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include <boost/foreach.hpp> using namespace std; static CCriticalSection cs_nTimeOffset; static int64_t nTimeOffset = 0; /** * "Never go to sea with two chronometers; take one or three." * Our three time sources are: * - System clock * - Median of other nodes clocks * - The user (asking the user to fix the system clock if the first two disagree) */ int64_t GetTimeOffset() { LOCK(cs_nTimeOffset); return nTimeOffset; } int64_t GetAdjustedTime() { return GetTime() + GetTimeOffset(); } static int64_t abs64(int64_t n) { return (n >= 0 ? n : -n); } void AddTimeData(const CNetAddr& ip, int64_t nTime) { int64_t nOffsetSample = nTime - GetTime(); LOCK(cs_nTimeOffset); // Ignore duplicates static set<CNetAddr> setKnown; if (!setKnown.insert(ip).second) return; // Add data static CMedianFilter<int64_t> vTimeOffsets(200, 0); vTimeOffsets.input(nOffsetSample); LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample / 60); // There is a known issue here (see issue #4521): // // - The structure vTimeOffsets contains up to 200 elements, after which // any new element added to it will not increase its size, replacing the // oldest element. // // - The condition to update nTimeOffset includes checking whether the // number of elements in vTimeOffsets is odd, which will never happen after // there are 200 elements. // // But in this case the 'bug' is protective against some attacks, and may // actually explain why we've never seen attacks which manipulate the // clock offset. // // So we should hold off on fixing this and clean it up as part of // a timing cleanup that strengthens it in a number of other ways. // if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) { int64_t nMedian = vTimeOffsets.median(); std::vector<int64_t> vSorted = vTimeOffsets.sorted(); // Only let other nodes change our time by so much if (abs64(nMedian) < 70 * 60) { nTimeOffset = nMedian; } else { nTimeOffset = 0; static bool fDone; if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; BOOST_FOREACH (int64_t nOffset, vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; if (!fMatch) { fDone = true; string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong DWE Core will not work properly."); strMiscWarning = strMessage; LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); } } } if (fDebug) { BOOST_FOREACH (int64_t n, vSorted) LogPrintf("%+d ", n); LogPrintf("| "); } LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset / 60); } }
; A013656: n*(9*n-2). ; 0,7,32,75,136,215,312,427,560,711,880,1067,1272,1495,1736,1995,2272,2567,2880,3211,3560,3927,4312,4715,5136,5575,6032,6507,7000,7511,8040,8587,9152,9735,10336,10955,11592,12247,12920,13611,14320,15047,15792,16555 mov $1,$0 mul $1,9 sub $1,2 mul $0,$1
#include <iostream> #include <fstream> #include <algorithm> #include <glimac/File.hpp> #include <glm/glm.hpp> namespace glimac{ void readFileControl(const FilePath &applicationPath,std::string filename,std::vector <ControlPoint> &list_ctrl){ std::ifstream fichier(applicationPath.dirPath() + "../assets/doc"+filename, std::ios::in); if (fichier) { std::string line; while(getline(fichier, line)) { ControlPoint control; fichier >> control.m_position.x; fichier >> control.m_position.y; fichier >> control.m_position.z; fichier >> control.m_value; list_ctrl.push_back(control); } fichier.close(); } else std::cerr << "Impossible d'ouvrir le fichier de sauvegarde !" << std::endl; } void saveFile(const FilePath &applicationPath,std::string filename,std::vector <Cube> &list_cube){ std::ofstream fichier(applicationPath.dirPath() + "../assets/doc"+filename, std::ios::out | std::ios::trunc); if(fichier) { for (int i = 0; i < list_cube.size(); ++i) { fichier << list_cube[i].getPosition().x <<" "; fichier << list_cube[i].getPosition().y <<" "; fichier << list_cube[i].getPosition().z <<" "; fichier << list_cube[i].getType() <<" "; fichier << list_cube[i].isVisible()<< std::endl; } fichier.close(); } else std::cerr << "Impossible d'écrire le fichier de sauvegarde !" << std::endl; } void loadFile(const FilePath &applicationPath,std::string filename,std::vector <Cube> &list_cube){ std::ifstream fichier(applicationPath.dirPath() + "../assets/doc"+filename, std::ios::in); if (fichier) { std::string line; int i=0; glm::vec3 position; int type; bool visibility; fichier >> position.x ; fichier >> position.y ; fichier >> position.z ; fichier >> type ; fichier >> visibility; list_cube[0].setPosition(position); list_cube[0].setType(type); if (visibility == true) { list_cube[0].addCube(); } else list_cube[0].removeCube(); while(getline(fichier, line)) { i++; glm::vec3 position; fichier >> position.x ; fichier >> position.y ; fichier >> position.z ; fichier >> type ; fichier >> visibility; list_cube[i].setPosition(position); list_cube[i].setType(type); if (visibility == true) { list_cube[i].addCube(); } else list_cube[i].removeCube(); } fichier.close(); } else std::cerr << "Impossible de charger le fichier de sauvegarde !" << std::endl; } }
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "RuntimeDebugPch.h" #if ENABLE_TTD namespace TTD { void SnapshotExtractor::MarkVisitHandler(Js::DynamicTypeHandler* handler) { this->m_marks.MarkAndTestAddr<MarkTableTag::TypeHandlerTag>(handler); } void SnapshotExtractor::MarkVisitType(Js::Type* type) { //Must ensure this is de-serialized before you call this if(this->m_marks.MarkAndTestAddr<MarkTableTag::TypeTag>(type)) { if(Js::DynamicType::Is(type)) { Js::DynamicTypeHandler* handler = (static_cast<Js::DynamicType*>(type))->GetTypeHandler(); this->MarkVisitHandler(handler); } Js::RecyclableObject* proto = type->GetPrototype(); if(proto != nullptr) { this->MarkVisitVar(proto); } } } void SnapshotExtractor::MarkVisitStandardProperties(Js::RecyclableObject* obj) { TTDAssert(Js::DynamicType::Is(obj->GetTypeId()) || obj->GetPropertyCount() == 0, "Only dynamic objects should have standard properties."); if(Js::DynamicType::Is(obj->GetTypeId())) { Js::DynamicObject* dynObj = Js::DynamicObject::FromVar(obj); dynObj->GetDynamicType()->GetTypeHandler()->MarkObjectSlots_TTD(this, dynObj); Js::ArrayObject* parray = dynObj->GetObjectArray(); if(parray != nullptr) { this->MarkVisitVar(parray); } } } void SnapshotExtractor::ExtractHandlerIfNeeded(Js::DynamicTypeHandler* handler, ThreadContext* threadContext) { if(this->m_marks.IsMarked(handler)) { NSSnapType::SnapHandler* sHandler = this->m_pendingSnap->GetNextAvailableHandlerEntry(); handler->ExtractSnapHandler(sHandler, threadContext, this->m_pendingSnap->GetSnapshotSlabAllocator()); this->m_idToHandlerMap.AddItem(sHandler->HandlerId, sHandler); this->m_marks.ClearMark(handler); } } void SnapshotExtractor::ExtractTypeIfNeeded(Js::Type* jstype, ThreadContext* threadContext) { if(this->m_marks.IsMarked(jstype)) { NSSnapType::SnapHandler* sHandler = nullptr; if(Js::DynamicType::Is(jstype)) { this->ExtractHandlerIfNeeded(static_cast<Js::DynamicType*>(jstype)->GetTypeHandler(), threadContext); Js::DynamicTypeHandler* dhandler = static_cast<const Js::DynamicType*>(jstype)->GetTypeHandler(); TTD_PTR_ID handlerId = TTD_CONVERT_TYPEINFO_TO_PTR_ID(dhandler); sHandler = this->m_idToHandlerMap.LookupKnownItem(handlerId); } NSSnapType::SnapType* sType = this->m_pendingSnap->GetNextAvailableTypeEntry(); jstype->ExtractSnapType(sType, sHandler, this->m_pendingSnap->GetSnapshotSlabAllocator()); this->m_idToTypeMap.AddItem(sType->TypePtrId, sType); this->m_marks.ClearMark(jstype); } } void SnapshotExtractor::ExtractSlotArrayIfNeeded(Js::ScriptContext* ctx, Js::Var* scope) { if(this->m_marks.IsMarked(scope)) { NSSnapValues::SlotArrayInfo* slotInfo = this->m_pendingSnap->GetNextAvailableSlotArrayEntry(); Js::ScopeSlots slots(scope); slotInfo->SlotId = TTD_CONVERT_VAR_TO_PTR_ID(scope); slotInfo->ScriptContextLogId = ctx->ScriptContextLogTag; slotInfo->SlotCount = static_cast<uint>(slots.GetCount()); slotInfo->Slots = this->m_pendingSnap->GetSnapshotSlabAllocator().SlabAllocateArray<TTDVar>(slotInfo->SlotCount); for(uint32 j = 0; j < slotInfo->SlotCount; ++j) { slotInfo->Slots[j] = slots.Get(j); } if(!slots.IsDebuggerScopeSlotArray()) { Js::FunctionBody* fb = slots.GetFunctionInfo()->GetFunctionBody(); slotInfo->isFunctionBodyMetaData = true; slotInfo->OptFunctionBodyId = TTD_CONVERT_FUNCTIONBODY_TO_PTR_ID(fb); slotInfo->OptDebugScopeId = TTD_INVALID_PTR_ID; slotInfo->OptWellKnownDbgScope = TTD_INVALID_WELLKNOWN_TOKEN; Js::PropertyId* propertyIds = fb->GetPropertyIdsForScopeSlotArray(); slotInfo->PIDArray = this->m_pendingSnap->GetSnapshotSlabAllocator().SlabAllocateArray<Js::PropertyId>(slotInfo->SlotCount); js_memcpy_s(slotInfo->PIDArray, sizeof(Js::PropertyId) * slotInfo->SlotCount, propertyIds, sizeof(Js::PropertyId) * slots.GetCount()); } else { Js::DebuggerScope* dbgScope = slots.GetDebuggerScope(); slotInfo->isFunctionBodyMetaData = false; slotInfo->OptFunctionBodyId = TTD_INVALID_PTR_ID; TTD_WELLKNOWN_TOKEN wellKnownToken = ctx->TTDWellKnownInfo->ResolvePathForKnownDbgScopeIfExists(dbgScope); if(wellKnownToken == TTD_INVALID_WELLKNOWN_TOKEN) { slotInfo->OptDebugScopeId = TTD_CONVERT_DEBUGSCOPE_TO_PTR_ID(dbgScope); slotInfo->OptWellKnownDbgScope = TTD_INVALID_WELLKNOWN_TOKEN; } else { slotInfo->OptDebugScopeId = TTD_INVALID_PTR_ID; slotInfo->OptWellKnownDbgScope = this->m_pendingSnap->GetSnapshotSlabAllocator().CopyRawNullTerminatedStringInto(wellKnownToken); } slotInfo->PIDArray = this->m_pendingSnap->GetSnapshotSlabAllocator().SlabAllocateArray<Js::PropertyId>(slotInfo->SlotCount); for(uint32 j = 0; j < slotInfo->SlotCount; ++j) { slotInfo->PIDArray[j] = dbgScope->GetPropertyIdForSlotIndex_TTD(j); } } this->m_marks.ClearMark(scope); } } void SnapshotExtractor::ExtractScopeIfNeeded(Js::ScriptContext* ctx, Js::FrameDisplay* environment) { if(this->m_marks.IsMarked(environment)) { TTDAssert(environment->GetLength() > 0, "This doesn't make sense"); NSSnapValues::ScriptFunctionScopeInfo* funcScopeInfo = this->m_pendingSnap->GetNextAvailableFunctionScopeEntry(); funcScopeInfo->ScopeId = TTD_CONVERT_ENV_TO_PTR_ID(environment); funcScopeInfo->ScriptContextLogId = ctx->ScriptContextLogTag; funcScopeInfo->ScopeCount = environment->GetLength(); funcScopeInfo->ScopeArray = this->m_pendingSnap->GetSnapshotSlabAllocator().SlabAllocateArray<NSSnapValues::ScopeInfoEntry>(funcScopeInfo->ScopeCount); for(uint16 i = 0; i < funcScopeInfo->ScopeCount; ++i) { void* scope = environment->GetItem(i); NSSnapValues::ScopeInfoEntry* entryInfo = (funcScopeInfo->ScopeArray + i); entryInfo->Tag = environment->GetScopeType(scope); switch(entryInfo->Tag) { case Js::ScopeType::ScopeType_ActivationObject: case Js::ScopeType::ScopeType_WithScope: entryInfo->IDValue = TTD_CONVERT_VAR_TO_PTR_ID((Js::Var)scope); break; case Js::ScopeType::ScopeType_SlotArray: { this->ExtractSlotArrayIfNeeded(ctx, (Js::Var*)scope); entryInfo->IDValue = TTD_CONVERT_SLOTARRAY_TO_PTR_ID((Js::Var*)scope); break; } default: TTDAssert(false, "Unknown scope kind"); entryInfo->IDValue = TTD_INVALID_PTR_ID; break; } } this->m_marks.ClearMark(environment); } } void SnapshotExtractor::ExtractScriptFunctionEnvironmentIfNeeded(Js::ScriptFunction* function) { Js::FrameDisplay* environment = function->GetEnvironment(); if(environment->GetLength() != 0) { this->ExtractScopeIfNeeded(function->GetScriptContext(), environment); } } void SnapshotExtractor::UnloadDataFromExtractor() { this->m_marks.Clear(); this->m_worklist.Clear(); this->m_idToHandlerMap.Unload(); this->m_idToTypeMap.Unload(); this->m_pendingSnap = nullptr; } SnapshotExtractor::SnapshotExtractor() : m_marks(), m_worklist(&HeapAllocator::Instance), m_idToHandlerMap(), m_idToTypeMap(), m_pendingSnap(nullptr), m_snapshotsTakenCount(0), m_totalMarkMillis(0.0), m_totalExtractMillis(0.0), m_maxMarkMillis(0.0), m_maxExtractMillis(0.0), m_lastMarkMillis(0.0), m_lastExtractMillis(0.0) { ; } SnapshotExtractor::~SnapshotExtractor() { this->UnloadDataFromExtractor(); } SnapShot* SnapshotExtractor::GetPendingSnapshot() { TTDAssert(this->m_pendingSnap != nullptr, "Should only call if we are extracting a snapshot"); return this->m_pendingSnap; } SlabAllocator& SnapshotExtractor::GetActiveSnapshotSlabAllocator() { TTDAssert(this->m_pendingSnap != nullptr, "Should only call if we are extracting a snapshot"); return this->m_pendingSnap->GetSnapshotSlabAllocator(); } void SnapshotExtractor::MarkVisitVar(Js::Var var) { TTDAssert(var != nullptr, "I don't think this should happen but not 100% sure."); TTDAssert(Js::JavascriptOperators::GetTypeId(var) < Js::TypeIds_Limit || Js::RecyclableObject::FromVar(var)->IsExternal(), "Not cool."); //We don't need to visit tagged things if(JsSupport::IsVarTaggedInline(var)) { return; } if(JsSupport::IsVarPrimitiveKind(var)) { if(this->m_marks.MarkAndTestAddr<MarkTableTag::PrimitiveObjectTag>(var)) { Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(var); this->MarkVisitType(obj->GetType()); } } else { TTDAssert(JsSupport::IsVarComplexKind(var), "Shouldn't be anything else"); if(this->m_marks.MarkAndTestAddr<MarkTableTag::CompoundObjectTag>(var)) { Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(var); //do this here instead of in mark visit type as it wants the dynamic object as well if(Js::DynamicType::Is(obj->GetTypeId())) { Js::DynamicObject* dynObj = Js::DynamicObject::FromVar(obj); if(dynObj->GetDynamicType()->GetTypeHandler()->IsDeferredTypeHandler()) { dynObj->GetDynamicType()->GetTypeHandler()->EnsureObjectReady(dynObj); } } this->MarkVisitType(obj->GetType()); this->m_worklist.Enqueue(obj); } } } void SnapshotExtractor::MarkFunctionBody(Js::FunctionBody* fb) { if(this->m_marks.MarkAndTestAddr<MarkTableTag::FunctionBodyTag>(fb)) { Js::FunctionBody* currfb = fb->GetScriptContext()->TTDContextInfo->ResolveParentBody(fb); while(currfb != nullptr && this->m_marks.MarkAndTestAddr<MarkTableTag::FunctionBodyTag>(currfb)) { currfb = currfb->GetScriptContext()->TTDContextInfo->ResolveParentBody(currfb); } } } void SnapshotExtractor::MarkScriptFunctionScopeInfo(Js::FrameDisplay* environment) { if(this->m_marks.MarkAndTestAddr<MarkTableTag::EnvironmentTag>(environment)) { uint32 scopeCount = environment->GetLength(); for(uint32 i = 0; i < scopeCount; ++i) { void* scope = environment->GetItem(i); switch(environment->GetScopeType(scope)) { case Js::ScopeType::ScopeType_ActivationObject: case Js::ScopeType::ScopeType_WithScope: { this->MarkVisitVar((Js::Var)scope); break; } case Js::ScopeType::ScopeType_SlotArray: { if(this->m_marks.MarkAndTestAddr<MarkTableTag::SlotArrayTag>(scope)) { Js::ScopeSlots slotArray = (Js::Var*)scope; uint slotArrayCount = static_cast<uint>(slotArray.GetCount()); if(!slotArray.IsDebuggerScopeSlotArray()) { this->MarkFunctionBody(slotArray.GetFunctionInfo()->GetFunctionBody()); } for(uint j = 0; j < slotArrayCount; j++) { Js::Var sval = slotArray.Get(j); this->MarkVisitVar(sval); } } break; } default: TTDAssert(false, "Unknown scope kind"); } } } } void SnapshotExtractor::BeginSnapshot(ThreadContext* threadContext, double gcTime) { TTDAssert((this->m_pendingSnap == nullptr) & this->m_worklist.Empty(), "Something went wrong."); this->m_pendingSnap = TT_HEAP_NEW(SnapShot, gcTime); } void SnapshotExtractor::DoMarkWalk(ThreadContext* threadContext) { TTDTimer timer; double startTime = timer.Now(); //Add the global roots for(auto iter = threadContext->TTDContext->GetRootTagToObjectMap().GetIterator(); iter.IsValid(); iter.MoveNext()) { Js::Var root = iter.CurrentValue(); this->MarkVisitVar(root); } while(!this->m_worklist.Empty()) { Js::RecyclableObject* nobj = this->m_worklist.Dequeue(); TTDAssert(JsSupport::IsVarComplexKind(nobj), "Should only be these two options"); this->MarkVisitStandardProperties(nobj); nobj->MarkVisitKindSpecificPtrs(this); } //Mark all of the well known objects/types for(int32 i = 0; i < threadContext->TTDContext->GetTTDContexts().Count(); ++i) { threadContext->TTDContext->GetTTDContexts().Item(i)->TTDWellKnownInfo->MarkWellKnownObjects_TTD(this->m_marks); } double endTime = timer.Now(); this->m_pendingSnap->MarkTime = (endTime - startTime) / 1000.0; } void SnapshotExtractor::EvacuateMarkedIntoSnapshot(ThreadContext* threadContext, JsUtil::BaseHashSet<Js::FunctionBody*, HeapAllocator>& liveTopLevelBodies) { TTDTimer timer; double startTime = timer.Now(); SnapShot* snap = this->m_pendingSnap; SlabAllocator& alloc = this->m_pendingSnap->GetSnapshotSlabAllocator(); //invert the root map for extracting JsUtil::BaseDictionary<Js::RecyclableObject*, TTD_LOG_PTR_ID, HeapAllocator> objToLogIdMap(&HeapAllocator::Instance); threadContext->TTDContext->LoadInvertedRootMap(objToLogIdMap); //We extract all the global code function bodies with the context so clear their marks now for(int32 i = 0; i < threadContext->TTDContext->GetTTDContexts().Count(); ++i) { JsUtil::List<TopLevelFunctionInContextRelation, HeapAllocator> topLevelScriptLoad(&HeapAllocator::Instance); JsUtil::List<TopLevelFunctionInContextRelation, HeapAllocator> topLevelNewFunction(&HeapAllocator::Instance); JsUtil::List<TopLevelFunctionInContextRelation, HeapAllocator> topLevelEval(&HeapAllocator::Instance); Js::ScriptContext* ctx = threadContext->TTDContext->GetTTDContexts().Item(i); ctx->TTDContextInfo->GetLoadedSources(nullptr, topLevelScriptLoad, topLevelNewFunction, topLevelEval); for(int32 j = 0; j < topLevelScriptLoad.Count(); ++j) { Js::FunctionBody* body = TTD_COERCE_PTR_ID_TO_FUNCTIONBODY(topLevelScriptLoad.Item(j).ContextSpecificBodyPtrId); if(this->m_marks.IsMarked(body)) { liveTopLevelBodies.Add(body); this->m_marks.ClearMark(body); } } for(int32 j = 0; j < topLevelNewFunction.Count(); ++j) { Js::FunctionBody* body = TTD_COERCE_PTR_ID_TO_FUNCTIONBODY(topLevelNewFunction.Item(j).ContextSpecificBodyPtrId); if(this->m_marks.IsMarked(body)) { liveTopLevelBodies.Add(body); this->m_marks.ClearMark(body); } } for(int32 j = 0; j < topLevelEval.Count(); ++j) { Js::FunctionBody* body = TTD_COERCE_PTR_ID_TO_FUNCTIONBODY(topLevelEval.Item(j).ContextSpecificBodyPtrId); if(this->m_marks.IsMarked(body)) { liveTopLevelBodies.Add(body); this->m_marks.ClearMark(body); } } } UnorderedArrayList<NSSnapValues::SnapContext, TTD_ARRAY_LIST_SIZE_XSMALL>& snpCtxs = this->m_pendingSnap->GetContextList(); for(int32 i = 0; i < threadContext->TTDContext->GetTTDContexts().Count(); ++i) { NSSnapValues::SnapContext* snpCtx = snpCtxs.NextOpenEntry(); NSSnapValues::ExtractScriptContext(snpCtx, threadContext->TTDContext->GetTTDContexts().Item(i), objToLogIdMap, liveTopLevelBodies, snap->GetSnapshotSlabAllocator()); } //extract the thread context symbol map info JsUtil::BaseDictionary<Js::HashedCharacterBuffer<char16>*, const Js::PropertyRecord*, Recycler, PowerOf2SizePolicy, Js::PropertyRecordStringHashComparer>* tcSymbolRegistrationMap = threadContext->GetSymbolRegistrationMap_TTD(); UnorderedArrayList<Js::PropertyId, TTD_ARRAY_LIST_SIZE_XSMALL>& tcSymbolMapInfo = this->m_pendingSnap->GetTCSymbolMapInfoList(); for(auto iter = tcSymbolRegistrationMap->GetIterator(); iter.IsValid(); iter.MoveNext()) { Js::PropertyId* tcpid = tcSymbolMapInfo.NextOpenEntry(); *tcpid = iter.CurrentValue()->GetPropertyId(); } this->m_idToHandlerMap.Initialize(this->m_marks.GetCountForTag<MarkTableTag::TypeHandlerTag>()); this->m_idToTypeMap.Initialize(this->m_marks.GetCountForTag<MarkTableTag::TypeTag>()); //walk all the marked objects this->m_marks.InitializeIter(); MarkTableTag tag = this->m_marks.GetTagValue(); while(tag != MarkTableTag::Clear) { switch(tag & MarkTableTag::AllKindMask) { case MarkTableTag::TypeHandlerTag: this->ExtractHandlerIfNeeded(this->m_marks.GetPtrValue<Js::DynamicTypeHandler*>(), threadContext); break; case MarkTableTag::TypeTag: this->ExtractTypeIfNeeded(this->m_marks.GetPtrValue<Js::Type*>(), threadContext); break; case MarkTableTag::PrimitiveObjectTag: { this->ExtractTypeIfNeeded(this->m_marks.GetPtrValue<Js::RecyclableObject*>()->GetType(), threadContext); NSSnapValues::ExtractSnapPrimitiveValue(snap->GetNextAvailablePrimitiveObjectEntry(), this->m_marks.GetPtrValue<Js::RecyclableObject*>(), this->m_marks.GetTagValueIsWellKnown(), this->m_idToTypeMap, alloc); break; } case MarkTableTag::CompoundObjectTag: { this->ExtractTypeIfNeeded(this->m_marks.GetPtrValue<Js::RecyclableObject*>()->GetType(), threadContext); if(Js::ScriptFunction::Is(this->m_marks.GetPtrValue<Js::RecyclableObject*>())) { this->ExtractScriptFunctionEnvironmentIfNeeded(this->m_marks.GetPtrValue<Js::ScriptFunction*>()); } NSSnapObjects::ExtractCompoundObject(snap->GetNextAvailableCompoundObjectEntry(), this->m_marks.GetPtrValue<Js::RecyclableObject*>(), this->m_marks.GetTagValueIsWellKnown(), this->m_idToTypeMap, alloc); break; } case MarkTableTag::FunctionBodyTag: NSSnapValues::ExtractFunctionBodyInfo(snap->GetNextAvailableFunctionBodyResolveInfoEntry(), this->m_marks.GetPtrValue<Js::FunctionBody*>(), this->m_marks.GetTagValueIsWellKnown(), alloc); break; case MarkTableTag::EnvironmentTag: case MarkTableTag::SlotArrayTag: break; //should be handled with the associated script function default: TTDAssert(false, "If this isn't true then we have an unknown tag"); break; } this->m_marks.MoveToNextAddress(); tag = this->m_marks.GetTagValue(); } //Extract the roots ThreadContextTTD* txctx = threadContext->TTDContext; UnorderedArrayList<NSSnapValues::SnapRootInfoEntry, TTD_ARRAY_LIST_SIZE_MID>& rootlist = this->m_pendingSnap->GetRootList(); for(auto iter = threadContext->TTDContext->GetRootTagToObjectMap().GetIterator(); iter.IsValid(); iter.MoveNext()) { NSSnapValues::SnapRootInfoEntry* spe = rootlist.NextOpenEntry(); spe->LogObject = TTD_CONVERT_VAR_TO_PTR_ID(iter.CurrentValue()); spe->LogId = iter.CurrentKey(); spe->MaybeLongLivedRoot = txctx->ResolveIsLongLivedForExtract(spe->LogId); } if(threadContext->TTDContext->GetActiveScriptContext() == nullptr) { this->m_pendingSnap->SetActiveScriptContext(TTD_INVALID_LOG_PTR_ID); } else { TTD_LOG_PTR_ID ctxId = threadContext->TTDContext->GetActiveScriptContext()->ScriptContextLogTag; this->m_pendingSnap->SetActiveScriptContext(ctxId); } double endTime = timer.Now(); snap->ExtractTime = (endTime - startTime) / 1000.0; } SnapShot* SnapshotExtractor::CompleteSnapshot() { SnapShot* snap = this->m_pendingSnap; this->UnloadDataFromExtractor(); this->m_snapshotsTakenCount++; this->m_totalMarkMillis += snap->MarkTime; this->m_totalExtractMillis += snap->ExtractTime; if(this->m_maxMarkMillis < snap->MarkTime) { this->m_maxMarkMillis = snap->MarkTime; } if(this->m_maxExtractMillis < snap->ExtractTime) { this->m_maxExtractMillis = snap->ExtractTime; } this->m_lastMarkMillis = snap->MarkTime; this->m_lastExtractMillis = snap->ExtractTime; return snap; } void SnapshotExtractor::DoResetWeakCollectionPinSet(ThreadContext* threadContext) { //Add the roots for(auto iter = threadContext->TTDContext->GetRootTagToObjectMap().GetIterator(); iter.IsValid(); iter.MoveNext()) { Js::Var root = iter.CurrentValue(); this->MarkVisitVar(root); } while(!this->m_worklist.Empty()) { Js::RecyclableObject* nobj = this->m_worklist.Dequeue(); TTDAssert(JsSupport::IsVarComplexKind(nobj), "Should only be these two options"); this->MarkVisitStandardProperties(nobj); nobj->MarkVisitKindSpecificPtrs(this); } this->UnloadDataFromExtractor(); } } #endif
;/*! ; @file ; ; @ingroup fapi ; ; @brief DosWriteQueue DOS wrapper ; ; (c) osFree Project 2022, <http://www.osFree.org> ; for licence see licence.txt in root directory, or project website ; ; This is Family API implementation for DOS, used with BIND tools ; to link required API ; ; @author Yuri Prokushev (yuri.prokushev@gmail.com) ; ; ; ;*/ .8086 ; Helpers INCLUDE helpers.inc _TEXT SEGMENT BYTE PUBLIC 'CODE' USE16 @PROLOG DOSWRITEQUEUE @START DOSWRITEQUEUE XOR AX, AX EXIT: @EPILOG DOSWRITEQUEUE _TEXT ENDS END
;***************************************************************************** ;* trellis-64.asm: x86_64 trellis quantization ;***************************************************************************** ;* Copyright (C) 2012-2016 x264 project ;* ;* Authors: Loren Merritt <lorenm@u.washington.edu> ;* ;* This program is free software; you can redistribute it and/or modify ;* it under the terms of the GNU General Public License as published by ;* the Free Software Foundation; either version 2 of the License, or ;* (at your option) any later version. ;* ;* This program is distributed in the hope that it will be useful, ;* but WITHOUT ANY WARRANTY; without even the implied warranty of ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;* GNU General Public License for more details. ;* ;* You should have received a copy of the GNU General Public License ;* along with this program; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. ;* ;* This program is also available under a commercial proprietary license. ;* For more information, contact us at licensing@x264.com. ;***************************************************************************** ; This is a pretty straight-forward translation of the C code, except: ; * simd ssd and psy: 2x parallel, handling the 2 candidate values of abs_level. ; * simd trellis_coef0, ZERO_LEVEL_IDX, and the coef0 part of the main loop: ; 4x parallel, handling 4 node_ctxs of the same coef (even if some of those ; nodes are invalid). ; * Interprocedural register allocation. Eliminates argument-passing overhead ; to trellis_coef* subroutines. Also reduces codesize. ; Optimizations that I tried, and rejected because they were not faster: ; * Separate loops for node_ctx [4..7] or smaller subsets of [0..3]. ; Costs too much icache compared to the negligible speedup. ; * There are only 21 possible sets of live node_ctxs; we could keep track of ; exactly which set we're in and feed that (along with abs_level) into a jump ; table instead of the switch to select a trellis_coef subroutine. This would ; eliminate all branches about which node_ctxs are live, but costs either a ; bunch of icache or a bunch of call/ret, and the jump table itself is ; unpredictable. ; * Separate versions of trellis_coef* depending on whether we're doing the 1st ; or the 2nd of the two abs_level candidates. This would eliminate some ; branches about if(score is better). ; * Special case more values of coef. I had a coef2 at some intermediate point ; in the optimization process, but it didn't end up worthwhile in conjunction ; with all the other optimizations. ; * Unroll or simd writeback. I don't know why this didn't help. %include "x86inc.asm" %include "x86util.asm" SECTION_RODATA pd_8: times 4 dd 8 pd_m16: times 4 dd -16 pd_0123: dd 0, 1, 2, 3 pd_4567: dd 4, 5, 6, 7 sq_1: dq 1, 0 pq_128: times 2 dq 128 pq_ffffffff: times 2 dq 0xffffffff cextern cabac_entropy cextern cabac_transition cextern cabac_size_unary cextern cabac_transition_unary cextern dct4_weight_tab cextern dct8_weight_tab cextern dct4_weight2_tab cextern dct8_weight2_tab cextern last_coeff_flag_offset_8x8 cextern significant_coeff_flag_offset_8x8 cextern coeff_flag_offset_chroma_422_dc SECTION .text %define TRELLIS_SCORE_BIAS 1<<60 %define SIZEOF_NODE 16 %define CABAC_SIZE_BITS 8 %define LAMBDA_BITS 4 %macro SQUARE 2 ; dst, tmp ; could use pmuldq here, to eliminate the abs. but that would involve ; templating a sse4 version of all of trellis, for negligible speedup. %if cpuflag(ssse3) pabsd m%1, m%1 pmuludq m%1, m%1 %elif HIGH_BIT_DEPTH ABSD m%2, m%1 SWAP %1, %2 pmuludq m%1, m%1 %else pmuludq m%1, m%1 pand m%1, [pq_ffffffff] %endif %endmacro %macro LOAD_DUP 2 ; dst, src %if cpuflag(ssse3) movddup %1, %2 %else movd %1, %2 punpcklqdq %1, %1 %endif %endmacro ;----------------------------------------------------------------------------- ; int trellis_cabac_4x4_psy( ; const int *unquant_mf, const uint8_t *zigzag, int lambda2, ; int last_nnz, dctcoef *orig_coefs, dctcoef *quant_coefs, dctcoef *dct, ; uint8_t *cabac_state_sig, uint8_t *cabac_state_last, ; uint64_t level_state0, uint16_t level_state1, ; int b_ac, dctcoef *fenc_dct, int psy_trellis ) ;----------------------------------------------------------------------------- %macro TRELLIS 4 %define num_coefs %2 %define dc %3 %define psy %4 cglobal %1, 4,15,9 %assign level_tree_size 64*8*2*4 ; could depend on num_coefs, but nonuniform stack size would prevent accessing args from trellis_coef* %assign pad 96 + level_tree_size + 16*SIZEOF_NODE + 16-gprsize-(stack_offset&15) SUB rsp, pad DEFINE_ARGS unquant_mf, zigzag, lambda2, ii, orig_coefs, quant_coefs, dct, cabac_state_sig, cabac_state_last %if WIN64 %define level_statem rsp+stack_offset+80 ; r9m, except that we need to index into it (and r10m) as an array %else %define level_statem rsp+stack_offset+32 %endif %define b_acm r11m ; 4x4 only %define b_interlacedm r11m ; 8x8 only %define i_coefsm1 r11m ; dc only %define fenc_dctm r12m %define psy_trellism r13m %if num_coefs == 64 shl dword b_interlacedm, 6 %define dct_weight1_tab dct8_weight_tab %define dct_weight2_tab dct8_weight2_tab %else %define dct_weight1_tab dct4_weight_tab %define dct_weight2_tab dct4_weight2_tab %endif %define stack rsp %define last_nnzm [stack+0] %define zigzagm [stack+8] mov last_nnzm, iid mov zigzagm, zigzagq %if WIN64 == 0 %define orig_coefsm [stack+16] %define quant_coefsm [stack+24] mov orig_coefsm, orig_coefsq mov quant_coefsm, quant_coefsq %endif %define unquant_mfm [stack+32] %define levelgt1_ctxm [stack+40] %define ssd stack+48 %define cost_siglast stack+80 %define level_tree stack+96 ; trellis_node_t is layed out differently than C. ; struct-of-arrays rather than array-of-structs, for simd. %define nodes_curq r7 %define nodes_prevq r8 %define node_score(x) x*8 %define node_level_idx(x) 64+x*4 %define node_cabac_state(x) 96+x*4 lea nodes_curq, [level_tree + level_tree_size] lea nodes_prevq, [nodes_curq + 8*SIZEOF_NODE] mov r6, TRELLIS_SCORE_BIAS mov [nodes_curq + node_score(0)], r6 mov dword [nodes_curq + node_level_idx(0)], 0 movd mm0, [level_statem + 0] punpcklbw mm0, [level_statem + 4] punpcklwd mm0, [level_statem + 8] %define level_state_packed mm0 ; version for copying into node.cabac_state pcmpeqb m7, m7 ; TRELLIS_SCORE_MAX movq [nodes_curq + node_score(1)], m7 mova [nodes_curq + node_score(2)], m7 %define levels_usedq r4 %define levels_usedd r4d mov dword [level_tree], 0 mov levels_usedd, 1 %define abs_levelq r9 %define abs_leveld r9d %define abs_coefq r14 %define zigzagiq r5 %define zigzagid r5d %if num_coefs == 8 mov dword levelgt1_ctxm, 8 %else mov dword levelgt1_ctxm, 9 %endif %if psy LOAD_DUP m6, psy_trellism %define psy_trellis m6 %elif dc LOAD_DUP m6, [unquant_mfq] paddd m6, m6 %define unquant_mf m6 %endif %ifdef PIC %if dc == 0 mov unquant_mfm, unquant_mfq %endif ; Keep a single offset register to PICify all global constants. ; They're all relative to "beginning of this asm file's .text section", ; even tables that aren't in this file. ; (Any address in .text would work, this one was just convenient.) lea r0, [$$] %define GLOBAL +r0-$$ %else %define GLOBAL %endif TRELLIS_LOOP 0 ; node_ctx 0..3 TRELLIS_LOOP 1 ; node_ctx 1..7 .writeback: ; int level = bnode->level_idx; ; for( int i = b_ac; i <= last_nnz; i++ ) ; dct[zigzag[i]] = SIGN(level_tree[level].abs_level, orig_coefs[zigzag[i]]); ; level = level_tree[level].next; mov iid, last_nnzm add zigzagq, iiq neg iiq %if num_coefs == 16 && dc == 0 mov r2d, b_acm add iiq, r2 %endif %define dctq r10 mov r0d, [nodes_curq + node_level_idx(0) + rax*4] .writeback_loop: movzx r2, byte [zigzagq + iiq] %if cpuflag(ssse3) movd m0, [level_tree + r0*4] movzx r0, word [level_tree + r0*4] psrld m0, 16 movd m1, [dctq + r2*SIZEOF_DCTCOEF] %if HIGH_BIT_DEPTH psignd m0, m1 movd [dctq + r2*SIZEOF_DCTCOEF], m0 %else psignw m0, m1 movd r4d, m0 mov [dctq + r2*SIZEOF_DCTCOEF], r4w %endif %else mov r5d, [level_tree + r0*4] %if HIGH_BIT_DEPTH mov r4d, dword [dctq + r2*SIZEOF_DCTCOEF] %else movsx r4d, word [dctq + r2*SIZEOF_DCTCOEF] %endif movzx r0d, r5w sar r4d, 31 shr r5d, 16 xor r5d, r4d sub r5d, r4d %if HIGH_BIT_DEPTH mov [dctq + r2*SIZEOF_DCTCOEF], r5d %else mov [dctq + r2*SIZEOF_DCTCOEF], r5w %endif %endif inc iiq jle .writeback_loop mov eax, 1 .return: ADD rsp, pad RET %if num_coefs == 16 && dc == 0 .return_zero: pxor m0, m0 mova [r10+ 0], m0 mova [r10+16], m0 %if HIGH_BIT_DEPTH mova [r10+32], m0 mova [r10+48], m0 %endif jmp .return %endif %endmacro ; TRELLIS %macro TRELLIS_LOOP 1 ; ctx_hi .i_loop%1: ; if( !quant_coefs[i] ) mov r6, quant_coefsm %if HIGH_BIT_DEPTH mov abs_leveld, dword [r6 + iiq*SIZEOF_DCTCOEF] %else movsx abs_leveld, word [r6 + iiq*SIZEOF_DCTCOEF] %endif ; int sigindex = num_coefs == 64 ? significant_coeff_flag_offset_8x8[b_interlaced][i] : ; num_coefs == 8 ? coeff_flag_offset_chroma_422_dc[i] : i; mov r10, cabac_state_sigm %if num_coefs == 64 mov r6d, b_interlacedm %ifdef PIC add r6d, iid movzx r6d, byte [significant_coeff_flag_offset_8x8 + r6 GLOBAL] %else movzx r6d, byte [significant_coeff_flag_offset_8x8 + r6 + iiq] %endif movzx r10, byte [r10 + r6] %elif num_coefs == 8 movzx r13, byte [coeff_flag_offset_chroma_422_dc + iiq GLOBAL] movzx r10, byte [r10 + r13] %else movzx r10, byte [r10 + iiq] %endif test abs_leveld, abs_leveld jnz %%.nonzero_quant_coef %if %1 == 0 ; int cost_sig0 = x264_cabac_size_decision_noup2( &cabac_state_sig[sigindex], 0 ) ; * (uint64_t)lambda2 >> ( CABAC_SIZE_BITS - LAMBDA_BITS ); ; nodes_cur[0].score -= cost_sig0; movzx r10, word [cabac_entropy + r10*2 GLOBAL] imul r10, lambda2q shr r10, CABAC_SIZE_BITS - LAMBDA_BITS sub [nodes_curq + node_score(0)], r10 %endif ZERO_LEVEL_IDX %1, cur jmp .i_continue%1 %%.nonzero_quant_coef: ; int sign_coef = orig_coefs[zigzag[i]]; ; int abs_coef = abs( sign_coef ); ; int q = abs( quant_coefs[i] ); movzx zigzagid, byte [zigzagq+iiq] movd m0, abs_leveld mov r6, orig_coefsm %if HIGH_BIT_DEPTH LOAD_DUP m1, [r6 + zigzagiq*SIZEOF_DCTCOEF] %else LOAD_DUP m1, [r6 + zigzagiq*SIZEOF_DCTCOEF - 2] psrad m1, 16 ; sign_coef %endif punpcklqdq m0, m0 ; quant_coef %if cpuflag(ssse3) pabsd m0, m0 pabsd m2, m1 ; abs_coef %else pxor m8, m8 pcmpgtd m8, m1 ; sign_mask pxor m0, m8 pxor m2, m1, m8 psubd m0, m8 psubd m2, m8 %endif psubd m0, [sq_1] ; abs_level movd abs_leveld, m0 xchg nodes_curq, nodes_prevq ; if( i < num_coefs-1 ) ; int lastindex = num_coefs == 64 ? last_coeff_flag_offset_8x8[i] : i; ; num_coefs == 8 ? coeff_flag_offset_chroma_422_dc[i] : i ; cost_siglast[0] = x264_cabac_size_decision_noup2( &cabac_state_sig[sigindex], 0 ); ; cost_sig1 = x264_cabac_size_decision_noup2( &cabac_state_sig[sigindex], 1 ); ; cost_siglast[1] = x264_cabac_size_decision_noup2( &cabac_state_last[lastindex], 0 ) + cost_sig1; ; cost_siglast[2] = x264_cabac_size_decision_noup2( &cabac_state_last[lastindex], 1 ) + cost_sig1; %if %1 == 0 %if dc && num_coefs != 8 cmp iid, i_coefsm1 %else cmp iid, num_coefs-1 %endif je %%.zero_siglast %endif movzx r11, word [cabac_entropy + r10*2 GLOBAL] xor r10, 1 movzx r12, word [cabac_entropy + r10*2 GLOBAL] mov [cost_siglast+0], r11d mov r10, cabac_state_lastm %if num_coefs == 64 movzx r6d, byte [last_coeff_flag_offset_8x8 + iiq GLOBAL] movzx r10, byte [r10 + r6] %elif num_coefs == 8 movzx r10, byte [r10 + r13] %else movzx r10, byte [r10 + iiq] %endif movzx r11, word [cabac_entropy + r10*2 GLOBAL] add r11, r12 mov [cost_siglast+4], r11d %if %1 == 0 xor r10, 1 movzx r10, word [cabac_entropy + r10*2 GLOBAL] add r10, r12 mov [cost_siglast+8], r10d %endif %%.skip_siglast: ; int unquant_abs_level = ((unquant_mf[zigzag[i]] * abs_level + 128) >> 8); ; int d = abs_coef - unquant_abs_level; ; uint64_t ssd = (int64_t)d*d * coef_weight[i]; %if dc pmuludq m0, unquant_mf %else %ifdef PIC mov r10, unquant_mfm LOAD_DUP m3, [r10 + zigzagiq*4] %else LOAD_DUP m3, [unquant_mfq + zigzagiq*4] %endif pmuludq m0, m3 %endif paddd m0, [pq_128] psrld m0, 8 ; unquant_abs_level %if psy || dc == 0 mova m4, m0 %endif psubd m0, m2 SQUARE 0, 3 %if dc psllq m0, 8 %else LOAD_DUP m5, [dct_weight2_tab + zigzagiq*4 GLOBAL] pmuludq m0, m5 %endif %if psy test iid, iid jz %%.dc_rounding ; int predicted_coef = fenc_dct[zigzag[i]] - sign_coef ; int psy_value = abs(unquant_abs_level + SIGN(predicted_coef, sign_coef)); ; int psy_weight = dct_weight_tab[zigzag[i]] * h->mb.i_psy_trellis; ; ssd1[k] -= psy_weight * psy_value; mov r6, fenc_dctm %if HIGH_BIT_DEPTH LOAD_DUP m3, [r6 + zigzagiq*SIZEOF_DCTCOEF] %else LOAD_DUP m3, [r6 + zigzagiq*SIZEOF_DCTCOEF - 2] psrad m3, 16 ; orig_coef %endif %if cpuflag(ssse3) psignd m4, m1 ; SIGN(unquant_abs_level, sign_coef) %else PSIGN d, m4, m8 %endif psubd m3, m1 ; predicted_coef paddd m4, m3 %if cpuflag(ssse3) pabsd m4, m4 %else ABSD m3, m4 SWAP 4, 3 %endif LOAD_DUP m1, [dct_weight1_tab + zigzagiq*4 GLOBAL] pmuludq m1, psy_trellis pmuludq m4, m1 psubq m0, m4 %if %1 %%.dc_rounding: %endif %endif %if %1 == 0 mova [ssd], m0 %endif %if dc == 0 && %1 == 0 test iid, iid jnz %%.skip_dc_rounding %%.dc_rounding: ; Optimize rounding for DC coefficients in DC-only luma 4x4/8x8 blocks. ; int d = abs_coef - ((unquant_abs_level + (sign_coef>>31) + 8)&~15); ; uint64_t ssd = (int64_t)d*d * coef_weight[i]; psrad m1, 31 ; sign_coef>>31 paddd m4, [pd_8] paddd m4, m1 pand m4, [pd_m16] ; (unquant_abs_level + (sign_coef>>31) + 8)&~15 psubd m4, m2 ; d SQUARE 4, 3 pmuludq m4, m5 mova [ssd], m4 %%.skip_dc_rounding: %endif mova [ssd+16], m0 %assign stack_offset_bak stack_offset cmp abs_leveld, 1 jl %%.switch_coef0 %if %1 == 0 mov r10, [ssd] ; trellis_coef* args %endif movq r12, m0 ; for( int j = 0; j < 8; j++ ) ; nodes_cur[j].score = TRELLIS_SCORE_MAX; %if cpuflag(ssse3) mova [nodes_curq + node_score(0)], m7 mova [nodes_curq + node_score(2)], m7 %else ; avoid store-forwarding stalls on k8/k10 %if %1 == 0 movq [nodes_curq + node_score(0)], m7 %endif movq [nodes_curq + node_score(1)], m7 movq [nodes_curq + node_score(2)], m7 movq [nodes_curq + node_score(3)], m7 %endif mova [nodes_curq + node_score(4)], m7 mova [nodes_curq + node_score(6)], m7 je %%.switch_coef1 %%.switch_coefn: call trellis_coefn.entry%1 call trellis_coefn.entry%1b jmp .i_continue1 %%.switch_coef1: call trellis_coef1.entry%1 call trellis_coefn.entry%1b jmp .i_continue1 %%.switch_coef0: call trellis_coef0_%1 call trellis_coef1.entry%1b .i_continue%1: dec iid %if num_coefs == 16 && dc == 0 cmp iid, b_acm %endif jge .i_loop%1 call trellis_bnode_%1 %if %1 == 0 %if num_coefs == 16 && dc == 0 jz .return_zero %else jz .return %endif jmp .writeback %%.zero_siglast: xor r6d, r6d mov [cost_siglast+0], r6 mov [cost_siglast+8], r6d jmp %%.skip_siglast %endif %endmacro ; TRELLIS_LOOP ; just a synonym for %if %macro IF0 1+ %endmacro %macro IF1 1+ %1 %endmacro %macro ZERO_LEVEL_IDX 2 ; ctx_hi, prev ; for( int j = 0; j < 8; j++ ) ; nodes_cur[j].level_idx = levels_used; ; level_tree[levels_used].next = (trellis_level_t){ .next = nodes_cur[j].level_idx, .abs_level = 0 }; ; levels_used++; add levels_usedd, 3 and levels_usedd, ~3 ; allow aligned stores movd m0, levels_usedd pshufd m0, m0, 0 IF%1 mova m1, m0 paddd m0, [pd_0123] IF%1 paddd m1, [pd_4567] mova m2, [nodes_%2q + node_level_idx(0)] IF%1 mova m3, [nodes_%2q + node_level_idx(4)] mova [nodes_curq + node_level_idx(0)], m0 IF%1 mova [nodes_curq + node_level_idx(4)], m1 mova [level_tree + (levels_usedq+0)*4], m2 IF%1 mova [level_tree + (levels_usedq+4)*4], m3 add levels_usedd, (1+%1)*4 %endmacro INIT_XMM sse2 TRELLIS trellis_cabac_4x4, 16, 0, 0 TRELLIS trellis_cabac_8x8, 64, 0, 0 TRELLIS trellis_cabac_4x4_psy, 16, 0, 1 TRELLIS trellis_cabac_8x8_psy, 64, 0, 1 TRELLIS trellis_cabac_dc, 16, 1, 0 TRELLIS trellis_cabac_chroma_422_dc, 8, 1, 0 INIT_XMM ssse3 TRELLIS trellis_cabac_4x4, 16, 0, 0 TRELLIS trellis_cabac_8x8, 64, 0, 0 TRELLIS trellis_cabac_4x4_psy, 16, 0, 1 TRELLIS trellis_cabac_8x8_psy, 64, 0, 1 TRELLIS trellis_cabac_dc, 16, 1, 0 TRELLIS trellis_cabac_chroma_422_dc, 8, 1, 0 %define stack rsp+gprsize %define scoreq r14 %define bitsq r13 %define bitsd r13d INIT_XMM %macro clocal 1 ALIGN 16 global mangle(x264_%1) mangle(x264_%1): %1: %assign stack_offset stack_offset_bak+gprsize %endmacro %macro TRELLIS_BNODE 1 ; ctx_hi clocal trellis_bnode_%1 ; int j = ctx_hi?1:0; ; trellis_node_t *bnode = &nodes_cur[j]; ; while( ++j < (ctx_hi?8:4) ) ; if( nodes_cur[j].score < bnode->score ) ; bnode = &nodes_cur[j]; %assign j %1 mov rax, [nodes_curq + node_score(j)] lea rax, [rax*8 + j] %rep 3+3*%1 %assign j j+1 mov r11, [nodes_curq + node_score(j)] lea r11, [r11*8 + j] cmp rax, r11 cmova rax, r11 %endrep mov r10, dctm and eax, 7 ret %endmacro ; TRELLIS_BNODE TRELLIS_BNODE 0 TRELLIS_BNODE 1 %macro TRELLIS_COEF0 1 ; ctx_hi clocal trellis_coef0_%1 ; ssd1 += (uint64_t)cost_sig * lambda2 >> ( CABAC_SIZE_BITS - LAMBDA_BITS ); mov r11d, [cost_siglast+0] imul r11, lambda2q shr r11, CABAC_SIZE_BITS - LAMBDA_BITS add r11, [ssd+16] %if %1 == 0 ; nodes_cur[0].score = nodes_prev[0].score + ssd - ssd1; mov scoreq, [nodes_prevq + node_score(0)] add scoreq, [ssd] sub scoreq, r11 mov [nodes_curq + node_score(0)], scoreq %endif ; memcpy mov scoreq, [nodes_prevq + node_score(1)] mov [nodes_curq + node_score(1)], scoreq mova m1, [nodes_prevq + node_score(2)] mova [nodes_curq + node_score(2)], m1 %if %1 mova m1, [nodes_prevq + node_score(4)] mova [nodes_curq + node_score(4)], m1 mova m1, [nodes_prevq + node_score(6)] mova [nodes_curq + node_score(6)], m1 %endif mov r6d, [nodes_prevq + node_cabac_state(3)] mov [nodes_curq + node_cabac_state(3)], r6d %if %1 mova m1, [nodes_prevq + node_cabac_state(4)] mova [nodes_curq + node_cabac_state(4)], m1 %endif ZERO_LEVEL_IDX %1, prev ret %endmacro ; TRELLIS_COEF0 TRELLIS_COEF0 0 TRELLIS_COEF0 1 %macro START_COEF 1 ; gt1 ; if( (int64_t)nodes_prev[0].score < 0 ) continue; mov scoreq, [nodes_prevq + node_score(j)] %if j > 0 test scoreq, scoreq js .ctx %+ nextj_if_invalid %endif ; f8_bits += x264_cabac_size_decision2( &n.cabac_state[coeff_abs_level1_ctx[j]], abs_level > 1 ); %if j >= 3 movzx r6d, byte [nodes_prevq + node_cabac_state(j) + (coeff_abs_level1_offs>>2)] ; >> because node only stores ctx 0 and 4 movzx r11, byte [cabac_transition + r6*2 + %1 GLOBAL] %else movzx r6d, byte [level_statem + coeff_abs_level1_offs] %endif %if %1 xor r6d, 1 %endif movzx bitsd, word [cabac_entropy + r6*2 GLOBAL] ; n.score += ssd; ; unsigned f8_bits = cost_siglast[ j ? 1 : 2 ]; %if j == 0 add scoreq, r10 add bitsd, [cost_siglast+8] %else add scoreq, r12 add bitsd, [cost_siglast+4] %endif %endmacro ; START_COEF %macro END_COEF 1 ; n.score += (uint64_t)f8_bits * lambda2 >> ( CABAC_SIZE_BITS - LAMBDA_BITS ); imul bitsq, lambda2q shr bitsq, CABAC_SIZE_BITS - LAMBDA_BITS add scoreq, bitsq ; if( n.score < nodes_cur[node_ctx].score ) ; SET_LEVEL( n, abs_level ); ; nodes_cur[node_ctx] = n; cmp scoreq, [nodes_curq + node_score(node_ctx)] jae .ctx %+ nextj_if_valid mov [nodes_curq + node_score(node_ctx)], scoreq %if j == 2 || (j <= 3 && node_ctx == 4) ; if this node hasn't previously needed to keep track of abs_level cabac_state, import a pristine copy of the input states movd [nodes_curq + node_cabac_state(node_ctx)], level_state_packed %elif j >= 3 ; if we have updated before, then copy cabac_state from the parent node mov r6d, [nodes_prevq + node_cabac_state(j)] mov [nodes_curq + node_cabac_state(node_ctx)], r6d %endif %if j >= 3 ; skip the transition if we're not going to reuse the context mov [nodes_curq + node_cabac_state(node_ctx) + (coeff_abs_level1_offs>>2)], r11b ; delayed from x264_cabac_size_decision2 %endif %if %1 && node_ctx == 7 mov r6d, levelgt1_ctxm mov [nodes_curq + node_cabac_state(node_ctx) + coeff_abs_levelgt1_offs-6], r10b %endif mov r6d, [nodes_prevq + node_level_idx(j)] %if %1 mov r11d, abs_leveld shl r11d, 16 or r6d, r11d %else or r6d, 1<<16 %endif mov [level_tree + levels_usedq*4], r6d mov [nodes_curq + node_level_idx(node_ctx)], levels_usedd inc levels_usedd %endmacro ; END_COEF %macro COEF1 2 %assign j %1 %assign nextj_if_valid %1+1 %assign nextj_if_invalid %2 %if j < 4 %assign coeff_abs_level1_offs j+1 %else %assign coeff_abs_level1_offs 0 %endif %if j < 3 %assign node_ctx j+1 %else %assign node_ctx j %endif .ctx %+ j: START_COEF 0 add bitsd, 1 << CABAC_SIZE_BITS END_COEF 0 %endmacro ; COEF1 %macro COEFN 2 %assign j %1 %assign nextj_if_valid %2 %assign nextj_if_invalid %2 %if j < 4 %assign coeff_abs_level1_offs j+1 %assign coeff_abs_levelgt1_offs 5 %else %assign coeff_abs_level1_offs 0 %assign coeff_abs_levelgt1_offs j+2 ; this is the one used for all block types except 4:2:2 chroma dc %endif %if j < 4 %assign node_ctx 4 %elif j < 7 %assign node_ctx j+1 %else %assign node_ctx 7 %endif .ctx %+ j: START_COEF 1 ; if( abs_level >= 15 ) ; bits += bs_size_ue_big(...) add bitsd, r5d ; bs_size_ue_big from COEFN_SUFFIX ; n.cabac_state[levelgt1_ctx] %if j == 7 ; && compiling support for 4:2:2 mov r6d, levelgt1_ctxm %define coeff_abs_levelgt1_offs r6 %endif %if j == 7 movzx r10, byte [nodes_prevq + node_cabac_state(j) + coeff_abs_levelgt1_offs-6] ; -6 because node only stores ctx 8 and 9 %else movzx r10, byte [level_statem + coeff_abs_levelgt1_offs] %endif ; f8_bits += cabac_size_unary[abs_level-1][n.cabac_state[levelgt1_ctx[j]]]; add r10d, r1d movzx r6d, word [cabac_size_unary + (r10-128)*2 GLOBAL] add bitsd, r6d %if node_ctx == 7 movzx r10, byte [cabac_transition_unary + r10-128 GLOBAL] %endif END_COEF 1 %endmacro ; COEFN clocal trellis_coef1 .entry0b: ; ctx_lo, larger of the two abs_level candidates mov r10, [ssd+8] sub r10, r11 mov r12, [ssd+24] sub r12, r11 .entry0: ; ctx_lo, smaller of the two abs_level candidates COEF1 0, 4 COEF1 1, 4 COEF1 2, 4 COEF1 3, 4 .ctx4: rep ret .entry1b: ; ctx_hi, larger of the two abs_level candidates mov r12, [ssd+24] sub r12, r11 .entry1: ; ctx_hi, smaller of the two abs_level candidates trellis_coef1_hi: COEF1 1, 2 COEF1 2, 3 COEF1 3, 4 COEF1 4, 5 COEF1 5, 6 COEF1 6, 7 COEF1 7, 8 .ctx8: rep ret %macro COEFN_PREFIX 1 ; int prefix = X264_MIN( abs_level - 1, 14 ); mov r1d, abs_leveld cmp abs_leveld, 15 jge .level_suffix%1 xor r5d, r5d .skip_level_suffix%1: shl r1d, 7 %endmacro %macro COEFN_SUFFIX 1 .level_suffix%1: ; bs_size_ue_big( abs_level - 15 ) << CABAC_SIZE_BITS; lea r5d, [abs_levelq-14] bsr r5d, r5d shl r5d, CABAC_SIZE_BITS+1 add r5d, 1<<CABAC_SIZE_BITS ; int prefix = X264_MIN( abs_level - 1, 14 ); mov r1d, 15 jmp .skip_level_suffix%1 %endmacro clocal trellis_coefn .entry0b: mov r10, [ssd+8] mov r12, [ssd+24] inc abs_leveld .entry0: ; I could fully separate the ctx_lo and ctx_hi versions of coefn, and then ; apply return-on-first-failure to ctx_lo. Or I can use multiple entrypoints ; to merge the common portion of ctx_lo and ctx_hi, and thus reduce codesize. ; I can't do both, as return-on-first-failure doesn't work for ctx_hi. ; The C version has to be fully separate since C doesn't support multiple ; entrypoints. But return-on-first-failure isn't very important here (as ; opposed to coef1), so I might as well reduce codesize. COEFN_PREFIX 0 COEFN 0, 1 COEFN 1, 2 COEFN 2, 3 COEFN 3, 8 .ctx8: mov zigzagq, zigzagm ; unspill since r1 was clobbered ret .entry1b: mov r12, [ssd+24] inc abs_leveld .entry1: COEFN_PREFIX 1 COEFN 4, 5 COEFN 5, 6 COEFN 6, 7 COEFN 7, 1 jmp .ctx1 COEFN_SUFFIX 0 COEFN_SUFFIX 1
; ; Speed-optimized LZSA1 decompressor by spke & uniabis (109 bytes) ; ; ver.00 by spke for LZSA 0.5.4 (03-24/04/2019, 134 bytes); ; ver.01 by spke for LZSA 0.5.6 (25/04/2019, 110(-24) bytes, +0.2% speed); ; ver.02 by spke for LZSA 1.0.5 (24/07/2019, added support for backward decompression); ; ver.03 by uniabis (30/07/2019, 109(-1) bytes, +3.5% speed); ; ver.04 by spke (31/07/2019, small re-organization of macros); ; ver.05 by uniabis (22/08/2019, 107(-2) bytes, same speed); ; ver.06 by spke for LZSA 1.0.7 (27/08/2019, 111(+4) bytes, +2.1% speed); ; ver.07 by spke for LZSA 1.1.0 (25/09/2019, added full revision history); ; ver.08 by spke for LZSA 1.1.2 (22/10/2019, re-organized macros and added an option for unrolled copying of long matches); ; ver.09 by spke for LZSA 1.2.1 (02/01/2020, 109(-2) bytes, same speed) ; ; The data must be compressed using the command line compressor by Emmanuel Marty ; The compression is done as follows: ; ; lzsa.exe -f1 -r <sourcefile> <outfile> ; ; where option -r asks for the generation of raw (frame-less) data. ; ; The decompression is done in the standard way: ; ; ld hl,FirstByteOfCompressedData ; ld de,FirstByteOfMemoryForDecompressedData ; call DecompressLZSA1 ; ; Backward compression is also supported; you can compress files backward using: ; ; lzsa.exe -f1 -r -b <sourcefile> <outfile> ; ; and decompress the resulting files using: ; ; ld hl,LastByteOfCompressedData ; ld de,LastByteOfMemoryForDecompressedData ; call DecompressLZSA1 ; ; (do not forget to uncomment the BACKWARD_DECOMPRESS option in the decompressor). ; ; Of course, LZSA compression algorithms are (c) 2019 Emmanuel Marty, ; see https://github.com/emmanuel-marty/lzsa for more information ; ; Drop me an email if you have any comments/ideas/suggestions: zxintrospec@gmail.com ; ; This software is provided 'as-is', without any express or implied ; warranty. In no event will the authors be held liable for any damages ; arising from the use of this software. ; ; Permission is granted to anyone to use this software for any purpose, ; including commercial applications, and to alter it and redistribute it ; freely, subject to the following restrictions: ; ; 1. The origin of this software must not be misrepresented; you must not ; claim that you wrote the original software. If you use this software ; in a product, an acknowledgment in the product documentation would be ; appreciated but is not required. ; 2. Altered source versions must be plainly marked as such, and must not be ; misrepresented as being the original software. ; 3. This notice may not be removed or altered from any source distribution. ; DEFINE UNROLL_LONG_MATCHES ; uncomment for faster decompression of very compressible data (+57 bytes) ; DEFINE BACKWARD_DECOMPRESS IFNDEF BACKWARD_DECOMPRESS MACRO NEXT_HL inc hl ENDM MACRO ADD_OFFSET ex de,hl : add hl,de ENDM MACRO COPY1 ldi ENDM MACRO COPYBC ldir ENDM ELSE MACRO NEXT_HL dec hl ENDM MACRO ADD_OFFSET ex de,hl : ld a,e : sub l : ld l,a ld a,d : sbc h : ld h,a ; 4*4+3*4 = 28t / 7 bytes ENDM MACRO COPY1 ldd ENDM MACRO COPYBC lddr ENDM ENDIF @DecompressLZSA1: ld b,0 : jr ReadToken NoLiterals: xor (hl) : NEXT_HL : jp m,LongOffset ShortOffset: push de : ld e,(hl) : ld d,#FF ; short matches have length 0+3..14+3 add 3 : cp 15+3 : jr nc,LongerMatch ; placed here this saves a JP per iteration CopyMatch: ld c,a .UseC NEXT_HL : ex (sp),hl ; BC = len, DE = offset, HL = dest, SP ->[dest,src] ADD_OFFSET ; BC = len, DE = dest, HL = dest-offset, SP->[src] COPY1 : COPY1 : COPYBC ; BC = 0, DE = dest .popSrc pop hl ; HL = src ReadToken: ; first a byte token "O|LLL|MMMM" is read from the stream, ; where LLL is the number of literals and MMMM is ; a length of the match that follows after the literals ld a,(hl) : and #70 : jr z,NoLiterals cp #70 : jr z,MoreLiterals ; LLL=7 means 7+ literals... rrca : rrca : rrca : rrca : ld c,a ; LLL<7 means 0..6 literals... ld a,(hl) : NEXT_HL COPYBC ; the top bit of token is set if the offset contains two bytes and #8F : jp p,ShortOffset LongOffset: ; read second byte of the offset push de : ld e,(hl) : NEXT_HL : ld d,(hl) add -128+3 : cp 15+3 : jp c,CopyMatch IFNDEF UNROLL_LONG_MATCHES ; MMMM=15 indicates a multi-byte number of literals LongerMatch: NEXT_HL : add (hl) : jr nc,CopyMatch ; the codes are designed to overflow; ; the overflow value 1 means read 1 extra byte ; and overflow value 0 means read 2 extra bytes .code1 ld b,a : NEXT_HL : ld c,(hl) : jr nz,CopyMatch.UseC .code0 NEXT_HL : ld b,(hl) ; the two-byte match length equal to zero ; designates the end-of-data marker ld a,b : or c : jr nz,CopyMatch.UseC pop de : ret ELSE ; MMMM=15 indicates a multi-byte number of literals LongerMatch: NEXT_HL : add (hl) : jr c,VeryLongMatch ld c,a .UseC NEXT_HL : ex (sp),hl ADD_OFFSET COPY1 : COPY1 ; this is an unrolled equivalent of LDIR xor a : sub c and 16-1 : add a ld (.jrOffset),a : jr nz,$+2 .jrOffset EQU $-1 .fastLDIR DUP 16 COPY1 EDUP jp pe,.fastLDIR jp CopyMatch.popSrc VeryLongMatch: ; the codes are designed to overflow; ; the overflow value 1 means read 1 extra byte ; and overflow value 0 means read 2 extra bytes .code1 ld b,a : NEXT_HL : ld c,(hl) : jr nz,LongerMatch.UseC .code0 NEXT_HL : ld b,(hl) ; the two-byte match length equal to zero ; designates the end-of-data marker ld a,b : or c : jr nz,LongerMatch.UseC pop de : ret ENDIF MoreLiterals: ; there are three possible situations here xor (hl) : NEXT_HL : exa ld a,7 : add (hl) : jr c,ManyLiterals CopyLiterals: ld c,a .UseC NEXT_HL : COPYBC exa : jp p,ShortOffset : jr LongOffset ManyLiterals: .code1 ld b,a : NEXT_HL : ld c,(hl) : jr nz,CopyLiterals.UseC .code0 NEXT_HL : ld b,(hl) : jr CopyLiterals.UseC
db 0 ; species ID placeholder db 40, 30, 32, 65, 50, 52 ; hp atk def spd sat sdf db BUG, WATER ; type db 200 ; catch rate db 54 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F50 ; gender ratio db 100 ; unknown 1 db 15 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/surskit/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_MEDIUM_FAST ; growth rate dn EGG_WATER_1, EGG_BUG ; egg groups ; tm/hm learnset tmhm DYNAMICPUNCH, HEADBUTT, CURSE, TOXIC, ZAP_CANNON, PSYCH_UP, HIDDEN_POWER, SUNNY_DAY, SNORE, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, RETURN, PSYCHIC_M, SHADOW_BALL, DOUBLE_TEAM, ICE_PUNCH, SWAGGER, SLEEP_TALK, THUNDERPUNCH, DREAM_EATER, REST, ATTRACT, THIEF, FIRE_PUNCH, NIGHTMARE, FLASH ; end
; A203516: a(n) = Product_{1 <= i < j <= n} 2*(i+j-1). ; Submitted by Jon Maiga ; 1,4,192,184320,4954521600,4794391461888000,204135216112950312960000,451965950843675288237663846400000,60040562704967329457107799785403842560000000,542366306792798635131534558788357929673196306432000000000 add $0,1 mov $1,1 mov $2,1 lpb $0 sub $0,1 add $2,1 mov $3,$2 mul $2,2 pow $2,$0 mul $1,$2 mov $2,3 add $2,$3 lpe mov $0,$1
#include "iEnv.h" #include <types.h> static void* lbl_803CBAB0; static void* lbl_803CBAB4; static RwCamera* sPipeCamera; static iEnv* lastEnv; const static float lbl_80260130[6] = { 1000.0f, 1000.0f, 1000.0f, -1000.0f, -1000.0f, -1000.0f }; RpAtomic* SetPipelineCB(RpAtomic* param_1, void* param_2) { if (RwCameraBeginUpdate(sPipeCamera) != NULL) { RpAtomicInstance(param_1); RwCameraEndUpdate(sPipeCamera); } if (param_2 != NULL) { param_1->pipeline = (RxPipeline*)param_2; } return param_1; } void iEnvSetBSP(iEnv* env, int32 envDataType, RpWorld* bsp) { if (envDataType == 0) { env->world = bsp; return; } if (envDataType == 1) { env->collision = bsp; return; } if (envDataType == 2) { env->fx = bsp; return; } if (envDataType == 3) { env->camera = bsp; return; } } // func_800C2F50 #pragma GLOBAL_ASM("asm/Core/p2/iEnv.s", "iEnvLoad__FP4iEnvPCvUii") void iEnvFree(iEnv* param_1) { _rwFrameSyncDirty(); RpWorldDestroy(param_1->world); param_1->world = NULL; if (param_1->fx != NULL) { RpWorldDestroy(param_1->fx); param_1->fx = NULL; } if (param_1->collision != NULL) { RpWorldDestroy(param_1->collision); param_1->collision = NULL; } return; } void iEnvDefaultLighting(iEnv* param) { } void iEnvLightingBasics(iEnv* param_1, xEnvAsset* param_2) { } // func_800C3128 #pragma GLOBAL_ASM("asm/Core/p2/iEnv.s", "Jsp_ClumpRender__FP7RpClumpP12xJSPNodeInfo") #ifdef NON_MATCHING // this cant cant possibly match until we add the type for xJSPHeader void iEnvRender(iEnv* param_1) { RwRenderStateSet(rwRENDERSTATESRCBLEND, 5); RwRenderStateSet(rwRENDERSTATEDESTBLEND, 6); if (param_1->jsp == NULL) { RpWorldRender(param_1->world); } else { Jsp_ClumpRender(param_1->jsp->field_0xc, param_1->jsp->field_0x14); } lastEnv = param_1; return; } #else #pragma GLOBAL_ASM("asm/Core/p2/iEnv.s", "iEnvRender__FP4iEnv") #endif // func_800C329C #pragma GLOBAL_ASM("asm/Core/p2/iEnv.s", "iEnvEndRenderFX__FP4iEnv")
; A305064: a(n) = 42*2^n - 20. ; 22,64,148,316,652,1324,2668,5356,10732,21484,42988,85996,172012,344044,688108,1376236,2752492,5505004,11010028,22020076,44040172,88080364,176160748,352321516,704643052,1409286124,2818572268,5637144556,11274289132,22548578284,45097156588,90194313196,180388626412,360777252844,721554505708,1443109011436,2886218022892,5772436045804,11544872091628,23089744183276,46179488366572,92358976733164,184717953466348,369435906932716,738871813865452,1477743627730924,2955487255461868,5910974510923756 mov $1,2 pow $1,$0 sub $1,1 mul $1,42 add $1,22
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r10 push %r9 push %rbp push %rbx push %rcx push %rdi push %rsi // Store lea addresses_PSE+0x1d2ec, %rcx nop nop nop sub $45637, %rsi movl $0x51525354, (%rcx) nop nop nop nop nop xor $51944, %rbp // Load lea addresses_US+0x116c, %rbx nop add $20087, %rdi movups (%rbx), %xmm0 vpextrq $0, %xmm0, %rcx nop nop and $15346, %r10 // Faulty Load lea addresses_UC+0x1996c, %rdi nop nop and $41373, %rbp mov (%rdi), %esi lea oracles, %rcx and $0xff, %rsi shlq $12, %rsi mov (%rcx,%rsi,1), %rsi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r9 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 7, 'size': 4, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 11, 'size': 16, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}} <gen_prepare_buffer> {'00': 17965} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
dnl mpn_copyi dnl Copyright 2009 Jason Moxham dnl This file is part of the MPIR Library. dnl The MPIR Library is free software; you can redistribute it and/or modify dnl it under the terms of the GNU Lesser General Public License as published dnl by the Free Software Foundation; either version 2.1 of the License, or (at dnl your option) any later version. dnl The MPIR Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public dnl License for more details. dnl You should have received a copy of the GNU Lesser General Public License dnl along with the MPIR Library; see the file COPYING.LIB. If not, write dnl to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, dnl Boston, MA 02110-1301, USA. include(`../config.m4') C ret mpn_copyi(mp_ptr,mp_ptr,mp_size_t) C rax rdi, rsi, rdx ASM_START() PROLOGUE(mpn_copyi) mov $3,%rcx lea -24(%rsi,%rdx,8),%rsi lea -24(%rdi,%rdx,8),%rdi sub %rdx,%rcx jnc skiplp ALIGN(16) lp: movdqu (%rsi,%rcx,8),%xmm0 movdqu 16(%rsi,%rcx,8),%xmm1 add $4,%rcx movdqu %xmm1,16-32(%rdi,%rcx,8) movdqu %xmm0,-32(%rdi,%rcx,8) jnc lp skiplp: cmp $2,%rcx ja case0 je case1 jp case2 case3: movdqu (%rsi,%rcx,8),%xmm0 mov 16(%rsi,%rcx,8),%rax mov %rax,16(%rdi,%rcx,8) movdqu %xmm0,(%rdi,%rcx,8) ret case2: movdqu (%rsi,%rcx,8),%xmm0 movdqu %xmm0,(%rdi,%rcx,8) ret case1: mov (%rsi,%rcx,8),%rax mov %rax,(%rdi,%rcx,8) case0: ret EPILOGUE()
/* Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org> 2004, 2005 Rob Buis <buis@kde.org> This file is part of the KDE project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "wtf/Platform.h" #if ENABLE(SVG) #include "AffineTransform.h" #include "SVGTransform.h" #include "SVGSVGElement.h" #include "SVGTransformDistance.h" #include "SVGTransformList.h" using namespace WebCore; SVGTransformList::SVGTransformList(const QualifiedName &attributeName) : SVGPODList<SVGTransform>(attributeName) { } SVGTransformList::~SVGTransformList() { } SVGTransform SVGTransformList::createSVGTransformFromMatrix(const AffineTransform &matrix) const { return SVGSVGElement::createSVGTransformFromMatrix(matrix); } SVGTransform SVGTransformList::consolidate() { ExceptionCode ec = 0; return initialize(concatenate(), ec); } SVGTransform SVGTransformList::concatenate() const { unsigned int length = numberOfItems(); if (!length) { return SVGTransform(); } AffineTransform matrix; ExceptionCode ec = 0; for (unsigned int i = 0; i < length; i++) { matrix = getItem(i, ec).matrix() * matrix; } return SVGTransform(matrix); } SVGTransform SVGTransformList::concatenateForType(SVGTransform::SVGTransformType type) const { unsigned int length = numberOfItems(); if (!length) { return SVGTransform(); } ExceptionCode ec = 0; SVGTransformDistance totalTransform; for (unsigned int i = 0; i < length; i++) { const SVGTransform &transform = getItem(i, ec); if (transform.type() == type) { totalTransform.addSVGTransform(transform); } } return totalTransform.addToSVGTransform(SVGTransform()); } #endif // ENABLE(SVG)
.data entrada:.word 201 um:.word 1 .text lw s0, entrada lw x10, um is_even: add x5, s0, x0 addi x6, x0, 2 rem x11,x5, x6 mul x11, x11, x11 ecall
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT /** * @brief Includes all public headers from Azure Identity SDK library. * */ #pragma once #include "azure/identity/chained_token_credential.hpp" #include "azure/identity/client_certificate_credential.hpp" #include "azure/identity/client_secret_credential.hpp" #include "azure/identity/dll_import_export.hpp" #include "azure/identity/environment_credential.hpp" #include "azure/identity/managed_identity_credential.hpp" #include "azure/identity/rtti.hpp"
; A061506: a(n) = lcm(6n+2, 6n+4, 6n+6). ; 12,120,1008,1320,5460,4896,15960,12144,35100,24360,65472,42840,109668,68880,170280,103776,249900,148824,351120,205320,476532,274560,628728,357840,810300,456456,1023840,571704,1271940,704880,1557192,857280,1882188,1030200,2249520,1224936,2661780,1442784,3121560,1685040,3631452,1953000,4194048,2247960,4811940,2571216,5487720,2924064,6223980,3307800,7023312,3723720,7888308,4173120,8821560,4657296,9825660,5177544,10903200,5735160,12056772,6331440,13288968,6967680,14602380,7645176,15999600,8365224 mul $0,3 seq $0,67046 ; a(n) = lcm(n, n+1, n+2)/6. mul $0,12
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.16.27026.1 include listing.inc INCLUDELIB MSVCRTD INCLUDELIB OLDNAMES _DATA SEGMENT COMM uint_number_zero:QWORD COMM uint_number_one:QWORD _DATA ENDS msvcjmc SEGMENT __7B7A869E_ctype@h DB 01H __457DD326_basetsd@h DB 01H __4384A2D9_corecrt_memcpy_s@h DB 01H __4E51A221_corecrt_wstring@h DB 01H __2140C079_string@h DB 01H __1887E595_winnt@h DB 01H __9FC7C64B_processthreadsapi@h DB 01H __FA470AEC_memoryapi@h DB 01H __F37DAFF1_winerror@h DB 01H __7A450CCC_winbase@h DB 01H __B4B40122_winioctl@h DB 01H __86261D59_stralign@h DB 01H __059414E1_pmc_sint_debug@h DB 01H __2415E362_test_op_equals@c DB 01H msvcjmc ENDS PUBLIC TEST_Equals_I_X PUBLIC TEST_Equals_L_X PUBLIC TEST_Equals_UX_X PUBLIC TEST_Equals_X_I PUBLIC TEST_Equals_X_L PUBLIC TEST_Equals_X_UX PUBLIC TEST_Equals_X_X PUBLIC __JustMyCode_Default PUBLIC ??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ ; `string' PUBLIC ??_C@_1CG@ECJOMMLD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ ; `string' PUBLIC ??_C@_1DM@DIPCKLML@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ ; `string' PUBLIC ??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ ; `string' PUBLIC ??_C@_1CG@KKLNDHML@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAL?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ ; `string' PUBLIC ??_C@_1DM@GDGMFIFF@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAL?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ ; `string' PUBLIC ??_C@_1CI@OFNPDABI@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ ; `string' PUBLIC ??_C@_1DO@PEPKKHHD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD@ ; `string' PUBLIC ??_C@_1CG@DJHBEGMK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAI?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ ; `string' PUBLIC ??_C@_1DM@GEGJHNOM@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAI?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ ; `string' PUBLIC ??_C@_1CG@BCPLJGNF@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAL?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ ; `string' PUBLIC ??_C@_1DM@CMCFOAHJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAL?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ ; `string' PUBLIC ??_C@_1CI@NLHEPFBK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ ; `string' PUBLIC ??_C@_1DO@HDBPOJFD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD@ ; `string' PUBLIC ??_C@_1CG@LMNANGKJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ ; `string' PUBLIC ??_C@_1DM@NGGGJAGM@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ ; `string' EXTRN TEST_Assert:PROC EXTRN FormatTestLabel:PROC EXTRN FormatTestMesssage:PROC EXTRN _RTC_CheckStackVars:PROC EXTRN _RTC_InitBase:PROC EXTRN _RTC_Shutdown:PROC EXTRN __CheckForDebuggerJustMyCode:PROC EXTRN __GSHandlerCheck:PROC EXTRN __security_check_cookie:PROC EXTRN __security_cookie:QWORD ; COMDAT pdata pdata SEGMENT $pdata$TEST_Equals_I_X DD imagerel $LN10 DD imagerel $LN10+512 DD imagerel $unwind$TEST_Equals_I_X pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$TEST_Equals_L_X DD imagerel $LN10 DD imagerel $LN10+513 DD imagerel $unwind$TEST_Equals_L_X pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$TEST_Equals_UX_X DD imagerel $LN13 DD imagerel $LN13+691 DD imagerel $unwind$TEST_Equals_UX_X pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$TEST_Equals_X_I DD imagerel $LN10 DD imagerel $LN10+512 DD imagerel $unwind$TEST_Equals_X_I pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$TEST_Equals_X_L DD imagerel $LN10 DD imagerel $LN10+513 DD imagerel $unwind$TEST_Equals_X_L pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$TEST_Equals_X_UX DD imagerel $LN13 DD imagerel $LN13+691 DD imagerel $unwind$TEST_Equals_X_UX pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$TEST_Equals_X_X DD imagerel $LN13 DD imagerel $LN13+697 DD imagerel $unwind$TEST_Equals_X_X pdata ENDS ; COMDAT rtc$TMZ rtc$TMZ SEGMENT _RTC_Shutdown.rtc$TMZ DQ FLAT:_RTC_Shutdown rtc$TMZ ENDS ; COMDAT rtc$IMZ rtc$IMZ SEGMENT _RTC_InitBase.rtc$IMZ DQ FLAT:_RTC_InitBase rtc$IMZ ENDS ; COMDAT ??_C@_1DM@NGGGJAGM@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ CONST SEGMENT ??_C@_1DM@NGGGJAGM@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'X', 00H, '_', 00H, 'X', 00H, 'n0', 0a9H, '_0^', 0b3H, '0', 0fcH DB '0', 0c9H, '0L0', 01fH, 'g', 085H, '_', 01aH, 090H, 08aH, '0g0' DB 'o0j0D0(', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1CG@LMNANGKJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ CONST SEGMENT ??_C@_1CG@LMNANGKJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'X', 00H, '_', 00H, 'X', 00H, ' ', 00H, '(', 00H, '%', 00H, 'd' DB 00H, '.', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1DO@HDBPOJFD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD@ CONST SEGMENT ??_C@_1DO@HDBPOJFD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'X', 00H, '_', 00H, 'U', 00H, 'X', 00H, 'n0', 0a9H, '_0^', 0b3H DB '0', 0fcH, '0', 0c9H, '0L0', 01fH, 'g', 085H, '_', 01aH, 090H, 08aH DB '0g0o0j0D0(', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1CI@NLHEPFBK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ CONST SEGMENT ??_C@_1CI@NLHEPFBK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'X', 00H, '_', 00H, 'U', 00H, 'X', 00H, ' ', 00H, '(', 00H, '%' DB 00H, 'd', 00H, '.', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1DM@CMCFOAHJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAL?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ CONST SEGMENT ??_C@_1DM@CMCFOAHJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAL?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'X', 00H, '_', 00H, 'L', 00H, 'n0', 0a9H, '_0^', 0b3H, '0', 0fcH DB '0', 0c9H, '0L0', 01fH, 'g', 085H, '_', 01aH, 090H, 08aH, '0g0' DB 'o0j0D0(', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1CG@BCPLJGNF@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAL?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ CONST SEGMENT ??_C@_1CG@BCPLJGNF@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAL?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'X', 00H, '_', 00H, 'L', 00H, ' ', 00H, '(', 00H, '%', 00H, 'd' DB 00H, '.', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1DM@GEGJHNOM@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAI?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ CONST SEGMENT ??_C@_1DM@GEGJHNOM@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAI?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'X', 00H, '_', 00H, 'I', 00H, 'n0', 0a9H, '_0^', 0b3H, '0', 0fcH DB '0', 0c9H, '0L0', 01fH, 'g', 085H, '_', 01aH, 090H, 08aH, '0g0' DB 'o0j0D0(', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1CG@DJHBEGMK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAI?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ CONST SEGMENT ??_C@_1CG@DJHBEGMK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAI?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'X', 00H, '_', 00H, 'I', 00H, ' ', 00H, '(', 00H, '%', 00H, 'd' DB 00H, '.', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1DO@PEPKKHHD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD@ CONST SEGMENT ??_C@_1DO@PEPKKHHD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'U', 00H, 'X', 00H, '_', 00H, 'X', 00H, 'n0', 0a9H, '_0^', 0b3H DB '0', 0fcH, '0', 0c9H, '0L0', 01fH, 'g', 085H, '_', 01aH, 090H, 08aH DB '0g0o0j0D0(', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1CI@OFNPDABI@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ CONST SEGMENT ??_C@_1CI@OFNPDABI@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'U', 00H, 'X', 00H, '_', 00H, 'X', 00H, ' ', 00H, '(', 00H, '%' DB 00H, 'd', 00H, '.', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1DM@GDGMFIFF@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAL?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ CONST SEGMENT ??_C@_1DM@GDGMFIFF@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAL?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'L', 00H, '_', 00H, 'X', 00H, 'n0', 0a9H, '_0^', 0b3H, '0', 0fcH DB '0', 0c9H, '0L0', 01fH, 'g', 085H, '_', 01aH, 090H, 08aH, '0g0' DB 'o0j0D0(', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1CG@KKLNDHML@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAL?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ CONST SEGMENT ??_C@_1CG@KKLNDHML@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAL?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'L', 00H, '_', 00H, 'X', 00H, ' ', 00H, '(', 00H, '%', 00H, 'd' DB 00H, '.', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ CONST SEGMENT ??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ DB 0c7H DB '0', 0fcH, '0', 0bfH, '0n0', 085H, 'Q', 0b9H, '[L0', 00H, 'N', 0f4H DB 081H, 'W0j0D0', 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1DM@DIPCKLML@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ CONST SEGMENT ??_C@_1DM@DIPCKLML@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'I', 00H, '_', 00H, 'X', 00H, 'n0', 0a9H, '_0^', 0b3H, '0', 0fcH DB '0', 0c9H, '0L0', 01fH, 'g', 085H, '_', 01aH, 090H, 08aH, '0g0' DB 'o0j0D0(', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1CG@ECJOMMLD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ CONST SEGMENT ??_C@_1CG@ECJOMMLD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ DB 'E' DB 00H, 'q', 00H, 'u', 00H, 'a', 00H, 'l', 00H, 's', 00H, '_', 00H DB 'I', 00H, '_', 00H, 'X', 00H, ' ', 00H, '(', 00H, '%', 00H, 'd' DB 00H, '.', 00H, '%', 00H, 'd', 00H, ')', 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT ??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ CONST SEGMENT ??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ DB 'F' DB 00H, 'r', 00H, 'o', 00H, 'm', 00H, 'B', 00H, 'y', 00H, 't', 00H DB 'e', 00H, 'A', 00H, 'r', 00H, 'r', 00H, 'a', 00H, 'y', 00H, 'n' DB '0', 0a9H, '_0^', 0b3H, '0', 0fcH, '0', 0c9H, '0L0', 01fH, 'g', 085H DB '_', 01aH, 090H, 08aH, '0g0o0j0D0(', 00H, '%', 00H, 'd', 00H, ')' DB 00H, 00H, 00H ; `string' CONST ENDS ; COMDAT xdata xdata SEGMENT $unwind$TEST_Equals_X_X DD 025054a19H DD 011d2322H DD 070160037H DD 05015H DD imagerel __GSHandlerCheck DD 01a0H xdata ENDS ; COMDAT CONST CONST SEGMENT TEST_Equals_X_X$rtcName$0 DB 075H DB 00H ORG $+2 TEST_Equals_X_X$rtcName$1 DB 076H DB 00H ORG $+2 TEST_Equals_X_X$rtcName$2 DB 061H DB 063H DB 074H DB 075H DB 061H DB 06cH DB 05fH DB 077H DB 00H ORG $+15 TEST_Equals_X_X$rtcVarDesc DD 064H DD 04H DQ FLAT:TEST_Equals_X_X$rtcName$2 DD 048H DD 08H DQ FLAT:TEST_Equals_X_X$rtcName$1 DD 028H DD 08H DQ FLAT:TEST_Equals_X_X$rtcName$0 ORG $+144 TEST_Equals_X_X$rtcFrameData DD 03H DD 00H DQ FLAT:TEST_Equals_X_X$rtcVarDesc CONST ENDS ; COMDAT xdata xdata SEGMENT $unwind$TEST_Equals_X_UX DD 025054a19H DD 011d2322H DD 070160037H DD 05015H DD imagerel __GSHandlerCheck DD 01a0H xdata ENDS ; COMDAT CONST CONST SEGMENT TEST_Equals_X_UX$rtcName$0 DB 075H DB 00H ORG $+2 TEST_Equals_X_UX$rtcName$1 DB 076H DB 00H ORG $+2 TEST_Equals_X_UX$rtcName$2 DB 061H DB 063H DB 074H DB 075H DB 061H DB 06cH DB 05fH DB 077H DB 00H ORG $+15 TEST_Equals_X_UX$rtcVarDesc DD 064H DD 04H DQ FLAT:TEST_Equals_X_UX$rtcName$2 DD 048H DD 08H DQ FLAT:TEST_Equals_X_UX$rtcName$1 DD 028H DD 08H DQ FLAT:TEST_Equals_X_UX$rtcName$0 ORG $+144 TEST_Equals_X_UX$rtcFrameData DD 03H DD 00H DQ FLAT:TEST_Equals_X_UX$rtcVarDesc CONST ENDS ; COMDAT xdata xdata SEGMENT $unwind$TEST_Equals_X_L DD 025054a19H DD 011d2322H DD 07016002fH DD 05015H DD imagerel __GSHandlerCheck DD 0160H xdata ENDS ; COMDAT CONST CONST SEGMENT TEST_Equals_X_L$rtcName$0 DB 075H DB 00H ORG $+6 TEST_Equals_X_L$rtcName$1 DB 061H DB 063H DB 074H DB 075H DB 061H DB 06cH DB 05fH DB 077H DB 00H ORG $+15 TEST_Equals_X_L$rtcVarDesc DD 044H DD 04H DQ FLAT:TEST_Equals_X_L$rtcName$1 DD 028H DD 08H DQ FLAT:TEST_Equals_X_L$rtcName$0 ORG $+96 TEST_Equals_X_L$rtcFrameData DD 02H DD 00H DQ FLAT:TEST_Equals_X_L$rtcVarDesc CONST ENDS ; COMDAT xdata xdata SEGMENT $unwind$TEST_Equals_X_I DD 025054a19H DD 011d2322H DD 07016002fH DD 05015H DD imagerel __GSHandlerCheck DD 0160H xdata ENDS ; COMDAT CONST CONST SEGMENT TEST_Equals_X_I$rtcName$0 DB 075H DB 00H ORG $+6 TEST_Equals_X_I$rtcName$1 DB 061H DB 063H DB 074H DB 075H DB 061H DB 06cH DB 05fH DB 077H DB 00H ORG $+15 TEST_Equals_X_I$rtcVarDesc DD 044H DD 04H DQ FLAT:TEST_Equals_X_I$rtcName$1 DD 028H DD 08H DQ FLAT:TEST_Equals_X_I$rtcName$0 ORG $+96 TEST_Equals_X_I$rtcFrameData DD 02H DD 00H DQ FLAT:TEST_Equals_X_I$rtcVarDesc CONST ENDS ; COMDAT xdata xdata SEGMENT $unwind$TEST_Equals_UX_X DD 025054a19H DD 011d2322H DD 070160037H DD 05015H DD imagerel __GSHandlerCheck DD 01a0H xdata ENDS ; COMDAT CONST CONST SEGMENT TEST_Equals_UX_X$rtcName$0 DB 075H DB 00H ORG $+2 TEST_Equals_UX_X$rtcName$1 DB 076H DB 00H ORG $+2 TEST_Equals_UX_X$rtcName$2 DB 061H DB 063H DB 074H DB 075H DB 061H DB 06cH DB 05fH DB 077H DB 00H ORG $+15 TEST_Equals_UX_X$rtcVarDesc DD 064H DD 04H DQ FLAT:TEST_Equals_UX_X$rtcName$2 DD 048H DD 08H DQ FLAT:TEST_Equals_UX_X$rtcName$1 DD 028H DD 08H DQ FLAT:TEST_Equals_UX_X$rtcName$0 ORG $+144 TEST_Equals_UX_X$rtcFrameData DD 03H DD 00H DQ FLAT:TEST_Equals_UX_X$rtcVarDesc CONST ENDS ; COMDAT xdata xdata SEGMENT $unwind$TEST_Equals_L_X DD 025054a19H DD 011d2322H DD 07016002fH DD 05015H DD imagerel __GSHandlerCheck DD 0160H xdata ENDS ; COMDAT CONST CONST SEGMENT TEST_Equals_L_X$rtcName$0 DB 076H DB 00H ORG $+6 TEST_Equals_L_X$rtcName$1 DB 061H DB 063H DB 074H DB 075H DB 061H DB 06cH DB 05fH DB 077H DB 00H ORG $+15 TEST_Equals_L_X$rtcVarDesc DD 044H DD 04H DQ FLAT:TEST_Equals_L_X$rtcName$1 DD 028H DD 08H DQ FLAT:TEST_Equals_L_X$rtcName$0 ORG $+96 TEST_Equals_L_X$rtcFrameData DD 02H DD 00H DQ FLAT:TEST_Equals_L_X$rtcVarDesc CONST ENDS ; COMDAT xdata xdata SEGMENT $unwind$TEST_Equals_I_X DD 025054a19H DD 011d2322H DD 07016002fH DD 05015H DD imagerel __GSHandlerCheck DD 0160H xdata ENDS ; COMDAT CONST CONST SEGMENT TEST_Equals_I_X$rtcName$0 DB 076H DB 00H ORG $+6 TEST_Equals_I_X$rtcName$1 DB 061H DB 063H DB 074H DB 075H DB 061H DB 06cH DB 05fH DB 077H DB 00H ORG $+15 TEST_Equals_I_X$rtcVarDesc DD 044H DD 04H DQ FLAT:TEST_Equals_I_X$rtcName$1 DD 028H DD 08H DQ FLAT:TEST_Equals_I_X$rtcName$0 ORG $+96 TEST_Equals_I_X$rtcFrameData DD 02H DD 00H DQ FLAT:TEST_Equals_I_X$rtcVarDesc CONST ENDS ; Function compile flags: /Odt ; COMDAT __JustMyCode_Default _TEXT SEGMENT __JustMyCode_Default PROC ; COMDAT ret 0 __JustMyCode_Default ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu /ZI ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.sint\palmtree.math.core.sint\test_op_equals.c ; COMDAT TEST_Equals_X_X _TEXT SEGMENT u$ = 8 v$ = 40 actual_w$ = 68 result$ = 100 u_result$ = 132 v_result$ = 164 tv152 = 372 tv142 = 372 tv92 = 372 tv74 = 372 tv132 = 376 tv82 = 376 tv64 = 376 __$ArrayPad$ = 384 env$ = 432 ep$ = 440 no$ = 448 u_buf$ = 456 u_buf_size$ = 464 v_buf$ = 472 v_buf_size$ = 480 desired_w$ = 488 TEST_Equals_X_X PROC ; COMDAT ; 120 : { $LN13: mov QWORD PTR [rsp+32], r9 mov DWORD PTR [rsp+24], r8d mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx push rbp push rdi sub rsp, 440 ; 000001b8H lea rbp, QWORD PTR [rsp+32] mov rdi, rsp mov ecx, 110 ; 0000006eH mov eax, -858993460 ; ccccccccH rep stosd mov rcx, QWORD PTR [rsp+472] mov rax, QWORD PTR __security_cookie xor rax, rbp mov QWORD PTR __$ArrayPad$[rbp], rax lea rcx, OFFSET FLAT:__2415E362_test_op_equals@c call __CheckForDebuggerJustMyCode ; 121 : PMC_HANDLE_SINT u; ; 122 : PMC_HANDLE_SINT v; ; 123 : __int32 actual_w; ; 124 : PMC_STATUS_CODE result; ; 125 : PMC_STATUS_CODE u_result; ; 126 : PMC_STATUS_CODE v_result; ; 127 : TEST_Assert(env, FormatTestLabel(L"Equals_X_X (%d.%d)", no, 1), (u_result = ep->FromByteArray(u_buf, u_buf_size, &u)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", u_result)); lea r8, QWORD PTR u$[rbp] mov rdx, QWORD PTR u_buf_size$[rbp] mov rcx, QWORD PTR u_buf$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+608] mov DWORD PTR u_result$[rbp], eax cmp DWORD PTR u_result$[rbp], 0 jne SHORT $LN5@TEST_Equal mov DWORD PTR tv74[rbp], 1 jmp SHORT $LN6@TEST_Equal $LN5@TEST_Equal: mov DWORD PTR tv74[rbp], 0 $LN6@TEST_Equal: mov edx, DWORD PTR u_result$[rbp] lea rcx, OFFSET FLAT:??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call FormatTestMesssage mov QWORD PTR tv64[rbp], rax mov r8d, 1 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@LMNANGKJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv64[rbp] mov r9, rcx mov r8d, DWORD PTR tv74[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 128 : TEST_Assert(env, FormatTestLabel(L"Equals_X_X (%d.%d)", no, 2), (v_result = ep->FromByteArray(v_buf, v_buf_size, &v)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", v_result)); lea r8, QWORD PTR v$[rbp] mov rdx, QWORD PTR v_buf_size$[rbp] mov rcx, QWORD PTR v_buf$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+608] mov DWORD PTR v_result$[rbp], eax cmp DWORD PTR v_result$[rbp], 0 jne SHORT $LN7@TEST_Equal mov DWORD PTR tv92[rbp], 1 jmp SHORT $LN8@TEST_Equal $LN7@TEST_Equal: mov DWORD PTR tv92[rbp], 0 $LN8@TEST_Equal: mov edx, DWORD PTR v_result$[rbp] lea rcx, OFFSET FLAT:??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call FormatTestMesssage mov QWORD PTR tv82[rbp], rax mov r8d, 2 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@LMNANGKJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv82[rbp] mov r9, rcx mov r8d, DWORD PTR tv92[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 129 : TEST_Assert(env, FormatTestLabel(L"Equals_X_X (%d.%d)", no, 3), (result = ep->Equals_X_X(u, v, &actual_w)) == PMC_STATUS_OK, FormatTestMesssage(L"Equals_X_Xの復帰コードが期待通りではない(%d)", result)); lea r8, QWORD PTR actual_w$[rbp] mov rdx, QWORD PTR v$[rbp] mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+992] mov DWORD PTR result$[rbp], eax cmp DWORD PTR result$[rbp], 0 jne SHORT $LN9@TEST_Equal mov DWORD PTR tv142[rbp], 1 jmp SHORT $LN10@TEST_Equal $LN9@TEST_Equal: mov DWORD PTR tv142[rbp], 0 $LN10@TEST_Equal: mov edx, DWORD PTR result$[rbp] lea rcx, OFFSET FLAT:??_C@_1DM@NGGGJAGM@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ call FormatTestMesssage mov QWORD PTR tv132[rbp], rax mov r8d, 3 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@LMNANGKJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv132[rbp] mov r9, rcx mov r8d, DWORD PTR tv142[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 130 : TEST_Assert(env, FormatTestLabel(L"Equals_X_X (%d.%d)", no, 4), actual_w == desired_w, L"データの内容が一致しない"); mov eax, DWORD PTR desired_w$[rbp] cmp DWORD PTR actual_w$[rbp], eax jne SHORT $LN11@TEST_Equal mov DWORD PTR tv152[rbp], 1 jmp SHORT $LN12@TEST_Equal $LN11@TEST_Equal: mov DWORD PTR tv152[rbp], 0 $LN12@TEST_Equal: mov r8d, 4 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@LMNANGKJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel lea r9, OFFSET FLAT:??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ mov r8d, DWORD PTR tv152[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 131 : if (v_result == PMC_STATUS_OK) cmp DWORD PTR v_result$[rbp], 0 jne SHORT $LN2@TEST_Equal ; 132 : ep->Dispose(v); mov rcx, QWORD PTR v$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+592] $LN2@TEST_Equal: ; 133 : if (u_result == PMC_STATUS_OK) cmp DWORD PTR u_result$[rbp], 0 jne SHORT $LN3@TEST_Equal ; 134 : ep->Dispose(u); mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+592] $LN3@TEST_Equal: ; 135 : } lea rcx, QWORD PTR [rbp-32] lea rdx, OFFSET FLAT:TEST_Equals_X_X$rtcFrameData call _RTC_CheckStackVars mov rcx, QWORD PTR __$ArrayPad$[rbp] xor rcx, rbp call __security_check_cookie lea rsp, QWORD PTR [rbp+408] pop rdi pop rbp ret 0 TEST_Equals_X_X ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu /ZI ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.sint\palmtree.math.core.sint\test_op_equals.c ; COMDAT TEST_Equals_X_UX _TEXT SEGMENT u$ = 8 v$ = 40 actual_w$ = 68 result$ = 100 u_result$ = 132 v_result$ = 164 tv152 = 372 tv142 = 372 tv92 = 372 tv74 = 372 tv132 = 376 tv82 = 376 tv64 = 376 __$ArrayPad$ = 384 env$ = 432 ep$ = 440 no$ = 448 u_buf$ = 456 u_buf_size$ = 464 v_buf$ = 472 v_buf_size$ = 480 desired_w$ = 488 TEST_Equals_X_UX PROC ; COMDAT ; 102 : { $LN13: mov QWORD PTR [rsp+32], r9 mov DWORD PTR [rsp+24], r8d mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx push rbp push rdi sub rsp, 440 ; 000001b8H lea rbp, QWORD PTR [rsp+32] mov rdi, rsp mov ecx, 110 ; 0000006eH mov eax, -858993460 ; ccccccccH rep stosd mov rcx, QWORD PTR [rsp+472] mov rax, QWORD PTR __security_cookie xor rax, rbp mov QWORD PTR __$ArrayPad$[rbp], rax lea rcx, OFFSET FLAT:__2415E362_test_op_equals@c call __CheckForDebuggerJustMyCode ; 103 : PMC_HANDLE_SINT u; ; 104 : PMC_HANDLE_UINT v; ; 105 : __int32 actual_w; ; 106 : PMC_STATUS_CODE result; ; 107 : PMC_STATUS_CODE u_result; ; 108 : PMC_STATUS_CODE v_result; ; 109 : TEST_Assert(env, FormatTestLabel(L"Equals_X_UX (%d.%d)", no, 1), (u_result = ep->FromByteArray(u_buf, u_buf_size, &u)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", u_result)); lea r8, QWORD PTR u$[rbp] mov rdx, QWORD PTR u_buf_size$[rbp] mov rcx, QWORD PTR u_buf$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+608] mov DWORD PTR u_result$[rbp], eax cmp DWORD PTR u_result$[rbp], 0 jne SHORT $LN5@TEST_Equal mov DWORD PTR tv74[rbp], 1 jmp SHORT $LN6@TEST_Equal $LN5@TEST_Equal: mov DWORD PTR tv74[rbp], 0 $LN6@TEST_Equal: mov edx, DWORD PTR u_result$[rbp] lea rcx, OFFSET FLAT:??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call FormatTestMesssage mov QWORD PTR tv64[rbp], rax mov r8d, 1 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CI@NLHEPFBK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ call FormatTestLabel mov rcx, QWORD PTR tv64[rbp] mov r9, rcx mov r8d, DWORD PTR tv74[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 110 : TEST_Assert(env, FormatTestLabel(L"Equals_X_UX (%d.%d)", no, 2), (v_result = ep->UINT_ENTRY_POINTS.FromByteArray(v_buf, v_buf_size, &v)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", v_result)); lea r8, QWORD PTR v$[rbp] mov rdx, QWORD PTR v_buf_size$[rbp] mov rcx, QWORD PTR v_buf$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+48] mov DWORD PTR v_result$[rbp], eax cmp DWORD PTR v_result$[rbp], 0 jne SHORT $LN7@TEST_Equal mov DWORD PTR tv92[rbp], 1 jmp SHORT $LN8@TEST_Equal $LN7@TEST_Equal: mov DWORD PTR tv92[rbp], 0 $LN8@TEST_Equal: mov edx, DWORD PTR v_result$[rbp] lea rcx, OFFSET FLAT:??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call FormatTestMesssage mov QWORD PTR tv82[rbp], rax mov r8d, 2 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CI@NLHEPFBK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ call FormatTestLabel mov rcx, QWORD PTR tv82[rbp] mov r9, rcx mov r8d, DWORD PTR tv92[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 111 : TEST_Assert(env, FormatTestLabel(L"Equals_X_UX (%d.%d)", no, 3), (result = ep->Equals_X_UX(u, v, &actual_w)) == PMC_STATUS_OK, FormatTestMesssage(L"Equals_X_UXの復帰コードが期待通りではない(%d)", result)); lea r8, QWORD PTR actual_w$[rbp] mov rdx, QWORD PTR v$[rbp] mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+984] mov DWORD PTR result$[rbp], eax cmp DWORD PTR result$[rbp], 0 jne SHORT $LN9@TEST_Equal mov DWORD PTR tv142[rbp], 1 jmp SHORT $LN10@TEST_Equal $LN9@TEST_Equal: mov DWORD PTR tv142[rbp], 0 $LN10@TEST_Equal: mov edx, DWORD PTR result$[rbp] lea rcx, OFFSET FLAT:??_C@_1DO@HDBPOJFD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD@ call FormatTestMesssage mov QWORD PTR tv132[rbp], rax mov r8d, 3 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CI@NLHEPFBK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ call FormatTestLabel mov rcx, QWORD PTR tv132[rbp] mov r9, rcx mov r8d, DWORD PTR tv142[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 112 : TEST_Assert(env, FormatTestLabel(L"Equals_X_UX (%d.%d)", no, 4), actual_w == desired_w, L"データの内容が一致しない"); mov eax, DWORD PTR desired_w$[rbp] cmp DWORD PTR actual_w$[rbp], eax jne SHORT $LN11@TEST_Equal mov DWORD PTR tv152[rbp], 1 jmp SHORT $LN12@TEST_Equal $LN11@TEST_Equal: mov DWORD PTR tv152[rbp], 0 $LN12@TEST_Equal: mov r8d, 4 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CI@NLHEPFBK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAU?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ call FormatTestLabel lea r9, OFFSET FLAT:??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ mov r8d, DWORD PTR tv152[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 113 : if (v_result == PMC_STATUS_OK) cmp DWORD PTR v_result$[rbp], 0 jne SHORT $LN2@TEST_Equal ; 114 : ep->UINT_ENTRY_POINTS.Dispose(v); mov rcx, QWORD PTR v$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+32] $LN2@TEST_Equal: ; 115 : if (u_result == PMC_STATUS_OK) cmp DWORD PTR u_result$[rbp], 0 jne SHORT $LN3@TEST_Equal ; 116 : ep->Dispose(u); mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+592] $LN3@TEST_Equal: ; 117 : } lea rcx, QWORD PTR [rbp-32] lea rdx, OFFSET FLAT:TEST_Equals_X_UX$rtcFrameData call _RTC_CheckStackVars mov rcx, QWORD PTR __$ArrayPad$[rbp] xor rcx, rbp call __security_check_cookie lea rsp, QWORD PTR [rbp+408] pop rdi pop rbp ret 0 TEST_Equals_X_UX ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu /ZI ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.sint\palmtree.math.core.sint\test_op_equals.c ; COMDAT TEST_Equals_X_L _TEXT SEGMENT u$ = 8 actual_w$ = 36 result$ = 68 u_result$ = 100 tv134 = 308 tv92 = 308 tv74 = 308 tv82 = 312 tv64 = 312 __$ArrayPad$ = 320 env$ = 368 ep$ = 376 no$ = 384 u_buf$ = 392 u_buf_size$ = 400 v$ = 408 desired_w$ = 416 TEST_Equals_X_L PROC ; COMDAT ; 89 : { $LN10: mov QWORD PTR [rsp+32], r9 mov DWORD PTR [rsp+24], r8d mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx push rbp push rdi sub rsp, 376 ; 00000178H lea rbp, QWORD PTR [rsp+32] mov rdi, rsp mov ecx, 94 ; 0000005eH mov eax, -858993460 ; ccccccccH rep stosd mov rcx, QWORD PTR [rsp+408] mov rax, QWORD PTR __security_cookie xor rax, rbp mov QWORD PTR __$ArrayPad$[rbp], rax lea rcx, OFFSET FLAT:__2415E362_test_op_equals@c call __CheckForDebuggerJustMyCode ; 90 : PMC_HANDLE_SINT u; ; 91 : __int32 actual_w; ; 92 : PMC_STATUS_CODE result; ; 93 : PMC_STATUS_CODE u_result; ; 94 : TEST_Assert(env, FormatTestLabel(L"Equals_X_L (%d.%d)", no, 1), (u_result = ep->FromByteArray(u_buf, u_buf_size, &u)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", u_result)); lea r8, QWORD PTR u$[rbp] mov rdx, QWORD PTR u_buf_size$[rbp] mov rcx, QWORD PTR u_buf$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+608] mov DWORD PTR u_result$[rbp], eax cmp DWORD PTR u_result$[rbp], 0 jne SHORT $LN4@TEST_Equal mov DWORD PTR tv74[rbp], 1 jmp SHORT $LN5@TEST_Equal $LN4@TEST_Equal: mov DWORD PTR tv74[rbp], 0 $LN5@TEST_Equal: mov edx, DWORD PTR u_result$[rbp] lea rcx, OFFSET FLAT:??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call FormatTestMesssage mov QWORD PTR tv64[rbp], rax mov r8d, 1 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@BCPLJGNF@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAL?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv64[rbp] mov r9, rcx mov r8d, DWORD PTR tv74[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 95 : TEST_Assert(env, FormatTestLabel(L"Equals_X_L (%d.%d)", no, 2), (result = ep->Equals_X_L(u, v, &actual_w)) == PMC_STATUS_OK, FormatTestMesssage(L"Equals_X_Lの復帰コードが期待通りではない(%d)", result)); lea r8, QWORD PTR actual_w$[rbp] mov rdx, QWORD PTR v$[rbp] mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+976] mov DWORD PTR result$[rbp], eax cmp DWORD PTR result$[rbp], 0 jne SHORT $LN6@TEST_Equal mov DWORD PTR tv92[rbp], 1 jmp SHORT $LN7@TEST_Equal $LN6@TEST_Equal: mov DWORD PTR tv92[rbp], 0 $LN7@TEST_Equal: mov edx, DWORD PTR result$[rbp] lea rcx, OFFSET FLAT:??_C@_1DM@CMCFOAHJ@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAL?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ call FormatTestMesssage mov QWORD PTR tv82[rbp], rax mov r8d, 2 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@BCPLJGNF@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAL?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv82[rbp] mov r9, rcx mov r8d, DWORD PTR tv92[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 96 : TEST_Assert(env, FormatTestLabel(L"Equals_X_L (%d.%d)", no, 3), actual_w == desired_w, L"データの内容が一致しない"); mov eax, DWORD PTR desired_w$[rbp] cmp DWORD PTR actual_w$[rbp], eax jne SHORT $LN8@TEST_Equal mov DWORD PTR tv134[rbp], 1 jmp SHORT $LN9@TEST_Equal $LN8@TEST_Equal: mov DWORD PTR tv134[rbp], 0 $LN9@TEST_Equal: mov r8d, 3 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@BCPLJGNF@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAL?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel lea r9, OFFSET FLAT:??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ mov r8d, DWORD PTR tv134[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 97 : if (u_result == PMC_STATUS_OK) cmp DWORD PTR u_result$[rbp], 0 jne SHORT $LN2@TEST_Equal ; 98 : ep->Dispose(u); mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+592] $LN2@TEST_Equal: ; 99 : } lea rcx, QWORD PTR [rbp-32] lea rdx, OFFSET FLAT:TEST_Equals_X_L$rtcFrameData call _RTC_CheckStackVars mov rcx, QWORD PTR __$ArrayPad$[rbp] xor rcx, rbp call __security_check_cookie lea rsp, QWORD PTR [rbp+344] pop rdi pop rbp ret 0 TEST_Equals_X_L ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu /ZI ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.sint\palmtree.math.core.sint\test_op_equals.c ; COMDAT TEST_Equals_X_I _TEXT SEGMENT u$ = 8 actual_w$ = 36 result$ = 68 u_result$ = 100 tv134 = 308 tv92 = 308 tv74 = 308 tv82 = 312 tv64 = 312 __$ArrayPad$ = 320 env$ = 368 ep$ = 376 no$ = 384 u_buf$ = 392 u_buf_size$ = 400 v$ = 408 desired_w$ = 416 TEST_Equals_X_I PROC ; COMDAT ; 76 : { $LN10: mov QWORD PTR [rsp+32], r9 mov DWORD PTR [rsp+24], r8d mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx push rbp push rdi sub rsp, 376 ; 00000178H lea rbp, QWORD PTR [rsp+32] mov rdi, rsp mov ecx, 94 ; 0000005eH mov eax, -858993460 ; ccccccccH rep stosd mov rcx, QWORD PTR [rsp+408] mov rax, QWORD PTR __security_cookie xor rax, rbp mov QWORD PTR __$ArrayPad$[rbp], rax lea rcx, OFFSET FLAT:__2415E362_test_op_equals@c call __CheckForDebuggerJustMyCode ; 77 : PMC_HANDLE_SINT u; ; 78 : __int32 actual_w; ; 79 : PMC_STATUS_CODE result; ; 80 : PMC_STATUS_CODE u_result; ; 81 : TEST_Assert(env, FormatTestLabel(L"Equals_X_I (%d.%d)", no, 1), (u_result = ep->FromByteArray(u_buf, u_buf_size, &u)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", u_result)); lea r8, QWORD PTR u$[rbp] mov rdx, QWORD PTR u_buf_size$[rbp] mov rcx, QWORD PTR u_buf$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+608] mov DWORD PTR u_result$[rbp], eax cmp DWORD PTR u_result$[rbp], 0 jne SHORT $LN4@TEST_Equal mov DWORD PTR tv74[rbp], 1 jmp SHORT $LN5@TEST_Equal $LN4@TEST_Equal: mov DWORD PTR tv74[rbp], 0 $LN5@TEST_Equal: mov edx, DWORD PTR u_result$[rbp] lea rcx, OFFSET FLAT:??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call FormatTestMesssage mov QWORD PTR tv64[rbp], rax mov r8d, 1 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@DJHBEGMK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAI?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv64[rbp] mov r9, rcx mov r8d, DWORD PTR tv74[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 82 : TEST_Assert(env, FormatTestLabel(L"Equals_X_I (%d.%d)", no, 2), (result = ep->Equals_X_I(u, v, &actual_w)) == PMC_STATUS_OK, FormatTestMesssage(L"Equals_X_Iの復帰コードが期待通りではない(%d)", result)); lea r8, QWORD PTR actual_w$[rbp] mov edx, DWORD PTR v$[rbp] mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+968] mov DWORD PTR result$[rbp], eax cmp DWORD PTR result$[rbp], 0 jne SHORT $LN6@TEST_Equal mov DWORD PTR tv92[rbp], 1 jmp SHORT $LN7@TEST_Equal $LN6@TEST_Equal: mov DWORD PTR tv92[rbp], 0 $LN7@TEST_Equal: mov edx, DWORD PTR result$[rbp] lea rcx, OFFSET FLAT:??_C@_1DM@GEGJHNOM@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAI?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ call FormatTestMesssage mov QWORD PTR tv82[rbp], rax mov r8d, 2 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@DJHBEGMK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAI?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv82[rbp] mov r9, rcx mov r8d, DWORD PTR tv92[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 83 : TEST_Assert(env, FormatTestLabel(L"Equals_X_I (%d.%d)", no, 3), actual_w == desired_w, L"データの内容が一致しない"); mov eax, DWORD PTR desired_w$[rbp] cmp DWORD PTR actual_w$[rbp], eax jne SHORT $LN8@TEST_Equal mov DWORD PTR tv134[rbp], 1 jmp SHORT $LN9@TEST_Equal $LN8@TEST_Equal: mov DWORD PTR tv134[rbp], 0 $LN9@TEST_Equal: mov r8d, 3 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@DJHBEGMK@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAX?$AA_?$AAI?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel lea r9, OFFSET FLAT:??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ mov r8d, DWORD PTR tv134[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 84 : if (u_result == PMC_STATUS_OK) cmp DWORD PTR u_result$[rbp], 0 jne SHORT $LN2@TEST_Equal ; 85 : ep->Dispose(u); mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+592] $LN2@TEST_Equal: ; 86 : } lea rcx, QWORD PTR [rbp-32] lea rdx, OFFSET FLAT:TEST_Equals_X_I$rtcFrameData call _RTC_CheckStackVars mov rcx, QWORD PTR __$ArrayPad$[rbp] xor rcx, rbp call __security_check_cookie lea rsp, QWORD PTR [rbp+344] pop rdi pop rbp ret 0 TEST_Equals_X_I ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu /ZI ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.sint\palmtree.math.core.sint\test_op_equals.c ; COMDAT TEST_Equals_UX_X _TEXT SEGMENT u$ = 8 v$ = 40 actual_w$ = 68 result$ = 100 u_result$ = 132 v_result$ = 164 tv152 = 372 tv142 = 372 tv92 = 372 tv74 = 372 tv132 = 376 tv82 = 376 tv64 = 376 __$ArrayPad$ = 384 env$ = 432 ep$ = 440 no$ = 448 u_buf$ = 456 u_buf_size$ = 464 v_buf$ = 472 v_buf_size$ = 480 desired_w$ = 488 TEST_Equals_UX_X PROC ; COMDAT ; 58 : { $LN13: mov QWORD PTR [rsp+32], r9 mov DWORD PTR [rsp+24], r8d mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx push rbp push rdi sub rsp, 440 ; 000001b8H lea rbp, QWORD PTR [rsp+32] mov rdi, rsp mov ecx, 110 ; 0000006eH mov eax, -858993460 ; ccccccccH rep stosd mov rcx, QWORD PTR [rsp+472] mov rax, QWORD PTR __security_cookie xor rax, rbp mov QWORD PTR __$ArrayPad$[rbp], rax lea rcx, OFFSET FLAT:__2415E362_test_op_equals@c call __CheckForDebuggerJustMyCode ; 59 : PMC_HANDLE_UINT u; ; 60 : PMC_HANDLE_SINT v; ; 61 : __int32 actual_w; ; 62 : PMC_STATUS_CODE result; ; 63 : PMC_STATUS_CODE u_result; ; 64 : PMC_STATUS_CODE v_result; ; 65 : TEST_Assert(env, FormatTestLabel(L"Equals_UX_X (%d.%d)", no, 1), (u_result = ep->UINT_ENTRY_POINTS.FromByteArray(u_buf, u_buf_size, &u)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", u_result)); lea r8, QWORD PTR u$[rbp] mov rdx, QWORD PTR u_buf_size$[rbp] mov rcx, QWORD PTR u_buf$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+48] mov DWORD PTR u_result$[rbp], eax cmp DWORD PTR u_result$[rbp], 0 jne SHORT $LN5@TEST_Equal mov DWORD PTR tv74[rbp], 1 jmp SHORT $LN6@TEST_Equal $LN5@TEST_Equal: mov DWORD PTR tv74[rbp], 0 $LN6@TEST_Equal: mov edx, DWORD PTR u_result$[rbp] lea rcx, OFFSET FLAT:??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call FormatTestMesssage mov QWORD PTR tv64[rbp], rax mov r8d, 1 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CI@OFNPDABI@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ call FormatTestLabel mov rcx, QWORD PTR tv64[rbp] mov r9, rcx mov r8d, DWORD PTR tv74[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 66 : TEST_Assert(env, FormatTestLabel(L"Equals_UX_X (%d.%d)", no, 2), (v_result = ep->FromByteArray(v_buf, v_buf_size, &v)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", v_result)); lea r8, QWORD PTR v$[rbp] mov rdx, QWORD PTR v_buf_size$[rbp] mov rcx, QWORD PTR v_buf$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+608] mov DWORD PTR v_result$[rbp], eax cmp DWORD PTR v_result$[rbp], 0 jne SHORT $LN7@TEST_Equal mov DWORD PTR tv92[rbp], 1 jmp SHORT $LN8@TEST_Equal $LN7@TEST_Equal: mov DWORD PTR tv92[rbp], 0 $LN8@TEST_Equal: mov edx, DWORD PTR v_result$[rbp] lea rcx, OFFSET FLAT:??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call FormatTestMesssage mov QWORD PTR tv82[rbp], rax mov r8d, 2 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CI@OFNPDABI@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ call FormatTestLabel mov rcx, QWORD PTR tv82[rbp] mov r9, rcx mov r8d, DWORD PTR tv92[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 67 : TEST_Assert(env, FormatTestLabel(L"Equals_UX_X (%d.%d)", no, 3), (result = ep->Equals_UX_X(u, v, &actual_w)) == PMC_STATUS_OK, FormatTestMesssage(L"Equals_UX_Xの復帰コードが期待通りではない(%d)", result)); lea r8, QWORD PTR actual_w$[rbp] mov rdx, QWORD PTR v$[rbp] mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+960] mov DWORD PTR result$[rbp], eax cmp DWORD PTR result$[rbp], 0 jne SHORT $LN9@TEST_Equal mov DWORD PTR tv142[rbp], 1 jmp SHORT $LN10@TEST_Equal $LN9@TEST_Equal: mov DWORD PTR tv142[rbp], 0 $LN10@TEST_Equal: mov edx, DWORD PTR result$[rbp] lea rcx, OFFSET FLAT:??_C@_1DO@PEPKKHHD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD@ call FormatTestMesssage mov QWORD PTR tv132[rbp], rax mov r8d, 3 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CI@OFNPDABI@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ call FormatTestLabel mov rcx, QWORD PTR tv132[rbp] mov r9, rcx mov r8d, DWORD PTR tv142[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 68 : TEST_Assert(env, FormatTestLabel(L"Equals_UX_X (%d.%d)", no, 4), actual_w == desired_w, L"データの内容が一致しない"); mov eax, DWORD PTR desired_w$[rbp] cmp DWORD PTR actual_w$[rbp], eax jne SHORT $LN11@TEST_Equal mov DWORD PTR tv152[rbp], 1 jmp SHORT $LN12@TEST_Equal $LN11@TEST_Equal: mov DWORD PTR tv152[rbp], 0 $LN12@TEST_Equal: mov r8d, 4 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CI@OFNPDABI@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAU?$AAX?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd@ call FormatTestLabel lea r9, OFFSET FLAT:??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ mov r8d, DWORD PTR tv152[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 69 : if (v_result == PMC_STATUS_OK) cmp DWORD PTR v_result$[rbp], 0 jne SHORT $LN2@TEST_Equal ; 70 : ep->Dispose(v); mov rcx, QWORD PTR v$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+592] $LN2@TEST_Equal: ; 71 : if (u_result == PMC_STATUS_OK) cmp DWORD PTR u_result$[rbp], 0 jne SHORT $LN3@TEST_Equal ; 72 : ep->UINT_ENTRY_POINTS.Dispose(u); mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+32] $LN3@TEST_Equal: ; 73 : } lea rcx, QWORD PTR [rbp-32] lea rdx, OFFSET FLAT:TEST_Equals_UX_X$rtcFrameData call _RTC_CheckStackVars mov rcx, QWORD PTR __$ArrayPad$[rbp] xor rcx, rbp call __security_check_cookie lea rsp, QWORD PTR [rbp+408] pop rdi pop rbp ret 0 TEST_Equals_UX_X ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu /ZI ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.sint\palmtree.math.core.sint\test_op_equals.c ; COMDAT TEST_Equals_L_X _TEXT SEGMENT v$ = 8 actual_w$ = 36 result$ = 68 v_result$ = 100 tv134 = 308 tv92 = 308 tv74 = 308 tv82 = 312 tv64 = 312 __$ArrayPad$ = 320 env$ = 368 ep$ = 376 no$ = 384 u$ = 392 v_buf$ = 400 v_buf_size$ = 408 desired_w$ = 416 TEST_Equals_L_X PROC ; COMDAT ; 45 : { $LN10: mov QWORD PTR [rsp+32], r9 mov DWORD PTR [rsp+24], r8d mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx push rbp push rdi sub rsp, 376 ; 00000178H lea rbp, QWORD PTR [rsp+32] mov rdi, rsp mov ecx, 94 ; 0000005eH mov eax, -858993460 ; ccccccccH rep stosd mov rcx, QWORD PTR [rsp+408] mov rax, QWORD PTR __security_cookie xor rax, rbp mov QWORD PTR __$ArrayPad$[rbp], rax lea rcx, OFFSET FLAT:__2415E362_test_op_equals@c call __CheckForDebuggerJustMyCode ; 46 : PMC_HANDLE_SINT v; ; 47 : __int32 actual_w; ; 48 : PMC_STATUS_CODE result; ; 49 : PMC_STATUS_CODE v_result; ; 50 : TEST_Assert(env, FormatTestLabel(L"Equals_L_X (%d.%d)", no, 1), (v_result = ep->FromByteArray(v_buf, v_buf_size, &v)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", v_result)); lea r8, QWORD PTR v$[rbp] mov rdx, QWORD PTR v_buf_size$[rbp] mov rcx, QWORD PTR v_buf$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+608] mov DWORD PTR v_result$[rbp], eax cmp DWORD PTR v_result$[rbp], 0 jne SHORT $LN4@TEST_Equal mov DWORD PTR tv74[rbp], 1 jmp SHORT $LN5@TEST_Equal $LN4@TEST_Equal: mov DWORD PTR tv74[rbp], 0 $LN5@TEST_Equal: mov edx, DWORD PTR v_result$[rbp] lea rcx, OFFSET FLAT:??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call FormatTestMesssage mov QWORD PTR tv64[rbp], rax mov r8d, 1 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@KKLNDHML@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAL?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv64[rbp] mov r9, rcx mov r8d, DWORD PTR tv74[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 51 : TEST_Assert(env, FormatTestLabel(L"Equals_L_X (%d.%d)", no, 2), (result = ep->Equals_L_X(u, v, &actual_w)) == PMC_STATUS_OK, FormatTestMesssage(L"Equals_L_Xの復帰コードが期待通りではない(%d)", result)); lea r8, QWORD PTR actual_w$[rbp] mov rdx, QWORD PTR v$[rbp] mov rcx, QWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+952] mov DWORD PTR result$[rbp], eax cmp DWORD PTR result$[rbp], 0 jne SHORT $LN6@TEST_Equal mov DWORD PTR tv92[rbp], 1 jmp SHORT $LN7@TEST_Equal $LN6@TEST_Equal: mov DWORD PTR tv92[rbp], 0 $LN7@TEST_Equal: mov edx, DWORD PTR result$[rbp] lea rcx, OFFSET FLAT:??_C@_1DM@GDGMFIFF@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAL?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ call FormatTestMesssage mov QWORD PTR tv82[rbp], rax mov r8d, 2 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@KKLNDHML@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAL?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv82[rbp] mov r9, rcx mov r8d, DWORD PTR tv92[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 52 : TEST_Assert(env, FormatTestLabel(L"Equals_I_X (%d.%d)", no, 3), actual_w == desired_w, L"データの内容が一致しない"); mov eax, DWORD PTR desired_w$[rbp] cmp DWORD PTR actual_w$[rbp], eax jne SHORT $LN8@TEST_Equal mov DWORD PTR tv134[rbp], 1 jmp SHORT $LN9@TEST_Equal $LN8@TEST_Equal: mov DWORD PTR tv134[rbp], 0 $LN9@TEST_Equal: mov r8d, 3 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@ECJOMMLD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel lea r9, OFFSET FLAT:??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ mov r8d, DWORD PTR tv134[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 53 : if (v_result == PMC_STATUS_OK) cmp DWORD PTR v_result$[rbp], 0 jne SHORT $LN2@TEST_Equal ; 54 : ep->Dispose(v); mov rcx, QWORD PTR v$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+592] $LN2@TEST_Equal: ; 55 : } lea rcx, QWORD PTR [rbp-32] lea rdx, OFFSET FLAT:TEST_Equals_L_X$rtcFrameData call _RTC_CheckStackVars mov rcx, QWORD PTR __$ArrayPad$[rbp] xor rcx, rbp call __security_check_cookie lea rsp, QWORD PTR [rbp+344] pop rdi pop rbp ret 0 TEST_Equals_L_X ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu /ZI ; File z:\sources\lunor\repos\rougemeilland\palmtree.math.core.sint\palmtree.math.core.sint\test_op_equals.c ; COMDAT TEST_Equals_I_X _TEXT SEGMENT v$ = 8 actual_w$ = 36 result$ = 68 v_result$ = 100 tv134 = 308 tv92 = 308 tv74 = 308 tv82 = 312 tv64 = 312 __$ArrayPad$ = 320 env$ = 368 ep$ = 376 no$ = 384 u$ = 392 v_buf$ = 400 v_buf_size$ = 408 desired_w$ = 416 TEST_Equals_I_X PROC ; COMDAT ; 32 : { $LN10: mov DWORD PTR [rsp+32], r9d mov DWORD PTR [rsp+24], r8d mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx push rbp push rdi sub rsp, 376 ; 00000178H lea rbp, QWORD PTR [rsp+32] mov rdi, rsp mov ecx, 94 ; 0000005eH mov eax, -858993460 ; ccccccccH rep stosd mov rcx, QWORD PTR [rsp+408] mov rax, QWORD PTR __security_cookie xor rax, rbp mov QWORD PTR __$ArrayPad$[rbp], rax lea rcx, OFFSET FLAT:__2415E362_test_op_equals@c call __CheckForDebuggerJustMyCode ; 33 : PMC_HANDLE_SINT v; ; 34 : __int32 actual_w; ; 35 : PMC_STATUS_CODE result; ; 36 : PMC_STATUS_CODE v_result; ; 37 : TEST_Assert(env, FormatTestLabel(L"Equals_I_X (%d.%d)", no, 1), (v_result = ep->FromByteArray(v_buf, v_buf_size, &v)) == PMC_STATUS_OK, FormatTestMesssage(L"FromByteArrayの復帰コードが期待通りではない(%d)", v_result)); lea r8, QWORD PTR v$[rbp] mov rdx, QWORD PTR v_buf_size$[rbp] mov rcx, QWORD PTR v_buf$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+608] mov DWORD PTR v_result$[rbp], eax cmp DWORD PTR v_result$[rbp], 0 jne SHORT $LN4@TEST_Equal mov DWORD PTR tv74[rbp], 1 jmp SHORT $LN5@TEST_Equal $LN4@TEST_Equal: mov DWORD PTR tv74[rbp], 0 $LN5@TEST_Equal: mov edx, DWORD PTR v_result$[rbp] lea rcx, OFFSET FLAT:??_C@_1EC@NPMCAPKO@?$AAF?$AAr?$AAo?$AAm?$AAB?$AAy?$AAt?$AAe?$AAA?$AAr?$AAr?$AAa?$AAy?$AAn?$PP?$KJ@ call FormatTestMesssage mov QWORD PTR tv64[rbp], rax mov r8d, 1 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@ECJOMMLD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv64[rbp] mov r9, rcx mov r8d, DWORD PTR tv74[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 38 : TEST_Assert(env, FormatTestLabel(L"Equals_I_X (%d.%d)", no, 2), (result = ep->Equals_I_X(u, v, &actual_w)) == PMC_STATUS_OK, FormatTestMesssage(L"Equals_I_Xの復帰コードが期待通りではない(%d)", result)); lea r8, QWORD PTR actual_w$[rbp] mov rdx, QWORD PTR v$[rbp] mov ecx, DWORD PTR u$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+944] mov DWORD PTR result$[rbp], eax cmp DWORD PTR result$[rbp], 0 jne SHORT $LN6@TEST_Equal mov DWORD PTR tv92[rbp], 1 jmp SHORT $LN7@TEST_Equal $LN6@TEST_Equal: mov DWORD PTR tv92[rbp], 0 $LN7@TEST_Equal: mov edx, DWORD PTR result$[rbp] lea rcx, OFFSET FLAT:??_C@_1DM@DIPCKLML@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AAn?$PP?$KJ?$AA0?$PP?$LD?$PP?$PM@ call FormatTestMesssage mov QWORD PTR tv82[rbp], rax mov r8d, 2 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@ECJOMMLD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel mov rcx, QWORD PTR tv82[rbp] mov r9, rcx mov r8d, DWORD PTR tv92[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 39 : TEST_Assert(env, FormatTestLabel(L"Equals_I_X (%d.%d)", no, 3), actual_w == desired_w, L"データの内容が一致しない"); mov eax, DWORD PTR desired_w$[rbp] cmp DWORD PTR actual_w$[rbp], eax jne SHORT $LN8@TEST_Equal mov DWORD PTR tv134[rbp], 1 jmp SHORT $LN9@TEST_Equal $LN8@TEST_Equal: mov DWORD PTR tv134[rbp], 0 $LN9@TEST_Equal: mov r8d, 3 mov edx, DWORD PTR no$[rbp] lea rcx, OFFSET FLAT:??_C@_1CG@ECJOMMLD@?$AAE?$AAq?$AAu?$AAa?$AAl?$AAs?$AA_?$AAI?$AA_?$AAX?$AA?5?$AA?$CI?$AA?$CF?$AAd?$AA?4@ call FormatTestLabel lea r9, OFFSET FLAT:??_C@_1BK@CBDJCOBM@?$PP?G?$PP?$PM?$PP?$LP?$AAn?$PP?$IF?$PP?$LJ?$AAL?$AA?$AA?$PP?t?$AAW?$AAj?$AAD@ mov r8d, DWORD PTR tv134[rbp] mov rdx, rax mov rcx, QWORD PTR env$[rbp] call TEST_Assert ; 40 : if (v_result == PMC_STATUS_OK) cmp DWORD PTR v_result$[rbp], 0 jne SHORT $LN2@TEST_Equal ; 41 : ep->Dispose(v); mov rcx, QWORD PTR v$[rbp] mov rax, QWORD PTR ep$[rbp] call QWORD PTR [rax+592] $LN2@TEST_Equal: ; 42 : } lea rcx, QWORD PTR [rbp-32] lea rdx, OFFSET FLAT:TEST_Equals_I_X$rtcFrameData call _RTC_CheckStackVars mov rcx, QWORD PTR __$ArrayPad$[rbp] xor rcx, rbp call __security_check_cookie lea rsp, QWORD PTR [rbp+344] pop rdi pop rbp ret 0 TEST_Equals_I_X ENDP _TEXT ENDS END
; A157475: 512n + 16. ; 528,1040,1552,2064,2576,3088,3600,4112,4624,5136,5648,6160,6672,7184,7696,8208,8720,9232,9744,10256,10768,11280,11792,12304,12816,13328,13840,14352,14864,15376,15888,16400,16912,17424,17936,18448,18960,19472,19984,20496,21008,21520,22032,22544,23056,23568,24080,24592,25104,25616,26128,26640,27152,27664,28176,28688,29200,29712,30224,30736,31248,31760,32272,32784,33296,33808,34320,34832,35344,35856,36368,36880,37392,37904,38416,38928,39440,39952,40464,40976,41488,42000,42512,43024,43536,44048,44560,45072,45584,46096,46608,47120,47632,48144,48656,49168,49680,50192,50704,51216 mul $0,512 add $0,528
////////////////////////////////////////////////////////////////////////// // // pgAdmin III - PostgreSQL Tools // // Copyright (C) 2002 - 2013, The pgAdmin Development Team // This software is released under the PostgreSQL Licence // // ddMinMaxTableLocator.cpp - Locate table minimize/maximize button inside a table. // ////////////////////////////////////////////////////////////////////////// #include "pgAdmin3.h" // wxWindows headers #include <wx/wx.h> // App headers #include "dd/dditems/locators/ddMinMaxTableLocator.h" #include "dd/dditems/figures/ddTableFigure.h" ddMinMaxTableLocator::ddMinMaxTableLocator() { } ddMinMaxTableLocator::~ddMinMaxTableLocator() { } hdPoint &ddMinMaxTableLocator::locate(int posIdx, hdIFigure *owner) { if(owner) { ddTableFigure *table = (ddTableFigure *) owner; int x = table->displayBox().x[posIdx] + table->displayBox().width - 20; //(8+2) int y = table->displayBox().y[posIdx] + 6; locatePoint.x = x; locatePoint.y = y; return locatePoint; } locatePoint.x = 0; locatePoint.y = 0; return locatePoint; }
; A227430: Expansion of x^2*(1-x)^3/((1-2*x)*(1-x+x^2)*(1-3*x+3x^2)). ; Submitted by Jamie Morken(s1) ; 0,0,1,3,6,10,15,21,29,45,90,220,561,1365,3095,6555,13110,25126,46971,87381,164921,320001,640002,1309528,2707629,5592405,11450531,23166783,46333566,91869970,181348455,357913941,708653429,1410132405,2820264810,5662052980,11388676041,22906492245,46006694735,92207099715,184414199430,368247268126,734751144051,1466015503701,2926800830801,5848371485001,11696742970002,23409176469808,46865424529029,93824992236885,187791199242011,375723613252263,751447226504526,1502470808704330,3003670684494495 mov $3,$0 add $0,1000 lpb $0 sub $0,6 mov $2,$3 bin $2,$0 add $1,$2 lpe mov $0,$1
; --------------------------------------------------------------------------- ; Object 20 - cannonball that Ball Hog throws (SBZ) ; --------------------------------------------------------------------------- Cannonball: moveq #0,d0 move.b obRoutine(a0),d0 move.w Cbal_Index(pc,d0.w),d1 jmp Cbal_Index(pc,d1.w) ; =========================================================================== Cbal_Index: dc.w Cbal_Main-Cbal_Index dc.w Cbal_Bounce-Cbal_Index cbal_time: equ $30 ; time until the cannonball explodes (2 bytes) ; =========================================================================== Cbal_Main: ; Routine 0 addq.b #2,obRoutine(a0) move.b #7,obHeight(a0) move.l #Map_Hog,obMap(a0) move.w #$2302,obGfx(a0) move.b #4,obRender(a0) move.b #3,obPriority(a0) move.b #$87,obColType(a0) move.b #8,obActWid(a0) moveq #0,d0 move.b obSubtype(a0),d0 ; move subtype to d0 mulu.w #60,d0 ; multiply by 60 frames (1 second) move.w d0,cbal_time(a0) ; set explosion time move.b #4,obFrame(a0) Cbal_Bounce: ; Routine 2 jsr (ObjectFall).l tst.w obVelY(a0) bmi.s Cbal_ChkExplode jsr (ObjFloorDist).l tst.w d1 ; has ball hit the floor? bpl.s Cbal_ChkExplode ; if not, branch add.w d1,obY(a0) move.w #-$300,obVelY(a0) ; bounce tst.b d3 beq.s Cbal_ChkExplode bmi.s loc_8CA4 tst.w obVelX(a0) bpl.s Cbal_ChkExplode neg.w obVelX(a0) bra.s Cbal_ChkExplode ; =========================================================================== loc_8CA4: tst.w obVelX(a0) bmi.s Cbal_ChkExplode neg.w obVelX(a0) Cbal_ChkExplode: subq.w #1,cbal_time(a0) ; subtract 1 from explosion time bpl.s Cbal_Animate ; if time is > 0, branch Cbal_Explode: move.b #id_MissileDissolve,0(a0) move.b #id_ExplosionBomb,0(a0) ; change object to an explosion ($3F) move.b #0,obRoutine(a0) ; reset routine counter bra.w ExplosionBomb ; jump to explosion code ; =========================================================================== Cbal_Animate: subq.b #1,obTimeFrame(a0) ; subtract 1 from frame duration bpl.s Cbal_Display move.b #5,obTimeFrame(a0) ; set frame duration to 5 frames bchg #0,obFrame(a0) ; change frame Cbal_Display: bsr.w DisplaySprite move.w (v_limitbtm2).w,d0 addi.w #$E0,d0 cmp.w obY(a0),d0 ; has object fallen off the level? bcs.w DeleteObject ; if yes, branch rts
;############## CMonster by Patrick Davidson - level loading and rendering Load_Level: dec a #ifdef TI84CE ld de,0 #else ld d,0 #endif ld e,a #ifdef TI84CE push de pop hl #else ld h,d ld l,e #endif add hl,hl add hl,hl add hl,de ; HL = 5 * level number add hl,hl add hl,hl add hl,hl add hl,hl add hl,hl add hl,hl ; HL = 320 * level number ld de,levelData ld a,(map_name) or a jp nz,Read_Ext_Level add hl,de ; HL -> map ld de,map ld bc,320 ldir ret Draw_Map: ld c,15 Draw_Map_Partial: ld b,19 loop_draw_board: push bc call Draw_Brick pop bc dec b jp p,loop_draw_board dec c jp p,Draw_Map_Partial ret ;############## Find brick value ; Input C = brick Y coordinate (0-15) ; Input B = brick X coordinate (0-19) ; Output A = brick value Find_Brick_BC: ld a,c cp 16 jr nc,below_brick_area ld hl,map #ifdef TI84CE ld de,0 #else ld d,0 #endif add a,a add a,a add a,c ; A = 5 * Y add a,a ; A = 10 * Y ld e,a add hl,de add hl,de ; HL -> map + 20 * Y (start of row) ld e,b add hl,de ; HL -> relevant brick in map ld a,(hl) ret below_brick_area: xor a ret ;############## Detect if brick is present and update for bounce ; Input E = brick Y coordinate (0-15) ; Input D = brick X coordinate (0-19) ; Output zero flag set if no bounce, clear if we should bounce ; Preserves DE, destroys all other registers Bounce_Brick_DE_Check_Already: ld hl,already_hit ld a,(already_count) or a jr z,Bounce_Brick_DE inc a ld b,a already_check_loop: ld a,(hl) cp d inc hl ld a,(hl) inc hl jr nz,already_check_no_match cp e jr nz,already_check_no_match inc a ret already_check_no_match: djnz already_check_loop Bounce_Brick_DE: ld a,e cp 16 jr nc,below_brick_area ld hl,map #ifdef TI84CE ld bc,0 #else ld b,0 #endif add a,a add a,a add a,e ; A = 5 * Y add a,a ; A = 10 * Y ld c,a add hl,bc add hl,bc ; HL -> map + 20 * Y (start of row) ld c,d add hl,bc ; HL -> relevant brick in map ld a,(hl) and 15 #ifdef TI84CE add a,a add a,a #else ld b,a add a,a add a,b #endif ld (brick_hit_dispatch+1),a brick_hit_dispatch: jr brick_hit_dispatch ret ; 0 = no brick, return with Z set .fill WORDLEN jp hit_normal_brick ;1 jp hit_double_brick ;2 jp solid_brick ;3 jp hit_triple_brick ;4 jp solid_brick ;5 jp solid_brick ;6 jp tall_upper ;7 jp tall_lower ;8 jp wide_top ;9 jp wide_top ;10 jp wide_bottom ;11 jp wide_bottom ;12 jp tall_middle ;13 jp wide_top ;14 ;15 wide_bottom: push de push hl call wide_scan pop hl pop de push de ld bc,-20 add hl,bc dec e call wide_scan pop de ret wide_top: push de push hl call wide_scan pop hl pop de push de ld bc,20 add hl,bc inc e call wide_scan pop de ret wide_scan: ld a,e add a,a ret c ; negative Y coord invalid cp 32 ret nc ; Y above 16 invalid ld a,(hl) and %1111 cp 9 jr z,wide_scan_right_continue ; at left edge cp 12 jr z,wide_scan_right_continue ; at left edge cp 10 jr z,wide_scan_left_continue ; at right edge cp 11 jr z,wide_scan_left_continue ; at right edge cp 14 jr z,wide_middle cp 15 ret nz wide_middle: push de push hl call wide_scan_right_continue ; clear this col and to right pop hl pop de dec d ; move one col left to clear dec hl wide_scan_left: bit 7,d ret nz ; negative X coord invalid ld a,(hl) and %1111 cp 14 jr z,wide_scan_left_continue cp 15 jr z,wide_scan_left_continue cp 9 jr z,wide_scan_left_final cp 12 ret nz wide_scan_left_final: ld a,(hl) and %11110000 inc a ld (hl),a push hl push de call Draw_Brick_ADE_Set_Already pop de pop hl ret wide_scan_left_continue: call wide_scan_left_final dec hl dec d jr wide_scan_left wide_scan_right: ld a,d cp 20 ret nc ; X > 20 invalid ld a,(hl) and %1111 cp 14 jr z,wide_scan_right_continue cp 15 jr z,wide_scan_right_continue cp 10 jr z,wide_scan_right_final cp 11 ret nz wide_scan_right_final: ld a,(hl) and %11110000 inc a ld (hl),a push hl push de call Draw_Brick_ADE_Set_Already pop de pop hl ret wide_scan_right_continue: call wide_scan_right_final inc hl inc d jr wide_scan_right tall_middle: push hl push de inc e ld bc,20 add hl,bc call tall_scan_down ; first scan down from next row pop de pop hl ; fall through up from current row tall_lower: push de call tall_scan_up_continue pop de ret tall_scan_up: ld a,(hl) and %1111 cp 7 ; test if we found top brick jr z,tall_scan_up_final cp 13 ret nz ; exit if unexpected brick found tall_scan_up_continue: call tall_scan_up_final ld bc,-20 add hl,bc dec e bit 7,e ; check for going above the top jr z,tall_scan_up ret tall_scan_up_final: ld a,(hl) and %11110000 inc a ld (hl),a push hl push de call Draw_Brick_ADE_Set_Already pop de pop hl ret tall_upper: push de call tall_scan_down_continue pop de ret tall_scan_down: ld a,e cp 16 ret nc ; check for going below the bottom ld a,(hl) and %1111 cp 8 ; test if we found bottom brick jr z,tall_scan_down_final cp 13 jr z,tall_scan_down_continue ret ; reached if invalid map tall_scan_down_final: ld a,(hl) and %11110000 inc a ld (hl),a push hl push de call Draw_Brick_ADE_Set_Already pop de pop hl ret tall_scan_down_continue: call tall_scan_down_final ld bc,20 add hl,bc inc e jr tall_scan_down hit_triple_brick: dec (hl) hit_double_brick: dec (hl) ; change to single ld a,(hl) push de call Draw_Brick_ADE pop de ret hit_normal_brick: xor a ld (hl),a push de call Draw_Brick_ADE jr collect_points solid_brick: ld hl,since_bounce inc (hl) ret collect_points: ld hl,(brick_count) dec hl ld (brick_count),hl ld hl,bounce_count ld a,(hl) cp 10 jr z,max_bounce inc a ld (hl),a max_bounce: ld b,a add_score_loop: push bc call add_score pop bc djnz add_score_loop pop de call Check_Drop_Bonus xor a ; make sure zero flag is clear (NZ) inc a ret add_score: ld a,(hard_flag) or a call nz,do_add_score do_add_score: ld hl,score+6 ; and increment the score ld de,score_increment+5 ld a,(score_inc) ld (de),a inc de Add_6_Digits_BCD: ld b,6 loop_add_nocarry: xor a loop_add: dec hl dec de ld a,(de) adc a,(hl) sub '0' ; '0' was added twice because both ASCII cp '0'+10 jr c,loop_add_nocarry_end sub 10 ccf ld (hl),a djnz loop_add ret loop_add_nocarry_end: ld (hl),a djnz loop_add_nocarry ret score_increment: .db "000001" brick_results: .db 0,1,3,2,5,6 ;############## Draw brick using images below ; ; B = X coordinate (0-19) ; C = Y coordinate (0-29) Draw_Brick_If_Nonzero: push bc push hl push bc call Find_Brick_BC pop de or a call nz,Draw_Brick_ADE pop hl pop bc ret Draw_Brick_ADE_Set_Already: push af ld hl,already_count #ifdef TI84CE ld bc,0 #else ld b,0 #endif ld c,(hl) inc (hl) inc hl add hl,bc add hl,bc ld (hl),d inc hl ld (hl),e pop af jr Draw_Brick_ADE Draw_Brick: push bc call Find_Brick_BC pop de Draw_Brick_ADE: push af ld hl,packed_brick_images add a,a add a,a add a,a add a,a #ifdef TI84CE ld bc,0 #else ld b,0 #endif ld c,a add hl,bc add hl,bc ; HL -> brick image pop af rra and %1111000 ; A = palette image offset #ifdef TI84CE inc a ; second color byte copied first on 84+CE ld (smc_offset_1+1),a ld (smc_offset_2+1),a ld (smc_offset_3+1),a ld (smc_offset_4+1),a push hl ld a,e add a,a add a,a add a,a ; A = pixel Y coordinate of top of brick ld hl,0 ld l,a push hl pop bc add hl,hl add hl,hl ; HL = 4 * Y add hl,bc ; HL = 5 * Y add hl,hl add hl,hl ; HL = 20 * Y ld c,d add hl,bc ; HL = 20 * Y + brick X add hl,hl add hl,hl add hl,hl ; HL = 160 * Y + X add hl,hl add hl,hl ; HL = 640 * Y + 4 * X ld de,$D40000 add hl,de ; HL -> start pixel ex de,hl ; DE -> start pixel pop bc ; BC -> image data ld a,8 draw_brick_outer: push af ld a,4 ld hl,brick_palettes+1 draw_brick_inner: push af ld a,(bc) rlca rlca rlca and %110 smc_offset_1: or %11 ld l,a ld a,(hl) ld (de),a dec hl inc de ld a,(hl) ld (de),a inc de ld a,(bc) rra rra rra and %110 smc_offset_2: or %11 ld l,a ld a,(hl) ld (de),a dec hl inc de ld a,(hl) ld (de),a inc de ld a,(bc) rra and %110 smc_offset_3: or %11 ld l,a ld a,(hl) ld (de),a dec hl inc de ld a,(hl) ld (de),a inc de ld a,(bc) add a,a and %110 smc_offset_4: or %11 ld l,a ld a,(hl) ld (de),a dec hl inc de ld a,(hl) ld (de),a inc de inc bc pop af dec a jr nz,draw_brick_inner ld hl,640-32 add hl,de push hl pop de pop af dec a jr nz,draw_brick_outer inc a ; so that zero flag is clear ret #else ld (smc_offset_1+1),a ld (smc_offset_2+1),a ld (smc_offset_3+1),a ld (smc_offset_4+1),a push hl ld a,e add a,a add a,a add a,a ; A = pixel Y coordinate of top of brick ld h,0 ld l,a ld a,$50 ; set minimum Y call Write_Display_Control ld a,$20 ; set current Y call Write_Display_control_C11 ld a,d add a,a add a,a add a,a ; A = brick X * 8 ld l,a ld h,0 add hl,hl ; HL = pixel X = brick X * 16 ld a,$52 ; set minimum X call Write_Display_Control_C11 ld a,$21 ; set current X call Write_Display_Control_C11 ld a,l add a,15 ld l,a ld a,$53 ; set maximum X call Write_Display_Control_C11 ld a,$22 out ($10),a out ($10),a pop de ; DE -> brick image ld b,(32*(1+8))&255 ; loop 32 times, but 8 outis per loop ld hl,brick_palettes loop_draw_brick: ld a,(de) rlca rlca rlca and %110 smc_offset_1: or %11 ld l,a outi outi ld a,(de) rra rra rra and %110 smc_offset_2: or %11 ld l,a outi outi ld a,(de) rra and %110 smc_offset_3: or %11 ld l,a outi outi ld a,(de) add a,a and %110 smc_offset_4: or %11 ld l,a outi outi inc de djnz loop_draw_brick #endif ret
; ;================================================================================================== ; N8 STANDARD CONFIGURATION ;================================================================================================== ; ; THE COMPLETE SET OF DEFAULT CONFIGURATION SETTINGS FOR THIS PLATFORM ARE FOUND IN THE ; CFG_<PLT>.ASM INCLUDED FILE WHICH IS FOUND IN THE PARENT DIRECTORY. THIS FILE CONTAINS ; COMMON CONFIGURATION SETTINGS THAT OVERRIDE THE DEFAULTS. IT IS INTENDED THAT YOU MAKE ; YOUR CUSTOMIZATIONS IN THIS FILE AND JUST INHERIT ALL OTHER SETTINGS FROM THE DEFAULTS. ; EVEN BETTER, YOU CAN MAKE A COPY OF THIS FILE WITH A NAME LIKE <PLT>_XXX.ASM AND SPECIFY ; YOUR FILE IN THE BUILD PROCESS. ; ; THE SETTINGS BELOW ARE THE SETTINGS THAT ARE MOST COMMONLY MODIFIED FOR THIS PLATFORM. ; MANY OF THEM ARE EQUAL TO THE SETTINGS IN THE INCLUDED FILE, SO THEY DON'T REALLY DO ; ANYTHING AS IS. THEY ARE LISTED HERE TO MAKE IT EASY FOR YOU TO ADJUST THE MOST COMMON ; SETTINGS. ; ; N.B., SINCE THE SETTINGS BELOW ARE REDEFINING VALUES ALREADY SET IN THE INCLUDED FILE, ; TASM INSISTS THAT YOU USE THE .SET OPERATOR AND NOT THE .EQU OPERATOR BELOW. ATTEMPTING ; TO REDEFINE A VALUE WITH .EQU BELOW WILL CAUSE TASM ERRORS! ; ; PLEASE REFER TO THE CUSTOM BUILD INSTRUCTIONS (README.TXT) IN THE SOURCE DIRECTORY (TWO ; DIRECTORIES ABOVE THIS ONE). ; #DEFINE BOOT_DEFAULT "H" ; DEFAULT BOOT LOADER CMD ON <CR> OR AUTO BOOT ; #include "cfg_n8.asm" ; Z180_CLKDIV .SET 1 ; Z180: CHK DIV: 0=OSC/2, 1=OSC, 2=OSC*2 Z180_MEMWAIT .SET 0 ; Z180: MEMORY WAIT STATES (0-3) Z180_IOWAIT .SET 1 ; Z180: I/O WAIT STATES TO ADD ABOVE 1 W/S BUILT-IN (0-3) ; CRTACT .SET FALSE ; ACTIVATE CRT (VDU,CVDU,PROPIO,ETC) AT STARTUP ; AY38910ENABLE .SET TRUE ; AY: AY-3-8910 / YM2149 SOUND DRIVER ; SDMODE .SET SDMODE_CSIO ; SD: ENABLE SD CARD DISK DRIVER (SD.ASM)
%ifdef CONFIG { "RegData": { "RAX": "0x4600", "RCX": "0x3", "RDX": "0x1", "RDI": "0xE0000007", "RSI": "0xE0000017" }, "MemoryRegions": { "0x100000000": "4096" } } %endif %macro copy 3 ; Dest, Src, Size mov rdi, %1 mov rsi, %2 mov rcx, %3 cld rep movsb %endmacro mov rdx, 0xe0000000 lea r15, [rdx + 8 * 0] lea r14, [rel .StringOne] copy r15, r14, 11 lea r15, [rdx + 8 * 2] lea r14, [rel .StringTwo] copy r15, r14, 11 lea rdi, [rdx + 8 * 0] lea rsi, [rdx + 8 * 2] cld mov rcx, 10 ; Lower String length repne cmpsb ; rdi cmp rsi mov rax, 0 lahf mov rdx, 0 sete dl hlt .StringOne: db "StringTest\0" .StringTwo: db "UnmatcTest\0"
;******************************************************************************* ;* Tutorial Twenty-Six Basic Gravity Physics Engine * ;* * ;* Written By John C. Dale * ;* Tutorial #26 * ;* Date : 13th Dec, 2017 * ;* * ;******************************************************************************* ;* * ;******************************************************************************* WATCH XVELOCITY WATCH YVELOCITY WATCH YPOS ;******************************************************************************* ;* * ;******************************************************************************* *=$9000 GetKey = $FFE4 jmp START GRAVITY ; Constant Gravity Value BYTE 05 THRUST ; Constant Thrust Value BYTE 10 XVELOCITY ; X Velocity Value BYTE 00 YVELOCITY ; Y Velocity Value BYTE 00 YPOS ; Y Position (Height) BYTE 00 XPOS ; X Position BYTE 00 START ldx #0 ; Reset Value stx XPOS ; Reset X Position ldx #100 stx YPOS ; Reset Y Position ldy #$10 sty XVELOCITY ; Reset X Velocity ldy #$0 sty YVELOCITY ; Reset Y Velocity PLAYER_UPDATE lda XPOS ; Update the X Position for this cycle clc adc XVELOCITY ; Apply X Velocity to X Position sta XPOS ; Store back into X Position sec lda YVELOCITY ; Update Y Velocity for this cycle sbc GRAVITY ; Apply Gravity to Y Velocity pha ; Push Current Velocity Value onto Stack ;jsr DELAY ;jsr GetKey ; Grab the Next Key Value SIMULATION lda #0 ; For CBM Prg Studio Simulation use only cmp #" " ; is SPACE applied bne ThrustNotUsed ; No pla ; Yes, Retrieve Velociity Value fromn Stack clc adc THRUST ; Add counteracting Thrust value pha ; Place back on stack ThrustNotUsed pla bpl CHECK_POSITIVE_VELOCITY ; If Y Velocity still positive cmp #$F1 ; C4 = -60 bcc DONT_UPDATE_VELOCITY ; bigger then dont update Y Velocity jmp UPDATE_VELOCITY ; smaller, then update Y Velocity CHECK_POSITIVE_VELOCITY cmp #$3C ; 3c = +60 bcs DONT_UPDATE_VELOCITY ; bigger then dont update Y Velocity ; smaller, then update Y Velocity UPDATE_VELOCITY sta YVELOCITY ; Store Y Velocity DONT_UPDATE_VELOCITY lda YPOS ; Update Y Position for this cycle clc adc YVELOCITY ; Apply the Y Velocity to Y Position sta YPOS ; Store Y Position cmp #0 ; Is the Y Position equal or lower than floor bpl PLAYER_UPDATE ; If positive, loop back round for another cycle lda #00 ; Reset Y Position and Y Velocity sta YPOS sta YVELOCITY rts DELAY KT_LOOPER ldx #255 ; Loop For 255 Y Cycles KT_OUTERLOOP ldy #255 ; Loop 255 times KT_INNERLOOP dey ; Decrease Inner Loop Index bne KT_INNERLOOP ; Hit Zero?, No, Loop Round dex ; Yes, Decrease Outer Loop Index bne KT_OUTERLOOP ; Hit Zero?, No, Loop Round rts ; Yes, Exit