text
stringlengths 5
1.04M
|
|---|
// hello-world.cpp
#include <thread>
#include <iostream>
void hello( ) {
std::cout << "Hello ";
}
int main( ) {
std::thread t1( hello );
t1.join( );
std::cout << "World" << std::endl;
return 0;
}
|
/* Self header */
#include <aht20.h>
/* Arduino libraries */
#include "crc8.h"
/* Config */
#define CONFIG_AHT20_I2C_ADDRESS 0x38
#define CONFIG_AHT20_CALIBRATION_DURATION 10
#define CONFIG_AHT20_CALIBRATION_TIMEOUT 30
#define CONFIG_AHT20_MEASUREMENT_DURATION 80
#define CONFIG_AHT20_MEASUREMENT_RETRY 1
#define CONFIG_AHT20_MEASUREMENT_TIMEOUT 100
#define CONFIG_AHT20_DEBUG_ENABLED 1
/* Macros */
#if CONFIG_AHT20_DEBUG_ENABLED
#define CONFIG_AHT20_DEBUG_FUNCTION(x) Serial.println(x)
#else
#define CONFIG_AHT20_DEBUG_FUNCTION(x)
#endif
/**
* List of commands supported by the sensor.
*/
enum aht20_commands {
AHT20_COMMAND_CALIBRATION = 0xBE,
AHT20_COMMAND_MEASUREMENT_TRIGGER = 0xAC,
AHT20_COMMAND_RESET_SOFT = 0xBA,
};
/**
* Default constructor.
*/
aht20::aht20() {
m_i2c_library = NULL;
}
/**
*
* @param[in] i2C_library
*/
void aht20::setup(TwoWire &i2C_library) {
m_i2c_library = &i2C_library;
}
/**
* Tries to detect the sensor.
* @note It takes a maximum of 20 ms after power up for the sensor to be ready to receive commands.
* @param[in] wait If set to false the library will not make sure 20 ms have elapsed since boot.
* @return true if the sensor has been detected, or false otherwise.
*/
bool aht20::detect(bool wait) {
int res;
/* Wait for power up */
if (wait) {
while (millis() < 20)
;
}
/* Ping device */
m_i2c_library->beginTransmission(CONFIG_AHT20_I2C_ADDRESS);
res = m_i2c_library->endTransmission(true);
if (res != 0) {
return false;
}
/* Return success */
return true;
}
/**
* Request the sensor to trigger a measurement and returns immediately.
* After that, make repeated calls to measurement_async_get until the functions return anything else than -EINPROGRESS.
* @return 0 in case of success, or a negative error code otherwise.
*/
int aht20::measurement_async_trigger(void) {
int res;
/* Remember start time to detect timeout */
uint32_t time_start = millis();
/* Ensure calibration has been performed */
while (1) {
/* Read calibration status bit */
uint8_t reg_status;
res = m_register_read(®_status, 1);
if (res < 1) {
CONFIG_AHT20_DEBUG_FUNCTION(" [e] Failed to read status register!");
return res;
}
/* If calibration has been done, we can stop here */
if ((reg_status & (1 << 3))) {
break;
}
/* Request to start calibration */
uint8_t cmd[] = { AHT20_COMMAND_CALIBRATION, 0x08, 0x00 };
res = m_register_write(cmd, 3);
if (res < 0) {
CONFIG_AHT20_DEBUG_FUNCTION(" [e] Failed to send calibration command!");
return res;
}
/* Wait enough time for calibration to be done */
delay(CONFIG_AHT20_CALIBRATION_DURATION);
/* Detect timeout */
if (millis() - time_start > CONFIG_AHT20_CALIBRATION_TIMEOUT) {
CONFIG_AHT20_DEBUG_FUNCTION(" [e] Timed out waiting for calibration!");
return -ETIMEDOUT;
}
}
/* Request to trigger measurement */
uint8_t cmd[] = { AHT20_COMMAND_MEASUREMENT_TRIGGER, 0x33, 0x00 };
res = m_register_write(cmd, 3);
if (res < 0) {
CONFIG_AHT20_DEBUG_FUNCTION(" [e] Failed to send calibration command!");
return res;
}
/* Return success */
return 0;
}
/**
* Retrieves the measurement results if available.
* Call measurement_async_trigger first and then call this function repeatedly as long as it returns -EINPROGRESS.
* @param[out] temperature A pointer to a variable that will be updated with the temperature in degrees Celsius.
* @param[out] humidity A pointer to a variable that will be updated with the humidity in percents.
* @return 0 in case of success, -EINPROGRESS if a measurement is still in progress or a negative error code otherwise.
*/
int aht20::measurement_async_get(float * const temperature, float * const humidity) {
int res;
/* Read all registers */
uint8_t regs[7];
res = m_register_read(regs, 7);
if (res < 0) {
CONFIG_AHT20_DEBUG_FUNCTION(" [e] Failed to read registers!");
return res;
}
/* Wait for busy bit to be cleared */
if (regs[0] & (1 << 7)) {
return -EINPROGRESS;
}
/* Extract 20-bits of humidity data */
uint32_t reg_humidity = regs[1];
reg_humidity <<= 8;
reg_humidity |= regs[2];
reg_humidity <<= 4;
reg_humidity |= (regs[3] >> 4);
*humidity = (reg_humidity / 1048576.0);
/* Extract 20-bits of temperature data */
uint32_t reg_temperature = (regs[3] & 0x0F);
reg_temperature <<= 8;
reg_temperature |= regs[4];
reg_temperature <<= 8;
reg_temperature |= regs[5];
*temperature = (reg_temperature / 1048576.0) * 200.0 - 50.0;
/* Check crc */
crc8 crc8(0x31, 0xFF);
uint8_t crc8_computed = crc8.process(regs, 6);
if (crc8_computed != regs[6]) {
CONFIG_AHT20_DEBUG_FUNCTION(" [e] Checksum mismatch!");
return -EIO;
}
/* Return success */
return 0;
}
/**
*
* @param temperature
* @param humidity
* @return
*/
int aht20::measurement_sync_get(float * const temperature, float * const humidity) {
int res;
/* Trigger measurement */
res = measurement_async_trigger();
if (res < 0) {
CONFIG_AHT20_DEBUG_FUNCTION(" [e] Failed to trigger measurement!");
return res;
}
/* Remember start time to detect timeout */
uint32_t time_start = millis();
/* Wait enough time for measurement to be done and try to request results */
delay(CONFIG_AHT20_MEASUREMENT_DURATION);
while (1) {
/* Detect timeout */
if (millis() - time_start > CONFIG_AHT20_MEASUREMENT_TIMEOUT) {
CONFIG_AHT20_DEBUG_FUNCTION(" [e] Timed out waiting for measurement!");
return -ETIMEDOUT;
}
/* Request measurement results,
* But if they are not ready yet, wait a bit more */
res = measurement_async_get(temperature, humidity);
if (res == -EINPROGRESS) {
delay(CONFIG_AHT20_MEASUREMENT_RETRY);
continue;
} else if (res < 0) {
CONFIG_AHT20_DEBUG_FUNCTION(" [e] Failed to retrieve measurement!");
return res;
} else if (res == 0) {
break;
}
}
/* Return success */
return 0;
}
/**
*
* @param[out] bytes
* @param[in] length
* @return the number of bytes read from the sensor in case of success, or a negative error code otherwise.
*/
int aht20::m_register_read(uint8_t * const bytes, const size_t length) {
int res;
/* Ensure library has been set */
if (m_i2c_library == NULL) {
return -EINVAL;
}
/* Request to read */
res = m_i2c_library->requestFrom(CONFIG_AHT20_I2C_ADDRESS, length, true);
if (res < 0) {
return -EIO;
}
/* Return bytes */
for (size_t i = 0; i < length && i < (size_t) res; i++) {
bytes[i] = m_i2c_library->read();
}
return res;
}
/**
*
* @param[int] bytes
* @param[in] length
* @return the number of bytes written to the sensor in case of success, or a negative error code otherwise.
*/
int aht20::m_register_write(const uint8_t * const bytes, const size_t length) {
int res;
/* Ensure library has been set */
if (m_i2c_library == NULL) {
return -EINVAL;
}
/* Request to write */
m_i2c_library->beginTransmission(CONFIG_AHT20_I2C_ADDRESS);
m_i2c_library->write(bytes, length);
res = m_i2c_library->endTransmission(true);
if (res != 0) {
return -EIO;
}
/* Return bytes */
return res;
}
|
// Copyright 2016 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 "quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.h"
#include <stddef.h>
#include <string>
#include <tuple>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
// Provides friend access to an instance of the payload decoder, and also
// provides info to aid in testing.
class AltSvcPayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() { return Http2FrameType::ALTSVC; }
// Returns the mask of flags that affect the decoding of the payload (i.e.
// flags that that indicate the presence of certain fields or padding).
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
};
namespace {
struct Listener : public FramePartsCollector {
void OnAltSvcStart(const Http2FrameHeader& header, size_t origin_length,
size_t value_length) override {
QUICHE_VLOG(1) << "OnAltSvcStart header: " << header
<< "; origin_length=" << origin_length
<< "; value_length=" << value_length;
StartFrame(header)->OnAltSvcStart(header, origin_length, value_length);
}
void OnAltSvcOriginData(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnAltSvcOriginData: len=" << len;
CurrentFrame()->OnAltSvcOriginData(data, len);
}
void OnAltSvcValueData(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnAltSvcValueData: len=" << len;
CurrentFrame()->OnAltSvcValueData(data, len);
}
void OnAltSvcEnd() override {
QUICHE_VLOG(1) << "OnAltSvcEnd";
EndFrame()->OnAltSvcEnd();
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class AltSvcPayloadDecoderTest
: public AbstractPayloadDecoderTest<AltSvcPayloadDecoder,
AltSvcPayloadDecoderPeer, Listener> {};
// Confirm we get an error if the payload is not long enough to hold
// Http2AltSvcFields and the indicated length of origin.
TEST_F(AltSvcPayloadDecoderTest, Truncated) {
Http2FrameBuilder fb;
fb.Append(Http2AltSvcFields{0xffff}); // The longest possible origin length.
fb.Append("Too little origin!");
EXPECT_TRUE(
VerifyDetectsFrameSizeError(0, fb.buffer(), /*approve_size*/ nullptr));
}
class AltSvcPayloadLengthTests
: public AltSvcPayloadDecoderTest,
public ::testing::WithParamInterface<std::tuple<uint16_t, uint32_t>> {
protected:
AltSvcPayloadLengthTests()
: origin_length_(std::get<0>(GetParam())),
value_length_(std::get<1>(GetParam())) {
QUICHE_VLOG(1) << "################ origin_length_=" << origin_length_
<< " value_length_=" << value_length_
<< " ################";
}
const uint16_t origin_length_;
const uint32_t value_length_;
};
INSTANTIATE_TEST_SUITE_P(VariousOriginAndValueLengths, AltSvcPayloadLengthTests,
::testing::Combine(::testing::Values(0, 1, 3, 65535),
::testing::Values(0, 1, 3, 65537)));
TEST_P(AltSvcPayloadLengthTests, ValidOriginAndValueLength) {
std::string origin = Random().RandString(origin_length_);
std::string value = Random().RandString(value_length_);
Http2FrameBuilder fb;
fb.Append(Http2AltSvcFields{origin_length_});
fb.Append(origin);
fb.Append(value);
Http2FrameHeader header(fb.size(), Http2FrameType::ALTSVC, RandFlags(),
RandStreamId());
set_frame_header(header);
FrameParts expected(header);
expected.SetAltSvcExpected(origin, value);
ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
} // namespace
} // namespace test
} // namespace http2
|
// Copyright 2013 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/compiler/code-generator.h"
#include "src/compiler/code-generator-impl.h"
#include "src/compiler/gap-resolver.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-properties-inl.h"
#include "src/scopes.h"
#include "src/x64/assembler-x64.h"
#include "src/x64/macro-assembler-x64.h"
namespace v8 {
namespace internal {
namespace compiler {
#define __ masm()->
// TODO(turbofan): Cleanup these hacks.
enum Immediate64Type { kImm64Value, kImm64Handle, kImm64Reference };
struct Immediate64 {
uint64_t value;
Handle<Object> handle;
ExternalReference reference;
Immediate64Type type;
};
enum RegisterOrOperandType { kRegister, kDoubleRegister, kOperand };
struct RegisterOrOperand {
RegisterOrOperand() : operand(no_reg, 0) {}
Register reg;
DoubleRegister double_reg;
Operand operand;
RegisterOrOperandType type;
};
// Adds X64 specific methods for decoding operands.
class X64OperandConverter : public InstructionOperandConverter {
public:
X64OperandConverter(CodeGenerator* gen, Instruction* instr)
: InstructionOperandConverter(gen, instr) {}
RegisterOrOperand InputRegisterOrOperand(int index) {
return ToRegisterOrOperand(instr_->InputAt(index));
}
Immediate InputImmediate(int index) {
return ToImmediate(instr_->InputAt(index));
}
RegisterOrOperand OutputRegisterOrOperand() {
return ToRegisterOrOperand(instr_->Output());
}
Immediate64 InputImmediate64(int index) {
return ToImmediate64(instr_->InputAt(index));
}
Immediate64 ToImmediate64(InstructionOperand* operand) {
Constant constant = ToConstant(operand);
Immediate64 immediate;
immediate.value = 0xbeefdeaddeefbeed;
immediate.type = kImm64Value;
switch (constant.type()) {
case Constant::kInt32:
case Constant::kInt64:
immediate.value = constant.ToInt64();
return immediate;
case Constant::kFloat64:
immediate.type = kImm64Handle;
immediate.handle =
isolate()->factory()->NewNumber(constant.ToFloat64(), TENURED);
return immediate;
case Constant::kExternalReference:
immediate.type = kImm64Reference;
immediate.reference = constant.ToExternalReference();
return immediate;
case Constant::kHeapObject:
immediate.type = kImm64Handle;
immediate.handle = constant.ToHeapObject();
return immediate;
}
UNREACHABLE();
return immediate;
}
Immediate ToImmediate(InstructionOperand* operand) {
Constant constant = ToConstant(operand);
switch (constant.type()) {
case Constant::kInt32:
return Immediate(constant.ToInt32());
case Constant::kInt64:
case Constant::kFloat64:
case Constant::kExternalReference:
case Constant::kHeapObject:
break;
}
UNREACHABLE();
return Immediate(-1);
}
Operand ToOperand(InstructionOperand* op, int extra = 0) {
RegisterOrOperand result = ToRegisterOrOperand(op, extra);
DCHECK_EQ(kOperand, result.type);
return result.operand;
}
RegisterOrOperand ToRegisterOrOperand(InstructionOperand* op, int extra = 0) {
RegisterOrOperand result;
if (op->IsRegister()) {
DCHECK(extra == 0);
result.type = kRegister;
result.reg = ToRegister(op);
return result;
} else if (op->IsDoubleRegister()) {
DCHECK(extra == 0);
DCHECK(extra == 0);
result.type = kDoubleRegister;
result.double_reg = ToDoubleRegister(op);
return result;
}
DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
result.type = kOperand;
// The linkage computes where all spill slots are located.
FrameOffset offset = linkage()->GetFrameOffset(op->index(), frame(), extra);
result.operand =
Operand(offset.from_stack_pointer() ? rsp : rbp, offset.offset());
return result;
}
Operand MemoryOperand(int* first_input) {
const int offset = *first_input;
switch (AddressingModeField::decode(instr_->opcode())) {
case kMode_MR1I: {
*first_input += 2;
Register index = InputRegister(offset + 1);
return Operand(InputRegister(offset + 0), index, times_1,
0); // TODO(dcarney): K != 0
}
case kMode_MRI:
*first_input += 2;
return Operand(InputRegister(offset + 0), InputInt32(offset + 1));
default:
UNREACHABLE();
return Operand(no_reg, 0);
}
}
Operand MemoryOperand() {
int first_input = 0;
return MemoryOperand(&first_input);
}
};
static bool HasImmediateInput(Instruction* instr, int index) {
return instr->InputAt(index)->IsImmediate();
}
#define ASSEMBLE_BINOP(asm_instr) \
do { \
if (HasImmediateInput(instr, 1)) { \
RegisterOrOperand input = i.InputRegisterOrOperand(0); \
if (input.type == kRegister) { \
__ asm_instr(input.reg, i.InputImmediate(1)); \
} else { \
__ asm_instr(input.operand, i.InputImmediate(1)); \
} \
} else { \
RegisterOrOperand input = i.InputRegisterOrOperand(1); \
if (input.type == kRegister) { \
__ asm_instr(i.InputRegister(0), input.reg); \
} else { \
__ asm_instr(i.InputRegister(0), input.operand); \
} \
} \
} while (0)
#define ASSEMBLE_SHIFT(asm_instr, width) \
do { \
if (HasImmediateInput(instr, 1)) { \
__ asm_instr(i.OutputRegister(), Immediate(i.InputInt##width(1))); \
} else { \
__ asm_instr##_cl(i.OutputRegister()); \
} \
} while (0)
// Assembles an instruction after register allocation, producing machine code.
void CodeGenerator::AssembleArchInstruction(Instruction* instr) {
X64OperandConverter i(this, instr);
switch (ArchOpcodeField::decode(instr->opcode())) {
case kArchCallCodeObject: {
EnsureSpaceForLazyDeopt();
if (HasImmediateInput(instr, 0)) {
Handle<Code> code = Handle<Code>::cast(i.InputHeapObject(0));
__ Call(code, RelocInfo::CODE_TARGET);
} else {
Register reg = i.InputRegister(0);
int entry = Code::kHeaderSize - kHeapObjectTag;
__ Call(Operand(reg, entry));
}
AddSafepointAndDeopt(instr);
break;
}
case kArchCallJSFunction: {
EnsureSpaceForLazyDeopt();
Register func = i.InputRegister(0);
if (FLAG_debug_code) {
// Check the function's context matches the context argument.
__ cmpp(rsi, FieldOperand(func, JSFunction::kContextOffset));
__ Assert(equal, kWrongFunctionContext);
}
__ Call(FieldOperand(func, JSFunction::kCodeEntryOffset));
AddSafepointAndDeopt(instr);
break;
}
case kArchJmp:
__ jmp(code_->GetLabel(i.InputBlock(0)));
break;
case kArchNop:
// don't emit code for nops.
break;
case kArchRet:
AssembleReturn();
break;
case kArchTruncateDoubleToI:
__ TruncateDoubleToI(i.OutputRegister(), i.InputDoubleRegister(0));
break;
case kX64Add32:
ASSEMBLE_BINOP(addl);
break;
case kX64Add:
ASSEMBLE_BINOP(addq);
break;
case kX64Sub32:
ASSEMBLE_BINOP(subl);
break;
case kX64Sub:
ASSEMBLE_BINOP(subq);
break;
case kX64And32:
ASSEMBLE_BINOP(andl);
break;
case kX64And:
ASSEMBLE_BINOP(andq);
break;
case kX64Cmp32:
ASSEMBLE_BINOP(cmpl);
break;
case kX64Cmp:
ASSEMBLE_BINOP(cmpq);
break;
case kX64Test32:
ASSEMBLE_BINOP(testl);
break;
case kX64Test:
ASSEMBLE_BINOP(testq);
break;
case kX64Imul32:
if (HasImmediateInput(instr, 1)) {
RegisterOrOperand input = i.InputRegisterOrOperand(0);
if (input.type == kRegister) {
__ imull(i.OutputRegister(), input.reg, i.InputImmediate(1));
} else {
__ movq(kScratchRegister, input.operand);
__ imull(i.OutputRegister(), kScratchRegister, i.InputImmediate(1));
}
} else {
RegisterOrOperand input = i.InputRegisterOrOperand(1);
if (input.type == kRegister) {
__ imull(i.OutputRegister(), input.reg);
} else {
__ imull(i.OutputRegister(), input.operand);
}
}
break;
case kX64Imul:
if (HasImmediateInput(instr, 1)) {
RegisterOrOperand input = i.InputRegisterOrOperand(0);
if (input.type == kRegister) {
__ imulq(i.OutputRegister(), input.reg, i.InputImmediate(1));
} else {
__ movq(kScratchRegister, input.operand);
__ imulq(i.OutputRegister(), kScratchRegister, i.InputImmediate(1));
}
} else {
RegisterOrOperand input = i.InputRegisterOrOperand(1);
if (input.type == kRegister) {
__ imulq(i.OutputRegister(), input.reg);
} else {
__ imulq(i.OutputRegister(), input.operand);
}
}
break;
case kX64Idiv32:
__ cdq();
__ idivl(i.InputRegister(1));
break;
case kX64Idiv:
__ cqo();
__ idivq(i.InputRegister(1));
break;
case kX64Udiv32:
__ xorl(rdx, rdx);
__ divl(i.InputRegister(1));
break;
case kX64Udiv:
__ xorq(rdx, rdx);
__ divq(i.InputRegister(1));
break;
case kX64Not: {
RegisterOrOperand output = i.OutputRegisterOrOperand();
if (output.type == kRegister) {
__ notq(output.reg);
} else {
__ notq(output.operand);
}
break;
}
case kX64Not32: {
RegisterOrOperand output = i.OutputRegisterOrOperand();
if (output.type == kRegister) {
__ notl(output.reg);
} else {
__ notl(output.operand);
}
break;
}
case kX64Neg: {
RegisterOrOperand output = i.OutputRegisterOrOperand();
if (output.type == kRegister) {
__ negq(output.reg);
} else {
__ negq(output.operand);
}
break;
}
case kX64Neg32: {
RegisterOrOperand output = i.OutputRegisterOrOperand();
if (output.type == kRegister) {
__ negl(output.reg);
} else {
__ negl(output.operand);
}
break;
}
case kX64Or32:
ASSEMBLE_BINOP(orl);
break;
case kX64Or:
ASSEMBLE_BINOP(orq);
break;
case kX64Xor32:
ASSEMBLE_BINOP(xorl);
break;
case kX64Xor:
ASSEMBLE_BINOP(xorq);
break;
case kX64Shl32:
ASSEMBLE_SHIFT(shll, 5);
break;
case kX64Shl:
ASSEMBLE_SHIFT(shlq, 6);
break;
case kX64Shr32:
ASSEMBLE_SHIFT(shrl, 5);
break;
case kX64Shr:
ASSEMBLE_SHIFT(shrq, 6);
break;
case kX64Sar32:
ASSEMBLE_SHIFT(sarl, 5);
break;
case kX64Sar:
ASSEMBLE_SHIFT(sarq, 6);
break;
case kX64Ror32:
ASSEMBLE_SHIFT(rorl, 5);
break;
case kX64Ror:
ASSEMBLE_SHIFT(rorq, 6);
break;
case kSSEFloat64Cmp: {
RegisterOrOperand input = i.InputRegisterOrOperand(1);
if (input.type == kDoubleRegister) {
__ ucomisd(i.InputDoubleRegister(0), input.double_reg);
} else {
__ ucomisd(i.InputDoubleRegister(0), input.operand);
}
break;
}
case kSSEFloat64Add:
__ addsd(i.InputDoubleRegister(0), i.InputDoubleRegister(1));
break;
case kSSEFloat64Sub:
__ subsd(i.InputDoubleRegister(0), i.InputDoubleRegister(1));
break;
case kSSEFloat64Mul:
__ mulsd(i.InputDoubleRegister(0), i.InputDoubleRegister(1));
break;
case kSSEFloat64Div:
__ divsd(i.InputDoubleRegister(0), i.InputDoubleRegister(1));
break;
case kSSEFloat64Mod: {
__ subq(rsp, Immediate(kDoubleSize));
// Move values to st(0) and st(1).
__ movsd(Operand(rsp, 0), i.InputDoubleRegister(1));
__ fld_d(Operand(rsp, 0));
__ movsd(Operand(rsp, 0), i.InputDoubleRegister(0));
__ fld_d(Operand(rsp, 0));
// Loop while fprem isn't done.
Label mod_loop;
__ bind(&mod_loop);
// This instructions traps on all kinds inputs, but we are assuming the
// floating point control word is set to ignore them all.
__ fprem();
// The following 2 instruction implicitly use rax.
__ fnstsw_ax();
if (CpuFeatures::IsSupported(SAHF) && masm()->IsEnabled(SAHF)) {
__ sahf();
} else {
__ shrl(rax, Immediate(8));
__ andl(rax, Immediate(0xFF));
__ pushq(rax);
__ popfq();
}
__ j(parity_even, &mod_loop);
// Move output to stack and clean up.
__ fstp(1);
__ fstp_d(Operand(rsp, 0));
__ movsd(i.OutputDoubleRegister(), Operand(rsp, 0));
__ addq(rsp, Immediate(kDoubleSize));
break;
}
case kSSEFloat64Sqrt: {
RegisterOrOperand input = i.InputRegisterOrOperand(0);
if (input.type == kDoubleRegister) {
__ sqrtsd(i.OutputDoubleRegister(), input.double_reg);
} else {
__ sqrtsd(i.OutputDoubleRegister(), input.operand);
}
break;
}
case kSSEFloat64ToInt32: {
RegisterOrOperand input = i.InputRegisterOrOperand(0);
if (input.type == kDoubleRegister) {
__ cvttsd2si(i.OutputRegister(), input.double_reg);
} else {
__ cvttsd2si(i.OutputRegister(), input.operand);
}
break;
}
case kSSEFloat64ToUint32: {
RegisterOrOperand input = i.InputRegisterOrOperand(0);
if (input.type == kDoubleRegister) {
__ cvttsd2siq(i.OutputRegister(), input.double_reg);
} else {
__ cvttsd2siq(i.OutputRegister(), input.operand);
}
__ andl(i.OutputRegister(), i.OutputRegister()); // clear upper bits.
// TODO(turbofan): generated code should not look at the upper 32 bits
// of the result, but those bits could escape to the outside world.
break;
}
case kSSEInt32ToFloat64: {
RegisterOrOperand input = i.InputRegisterOrOperand(0);
if (input.type == kRegister) {
__ cvtlsi2sd(i.OutputDoubleRegister(), input.reg);
} else {
__ cvtlsi2sd(i.OutputDoubleRegister(), input.operand);
}
break;
}
case kSSEUint32ToFloat64: {
// TODO(turbofan): X64 SSE cvtqsi2sd should support operands.
__ cvtqsi2sd(i.OutputDoubleRegister(), i.InputRegister(0));
break;
}
case kX64Movsxbl:
__ movsxbl(i.OutputRegister(), i.MemoryOperand());
break;
case kX64Movzxbl:
__ movzxbl(i.OutputRegister(), i.MemoryOperand());
break;
case kX64Movb: {
int index = 0;
Operand operand = i.MemoryOperand(&index);
if (HasImmediateInput(instr, index)) {
__ movb(operand, Immediate(i.InputInt8(index)));
} else {
__ movb(operand, i.InputRegister(index));
}
break;
}
case kX64Movsxwl:
__ movsxwl(i.OutputRegister(), i.MemoryOperand());
break;
case kX64Movzxwl:
__ movzxwl(i.OutputRegister(), i.MemoryOperand());
break;
case kX64Movw: {
int index = 0;
Operand operand = i.MemoryOperand(&index);
if (HasImmediateInput(instr, index)) {
__ movw(operand, Immediate(i.InputInt16(index)));
} else {
__ movw(operand, i.InputRegister(index));
}
break;
}
case kX64Movl:
if (instr->HasOutput()) {
if (instr->addressing_mode() == kMode_None) {
RegisterOrOperand input = i.InputRegisterOrOperand(0);
if (input.type == kRegister) {
__ movl(i.OutputRegister(), input.reg);
} else {
__ movl(i.OutputRegister(), input.operand);
}
} else {
__ movl(i.OutputRegister(), i.MemoryOperand());
}
} else {
int index = 0;
Operand operand = i.MemoryOperand(&index);
if (HasImmediateInput(instr, index)) {
__ movl(operand, i.InputImmediate(index));
} else {
__ movl(operand, i.InputRegister(index));
}
}
break;
case kX64Movsxlq: {
RegisterOrOperand input = i.InputRegisterOrOperand(0);
if (input.type == kRegister) {
__ movsxlq(i.OutputRegister(), input.reg);
} else {
__ movsxlq(i.OutputRegister(), input.operand);
}
break;
}
case kX64Movq:
if (instr->HasOutput()) {
__ movq(i.OutputRegister(), i.MemoryOperand());
} else {
int index = 0;
Operand operand = i.MemoryOperand(&index);
if (HasImmediateInput(instr, index)) {
__ movq(operand, i.InputImmediate(index));
} else {
__ movq(operand, i.InputRegister(index));
}
}
break;
case kX64Movss:
if (instr->HasOutput()) {
__ movss(i.OutputDoubleRegister(), i.MemoryOperand());
__ cvtss2sd(i.OutputDoubleRegister(), i.OutputDoubleRegister());
} else {
int index = 0;
Operand operand = i.MemoryOperand(&index);
__ cvtsd2ss(xmm0, i.InputDoubleRegister(index));
__ movss(operand, xmm0);
}
break;
case kX64Movsd:
if (instr->HasOutput()) {
__ movsd(i.OutputDoubleRegister(), i.MemoryOperand());
} else {
int index = 0;
Operand operand = i.MemoryOperand(&index);
__ movsd(operand, i.InputDoubleRegister(index));
}
break;
case kX64Push:
if (HasImmediateInput(instr, 0)) {
__ pushq(i.InputImmediate(0));
} else {
RegisterOrOperand input = i.InputRegisterOrOperand(0);
if (input.type == kRegister) {
__ pushq(input.reg);
} else {
__ pushq(input.operand);
}
}
break;
case kX64StoreWriteBarrier: {
Register object = i.InputRegister(0);
Register index = i.InputRegister(1);
Register value = i.InputRegister(2);
__ movsxlq(index, index);
__ movq(Operand(object, index, times_1, 0), value);
__ leaq(index, Operand(object, index, times_1, 0));
SaveFPRegsMode mode = code_->frame()->DidAllocateDoubleRegisters()
? kSaveFPRegs
: kDontSaveFPRegs;
__ RecordWrite(object, index, value, mode);
break;
}
}
}
// Assembles branches after this instruction.
void CodeGenerator::AssembleArchBranch(Instruction* instr,
FlagsCondition condition) {
X64OperandConverter i(this, instr);
Label done;
// Emit a branch. The true and false targets are always the last two inputs
// to the instruction.
BasicBlock* tblock = i.InputBlock(static_cast<int>(instr->InputCount()) - 2);
BasicBlock* fblock = i.InputBlock(static_cast<int>(instr->InputCount()) - 1);
bool fallthru = IsNextInAssemblyOrder(fblock);
Label* tlabel = code()->GetLabel(tblock);
Label* flabel = fallthru ? &done : code()->GetLabel(fblock);
Label::Distance flabel_distance = fallthru ? Label::kNear : Label::kFar;
switch (condition) {
case kUnorderedEqual:
__ j(parity_even, flabel, flabel_distance);
// Fall through.
case kEqual:
__ j(equal, tlabel);
break;
case kUnorderedNotEqual:
__ j(parity_even, tlabel);
// Fall through.
case kNotEqual:
__ j(not_equal, tlabel);
break;
case kSignedLessThan:
__ j(less, tlabel);
break;
case kSignedGreaterThanOrEqual:
__ j(greater_equal, tlabel);
break;
case kSignedLessThanOrEqual:
__ j(less_equal, tlabel);
break;
case kSignedGreaterThan:
__ j(greater, tlabel);
break;
case kUnorderedLessThan:
__ j(parity_even, flabel, flabel_distance);
// Fall through.
case kUnsignedLessThan:
__ j(below, tlabel);
break;
case kUnorderedGreaterThanOrEqual:
__ j(parity_even, tlabel);
// Fall through.
case kUnsignedGreaterThanOrEqual:
__ j(above_equal, tlabel);
break;
case kUnorderedLessThanOrEqual:
__ j(parity_even, flabel, flabel_distance);
// Fall through.
case kUnsignedLessThanOrEqual:
__ j(below_equal, tlabel);
break;
case kUnorderedGreaterThan:
__ j(parity_even, tlabel);
// Fall through.
case kUnsignedGreaterThan:
__ j(above, tlabel);
break;
case kOverflow:
__ j(overflow, tlabel);
break;
case kNotOverflow:
__ j(no_overflow, tlabel);
break;
}
if (!fallthru) __ jmp(flabel, flabel_distance); // no fallthru to flabel.
__ bind(&done);
}
// Assembles boolean materializations after this instruction.
void CodeGenerator::AssembleArchBoolean(Instruction* instr,
FlagsCondition condition) {
X64OperandConverter i(this, instr);
Label done;
// Materialize a full 64-bit 1 or 0 value. The result register is always the
// last output of the instruction.
Label check;
DCHECK_NE(0, instr->OutputCount());
Register reg = i.OutputRegister(static_cast<int>(instr->OutputCount() - 1));
Condition cc = no_condition;
switch (condition) {
case kUnorderedEqual:
__ j(parity_odd, &check, Label::kNear);
__ movl(reg, Immediate(0));
__ jmp(&done, Label::kNear);
// Fall through.
case kEqual:
cc = equal;
break;
case kUnorderedNotEqual:
__ j(parity_odd, &check, Label::kNear);
__ movl(reg, Immediate(1));
__ jmp(&done, Label::kNear);
// Fall through.
case kNotEqual:
cc = not_equal;
break;
case kSignedLessThan:
cc = less;
break;
case kSignedGreaterThanOrEqual:
cc = greater_equal;
break;
case kSignedLessThanOrEqual:
cc = less_equal;
break;
case kSignedGreaterThan:
cc = greater;
break;
case kUnorderedLessThan:
__ j(parity_odd, &check, Label::kNear);
__ movl(reg, Immediate(0));
__ jmp(&done, Label::kNear);
// Fall through.
case kUnsignedLessThan:
cc = below;
break;
case kUnorderedGreaterThanOrEqual:
__ j(parity_odd, &check, Label::kNear);
__ movl(reg, Immediate(1));
__ jmp(&done, Label::kNear);
// Fall through.
case kUnsignedGreaterThanOrEqual:
cc = above_equal;
break;
case kUnorderedLessThanOrEqual:
__ j(parity_odd, &check, Label::kNear);
__ movl(reg, Immediate(0));
__ jmp(&done, Label::kNear);
// Fall through.
case kUnsignedLessThanOrEqual:
cc = below_equal;
break;
case kUnorderedGreaterThan:
__ j(parity_odd, &check, Label::kNear);
__ movl(reg, Immediate(1));
__ jmp(&done, Label::kNear);
// Fall through.
case kUnsignedGreaterThan:
cc = above;
break;
case kOverflow:
cc = overflow;
break;
case kNotOverflow:
cc = no_overflow;
break;
}
__ bind(&check);
__ setcc(cc, reg);
__ movzxbl(reg, reg);
__ bind(&done);
}
void CodeGenerator::AssembleDeoptimizerCall(int deoptimization_id) {
Address deopt_entry = Deoptimizer::GetDeoptimizationEntry(
isolate(), deoptimization_id, Deoptimizer::LAZY);
__ call(deopt_entry, RelocInfo::RUNTIME_ENTRY);
}
void CodeGenerator::AssemblePrologue() {
CallDescriptor* descriptor = linkage()->GetIncomingDescriptor();
int stack_slots = frame()->GetSpillSlotCount();
if (descriptor->kind() == CallDescriptor::kCallAddress) {
__ pushq(rbp);
__ movq(rbp, rsp);
const RegList saves = descriptor->CalleeSavedRegisters();
if (saves != 0) { // Save callee-saved registers.
int register_save_area_size = 0;
for (int i = Register::kNumRegisters - 1; i >= 0; i--) {
if (!((1 << i) & saves)) continue;
__ pushq(Register::from_code(i));
register_save_area_size += kPointerSize;
}
frame()->SetRegisterSaveAreaSize(register_save_area_size);
}
} else if (descriptor->IsJSFunctionCall()) {
CompilationInfo* info = linkage()->info();
__ Prologue(info->IsCodePreAgingActive());
frame()->SetRegisterSaveAreaSize(
StandardFrameConstants::kFixedFrameSizeFromFp);
// Sloppy mode functions and builtins need to replace the receiver with the
// global proxy when called as functions (without an explicit receiver
// object).
// TODO(mstarzinger/verwaest): Should this be moved back into the CallIC?
if (info->strict_mode() == SLOPPY && !info->is_native()) {
Label ok;
StackArgumentsAccessor args(rbp, info->scope()->num_parameters());
__ movp(rcx, args.GetReceiverOperand());
__ CompareRoot(rcx, Heap::kUndefinedValueRootIndex);
__ j(not_equal, &ok, Label::kNear);
__ movp(rcx, GlobalObjectOperand());
__ movp(rcx, FieldOperand(rcx, GlobalObject::kGlobalProxyOffset));
__ movp(args.GetReceiverOperand(), rcx);
__ bind(&ok);
}
} else {
__ StubPrologue();
frame()->SetRegisterSaveAreaSize(
StandardFrameConstants::kFixedFrameSizeFromFp);
}
if (stack_slots > 0) {
__ subq(rsp, Immediate(stack_slots * kPointerSize));
}
}
void CodeGenerator::AssembleReturn() {
CallDescriptor* descriptor = linkage()->GetIncomingDescriptor();
if (descriptor->kind() == CallDescriptor::kCallAddress) {
if (frame()->GetRegisterSaveAreaSize() > 0) {
// Remove this frame's spill slots first.
int stack_slots = frame()->GetSpillSlotCount();
if (stack_slots > 0) {
__ addq(rsp, Immediate(stack_slots * kPointerSize));
}
const RegList saves = descriptor->CalleeSavedRegisters();
// Restore registers.
if (saves != 0) {
for (int i = 0; i < Register::kNumRegisters; i++) {
if (!((1 << i) & saves)) continue;
__ popq(Register::from_code(i));
}
}
__ popq(rbp); // Pop caller's frame pointer.
__ ret(0);
} else {
// No saved registers.
__ movq(rsp, rbp); // Move stack pointer back to frame pointer.
__ popq(rbp); // Pop caller's frame pointer.
__ ret(0);
}
} else {
__ movq(rsp, rbp); // Move stack pointer back to frame pointer.
__ popq(rbp); // Pop caller's frame pointer.
int pop_count = descriptor->IsJSFunctionCall()
? static_cast<int>(descriptor->JSParameterCount())
: 0;
__ ret(pop_count * kPointerSize);
}
}
void CodeGenerator::AssembleMove(InstructionOperand* source,
InstructionOperand* destination) {
X64OperandConverter g(this, NULL);
// Dispatch on the source and destination operand kinds. Not all
// combinations are possible.
if (source->IsRegister()) {
DCHECK(destination->IsRegister() || destination->IsStackSlot());
Register src = g.ToRegister(source);
if (destination->IsRegister()) {
__ movq(g.ToRegister(destination), src);
} else {
__ movq(g.ToOperand(destination), src);
}
} else if (source->IsStackSlot()) {
DCHECK(destination->IsRegister() || destination->IsStackSlot());
Operand src = g.ToOperand(source);
if (destination->IsRegister()) {
Register dst = g.ToRegister(destination);
__ movq(dst, src);
} else {
// Spill on demand to use a temporary register for memory-to-memory
// moves.
Register tmp = kScratchRegister;
Operand dst = g.ToOperand(destination);
__ movq(tmp, src);
__ movq(dst, tmp);
}
} else if (source->IsConstant()) {
ConstantOperand* constant_source = ConstantOperand::cast(source);
if (destination->IsRegister() || destination->IsStackSlot()) {
Register dst = destination->IsRegister() ? g.ToRegister(destination)
: kScratchRegister;
Immediate64 imm = g.ToImmediate64(constant_source);
switch (imm.type) {
case kImm64Value:
__ Set(dst, imm.value);
break;
case kImm64Reference:
__ Move(dst, imm.reference);
break;
case kImm64Handle:
__ Move(dst, imm.handle);
break;
}
if (destination->IsStackSlot()) {
__ movq(g.ToOperand(destination), kScratchRegister);
}
} else {
__ movq(kScratchRegister,
bit_cast<uint64_t, double>(g.ToDouble(constant_source)));
if (destination->IsDoubleRegister()) {
__ movq(g.ToDoubleRegister(destination), kScratchRegister);
} else {
DCHECK(destination->IsDoubleStackSlot());
__ movq(g.ToOperand(destination), kScratchRegister);
}
}
} else if (source->IsDoubleRegister()) {
XMMRegister src = g.ToDoubleRegister(source);
if (destination->IsDoubleRegister()) {
XMMRegister dst = g.ToDoubleRegister(destination);
__ movsd(dst, src);
} else {
DCHECK(destination->IsDoubleStackSlot());
Operand dst = g.ToOperand(destination);
__ movsd(dst, src);
}
} else if (source->IsDoubleStackSlot()) {
DCHECK(destination->IsDoubleRegister() || destination->IsDoubleStackSlot());
Operand src = g.ToOperand(source);
if (destination->IsDoubleRegister()) {
XMMRegister dst = g.ToDoubleRegister(destination);
__ movsd(dst, src);
} else {
// We rely on having xmm0 available as a fixed scratch register.
Operand dst = g.ToOperand(destination);
__ movsd(xmm0, src);
__ movsd(dst, xmm0);
}
} else {
UNREACHABLE();
}
}
void CodeGenerator::AssembleSwap(InstructionOperand* source,
InstructionOperand* destination) {
X64OperandConverter g(this, NULL);
// Dispatch on the source and destination operand kinds. Not all
// combinations are possible.
if (source->IsRegister() && destination->IsRegister()) {
// Register-register.
__ xchgq(g.ToRegister(source), g.ToRegister(destination));
} else if (source->IsRegister() && destination->IsStackSlot()) {
Register src = g.ToRegister(source);
Operand dst = g.ToOperand(destination);
__ xchgq(src, dst);
} else if ((source->IsStackSlot() && destination->IsStackSlot()) ||
(source->IsDoubleStackSlot() &&
destination->IsDoubleStackSlot())) {
// Memory-memory.
Register tmp = kScratchRegister;
Operand src = g.ToOperand(source);
Operand dst = g.ToOperand(destination);
__ movq(tmp, dst);
__ xchgq(tmp, src);
__ movq(dst, tmp);
} else if (source->IsDoubleRegister() && destination->IsDoubleRegister()) {
// XMM register-register swap. We rely on having xmm0
// available as a fixed scratch register.
XMMRegister src = g.ToDoubleRegister(source);
XMMRegister dst = g.ToDoubleRegister(destination);
__ movsd(xmm0, src);
__ movsd(src, dst);
__ movsd(dst, xmm0);
} else if (source->IsDoubleRegister() && destination->IsDoubleRegister()) {
// XMM register-memory swap. We rely on having xmm0
// available as a fixed scratch register.
XMMRegister src = g.ToDoubleRegister(source);
Operand dst = g.ToOperand(destination);
__ movsd(xmm0, src);
__ movsd(src, dst);
__ movsd(dst, xmm0);
} else {
// No other combinations are possible.
UNREACHABLE();
}
}
void CodeGenerator::AddNopForSmiCodeInlining() { __ nop(); }
void CodeGenerator::EnsureSpaceForLazyDeopt() {
int space_needed = Deoptimizer::patch_size();
if (!linkage()->info()->IsStub()) {
// Ensure that we have enough space after the previous lazy-bailout
// instruction for patching the code here.
int current_pc = masm()->pc_offset();
if (current_pc < last_lazy_deopt_pc_ + space_needed) {
int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
__ Nop(padding_size);
}
}
MarkLazyDeoptSite();
}
#undef __
} // namespace internal
} // namespace compiler
} // namespace v8
|
#include "TrtNet.h"
#include "EntroyCalibrator.h"
#include <cassert>
#include <cublas_v2.h>
#include <cudnn.h>
#include <iostream>
#include <sstream>
#include <string.h>
#include <time.h>
#include <unordered_map>
using namespace nvinfer1;
using namespace nvcaffeparser1;
using namespace plugin;
static Tn::Logger gLogger;
#define RETURN_AND_LOG(ret, severity, message) \
do \
{ \
std::string error_message = "ssd_error_log: " + std::string(message); \
gLogger.log(ILogger::Severity::k##severity, error_message.c_str()); \
return (ret); \
} while (0)
inline void* safeCudaMalloc(size_t memSize)
{
void* deviceMem;
CUDA_CHECK(cudaMalloc(&deviceMem, memSize));
if (deviceMem == nullptr)
{
std::cerr << "Out of memory" << std::endl;
exit(1);
}
return deviceMem;
}
inline int64_t volume(const nvinfer1::Dims& d)
{
return std::accumulate(d.d, d.d + d.nbDims, 1, std::multiplies<int64_t>());
}
inline unsigned int getElementSize(nvinfer1::DataType t)
{
switch (t)
{
case nvinfer1::DataType::kINT32: return 4;
case nvinfer1::DataType::kFLOAT: return 4;
case nvinfer1::DataType::kHALF: return 2;
case nvinfer1::DataType::kINT8: return 1;
}
throw std::runtime_error("Invalid DataType.");
return 0;
}
namespace Tn
{
trtNet::trtNet(const std::string& prototxt,const std::string& caffemodel,const std::vector<std::string>& outputNodesName,
const std::vector<std::vector<float>>& calibratorData,RUN_MODE mode /*= RUN_MODE::FLOAT32*/,int maxBatchSize /*= 1*/)
:mTrtContext(nullptr),mTrtEngine(nullptr),mTrtRunTime(nullptr),mTrtRunMode(mode),mTrtInputCount(0),mTrtIterationTime(0),mTrtBatchSize(maxBatchSize)
{
std::cout << "init plugin proto: " << prototxt << " caffemodel: " << caffemodel << std::endl;
auto parser = createCaffeParser();
IHostMemory* trtModelStream{nullptr};
Int8EntropyCalibrator * calibrator = nullptr;
if (calibratorData.size() > 0 ){
auto endPos= prototxt.find_last_of(".");
auto beginPos= prototxt.find_last_of('/') + 1;
std::string calibratorName = prototxt.substr(beginPos,endPos - beginPos);
std::cout << "create calibrator,Named:" << calibratorName << std::endl;
calibrator = new Int8EntropyCalibrator(maxBatchSize,calibratorData,calibratorName);
}
PluginFactory pluginFactorySerialize;
ICudaEngine* tmpEngine = loadModelAndCreateEngine(prototxt.c_str(),caffemodel.c_str(), maxBatchSize, parser, &pluginFactorySerialize, calibrator, trtModelStream,outputNodesName);
assert(tmpEngine != nullptr);
assert(trtModelStream != nullptr);
if(calibrator){
delete calibrator;
calibrator = nullptr;
}
tmpEngine->destroy();
pluginFactorySerialize.destroyPlugin();
mTrtRunTime = createInferRuntime(gLogger);
assert(mTrtRunTime != nullptr);
mTrtEngine= mTrtRunTime->deserializeCudaEngine(trtModelStream->data(), trtModelStream->size(), &mTrtPluginFactory);
assert(mTrtEngine != nullptr);
// Deserialize the engine.
trtModelStream->destroy();
InitEngine();
}
trtNet::trtNet(const std::string& engineFile)
:mTrtContext(nullptr),mTrtEngine(nullptr),mTrtRunTime(nullptr),mTrtRunMode(RUN_MODE::FLOAT32),mTrtInputCount(0),mTrtIterationTime(0)
{
using namespace std;
fstream file;
file.open(engineFile,ios::binary | ios::in);
if(!file.is_open())
{
cout << "read engine file" << engineFile <<" failed" << endl;
return;
}
file.seekg(0, ios::end);
int length = file.tellg();
file.seekg(0, ios::beg);
std::unique_ptr<char[]> data(new char[length]);
file.read(data.get(), length);
file.close();
std::cout << "deserializing" << std::endl;
mTrtRunTime = createInferRuntime(gLogger);
assert(mTrtRunTime != nullptr);
mTrtEngine= mTrtRunTime->deserializeCudaEngine(data.get(), length, &mTrtPluginFactory);
assert(mTrtEngine != nullptr);
InitEngine();
}
void trtNet::InitEngine()
{
mTrtBatchSize = mTrtEngine->getMaxBatchSize();
mTrtContext = mTrtEngine->createExecutionContext();
assert(mTrtContext != nullptr);
mTrtContext->setProfiler(&mTrtProfiler);
// Input and output buffer pointers that we pass to the engine - the engine requires exactly IEngine::getNbBindings()
int nbBindings = mTrtEngine->getNbBindings();
mTrtCudaBuffer.resize(nbBindings);
mTrtBindBufferSize.resize(nbBindings);
for (int i = 0; i < nbBindings; ++i)
{
Dims dims = mTrtEngine->getBindingDimensions(i);
DataType dtype = mTrtEngine->getBindingDataType(i);
int64_t totalSize = volume(dims) * mTrtBatchSize * getElementSize(dtype);
mTrtBindBufferSize[i] = totalSize;
mTrtCudaBuffer[i] = safeCudaMalloc(totalSize);
if(mTrtEngine->bindingIsInput(i))
mTrtInputCount++;
}
CUDA_CHECK(cudaStreamCreate(&mTrtCudaStream));
}
nvinfer1::ICudaEngine* trtNet::loadModelAndCreateEngine(const char* deployFile, const char* modelFile,int maxBatchSize,
ICaffeParser* parser, nvcaffeparser1::IPluginFactory* pluginFactory,
IInt8Calibrator* calibrator, IHostMemory*& trtModelStream,const std::vector<std::string>& outputNodesName)
{
// Create the builder
IBuilder* builder = createInferBuilder(gLogger);
// Parse the model to populate the network, then set the outputs.
INetworkDefinition* network = builder->createNetwork();
parser->setPluginFactory(pluginFactory);
std::cout << "Begin parsing model..." << std::endl;
const IBlobNameToTensor* blobNameToTensor = parser->parse(deployFile,modelFile, *network, nvinfer1::DataType::kFLOAT);
if (!blobNameToTensor)
RETURN_AND_LOG(nullptr, ERROR, "Fail to parse");
std::cout << "End parsing model..." << std::endl;
// specify which tensors are outputs
for (auto& name : outputNodesName)
{
auto output = blobNameToTensor->find(name.c_str());
assert(output!=nullptr);
if (output == nullptr)
std::cout << "can not find output named " << name << std::endl;
network->markOutput(*output);
}
// Build the engine.
builder->setMaxBatchSize(maxBatchSize);
builder->setMaxWorkspaceSize(1 << 30);// 1G
if (mTrtRunMode == RUN_MODE::INT8)
{
std::cout <<"setInt8Mode"<<std::endl;
if (!builder->platformHasFastInt8())
std::cout << "Notice: the platform do not has fast for int8" << std::endl;
builder->setInt8Mode(true);
builder->setInt8Calibrator(calibrator);
}
else if (mTrtRunMode == RUN_MODE::FLOAT16)
{
std::cout <<"setFp16Mode"<<std::endl;
if (!builder->platformHasFastFp16())
std::cout << "Notice: the platform do not has fast for fp16" << std::endl;
builder->setFp16Mode(true);
}
std::cout << "Begin building engine..." << std::endl;
ICudaEngine* engine = builder->buildCudaEngine(*network);
if (!engine)
RETURN_AND_LOG(nullptr, ERROR, "Unable to create engine");
std::cout << "End building engine..." << std::endl;
// We don't need the network any more, and we can destroy the parser.
network->destroy();
parser->destroy();
// Serialize the engine, then close everything down.
trtModelStream = engine->serialize();
builder->destroy();
shutdownProtobufLibrary();
return engine;
}
void trtNet::doInference(const void* inputData, void* outputData ,int batchSize /*= 1*/)
{
//static const int batchSize = 1;
assert(mTrtInputCount == 1);
assert(batchSize <= mTrtBatchSize);
// DMA the input to the GPU, execute the batch asynchronously, and DMA it back:
int inputIndex = 0;
CUDA_CHECK(cudaMemcpyAsync(mTrtCudaBuffer[inputIndex], inputData, mTrtBindBufferSize[inputIndex], cudaMemcpyHostToDevice, mTrtCudaStream));
mTrtContext->execute(batchSize, &mTrtCudaBuffer[inputIndex]);
for (size_t bindingIdx = mTrtInputCount; bindingIdx < mTrtBindBufferSize.size(); ++bindingIdx)
{
auto size = mTrtBindBufferSize[bindingIdx];
CUDA_CHECK(cudaMemcpyAsync(outputData, mTrtCudaBuffer[bindingIdx], size, cudaMemcpyDeviceToHost, mTrtCudaStream));
outputData = (char *)outputData + size;
}
//cudaStreamSynchronize(mTrtCudaStream);
mTrtIterationTime ++ ;
}
}
|
// MIT License
// Copyright (C) August 2016 Hotride
#include <cstdlib>
#include "WalkData.h"
void CWalkData::GetOffset(float &x, float &y, float &steps)
{
float step_NESW_D = 44.0f / steps; //NW NE SW SE
float step_NESW = 22.0f / steps; //N E S W
int checkX = 22;
int checkY = 22;
switch (Direction & 7)
{
case 0: //W
{
x *= step_NESW;
y *= -step_NESW;
break;
}
case 1: //NW
{
x *= step_NESW_D;
checkX = 44;
y = 0.0f;
break;
}
case 2: //N
{
x *= step_NESW;
y *= step_NESW;
break;
}
case 3: //NE
{
x = 0.0f;
y *= step_NESW_D;
checkY = 44;
break;
}
case 4: //E
{
x *= -step_NESW;
y *= step_NESW;
break;
}
case 5: //SE
{
x *= -step_NESW_D;
checkX = 44;
y = 0.0f;
break;
}
case 6: //S
{
x *= -step_NESW;
y *= -step_NESW;
break;
}
case 7: //SW
{
x = 0.0f;
y *= -step_NESW_D;
checkY = 44;
break;
}
default:
break;
}
int valueX = (int)x;
if (abs(valueX) > checkX)
{
if (valueX < 0)
{
x = -(float)checkX;
}
else
{
x = (float)checkX;
}
}
int valueY = (int)y;
if (abs(valueY) > checkY)
{
if (valueY < 0)
{
y = -(float)checkY;
}
else
{
y = (float)checkY;
}
}
}
|
#include "Timestep.h"
|
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
const double EPS = 1e-9;
const int INF = 0x7f7f7f7f;
const double PI=acos(-1.0);
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)
#define MP(x, y) make_pair(x, y)
#define SZ(c) (int)c.size()
#define PB(x) push_back(x)
#define F(i,L,R) for (int i = L; i < R; i++)
#define FF(i,L,R) for (int i = L; i <= R; i++)
#define FR(i,L,R) for (int i = L; i > R; i--)
#define FRF(i,L,R) for (int i = L; i >= R; i--)
#define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define ALL(p) p.begin(),p.end()
#define ALLR(p) p.rbegin(),p.rend()
#define SET(p) memset(p, -1, sizeof(p))
#define CLR(p) memset(p, 0, sizeof(p))
#define MEM(p, v) memset(p, v, sizeof(p))
#define CPY(d, s) memcpy(d, s, sizeof(s))
#define getI(a) scanf("%d", &a)
#define getII(a,b) scanf("%d%d", &a, &b)
#define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c)
#define getC(n) scanf("%c",&n)
#define getL(n) scanf("%lld",&n)
#define getF(n) scanf("%lf",&n)
#define getS(n) scanf("%s",n)
#define vi vector < int >
#define vii vector < vector < int > >
#define pii pair< int, int >
#define psi pair< string, int >
#define ff first
#define ss second
#define ll long long
#define ull unsigned long long
#define ui unsigned int
#define us unsigned short
#define ld long double
#define debug(a) { cout << a <<endl; }
#define debugI() { cout << "*" <<endl; }
#define debugII() { cout << "**" <<endl; }
#define debugIII() { cout << "***" <<endl; }
template< class T > inline T _abs(T n) { return ((n) < 0 ? -(n) : (n)); }
template< class T > inline T _max(T a, T b) { return (!((a)<(b))?(a):(b)); }
template< class T > inline T _min(T a, T b) { return (((a)<(b))?(a):(b)); }
template< class T > inline T _swap(T &a, T &b) { a=a^b;b=a^b;a=a^b;}
template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); }
template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); }
bool check(string st)
{
int len=st.size();
for(int i=0,j=len-1;i<len/2;i++,j--)
{
if(st[i]!=st[j])
return 0;
}
return 1;
}
int main() {
//READ("in.txt");
//WRITE("out.txt");
int t;
getI(t);
getchar();
for(int ci=1;ci<=t;ci++)
{
string st,st1="",st2="";
getline(cin,st);
int len=st.size();
for(int i=0;i<len;i++)
{
if(st[i]>='a' && st[i]<='z')
st1+=st[i];
}
if(!check(st1))
{
//debugI();
printf("Case #%d:\nNo magic :(\n",ci);
continue;
}
len=st1.size();
int fg=sqrt(len);
if(fg*fg!=len)
{
//debugIII();
printf("Case #%d:\nNo magic :(\n",ci);
continue;
}
for(int i=0;i<fg;i++)
{
for(int j=i;j<len;j+=fg)
{
st2+=st1[j];
}
}
//debug(st2);
if(check(st2))
printf("Case #%d:\n%d\n",ci,fg);
else
printf("Case #%d:\nNo magic :(\n",ci);
}
return 0;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageResliceMapper.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the side copyright notice for more information.
=========================================================================*/
#include "vtkImageResliceMapper.h"
#include "vtkAbstractImageInterpolator.h"
#include "vtkCamera.h"
#include "vtkGarbageCollector.h"
#include "vtkImageData.h"
#include "vtkImageProperty.h"
#include "vtkImageResliceToColors.h"
#include "vtkImageSlice.h"
#include "vtkImageSliceMapper.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkLinearTransform.h"
#include "vtkLookupTable.h"
#include "vtkMath.h"
#include "vtkMatrix4x4.h"
#include "vtkObjectFactory.h"
#include "vtkPlane.h"
#include "vtkPoints.h"
#include "vtkRenderer.h"
#include "vtkStreamingDemandDrivenPipeline.h"
// A tolerance to compensate for roundoff errors
#define VTK_RESLICE_MAPPER_VOXEL_TOL 7.62939453125e-06
vtkStandardNewMacro(vtkImageResliceMapper);
//----------------------------------------------------------------------------
vtkImageResliceMapper::vtkImageResliceMapper()
{
this->SliceMapper = vtkImageSliceMapper::New();
this->ImageReslice = vtkImageResliceToColors::New();
this->ResliceMatrix = vtkMatrix4x4::New();
this->WorldToDataMatrix = vtkMatrix4x4::New();
this->SliceToWorldMatrix = vtkMatrix4x4::New();
this->JumpToNearestSlice = 0;
this->AutoAdjustImageQuality = 1;
this->SeparateWindowLevelOperation = 1;
this->SlabType = VTK_IMAGE_SLAB_MEAN;
this->SlabThickness = 0.0;
this->SlabSampleFactor = 2;
this->ImageSampleFactor = 1;
this->ResampleToScreenPixels = 1;
this->InternalResampleToScreenPixels = 0;
this->ResliceNeedUpdate = 0;
// streaming requires an output port
this->SetNumberOfOutputPorts(1);
}
//----------------------------------------------------------------------------
vtkImageResliceMapper::~vtkImageResliceMapper()
{
if (this->SliceMapper)
{
this->SliceMapper->Delete();
}
if (this->ImageReslice)
{
this->ImageReslice->Delete();
}
if (this->ResliceMatrix)
{
this->ResliceMatrix->Delete();
}
if (this->WorldToDataMatrix)
{
this->WorldToDataMatrix->Delete();
}
if (this->SliceToWorldMatrix)
{
this->SliceToWorldMatrix->Delete();
}
}
//----------------------------------------------------------------------------
void vtkImageResliceMapper::SetSlicePlane(vtkPlane* plane)
{
if (this->SlicePlane == plane)
{
return;
}
if (this->SlicePlane)
{
this->SlicePlane->Delete();
}
if (!plane)
{
this->SlicePlane = vtkPlane::New();
}
else
{
this->SlicePlane = plane;
plane->Register(this);
}
this->Modified();
}
//----------------------------------------------------------------------------
void vtkImageResliceMapper::SetInterpolator(vtkAbstractImageInterpolator* interpolator)
{
vtkMTimeType mtime = this->ImageReslice->GetMTime();
this->ImageReslice->SetInterpolator(interpolator);
if (this->ImageReslice->GetMTime() > mtime)
{
this->Modified();
}
}
//----------------------------------------------------------------------------
vtkAbstractImageInterpolator* vtkImageResliceMapper::GetInterpolator()
{
return this->ImageReslice->GetInterpolator();
}
//----------------------------------------------------------------------------
void vtkImageResliceMapper::ReleaseGraphicsResources(vtkWindow* win)
{
this->SliceMapper->ReleaseGraphicsResources(win);
}
//----------------------------------------------------------------------------
void vtkImageResliceMapper::Render(vtkRenderer* ren, vtkImageSlice* prop)
{
if (this->ResliceNeedUpdate)
{
this->ImageReslice->SetInputConnection(this->GetInputConnection(0, 0));
this->ImageReslice->UpdateWholeExtent();
this->ResliceNeedUpdate = 0;
}
// apply checkerboard pattern (should have timestamps)
vtkImageProperty* property = prop->GetProperty();
if (property && property->GetCheckerboard() && this->InternalResampleToScreenPixels &&
!this->SeparateWindowLevelOperation && this->SliceFacesCamera)
{
this->CheckerboardImage(this->ImageReslice->GetOutput(), ren->GetActiveCamera(), property);
}
// delegate to vtkImageSliceMapper
this->SliceMapper->SetInputConnection(this->ImageReslice->GetOutputPort());
this->SliceMapper->GetDataToWorldMatrix()->DeepCopy(this->SliceToWorldMatrix);
// the mapper uses SliceFacesCamera to decide whether to use a polygon
// for the texture versus using a quad the size of the window
this->SliceMapper->SetSliceFacesCamera(
(this->SliceFacesCamera && !this->SeparateWindowLevelOperation));
this->SliceMapper->SetExactPixelMatch(this->InternalResampleToScreenPixels);
this->SliceMapper->SetBorder((this->Border || this->InternalResampleToScreenPixels));
this->SliceMapper->SetBackground((this->Background &&
!(this->SliceFacesCamera && this->InternalResampleToScreenPixels &&
!this->SeparateWindowLevelOperation)));
this->SliceMapper->SetPassColorData(!this->SeparateWindowLevelOperation);
this->SliceMapper->SetDisplayExtent(this->ImageReslice->GetOutputExtent());
// render pass info for members of vtkImageStack
this->SliceMapper->MatteEnable = this->MatteEnable;
this->SliceMapper->ColorEnable = this->ColorEnable;
this->SliceMapper->DepthEnable = this->DepthEnable;
// let vtkImageSliceMapper do the rest of the work
this->SliceMapper->SetNumberOfThreads(this->NumberOfThreads);
this->SliceMapper->SetClippingPlanes(this->ClippingPlanes);
this->SliceMapper->Render(ren, prop);
}
//----------------------------------------------------------------------------
void vtkImageResliceMapper::Update(int port)
{
// I don't like to override Update, or call Modified() in Update,
// but this allows updates to be forced where MTimes can't be used
bool resampleToScreenPixels = (this->ResampleToScreenPixels != 0);
vtkRenderer* ren = nullptr;
if (this->AutoAdjustImageQuality && resampleToScreenPixels)
{
// only use image-size texture if image is smaller than render window,
// since otherwise there is far less advantage in doing so
vtkImageSlice* prop = this->GetCurrentProp();
ren = this->GetCurrentRenderer();
if (ren && prop)
{
const int* rsize = ren->GetSize();
int maxrsize = (rsize[0] > rsize[1] ? rsize[0] : rsize[1]);
int* isize = this->GetInput()->GetDimensions();
int maxisize = (isize[0] > isize[1] ? isize[0] : isize[1]);
maxisize = (isize[2] > maxisize ? isize[2] : maxisize);
if (maxisize <= maxrsize && maxisize <= 1024)
{
resampleToScreenPixels = (prop->GetAllocatedRenderTime() >= 1.0);
}
}
}
if (resampleToScreenPixels)
{
// force update if quality has increased to "ResampleToScreenPixels"
if (!this->InternalResampleToScreenPixels)
{
this->Modified();
}
else
{
// force update if renderer size has changes, since the texture
// size is equal to the renderer size for "ResampleToScreenPixels"
if (!ren)
{
ren = this->GetCurrentRenderer();
}
if (ren)
{
int* extent = this->ImageReslice->GetOutputExtent();
const int* size = ren->GetSize();
if (size[0] != (extent[1] - extent[0] + 1) || size[1] != (extent[3] - extent[2] + 1))
{
this->Modified();
}
}
}
}
else if (this->InternalResampleToScreenPixels)
{
// if execution reaches this point in the code, then the
// rendering has just switched to interactive quality, and it is
// necessary to force update if modified since the last update
if (this->GetMTime() > this->UpdateTime.GetMTime())
{
this->Modified();
}
else
{
// don't switch yet: wait until the camera changes position,
// which will cause the MTime to change
resampleToScreenPixels = true;
}
}
this->InternalResampleToScreenPixels = resampleToScreenPixels;
// Always update if something else caused the input to update
vtkImageData* input = this->GetInput();
if (input && input->GetUpdateTime() > this->UpdateTime.GetMTime())
{
this->Modified();
}
this->Superclass::Update(port);
this->UpdateTime.Modified();
}
//----------------------------------------------------------------------------
void vtkImageResliceMapper::Update()
{
this->Superclass::Update();
}
//----------------------------------------------------------------------------
vtkTypeBool vtkImageResliceMapper::Update(int port, vtkInformationVector*)
{
// One can't really make requests of a mapper so default to regular
// update.
this->Update(port);
return 1;
}
//----------------------------------------------------------------------------
vtkTypeBool vtkImageResliceMapper::Update(vtkInformation*)
{
// One can't really make requests of a mapper so default to regular
// update.
this->Update();
return 1;
}
//----------------------------------------------------------------------------
vtkTypeBool vtkImageResliceMapper::ProcessRequest(
vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
if (request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_INFORMATION()))
{
// use superclass method to update some info
this->Superclass::ProcessRequest(request, inputVector, outputVector);
// need the prop and renderer
vtkImageSlice* prop = this->GetCurrentProp();
vtkRenderer* ren = this->GetCurrentRenderer();
if (ren && prop)
{
vtkImageProperty* property = prop->GetProperty();
// Get point/normal from camera
if (this->SliceFacesCamera || this->SliceAtFocalPoint)
{
vtkCamera* camera = ren->GetActiveCamera();
if (this->SliceFacesCamera)
{
double normal[3];
camera->GetDirectionOfProjection(normal);
normal[0] = -normal[0];
normal[1] = -normal[1];
normal[2] = -normal[2];
this->SlicePlane->SetNormal(normal);
}
if (this->SliceAtFocalPoint)
{
double point[4];
camera->GetFocalPoint(point);
if (this->JumpToNearestSlice)
{
double normal[4];
this->SlicePlane->GetNormal(normal);
normal[3] = -vtkMath::Dot(point, normal);
point[3] = 1.0;
// convert normal to data coordinates
double worldToData[16];
vtkMatrix4x4* dataToWorld = this->GetDataToWorldMatrix();
vtkMatrix4x4::Transpose(*dataToWorld->Element, worldToData);
vtkMatrix4x4::MultiplyPoint(worldToData, normal, normal);
// find the slice orientation from the normal
int k = 0;
double maxsq = 0;
double sumsq = 0;
for (int i = 0; i < 3; i++)
{
double tmpsq = normal[i] * normal[i];
sumsq += tmpsq;
if (tmpsq > maxsq)
{
maxsq = tmpsq;
k = i;
}
}
// if the slice is not oblique
if ((1.0 - maxsq / sumsq) < 1e-12)
{
// get the point in data coordinates
vtkMatrix4x4::Invert(*dataToWorld->Element, worldToData);
vtkMatrix4x4::MultiplyPoint(worldToData, point, point);
// set the point to lie exactly on a slice
double z = (point[k] - this->DataOrigin[k]) / this->DataSpacing[k];
if (z > VTK_INT_MIN && z < VTK_INT_MAX)
{
int j = vtkMath::Floor(z + 0.5);
point[k] = j * this->DataSpacing[k] + this->DataOrigin[k];
}
// convert back to world coordinates
dataToWorld->MultiplyPoint(point, point);
}
}
this->SlicePlane->SetOrigin(point);
}
} // end of "Get point/normal from camera"
// set the matrices
this->UpdateResliceMatrix(ren, prop);
// update the coords for the polygon to be textured
this->UpdatePolygonCoords(ren);
// set the reslice spacing/origin/extent/axes
this->UpdateResliceInformation(ren);
// set the reslice bits related to the property
this->UpdateResliceInterpolation(property);
// update anything related to the image coloring
this->UpdateColorInformation(property);
}
// set the number of threads to use when executing
this->ImageReslice->SetNumberOfThreads(this->NumberOfThreads);
// delegate request to vtkImageReslice (generally not a good thing to
// do, but I'm familiar with the vtkImageReslice code that gets called).
return this->ImageReslice->ProcessRequest(request, inputVector, outputVector);
}
if (request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT()))
{
if (this->Streaming)
{
// delegate request to vtkImageReslice (generally not a good thing to
// do, but I'm familiar with the vtkImageReslice code that gets called).
return this->ImageReslice->ProcessRequest(request, inputVector, outputVector);
}
else
{
vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
int ext[6];
inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), ext);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), ext, 6);
}
return 1;
}
if (request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_DATA()))
{
vtkInformation* outInfo = outputVector->GetInformationObject(0);
vtkImageData* output = vtkImageData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
// set output extent to avoid re-execution
output->GetInformation()->Set(vtkDataObject::DATA_EXTENT(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()), 6);
// do an update of Reslice on the next render
this->ResliceNeedUpdate = 1;
return 1;
}
return this->Superclass::ProcessRequest(request, inputVector, outputVector);
}
//----------------------------------------------------------------------------
// Update the WorldToData transformation matrix, which is just the
// inverse of the vtkProp3D matrix.
void vtkImageResliceMapper::UpdateWorldToDataMatrix(vtkImageSlice* prop)
{
// copy the matrix, but only if it has changed (we do this to
// preserve the modified time of the matrix)
double tmpmat[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
if (!prop->GetIsIdentity())
{
vtkMatrix4x4::Invert(*prop->GetMatrix()->Element, tmpmat);
}
double* mat = *this->WorldToDataMatrix->Element;
for (int i = 0; i < 16; i++)
{
if (mat[i] != tmpmat[i])
{
this->WorldToDataMatrix->DeepCopy(tmpmat);
break;
}
}
}
//----------------------------------------------------------------------------
// Update the SliceToWorld transformation matrix
void vtkImageResliceMapper::UpdateSliceToWorldMatrix(vtkCamera* camera)
{
// Get slice plane in world coords by passing null as the prop matrix
double plane[4];
this->GetSlicePlaneInDataCoords(nullptr, plane);
// Make sure normal is facing towards camera
vtkMatrix4x4* viewMatrix = camera->GetViewTransformMatrix();
double* ndop = viewMatrix->Element[2];
if (vtkMath::Dot(ndop, plane) < 0)
{
plane[0] = -plane[0];
plane[1] = -plane[1];
plane[2] = -plane[2];
plane[3] = -plane[3];
}
// The normal is the first three elements
double* normal = plane;
// The last element is -dot(normal, origin)
double dp = -plane[3];
// Compute rotation angle between camera axis and slice normal
double vec[3];
vtkMath::Cross(ndop, normal, vec);
double costheta = vtkMath::Dot(ndop, normal);
double sintheta = vtkMath::Norm(vec);
double theta = atan2(sintheta, costheta);
if (sintheta != 0)
{
vec[0] /= sintheta;
vec[1] /= sintheta;
vec[2] /= sintheta;
}
// convert to quaternion
costheta = cos(0.5 * theta);
sintheta = sin(0.5 * theta);
double quat[4];
quat[0] = costheta;
quat[1] = vec[0] * sintheta;
quat[2] = vec[1] * sintheta;
quat[3] = vec[2] * sintheta;
// convert to matrix
double mat[3][3];
vtkMath::QuaternionToMatrix3x3(quat, mat);
// Create a slice-to-world transform matrix
// The columns are v1, v2, normal
vtkMatrix4x4* sliceToWorld = this->SliceToWorldMatrix;
double v1[3], v2[3];
vtkMath::Multiply3x3(mat, viewMatrix->Element[0], v1);
vtkMath::Multiply3x3(mat, viewMatrix->Element[1], v2);
sliceToWorld->Element[0][0] = v1[0];
sliceToWorld->Element[1][0] = v1[1];
sliceToWorld->Element[2][0] = v1[2];
sliceToWorld->Element[3][0] = 0.0;
sliceToWorld->Element[0][1] = v2[0];
sliceToWorld->Element[1][1] = v2[1];
sliceToWorld->Element[2][1] = v2[2];
sliceToWorld->Element[3][1] = 0.0;
sliceToWorld->Element[0][2] = normal[0];
sliceToWorld->Element[1][2] = normal[1];
sliceToWorld->Element[2][2] = normal[2];
sliceToWorld->Element[3][2] = 0.0;
sliceToWorld->Element[0][3] = -dp * normal[0];
sliceToWorld->Element[1][3] = -dp * normal[1];
sliceToWorld->Element[2][3] = dp - dp * normal[2];
sliceToWorld->Element[3][3] = 1.0;
}
//----------------------------------------------------------------------------
// Update the reslice matrix, which is the slice-to-data matrix.
void vtkImageResliceMapper::UpdateResliceMatrix(vtkRenderer* ren, vtkImageSlice* prop)
{
// Save the old matrix
double* matrixElements = *this->ResliceMatrix->Element;
double oldMatrixElements[16];
vtkMatrix4x4::DeepCopy(oldMatrixElements, matrixElements);
// Get world-to-data matrix from the prop matrix
this->UpdateWorldToDataMatrix(prop);
// Check if prop matrix is orthonormal
bool propMatrixIsOrthonormal = false;
vtkMatrix4x4* propMatrix = nullptr;
if (!this->InternalResampleToScreenPixels)
{
static double tol = 1e-12;
propMatrix = prop->GetMatrix();
double* row0 = propMatrix->Element[0];
double* row1 = propMatrix->Element[1];
double* row2 = propMatrix->Element[2];
propMatrixIsOrthonormal =
(fabs(vtkMath::Dot(row0, row0) - 1.0) < tol && fabs(vtkMath::Dot(row1, row1) - 1.0) < tol &&
fabs(vtkMath::Dot(row2, row2) - 1.0) < tol && fabs(vtkMath::Dot(row0, row1)) < tol &&
fabs(vtkMath::Dot(row0, row2)) < tol && fabs(vtkMath::Dot(row1, row2)) < tol);
}
// Compute SliceToWorld matrix from camera if prop matrix is not
// orthonormal or if InternalResampleToScreenPixels is set
if (this->InternalResampleToScreenPixels || !propMatrixIsOrthonormal)
{
this->UpdateSliceToWorldMatrix(ren->GetActiveCamera());
vtkMatrix4x4::Multiply4x4(
this->WorldToDataMatrix, this->SliceToWorldMatrix, this->ResliceMatrix);
}
else
{
// Get the matrices used to compute the reslice matrix
vtkMatrix4x4* resliceMatrix = this->ResliceMatrix;
vtkMatrix4x4* viewMatrix = ren->GetActiveCamera()->GetViewTransformMatrix();
// Get slice plane in world coords by passing null as the matrix
double wplane[4];
this->GetSlicePlaneInDataCoords(nullptr, wplane);
// Check whether normal is facing towards camera, the "ndop" is
// the negative of the direction of projection for the camera
double* ndop = viewMatrix->Element[2];
double dotprod = vtkMath::Dot(ndop, wplane);
// Get slice plane in data coords by passing the prop matrix, flip
// normal to face the camera
double plane[4];
this->GetSlicePlaneInDataCoords(propMatrix, plane);
if (dotprod < 0)
{
plane[0] = -plane[0];
plane[1] = -plane[1];
plane[2] = -plane[2];
plane[3] = -plane[3];
wplane[0] = -wplane[0];
wplane[1] = -wplane[1];
wplane[2] = -wplane[2];
wplane[3] = -wplane[3];
}
// Find the largest component of the normal
int maxi = 0;
double maxv = 0.0;
for (int i = 0; i < 3; i++)
{
double tmp = plane[i] * plane[i];
if (tmp > maxv)
{
maxi = i;
maxv = tmp;
}
}
// Create the corresponding axis
double axis[3];
axis[0] = 0.0;
axis[1] = 0.0;
axis[2] = 0.0;
axis[maxi] = ((plane[maxi] < 0.0) ? -1.0 : 1.0);
// Create two orthogonal axes
double saxis[3], taxis[3];
taxis[0] = 0.0;
taxis[1] = 1.0;
taxis[2] = 0.0;
if (maxi == 1)
{
taxis[1] = 0.0;
taxis[2] = 1.0;
}
vtkMath::Cross(taxis, axis, saxis);
// The normal is the first three elements
double* normal = plane;
// The last element is -dot(normal, origin)
double dp = (-plane[3] + wplane[0] * propMatrix->Element[0][3] +
wplane[1] * propMatrix->Element[1][3] + wplane[2] * propMatrix->Element[2][3]);
// Compute the rotation angle between the axis and the normal
double vec[3];
vtkMath::Cross(axis, normal, vec);
double costheta = vtkMath::Dot(axis, normal);
double sintheta = vtkMath::Norm(vec);
double theta = atan2(sintheta, costheta);
if (sintheta != 0)
{
vec[0] /= sintheta;
vec[1] /= sintheta;
vec[2] /= sintheta;
}
// convert to quaternion
costheta = cos(0.5 * theta);
sintheta = sin(0.5 * theta);
double quat[4];
quat[0] = costheta;
quat[1] = vec[0] * sintheta;
quat[2] = vec[1] * sintheta;
quat[3] = vec[2] * sintheta;
// convert to matrix
double mat[3][3];
vtkMath::QuaternionToMatrix3x3(quat, mat);
// Create a slice-to-data transform matrix
// The columns are v1, v2, normal
double v1[3], v2[3];
vtkMath::Multiply3x3(mat, saxis, v1);
vtkMath::Multiply3x3(mat, taxis, v2);
resliceMatrix->Element[0][0] = v1[0];
resliceMatrix->Element[1][0] = v1[1];
resliceMatrix->Element[2][0] = v1[2];
resliceMatrix->Element[3][0] = 0.0;
resliceMatrix->Element[0][1] = v2[0];
resliceMatrix->Element[1][1] = v2[1];
resliceMatrix->Element[2][1] = v2[2];
resliceMatrix->Element[3][1] = 0.0;
resliceMatrix->Element[0][2] = normal[0];
resliceMatrix->Element[1][2] = normal[1];
resliceMatrix->Element[2][2] = normal[2];
resliceMatrix->Element[3][2] = 0.0;
resliceMatrix->Element[0][3] = dp * (propMatrix->Element[2][0] - normal[0]) -
(propMatrix->Element[0][3] * propMatrix->Element[0][0] +
propMatrix->Element[1][3] * propMatrix->Element[1][0] +
propMatrix->Element[2][3] * propMatrix->Element[2][0]);
resliceMatrix->Element[1][3] = dp * (propMatrix->Element[2][1] - normal[1]) -
(propMatrix->Element[0][3] * propMatrix->Element[0][1] +
propMatrix->Element[1][3] * propMatrix->Element[1][1] +
propMatrix->Element[2][3] * propMatrix->Element[2][1]);
resliceMatrix->Element[2][3] = dp * (propMatrix->Element[2][2] - normal[2]) -
(propMatrix->Element[0][3] * propMatrix->Element[0][2] +
propMatrix->Element[1][3] * propMatrix->Element[1][2] +
propMatrix->Element[2][3] * propMatrix->Element[2][2]);
resliceMatrix->Element[3][3] = 1.0;
// Compute the SliceToWorldMatrix
vtkMatrix4x4::Multiply4x4(propMatrix, resliceMatrix, this->SliceToWorldMatrix);
}
// If matrix changed, mark as modified so that Reslice will update
int matrixChanged = 0;
for (int j = 0; j < 16; j++)
{
matrixChanged |= (matrixElements[j] != oldMatrixElements[j]);
}
if (matrixChanged)
{
this->ResliceMatrix->Modified();
}
}
//----------------------------------------------------------------------------
// Do all the fancy math to set up the reslicing
void vtkImageResliceMapper::UpdateResliceInformation(vtkRenderer* ren)
{
vtkMatrix4x4* resliceMatrix = this->ResliceMatrix;
vtkImageResliceToColors* reslice = this->ImageReslice;
int extent[6];
double spacing[3];
double origin[3];
// Get current spacing and origin
reslice->GetOutputSpacing(spacing);
reslice->GetOutputOrigin(origin);
reslice->GetOutputExtent(extent);
// Get the view matrix
vtkCamera* camera = ren->GetActiveCamera();
vtkMatrix4x4* viewMatrix = camera->GetViewTransformMatrix();
// Get slice plane in world coords by passing null as the matrix
double plane[4];
this->GetSlicePlaneInDataCoords(nullptr, plane);
// Check whether normal is facing towards camera, the "ndop" is
// the negative of the direction of projection for the camera
double* ndop = viewMatrix->Element[2];
if (vtkMath::Dot(ndop, plane) < 0)
{
plane[0] = -plane[0];
plane[1] = -plane[1];
plane[2] = -plane[2];
plane[3] = -plane[3];
}
// Get the z position of the slice in slice coords
// (requires plane to be normalized by GetSlicePlaneInDataCoords)
double z = (plane[2] - 2.0) * plane[3];
if (this->InternalResampleToScreenPixels)
{
// Get the projection matrix
double aspect = ren->GetTiledAspectRatio();
vtkMatrix4x4* projMatrix = camera->GetProjectionTransformMatrix(aspect, 0, 1);
// Compute other useful matrices
double worldToView[16];
double viewToWorld[16];
double planeWorldToView[16];
vtkMatrix4x4::Multiply4x4(*projMatrix->Element, *viewMatrix->Element, worldToView);
vtkMatrix4x4::Invert(worldToView, viewToWorld);
vtkMatrix4x4::Transpose(viewToWorld, planeWorldToView);
double worldToSlice[16];
double viewToSlice[16];
vtkMatrix4x4::Invert(*this->SliceToWorldMatrix->Element, worldToSlice);
vtkMatrix4x4::Multiply4x4(worldToSlice, viewToWorld, viewToSlice);
// Transform the plane into view coordinates, using the transpose
// of the inverse of the world-to-view matrix
vtkMatrix4x4::MultiplyPoint(planeWorldToView, plane, plane);
// Compute the bounds in slice coords
double xmin = VTK_DOUBLE_MAX;
double xmax = -VTK_DOUBLE_MAX;
double ymin = VTK_DOUBLE_MAX;
double ymax = -VTK_DOUBLE_MAX;
for (int i = 0; i < 4; i++)
{
// The four corners of the view
double x = (((i & 1) == 0) ? -1.0 : 1.0);
double y = (((i & 2) == 0) ? -1.0 : 1.0);
double hpoint[4];
hpoint[0] = x;
hpoint[1] = y;
hpoint[2] = 0.0;
hpoint[3] = 1.0;
if (fabs(plane[2]) < 1e-6)
{
// Looking at plane edge-on, just put some
// points at front clipping plane, others at back plane
hpoint[2] = (((i & 1) == 0) ? 0.0 : 1.0);
}
else
{
// Intersect with the slice plane
hpoint[2] = -(x * plane[0] + y * plane[1] + plane[3]) / plane[2];
// Clip to the front and back clipping planes
if (hpoint[2] < 0)
{
hpoint[2] = 0.0;
}
else if (hpoint[2] > 1)
{
hpoint[2] = 1.0;
}
}
// Transform into slice coords
vtkMatrix4x4::MultiplyPoint(viewToSlice, hpoint, hpoint);
x = hpoint[0] / hpoint[3];
y = hpoint[1] / hpoint[3];
// Find min/max in slice coords
if (x < xmin)
{
xmin = x;
}
if (x > xmax)
{
xmax = x;
}
if (y < ymin)
{
ymin = y;
}
if (y > ymax)
{
ymax = y;
}
}
// The ResliceExtent is always set to the renderer size,
// this is the maximum size ever required and sticking to
// this size avoids any memory reallocation on GPU or CPU
const int* size = ren->GetSize();
int xsize = ((size[0] <= 0) ? 1 : size[0]);
int ysize = ((size[1] <= 0) ? 1 : size[1]);
extent[0] = 0;
extent[1] = xsize - 1;
extent[2] = 0;
extent[3] = ysize - 1;
extent[4] = 0;
extent[5] = 0;
// Find the spacing
spacing[0] = (xmax - xmin) / xsize;
spacing[1] = (ymax - ymin) / ysize;
// Corner of resliced plane, including half-pixel offset to
// exactly match texels to pixels in the final rendering
origin[0] = xmin + 0.5 * spacing[0];
origin[1] = ymin + 0.5 * spacing[1];
origin[2] = z;
}
else
{
// Compute texel spacing from image spacing
double inputSpacing[3];
this->GetInput()->GetSpacing(inputSpacing);
inputSpacing[0] = fabs(inputSpacing[0]);
inputSpacing[1] = fabs(inputSpacing[1]);
inputSpacing[2] = fabs(inputSpacing[2]);
for (int j = 0; j < 2; j++)
{
double xc = this->ResliceMatrix->Element[j][0];
double yc = this->ResliceMatrix->Element[j][1];
double zc = this->ResliceMatrix->Element[j][2];
double s =
(xc * xc * inputSpacing[0] + yc * yc * inputSpacing[1] + zc * zc * inputSpacing[2]) /
sqrt(xc * xc + yc * yc + zc * zc);
s /= this->ImageSampleFactor;
// only modify if difference is greater than roundoff tolerance
if (fabs((s - spacing[j]) / s) > 1e-12)
{
spacing[j] = s;
}
}
// Find the bounds for the texture
double xmin = VTK_DOUBLE_MAX;
double xmax = -VTK_DOUBLE_MAX;
double ymin = VTK_DOUBLE_MAX;
double ymax = -VTK_DOUBLE_MAX;
vtkPoints* points = this->SliceMapper->GetPoints();
vtkIdType n = points->GetNumberOfPoints();
if (n == 0)
{
double inputOrigin[3];
this->GetInput()->GetOrigin(inputOrigin);
xmin = inputOrigin[0];
xmax = inputOrigin[0];
ymin = inputOrigin[1];
ymax = inputOrigin[1];
}
for (vtkIdType k = 0; k < n; k++)
{
double point[3];
points->GetPoint(k, point);
xmin = ((xmin < point[0]) ? xmin : point[0]);
xmax = ((xmax > point[0]) ? xmax : point[0]);
ymin = ((ymin < point[1]) ? ymin : point[1]);
ymax = ((ymax > point[1]) ? ymax : point[1]);
}
double tol = VTK_RESLICE_MAPPER_VOXEL_TOL;
int xsize = vtkMath::Floor((xmax - xmin) / spacing[0] + tol);
int ysize = vtkMath::Floor((ymax - ymin) / spacing[1] + tol);
if (this->Border == 0)
{
xsize += 1;
ysize += 1;
}
if (xsize < 1)
{
xsize = 1;
}
if (ysize < 1)
{
ysize = 1;
}
// Keep old size if possible, to avoid memory reallocation
if ((xsize - 1) > extent[1] || (ysize - 1) > extent[3] || (0.9 * extent[1] / xsize) > 1.0 ||
(0.9 * extent[3] / ysize) > 1.0)
{
extent[1] = xsize - 1;
extent[3] = ysize - 1;
}
extent[0] = 0;
extent[2] = 0;
extent[4] = 0;
extent[5] = 0;
double x0 = xmin + 0.5 * spacing[0] * (this->Border != 0);
double y0 = ymin + 0.5 * spacing[1] * (this->Border != 0);
double dx = x0 - origin[0];
double dy = y0 - origin[1];
double dz = z - origin[2];
// only modify origin if it has changed by tolerance
if (dx * dx + dy * dy + dz * dz > tol * tol * spacing[0] * spacing[1])
{
origin[0] = x0;
origin[1] = y0;
origin[2] = z;
}
}
// Prepare for reslicing
reslice->SetResliceAxes(resliceMatrix);
reslice->SetOutputExtent(extent);
reslice->SetOutputSpacing(spacing);
reslice->SetOutputOrigin(origin);
if ((this->SliceFacesCamera && this->InternalResampleToScreenPixels &&
!this->SeparateWindowLevelOperation) ||
this->SlabThickness > 0)
{
// if slice follows camera, use reslice to set the border
reslice->SetBorder(this->Border);
}
else
{
// tell reslice to use a double-thickness border,
// since the polygon geometry will dictate the actual size
reslice->SetBorder(true);
reslice->SetBorderThickness(1.0);
}
}
//----------------------------------------------------------------------------
// Do all the fancy math to set up the reslicing
void vtkImageResliceMapper::UpdateColorInformation(vtkImageProperty* property)
{
vtkScalarsToColors* lookupTable = this->DefaultLookupTable;
if (property)
{
double colorWindow = property->GetColorWindow();
double colorLevel = property->GetColorLevel();
if (property->GetLookupTable())
{
lookupTable = property->GetLookupTable();
if (!property->GetUseLookupTableScalarRange())
{
lookupTable->SetRange(colorLevel - 0.5 * colorWindow, colorLevel + 0.5 * colorWindow);
}
}
else
{
lookupTable->SetRange(colorLevel - 0.5 * colorWindow, colorLevel + 0.5 * colorWindow);
}
}
else
{
lookupTable->SetRange(0, 255);
}
this->ImageReslice->SetBypass(this->SeparateWindowLevelOperation != 0);
this->ImageReslice->SetLookupTable(lookupTable);
double backgroundColor[4] = { 0.0, 0.0, 0.0, 0.0 };
if (this->Background)
{
this->GetBackgroundColor(property, backgroundColor);
backgroundColor[0] *= 255;
backgroundColor[1] *= 255;
backgroundColor[2] *= 255;
backgroundColor[3] *= 255;
}
this->ImageReslice->SetBackgroundColor(backgroundColor);
}
//----------------------------------------------------------------------------
// Set the reslice interpolation and slab thickness
void vtkImageResliceMapper::UpdateResliceInterpolation(vtkImageProperty* property)
{
// set the interpolation mode and border
int interpMode = VTK_RESLICE_NEAREST;
int slabSlices = 1;
if (property)
{
switch (property->GetInterpolationType())
{
case VTK_NEAREST_INTERPOLATION:
interpMode = VTK_RESLICE_NEAREST;
break;
case VTK_LINEAR_INTERPOLATION:
interpMode = VTK_RESLICE_LINEAR;
break;
case VTK_CUBIC_INTERPOLATION:
interpMode = VTK_RESLICE_CUBIC;
break;
}
}
// set up the slice spacing for slab views
double spacing[3], inputSpacing[3];
this->ImageReslice->GetOutputSpacing(spacing);
this->GetInput()->GetSpacing(inputSpacing);
inputSpacing[0] = fabs(inputSpacing[0]);
inputSpacing[1] = fabs(inputSpacing[1]);
inputSpacing[2] = fabs(inputSpacing[2]);
double xc = this->ResliceMatrix->Element[2][0];
double yc = this->ResliceMatrix->Element[2][1];
double zc = this->ResliceMatrix->Element[2][2];
spacing[2] = (xc * xc * inputSpacing[0] + yc * yc * inputSpacing[1] + zc * zc * inputSpacing[2]) /
sqrt(xc * xc + yc * yc + zc * zc);
// slab slice spacing is half the input slice spacing
int n = vtkMath::Ceil(this->SlabThickness / spacing[2]);
slabSlices = 1 + this->SlabSampleFactor * n;
if (slabSlices > 1)
{
spacing[2] = this->SlabThickness / (slabSlices - 1);
}
this->ImageReslice->SetOutputSpacing(spacing);
int slabMode = this->SlabType;
double scalarScale = 1.0;
if (slabMode == VTK_IMAGE_SLAB_SUM)
{
// "sum" means integrating over the path length of each ray through
// the volume, so we need to include the sample spacing as a factor
scalarScale = spacing[2];
}
this->ImageReslice->SetInterpolationMode(interpMode);
this->ImageReslice->SetSlabMode(slabMode);
this->ImageReslice->SetSlabNumberOfSlices(slabSlices);
this->ImageReslice->SetScalarScale(scalarScale);
this->ImageReslice->SlabTrapezoidIntegrationOn();
}
//----------------------------------------------------------------------------
void vtkImageResliceMapper::CheckerboardImage(
vtkImageData* input, vtkCamera* camera, vtkImageProperty* property)
{
// Use focal point as center of checkerboard pattern. This guarantees
// exactly the same checkerboard for all images in the scene, which is
// useful when doing multiple overlays.
double focalPoint[4];
camera->GetFocalPoint(focalPoint);
focalPoint[3] = 1.0;
double worldToSlice[16];
vtkMatrix4x4::Invert(*this->SliceToWorldMatrix->Element, worldToSlice);
vtkMatrix4x4::MultiplyPoint(worldToSlice, focalPoint, focalPoint);
if (focalPoint[3] != 0.0)
{
focalPoint[0] /= focalPoint[3];
focalPoint[1] /= focalPoint[3];
focalPoint[2] /= focalPoint[3];
}
// Get the checkerboard spacing and apply the offset fraction
double checkSpacing[2], checkOffset[2];
property->GetCheckerboardSpacing(checkSpacing);
property->GetCheckerboardOffset(checkOffset);
checkOffset[0] = checkOffset[0] * checkSpacing[0] + focalPoint[0];
checkOffset[1] = checkOffset[1] * checkSpacing[1] + focalPoint[1];
// Adjust according to the origin and spacing of the slice data
double origin[3], spacing[3];
input->GetSpacing(spacing);
input->GetOrigin(origin);
checkOffset[0] = (checkOffset[0] - origin[0]) / spacing[0];
checkOffset[1] = (checkOffset[1] - origin[1]) / spacing[1];
checkSpacing[0] /= spacing[0];
checkSpacing[1] /= spacing[1];
// Apply the checkerboard to the data
int extent[6];
input->GetExtent(extent);
unsigned char* data = static_cast<unsigned char*>(input->GetScalarPointerForExtent(extent));
vtkImageMapper3D::CheckerboardRGBA(data, extent[1] - extent[0] + 1, extent[3] - extent[2] + 1,
checkOffset[0], checkOffset[1], checkSpacing[0], checkSpacing[1]);
}
//----------------------------------------------------------------------------
// Compute the vertices of the polygon in the slice coordinate system
#define VTK_IRM_MAX_VERTS 32
#define VTK_IRM_MAX_COORDS 96
void vtkImageResliceMapper::UpdatePolygonCoords(vtkRenderer* ren)
{
// Get the projection matrix
double aspect = ren->GetTiledAspectRatio();
vtkCamera* camera = ren->GetActiveCamera();
vtkMatrix4x4* viewMatrix = camera->GetViewTransformMatrix();
vtkMatrix4x4* projMatrix = camera->GetProjectionTransformMatrix(aspect, 0, 1);
// Compute other useful matrices
double worldToView[16];
double viewToWorld[16];
vtkMatrix4x4::Multiply4x4(*projMatrix->Element, *viewMatrix->Element, worldToView);
vtkMatrix4x4::Invert(worldToView, viewToWorld);
double worldToSlice[16];
double viewToSlice[16];
vtkMatrix4x4::Invert(*this->SliceToWorldMatrix->Element, worldToSlice);
vtkMatrix4x4::Multiply4x4(worldToSlice, viewToWorld, viewToSlice);
// Get slice plane in world coords by passing null as the matrix
double plane[4];
this->GetSlicePlaneInDataCoords(nullptr, plane);
// Check whether normal is facing towards camera, the "ndop" is
// the negative of the direction of projection for the camera
double* ndop = viewMatrix->Element[2];
if (vtkMath::Dot(ndop, plane) < 0)
{
plane[0] = -plane[0];
plane[1] = -plane[1];
plane[2] = -plane[2];
plane[3] = -plane[3];
}
// Get the z position of the slice in slice coords
// (requires plane to be normalized by GetSlicePlaneInDataCoords)
double z = (plane[2] - 2.0) * plane[3];
// Generate a tolerance based on the screen pixel size
double fpoint[4];
camera->GetFocalPoint(fpoint);
fpoint[3] = 1.0;
vtkMatrix4x4::MultiplyPoint(worldToView, fpoint, fpoint);
fpoint[0] /= fpoint[3];
fpoint[1] /= fpoint[3];
fpoint[2] /= fpoint[3];
fpoint[3] = 1.0;
double topOfScreen[4], botOfScreen[4];
fpoint[1] -= 1.0;
vtkMatrix4x4::MultiplyPoint(viewToWorld, fpoint, topOfScreen);
fpoint[1] += 2.0;
vtkMatrix4x4::MultiplyPoint(viewToWorld, fpoint, botOfScreen);
topOfScreen[0] /= topOfScreen[3];
topOfScreen[1] /= topOfScreen[3];
topOfScreen[2] /= topOfScreen[3];
topOfScreen[3] = 1.0;
botOfScreen[0] /= botOfScreen[3];
botOfScreen[1] /= botOfScreen[3];
botOfScreen[2] /= botOfScreen[3];
botOfScreen[3] = 1.0;
// height of view in world coords at focal point
double viewHeight = sqrt(vtkMath::Distance2BetweenPoints(topOfScreen, botOfScreen));
// height of view in pixels
int height = ren->GetSize()[1];
double tol = (height == 0 ? 0.5 : viewHeight * 0.5 / height);
// make the data bounding box (with or without border)
double b = (this->Border ? 0.5 : VTK_RESLICE_MAPPER_VOXEL_TOL);
double bounds[6];
for (int ii = 0; ii < 3; ii++)
{
double c = b * this->DataSpacing[ii];
int lo = this->DataWholeExtent[2 * ii];
int hi = this->DataWholeExtent[2 * ii + 1];
if (lo == hi && tol > c)
{ // apply tolerance to avoid degeneracy
c = tol;
}
bounds[2 * ii] = lo * this->DataSpacing[ii] + this->DataOrigin[ii] - c;
bounds[2 * ii + 1] = hi * this->DataSpacing[ii] + this->DataOrigin[ii] + c;
}
// transform the vertices to the slice coord system
double xpoints[8], ypoints[8];
double weights1[8], weights2[8];
bool above[8], below[8];
double mat[16];
vtkMatrix4x4::Multiply4x4(
*this->WorldToDataMatrix->Element, *this->SliceToWorldMatrix->Element, mat);
vtkMatrix4x4::Invert(mat, mat);
// arrays for the list of polygon points
int n = 0;
double newxpoints[VTK_IRM_MAX_VERTS];
double newypoints[VTK_IRM_MAX_VERTS];
double cx = 0.0;
double cy = 0.0;
for (int i = 0; i < 8; i++)
{
double point[4];
point[0] = bounds[0 + ((i >> 0) & 1)];
point[1] = bounds[2 + ((i >> 1) & 1)];
point[2] = bounds[4 + ((i >> 2) & 1)];
point[3] = 1.0;
vtkMatrix4x4::MultiplyPoint(mat, point, point);
xpoints[i] = point[0] / point[3];
ypoints[i] = point[1] / point[3];
weights1[i] = point[2] / point[3] - z - 0.5 * this->SlabThickness;
weights2[i] = weights1[i] + this->SlabThickness;
below[i] = (weights1[i] < 0);
above[i] = (weights2[i] >= 0);
if (this->SlabThickness > 0 && above[i] && below[i])
{
newxpoints[n] = xpoints[i];
newypoints[n] = ypoints[i];
cx += xpoints[i];
cy += ypoints[i];
n++;
}
}
// go through the edges and find the new points
for (int j = 0; j < 12; j++)
{
// verts from edges (sorry about this..)
int i1 = (j & 3) | (((j << 1) ^ (j << 2)) & 4);
int i2 = (i1 ^ (1 << (j >> 2)));
double* weights = weights2;
bool* side = above;
int m = 1 + (this->SlabThickness > 0);
for (int k = 0; k < m; k++)
{
if (side[i1] ^ side[i2])
{
double w1 = weights[i2];
double w2 = -weights[i1];
double x = (w1 * xpoints[i1] + w2 * xpoints[i2]) / (w1 + w2);
double y = (w1 * ypoints[i1] + w2 * ypoints[i2]) / (w1 + w2);
newxpoints[n] = x;
newypoints[n] = y;
cx += x;
cy += y;
n++;
}
weights = weights1;
side = below;
}
}
double coords[VTK_IRM_MAX_COORDS];
if (n > 0)
{
// centroid
cx /= n;
cy /= n;
// sort the points to make a convex polygon
double angles[VTK_IRM_MAX_VERTS];
for (int k = 0; k < n; k++)
{
double x = newxpoints[k];
double y = newypoints[k];
double t = atan2(y - cy, x - cx);
int kk;
for (kk = 0; kk < k; kk++)
{
if (t < angles[kk])
{
break;
}
}
for (int jj = k; jj > kk; --jj)
{
int jj3 = jj * 3;
angles[jj] = angles[jj - 1];
coords[jj3] = coords[jj3 - 3];
coords[jj3 + 1] = coords[jj3 - 2];
coords[jj3 + 2] = coords[jj3 - 1];
}
int kk3 = kk * 3;
angles[kk] = t;
coords[kk3] = x;
coords[kk3 + 1] = y;
coords[kk3 + 2] = z;
}
}
// remove degenerate points
if (n > 0)
{
bool found = true;
int m = 0;
do
{
m = 0;
double xl = coords[3 * (n - 1) + 0];
double yl = coords[3 * (n - 1) + 1];
for (int k = 0; k < n; k++)
{
double x = coords[3 * k + 0];
double y = coords[3 * k + 1];
if (((x - xl) * (x - xl) + (y - yl) * (y - yl)) > tol * tol)
{
coords[3 * m + 0] = x;
coords[3 * m + 1] = y;
xl = x;
yl = y;
m++;
}
}
found = (m < n);
n = m;
} while (found && n > 0);
}
// find convex hull
if (this->SlabThickness > 0 && n > 0)
{
bool found = true;
int m = 0;
do
{
m = 0;
double xl = coords[3 * (n - 1) + 0];
double yl = coords[3 * (n - 1) + 1];
for (int k = 0; k < n; k++)
{
double x = coords[3 * k + 0];
double y = coords[3 * k + 1];
int k1 = (k + 1) % n;
double xn = coords[3 * k1 + 0];
double yn = coords[3 * k1 + 1];
if ((xn - xl) * (y - yl) - (yn - yl) * (x - xl) < tol * tol)
{
coords[3 * m + 0] = x;
coords[3 * m + 1] = y;
xl = x;
yl = y;
m++;
}
}
found = (m < n);
n = m;
} while (found && n > 0);
}
vtkPoints* points = this->SliceMapper->GetPoints();
if (!points)
{
points = vtkPoints::New();
points->SetDataTypeToDouble();
this->SliceMapper->SetPoints(points);
points->Delete();
}
points->SetNumberOfPoints(n);
for (int k = 0; k < n; k++)
{
points->SetPoint(k, &coords[3 * k]);
}
points->Modified();
}
//----------------------------------------------------------------------------
void vtkImageResliceMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "JumpToNearestSlice: " << (this->JumpToNearestSlice ? "On\n" : "Off\n");
os << indent << "AutoAdjustImageQuality: " << (this->AutoAdjustImageQuality ? "On\n" : "Off\n");
os << indent
<< "SeparateWindowLevelOperation: " << (this->SeparateWindowLevelOperation ? "On\n" : "Off\n");
os << indent << "ResampleToScreenPixels: " << (this->ResampleToScreenPixels ? "On\n" : "Off\n");
os << indent << "SlabThickness: " << this->SlabThickness << "\n";
os << indent << "SlabType: " << this->GetSlabTypeAsString() << "\n";
os << indent << "SlabSampleFactor: " << this->SlabSampleFactor << "\n";
os << indent << "ImageSampleFactor: " << this->ImageSampleFactor << "\n";
os << indent << "Interpolator: " << this->GetInterpolator() << "\n";
}
//----------------------------------------------------------------------------
const char* vtkImageResliceMapper::GetSlabTypeAsString()
{
switch (this->SlabType)
{
case VTK_IMAGE_SLAB_MIN:
return "Min";
case VTK_IMAGE_SLAB_MAX:
return "Max";
case VTK_IMAGE_SLAB_MEAN:
return "Mean";
case VTK_IMAGE_SLAB_SUM:
return "Sum";
}
return "";
}
//----------------------------------------------------------------------------
vtkMTimeType vtkImageResliceMapper::GetMTime()
{
vtkMTimeType mTime = this->Superclass::GetMTime();
// Check whether interpolator has changed
vtkAbstractImageInterpolator* interpolator = this->ImageReslice->GetInterpolator();
if (interpolator)
{
vtkMTimeType mTime2 = interpolator->GetMTime();
if (mTime2 > mTime)
{
mTime = mTime2;
}
}
// Include camera in MTime so that REQUEST_INFORMATION
// will be called if the camera changes
if (this->SliceFacesCamera || this->SliceAtFocalPoint || this->InternalResampleToScreenPixels)
{
vtkRenderer* ren = this->GetCurrentRenderer();
if (ren)
{
vtkCamera* camera = ren->GetActiveCamera();
vtkMTimeType mTime2 = camera->GetMTime();
mTime = (mTime2 > mTime ? mTime2 : mTime);
}
}
if (!this->SliceFacesCamera || !this->SliceAtFocalPoint)
{
vtkMTimeType sTime = this->SlicePlane->GetMTime();
mTime = (sTime > mTime ? sTime : mTime);
}
vtkImageSlice* prop = this->GetCurrentProp();
if (prop != nullptr)
{
vtkMTimeType mTime2 = prop->GetUserTransformMatrixMTime();
mTime = (mTime2 > mTime ? mTime2 : mTime);
vtkImageProperty* property = prop->GetProperty();
if (property != nullptr)
{
bool useMTime = true;
if (this->SeparateWindowLevelOperation)
{
// only care about property if interpolation mode has changed,
// since interpolation is the only property-related operation
// done by vtkImageReslice if SeparateWindowLevelOperation is on
int imode = this->ImageReslice->GetInterpolationMode();
this->UpdateResliceInterpolation(property);
useMTime = (imode != this->ImageReslice->GetInterpolationMode());
}
if (useMTime)
{
mTime2 = property->GetMTime();
mTime = (mTime2 > mTime ? mTime2 : mTime);
vtkScalarsToColors* lookupTable = property->GetLookupTable();
if (lookupTable != nullptr)
{
// check the lookup table mtime
mTime2 = lookupTable->GetMTime();
mTime = (mTime2 > mTime ? mTime2 : mTime);
}
}
}
}
return mTime;
}
//----------------------------------------------------------------------------
void vtkImageResliceMapper::GetIndexBounds(double extent[6])
{
if (!this->GetInput())
{
return;
}
this->UpdateInformation();
extent[0] = this->DataWholeExtent[0];
extent[1] = this->DataWholeExtent[1];
extent[2] = this->DataWholeExtent[2];
extent[3] = this->DataWholeExtent[3];
extent[4] = this->DataWholeExtent[4];
extent[5] = this->DataWholeExtent[5];
// expand by half a pixel if border is on
double border = 0.5 * (this->Border != 0);
extent[0] -= border;
extent[1] += border;
extent[2] -= border;
extent[3] += border;
extent[4] -= border;
extent[5] += border;
}
//----------------------------------------------------------------------------
double* vtkImageResliceMapper::GetBounds()
{
if (!this->GetInput())
{
vtkMath::UninitializeBounds(this->Bounds);
return this->Bounds;
}
double extent[6];
this->GetIndexBounds(extent);
double* spacing = this->DataSpacing;
double* origin = this->DataOrigin;
double* direction = this->DataDirection;
// compute bounds
for (int k = 0; k < 2; ++k)
{
double kval = extent[k + 4];
for (int j = 0; j < 2; ++j)
{
double jval = extent[j + 2];
for (int i = 0; i < 2; ++i)
{
double ival = extent[i];
double point[3];
for (int c = 0; c < 3; ++c)
{
point[c] = ival * spacing[0] * direction[c * 3] +
jval * spacing[1] * direction[c * 3 + 1] + kval * spacing[2] * direction[c * 3 + 2] +
origin[c];
}
if (i + j + k == 0)
{
this->Bounds[0] = point[0];
this->Bounds[1] = point[0];
this->Bounds[2] = point[1];
this->Bounds[3] = point[1];
this->Bounds[4] = point[2];
this->Bounds[5] = point[2];
}
else
{
for (int c = 0; c < 3; ++c)
{
this->Bounds[c * 2] = point[c] < this->Bounds[c * 2] ? point[c] : this->Bounds[c * 2];
this->Bounds[c * 2 + 1] =
point[c] > this->Bounds[c * 2 + 1] ? point[c] : this->Bounds[c * 2 + 1];
}
}
}
}
}
return this->Bounds;
}
//----------------------------------------------------------------------------
void vtkImageResliceMapper::ReportReferences(vtkGarbageCollector* collector)
{
this->Superclass::ReportReferences(collector);
// These filters share our input and are therefore involved in a
// reference loop.
vtkGarbageCollectorReport(collector, this->ImageReslice, "ImageReslice");
vtkGarbageCollectorReport(collector, this->SliceMapper, "SliceMapper");
}
|
#include <cbag/layout/boundary.h>
namespace cbag {
namespace layout {
boundary::boundary(boundary_type type) noexcept : type(type) {}
boundary_type boundary::get_type() const noexcept { return type; }
bool boundary::operator==(const boundary &rhs) const noexcept {
return polygon::operator==(rhs) && type == rhs.type;
}
} // namespace layout
} // namespace cbag
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:47 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
// Including type: Zenject.GuiRenderableManager
#include "Zenject/GuiRenderableManager.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: IGuiRenderable
class IGuiRenderable;
}
// Forward declaring namespace: ModestTree::Util
namespace ModestTree::Util {
// Forward declaring type: ValuePair`2<T1, T2>
template<typename T1, typename T2>
class ValuePair_2;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.GuiRenderableManager/<>c__DisplayClass1_0
class GuiRenderableManager::$$c__DisplayClass1_0 : public ::Il2CppObject {
public:
// public Zenject.IGuiRenderable renderable
// Offset: 0x10
Zenject::IGuiRenderable* renderable;
// System.Boolean <.ctor>b__1(ModestTree.Util.ValuePair`2<System.Type,System.Int32> x)
// Offset: 0xF2466C
bool $_ctor$b__1(ModestTree::Util::ValuePair_2<System::Type*, int>* x);
// public System.Void .ctor()
// Offset: 0xF2428C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static GuiRenderableManager::$$c__DisplayClass1_0* New_ctor();
}; // Zenject.GuiRenderableManager/<>c__DisplayClass1_0
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::GuiRenderableManager::$$c__DisplayClass1_0*, "Zenject", "GuiRenderableManager/<>c__DisplayClass1_0");
#pragma pack(pop)
|
#include<iostream>
#include<string>
struct Vector3
{
float x, y, z;
};
/*class Entity
{
public:
int x;
public:
void Print() const { std::cout << "Hello!" << std::endl; }
};
class ScopedPtr
{
private:
Entity* m_Obj;
public:
ScopedPtr(Entity* entity)
: m_Obj(entity)
{
}
~ScopedPtr()
{
delete m_Obj;
}
Entity* operator->() // operator overloading
{
return m_Obj;
}
const Entity* operator->() const
{
return m_Obj;
}
};*/
int main() // entry point
{
int offset = (int)&((Vector3*)nullptr)->z;
std::cout << offset << std::endl;
//const ScopedPtr entity = new Entity();
//entity->Print();
/*Entity e;
e.Print();
Entity* ptr = &e;
ptr->Print();
ptr->x = 2;*/
std::cin.get();
}
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <memory>
#include <mutex>
#include <gtest/gtest.h>
#include "caffe2/core/blob.h"
#include "caffe2/core/blob_serialization.h"
#include "caffe2/core/common.h"
#include "caffe2/core/context.h"
#include "caffe2/core/db.h"
#include "caffe2/core/operator.h"
#include "caffe2/core/qtensor.h"
#include "caffe2/core/qtensor_serialization.h"
#include "caffe2/core/registry.h"
#include "caffe2/core/tensor.h"
#include "caffe2/core/types.h"
#include "caffe2/core/workspace.h"
#include "caffe2/proto/caffe2.pb.h"
#include "caffe2/utils/proto_utils.h"
CAFFE2_DEFINE_int64(caffe2_test_big_tensor_size, 100000000, "");
CAFFE2_DECLARE_int(caffe2_tensor_chunk_size);
CAFFE2_DECLARE_bool(caffe2_serialize_fp16_as_bytes);
namespace caffe2 {
using namespace ::caffe2::db;
namespace {
class BlobTestFoo {};
class BlobTestBar {};
}
CAFFE_KNOWN_TYPE(BlobTestFoo);
CAFFE_KNOWN_TYPE(BlobTestBar);
namespace {
TEST(BlobTest, Blob) {
Blob blob;
int* int_unused CAFFE2_UNUSED = blob.GetMutable<int>();
EXPECT_TRUE(blob.IsType<int>());
EXPECT_FALSE(blob.IsType<BlobTestFoo>());
BlobTestFoo* foo_unused CAFFE2_UNUSED = blob.GetMutable<BlobTestFoo>();
EXPECT_TRUE(blob.IsType<BlobTestFoo>());
EXPECT_FALSE(blob.IsType<int>());
}
TEST(BlobTest, BlobNewObjectFlag) {
Blob blob;
bool is_new_object = true;
blob.GetMutable<int>(&is_new_object);
EXPECT_TRUE(is_new_object);
blob.GetMutable<int>(&is_new_object);
EXPECT_FALSE(is_new_object);
blob.GetMutable<BlobTestFoo>(&is_new_object);
EXPECT_TRUE(is_new_object);
blob.GetMutable<BlobTestFoo>(&is_new_object);
EXPECT_FALSE(is_new_object);
}
TEST(BlobTest, BlobUninitialized) {
Blob blob;
ASSERT_THROW(blob.Get<int>(), EnforceNotMet);
}
TEST(BlobTest, BlobWrongType) {
Blob blob;
BlobTestFoo* foo_unused CAFFE2_UNUSED = blob.GetMutable<BlobTestFoo>();
EXPECT_TRUE(blob.IsType<BlobTestFoo>());
EXPECT_FALSE(blob.IsType<int>());
// When not null, we should only call with the right type.
EXPECT_NE(&blob.Get<BlobTestFoo>(), nullptr);
ASSERT_THROW(blob.Get<int>(), EnforceNotMet);
}
TEST(BlobTest, BlobReset) {
Blob blob;
std::unique_ptr<BlobTestFoo> foo(new BlobTestFoo());
EXPECT_TRUE(blob.Reset(foo.release()) != nullptr);
// Also test that Reset works.
blob.Reset();
}
TEST(BlobTest, BlobMove) {
Blob blob1;
std::unique_ptr<BlobTestFoo> foo(new BlobTestFoo());
auto* fooPtr = foo.get();
EXPECT_TRUE(blob1.Reset(foo.release()) != nullptr);
Blob blob2;
blob2 = std::move(blob1);
ASSERT_THROW(blob1.Get<BlobTestFoo>(), EnforceNotMet);
EXPECT_EQ(&blob2.Get<BlobTestFoo>(), fooPtr);
Blob blob3{std::move(blob2)};
EXPECT_EQ(&blob3.Get<BlobTestFoo>(), fooPtr);
}
TEST(BlobTest, BlobShareExternalPointer) {
Blob blob;
std::unique_ptr<BlobTestFoo> foo(new BlobTestFoo());
EXPECT_EQ(blob.ShareExternal<BlobTestFoo>(foo.get()), foo.get());
EXPECT_TRUE(blob.IsType<BlobTestFoo>());
// Also test that Reset works.
blob.Reset();
}
TEST(BlobTest, BlobShareExternalObject) {
Blob blob;
BlobTestFoo foo;
EXPECT_EQ(blob.ShareExternal<BlobTestFoo>(&foo), &foo);
EXPECT_TRUE(blob.IsType<BlobTestFoo>());
// Also test that Reset works.
blob.Reset();
}
TEST(BlobTest, StringSerialization) {
const std::string kTestString = "Hello world?";
Blob blob;
*blob.GetMutable<std::string>() = kTestString;
string serialized = blob.Serialize("test");
BlobProto proto;
CHECK(proto.ParseFromString(serialized));
EXPECT_EQ(proto.name(), "test");
EXPECT_EQ(proto.type(), "std::string");
EXPECT_FALSE(proto.has_tensor());
EXPECT_EQ(proto.content(), kTestString);
}
TEST(TensorNonTypedTest, TensorChangeType) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
TensorCPU tensor(dims);
auto* ptr = tensor.mutable_data<int>();
EXPECT_TRUE(ptr != nullptr);
EXPECT_TRUE(tensor.data<int>() != nullptr);
EXPECT_TRUE(tensor.meta().Match<int>());
// int and float are same size, so should retain the pointer
EXPECT_TRUE(tensor.mutable_data<float>() == (float*)ptr);
EXPECT_TRUE(tensor.data<float>() == (const float*)ptr);
EXPECT_TRUE(tensor.meta().Match<float>());
// float16 is smaller, so still should share buffer
EXPECT_TRUE(tensor.mutable_data<float16>() == (float16*)ptr);
EXPECT_TRUE(tensor.data<float16>() == (const float16*)ptr);
EXPECT_TRUE(tensor.meta().Match<float16>());
// share the data with other tensor so that the pointer won't be reused
// when we reallocate
TensorCPU other_tensor(dims);
other_tensor.ShareData(tensor);
// but double is bigger, so it should allocate a new one
auto* doubleptr = tensor.mutable_data<double>();
EXPECT_TRUE(doubleptr != (double*)ptr);
EXPECT_TRUE(doubleptr != nullptr);
EXPECT_TRUE(tensor.data<double>() != nullptr);
EXPECT_TRUE(tensor.meta().Match<double>());
}
template <typename T> class TensorCPUTest : public ::testing::Test {};
template <typename T> class TensorCPUDeathTest : public ::testing::Test {};
typedef ::testing::Types<char, int, float> TensorTypes;
TYPED_TEST_CASE(TensorCPUTest, TensorTypes);
TYPED_TEST_CASE(TensorCPUDeathTest, TensorTypes);
TYPED_TEST(TensorCPUTest, TensorInitializedEmpty) {
TensorCPU tensor;
EXPECT_EQ(tensor.ndim(), 0);
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
tensor.Resize(dims);
EXPECT_EQ(tensor.ndim(), 3);
EXPECT_EQ(tensor.dim32(0), 2);
EXPECT_EQ(tensor.dim32(1), 3);
EXPECT_EQ(tensor.dim32(2), 5);
EXPECT_EQ(tensor.size(), 2 * 3 * 5);
EXPECT_TRUE(tensor.mutable_data<TypeParam>() != nullptr);
EXPECT_TRUE(tensor.data<TypeParam>() != nullptr);
}
TYPED_TEST(TensorCPUTest, TensorInitializedNonEmpty) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
TensorCPU tensor(dims);
EXPECT_EQ(tensor.ndim(), 3);
EXPECT_EQ(tensor.dim32(0), 2);
EXPECT_EQ(tensor.dim32(1), 3);
EXPECT_EQ(tensor.dim32(2), 5);
EXPECT_TRUE(tensor.mutable_data<TypeParam>() != nullptr);
EXPECT_TRUE(tensor.data<TypeParam>() != nullptr);
dims[0] = 7;
dims[1] = 11;
dims[2] = 13;
dims.push_back(17);
tensor.Resize(dims);
EXPECT_EQ(tensor.ndim(), 4);
EXPECT_EQ(tensor.dim32(0), 7);
EXPECT_EQ(tensor.dim32(1), 11);
EXPECT_EQ(tensor.dim32(2), 13);
EXPECT_EQ(tensor.dim32(3), 17);
EXPECT_TRUE(tensor.mutable_data<TypeParam>() != nullptr);
EXPECT_TRUE(tensor.data<TypeParam>() != nullptr);
}
TYPED_TEST(TensorCPUTest, TensorInitializedZeroDim) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 0;
dims[2] = 5;
TensorCPU tensor(dims);
EXPECT_EQ(tensor.ndim(), 3);
EXPECT_EQ(tensor.dim32(0), 2);
EXPECT_EQ(tensor.dim32(1), 0);
EXPECT_EQ(tensor.dim32(2), 5);
EXPECT_TRUE(tensor.mutable_data<TypeParam>() == nullptr);
EXPECT_TRUE(tensor.data<TypeParam>() == nullptr);
}
TYPED_TEST(TensorCPUTest, TensorResizeZeroDim) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
TensorCPU tensor(dims);
EXPECT_EQ(tensor.ndim(), 3);
EXPECT_EQ(tensor.dim32(0), 2);
EXPECT_EQ(tensor.dim32(1), 3);
EXPECT_EQ(tensor.dim32(2), 5);
EXPECT_TRUE(tensor.mutable_data<TypeParam>() != nullptr);
EXPECT_TRUE(tensor.data<TypeParam>() != nullptr);
dims[0] = 7;
dims[1] = 0;
dims[2] = 13;
tensor.Resize(dims);
EXPECT_EQ(tensor.size(), 0);
EXPECT_EQ(tensor.ndim(), 3);
EXPECT_EQ(tensor.dim32(0), 7);
EXPECT_EQ(tensor.dim32(1), 0);
EXPECT_EQ(tensor.dim32(2), 13);
// output value can be arbitrary, but the call to data() shouldn't crash
tensor.mutable_data<TypeParam>();
tensor.data<TypeParam>();
}
TYPED_TEST(TensorCPUTest, TensorInitializedScalar) {
vector<int> dims;
TensorCPU tensor(dims);
EXPECT_EQ(tensor.ndim(), 0);
EXPECT_EQ(tensor.size(), 1);
EXPECT_TRUE(tensor.mutable_data<TypeParam>() != nullptr);
EXPECT_TRUE(tensor.data<TypeParam>() != nullptr);
}
TYPED_TEST(TensorCPUTest, TensorShareData) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
TensorCPU tensor(dims);
TensorCPU other_tensor(dims);
EXPECT_TRUE(tensor.mutable_data<TypeParam>() != nullptr);
other_tensor.ShareData(tensor);
EXPECT_TRUE(tensor.data<TypeParam>() != nullptr);
EXPECT_TRUE(other_tensor.data<TypeParam>() != nullptr);
EXPECT_EQ(tensor.data<TypeParam>(), other_tensor.data<TypeParam>());
// Set one value, check the other
for (int i = 0; i < tensor.size(); ++i) {
tensor.mutable_data<TypeParam>()[i] = i;
EXPECT_EQ(other_tensor.data<TypeParam>()[i], i);
}
}
TYPED_TEST(TensorCPUTest, TensorShareDataRawPointer) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
std::unique_ptr<TypeParam[]> raw_buffer(new TypeParam[2*3*5]);
TensorCPU tensor(dims);
tensor.ShareExternalPointer(raw_buffer.get());
EXPECT_EQ(tensor.mutable_data<TypeParam>(), raw_buffer.get());
EXPECT_EQ(tensor.data<TypeParam>(), raw_buffer.get());
// Set one value, check the other
for (int i = 0; i < tensor.size(); ++i) {
raw_buffer.get()[i] = i;
EXPECT_EQ(tensor.data<TypeParam>()[i], i);
}
}
TYPED_TEST(TensorCPUTest, TensorShareDataRawPointerWithMeta) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
std::unique_ptr<TypeParam[]> raw_buffer(new TypeParam[2 * 3 * 5]);
TensorCPU tensor(dims);
TypeMeta meta = TypeMeta::Make<TypeParam>();
tensor.ShareExternalPointer(raw_buffer.get(), meta);
EXPECT_EQ(tensor.mutable_data<TypeParam>(), raw_buffer.get());
EXPECT_EQ(tensor.data<TypeParam>(), raw_buffer.get());
// Set one value, check the other
for (int i = 0; i < tensor.size(); ++i) {
raw_buffer.get()[i] = i;
EXPECT_EQ(tensor.data<TypeParam>()[i], i);
}
}
TYPED_TEST(TensorCPUTest, CannotShareDataWhenShapeNotSet) {
std::unique_ptr<TypeParam[]> raw_buffer(new TypeParam[10]);
TensorCPU tensor;
ASSERT_THROW(tensor.ShareExternalPointer(raw_buffer.get()), EnforceNotMet);
}
TYPED_TEST(TensorCPUTest, TensorShareDataCanUseDifferentShapes) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
vector<int> alternate_dims(1);
alternate_dims[0] = 2 * 3 * 5;
TensorCPU tensor(dims);
TensorCPU other_tensor(alternate_dims);
EXPECT_TRUE(tensor.mutable_data<TypeParam>() != nullptr);
other_tensor.ShareData(tensor);
EXPECT_EQ(other_tensor.ndim(), 1);
EXPECT_EQ(other_tensor.dim32(0), alternate_dims[0]);
EXPECT_TRUE(tensor.data<TypeParam>() != nullptr);
EXPECT_TRUE(other_tensor.data<TypeParam>() != nullptr);
EXPECT_EQ(tensor.data<TypeParam>(), other_tensor.data<TypeParam>());
// Set one value, check the other
for (int i = 0; i < tensor.size(); ++i) {
tensor.mutable_data<TypeParam>()[i] = i;
EXPECT_EQ(other_tensor.data<TypeParam>()[i], i);
}
}
TYPED_TEST(TensorCPUTest, NoLongerSharesAfterResize) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
TensorCPU tensor(dims);
TensorCPU other_tensor(dims);
EXPECT_TRUE(tensor.mutable_data<TypeParam>() != nullptr);
other_tensor.ShareData(tensor);
EXPECT_EQ(tensor.data<TypeParam>(), other_tensor.data<TypeParam>());
auto* old_pointer = other_tensor.data<TypeParam>();
dims[0] = 7;
tensor.Resize(dims);
EXPECT_EQ(old_pointer, other_tensor.data<TypeParam>());
EXPECT_NE(old_pointer, tensor.mutable_data<TypeParam>());
}
TYPED_TEST(TensorCPUTest, NoLongerSharesAfterFreeMemory) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
TensorCPU tensor(dims);
TensorCPU other_tensor(dims);
EXPECT_TRUE(tensor.mutable_data<TypeParam>() != nullptr);
other_tensor.ShareData(tensor);
EXPECT_EQ(tensor.data<TypeParam>(), other_tensor.data<TypeParam>());
auto* old_pointer = other_tensor.data<TypeParam>();
tensor.FreeMemory();
EXPECT_EQ(old_pointer, other_tensor.data<TypeParam>());
EXPECT_NE(old_pointer, tensor.mutable_data<TypeParam>());
}
TYPED_TEST(TensorCPUTest, KeepOnShrink) {
// Set flags (defaults)
FLAGS_caffe2_keep_on_shrink = true;
FLAGS_caffe2_max_keep_on_shrink_memory = LLONG_MAX;
vector<int> dims{2, 3, 5};
TensorCPU tensor(dims);
TypeParam* ptr = tensor.mutable_data<TypeParam>();
EXPECT_TRUE(ptr != nullptr);
// Expanding - will reallocate
tensor.Resize(3, 4, 6);
TypeParam* larger_ptr = tensor.mutable_data<TypeParam>();
EXPECT_TRUE(larger_ptr != nullptr);
// This check can fail when malloc() returns the same recently freed address
//EXPECT_NE(ptr, larger_ptr);
// Shrinking - will not reallocate
tensor.Resize(1, 2, 4);
TypeParam* smaller_ptr = tensor.mutable_data<TypeParam>();
EXPECT_TRUE(smaller_ptr != nullptr);
EXPECT_EQ(larger_ptr, smaller_ptr);
// resize to 0 in the meantime;
tensor.Resize(3, 0, 6);
// Expanding but still under capacity - will not reallocate
tensor.Resize(2, 3, 5);
TypeParam* new_ptr = tensor.mutable_data<TypeParam>();
EXPECT_TRUE(new_ptr != nullptr);
EXPECT_EQ(larger_ptr, new_ptr);
}
TYPED_TEST(TensorCPUTest, MaxKeepOnShrink) {
// Set flags
FLAGS_caffe2_keep_on_shrink = true;
FLAGS_caffe2_max_keep_on_shrink_memory = 8 * 4 * sizeof(TypeParam);
vector<int> dims{1, 8, 8};
TensorCPU tensor(dims);
TypeParam* ptr = tensor.mutable_data<TypeParam>();
EXPECT_TRUE(ptr != nullptr);
// Shrinking - will not reallocate
tensor.Resize(1, 7, 8);
TypeParam* smaller_ptr = tensor.mutable_data<TypeParam>();
EXPECT_TRUE(smaller_ptr != nullptr);
EXPECT_EQ(ptr, smaller_ptr);
// Resize to more than maximum shrink, should reallocate
tensor.Resize(1, 1, 8);
TypeParam* new_ptr = tensor.mutable_data<TypeParam>();
EXPECT_TRUE(new_ptr != nullptr);
// This check can fail when malloc() returns the same recently freed address
//EXPECT_NE(ptr, new_ptr);
// Restore default flags
FLAGS_caffe2_max_keep_on_shrink_memory = LLONG_MAX;
}
TYPED_TEST(TensorCPUDeathTest, CannotAccessRawDataWhenEmpty) {
TensorCPU tensor;
EXPECT_EQ(tensor.ndim(), 0);
ASSERT_ANY_THROW(tensor.raw_data());
}
TYPED_TEST(TensorCPUDeathTest, CannotAccessDataWhenEmpty) {
TensorCPU tensor;
EXPECT_EQ(tensor.ndim(), 0);
ASSERT_ANY_THROW(tensor.data<TypeParam>());
}
TEST(TensorTest, TensorNonFundamentalType) {
TensorCPU tensor(vector<int>{2, 3, 4});
EXPECT_TRUE(tensor.mutable_data<std::string>() != nullptr);
const std::string* ptr = tensor.data<std::string>();
for (int i = 0; i < tensor.size(); ++i) {
EXPECT_TRUE(ptr[i] == "");
}
}
TEST(TensorTest, TensorNonFundamentalTypeCopy) {
TensorCPU tensor(vector<int>{2, 3, 4});
std::string* ptr = tensor.mutable_data<std::string>();
EXPECT_TRUE(ptr != nullptr);
for (int i = 0; i < tensor.size(); ++i) {
EXPECT_TRUE(ptr[i] == "");
ptr[i] = "filled";
}
TensorCPU dst_tensor(tensor);
const std::string* dst_ptr = dst_tensor.data<std::string>();
for (int i = 0; i < dst_tensor.size(); ++i) {
EXPECT_TRUE(dst_ptr[i] == "filled");
}
}
TEST(TensorTest, Tensor64BitDimension) {
// Initialize a large tensor.
TIndex large_number =
static_cast<int64_t>(std::numeric_limits<int>::max()) + 1;
TensorCPU tensor(vector<TIndex>{large_number});
EXPECT_EQ(tensor.ndim(), 1);
EXPECT_EQ(tensor.dim(0), large_number);
EXPECT_EQ(tensor.size(), large_number);
EXPECT_TRUE(tensor.mutable_data<char>() != nullptr);
EXPECT_EQ(tensor.nbytes(), large_number * sizeof(char));
EXPECT_EQ(tensor.itemsize(), sizeof(char));
// Try to go even larger, but this time we will not do mutable_data because we
// do not have a large enough memory.
tensor.Resize(large_number, 100);
EXPECT_EQ(tensor.ndim(), 2);
EXPECT_EQ(tensor.dim(0), large_number);
EXPECT_EQ(tensor.dim(1), 100);
EXPECT_EQ(tensor.size(), large_number * 100);
}
TEST(TensorDeathTest, CannotCastDownLargeDims) {
TIndex large_number =
static_cast<int64_t>(std::numeric_limits<int>::max()) + 1;
TensorCPU tensor(vector<TIndex>{large_number});
EXPECT_EQ(tensor.ndim(), 1);
EXPECT_EQ(tensor.dim(0), large_number);
ASSERT_THROW(tensor.dim32(0), EnforceNotMet);
}
#define TEST_SERIALIZATION_WITH_TYPE(TypeParam, field_name) \
TEST(TensorTest, TensorSerialization_##TypeParam) { \
Blob blob; \
TensorCPU* tensor = blob.GetMutable<TensorCPU>(); \
tensor->Resize(2, 3); \
for (int i = 0; i < 6; ++i) { \
tensor->mutable_data<TypeParam>()[i] = static_cast<TypeParam>(i); \
} \
string serialized = blob.Serialize("test"); \
BlobProto proto; \
CHECK(proto.ParseFromString(serialized)); \
EXPECT_EQ(proto.name(), "test"); \
EXPECT_EQ(proto.type(), "Tensor"); \
EXPECT_TRUE(proto.has_tensor()); \
const TensorProto& tensor_proto = proto.tensor(); \
EXPECT_EQ( \
tensor_proto.data_type(), \
TypeMetaToDataType(TypeMeta::Make<TypeParam>())); \
EXPECT_EQ(tensor_proto.field_name##_size(), 6); \
for (int i = 0; i < 6; ++i) { \
EXPECT_EQ(tensor_proto.field_name(i), static_cast<TypeParam>(i)); \
} \
Blob new_blob; \
EXPECT_NO_THROW(new_blob.Deserialize(serialized)); \
EXPECT_TRUE(new_blob.IsType<TensorCPU>()); \
const TensorCPU& new_tensor = blob.Get<TensorCPU>(); \
EXPECT_EQ(new_tensor.ndim(), 2); \
EXPECT_EQ(new_tensor.dim(0), 2); \
EXPECT_EQ(new_tensor.dim(1), 3); \
for (int i = 0; i < 6; ++i) { \
EXPECT_EQ( \
tensor->data<TypeParam>()[i], new_tensor.data<TypeParam>()[i]); \
} \
} \
\
TEST(EmptyTensorTest, TensorSerialization_##TypeParam) { \
Blob blob; \
TensorCPU* tensor = blob.GetMutable<TensorCPU>(); \
tensor->Resize(0, 3); \
tensor->mutable_data<TypeParam>(); \
string serialized = blob.Serialize("test"); \
BlobProto proto; \
CHECK(proto.ParseFromString(serialized)); \
EXPECT_EQ(proto.name(), "test"); \
EXPECT_EQ(proto.type(), "Tensor"); \
EXPECT_TRUE(proto.has_tensor()); \
const TensorProto& tensor_proto = proto.tensor(); \
EXPECT_EQ( \
tensor_proto.data_type(), \
TypeMetaToDataType(TypeMeta::Make<TypeParam>())); \
EXPECT_EQ(tensor_proto.field_name##_size(), 0); \
Blob new_blob; \
EXPECT_NO_THROW(new_blob.Deserialize(serialized)); \
EXPECT_TRUE(new_blob.IsType<TensorCPU>()); \
const TensorCPU& new_tensor = blob.Get<TensorCPU>(); \
EXPECT_EQ(new_tensor.ndim(), 2); \
EXPECT_EQ(new_tensor.dim(0), 0); \
EXPECT_EQ(new_tensor.dim(1), 3); \
}
TEST_SERIALIZATION_WITH_TYPE(bool, int32_data)
TEST_SERIALIZATION_WITH_TYPE(double, double_data)
TEST_SERIALIZATION_WITH_TYPE(float, float_data)
TEST_SERIALIZATION_WITH_TYPE(int, int32_data)
TEST_SERIALIZATION_WITH_TYPE(int8_t, int32_data)
TEST_SERIALIZATION_WITH_TYPE(int16_t, int32_data)
TEST_SERIALIZATION_WITH_TYPE(uint8_t, int32_data)
TEST_SERIALIZATION_WITH_TYPE(uint16_t, int32_data)
TEST_SERIALIZATION_WITH_TYPE(int64_t, int64_data)
TEST(TensorTest, float16) {
const TIndex kSize = 3000000;
Blob blob;
TensorCPU* tensor = blob.GetMutable<TensorCPU>();
tensor->Resize(kSize);
for (int i = 0; i < tensor->size(); ++i) {
tensor->mutable_data<float16>()[i].x = i % 10000;
}
string serialized = blob.Serialize("test");
BlobProto proto;
CHECK(proto.ParseFromString(serialized));
EXPECT_EQ(proto.name(), "test");
EXPECT_EQ(proto.type(), "Tensor");
EXPECT_TRUE(proto.has_tensor());
const TensorProto& tensor_proto = proto.tensor();
EXPECT_EQ(
tensor_proto.data_type(), TypeMetaToDataType(TypeMeta::Make<float16>()));
if (FLAGS_caffe2_serialize_fp16_as_bytes) {
EXPECT_EQ(tensor_proto.byte_data().size(), 2 * kSize);
for (int i = 0; i < kSize; ++i) {
auto value = tensor->mutable_data<float16>()[i].x;
auto low_bits = static_cast<char>(value & 0xff);
auto high_bits = static_cast<char>(value >> 8);
EXPECT_EQ(tensor_proto.byte_data()[2 * i], low_bits);
EXPECT_EQ(tensor_proto.byte_data()[2 * i + 1], high_bits);
}
} else {
EXPECT_EQ(tensor_proto.int32_data().size(), kSize);
}
Blob new_blob;
EXPECT_NO_THROW(new_blob.Deserialize(serialized));
EXPECT_TRUE(new_blob.IsType<TensorCPU>());
const TensorCPU& new_tensor = blob.Get<TensorCPU>();
EXPECT_EQ(new_tensor.ndim(), 1);
EXPECT_EQ(new_tensor.dim(0), kSize);
for (int i = 0; i < kSize; ++i) {
EXPECT_EQ(new_tensor.data<float16>()[i].x, i % 10000);
}
}
TEST(QTensorTest, QTensorSerialization) {
Blob blob;
QTensor<CPUContext>* qtensor = blob.GetMutable<QTensor<CPUContext>>();
qtensor->SetPrecision(5);
qtensor->SetSigned(false);
qtensor->SetScale(1.337);
qtensor->SetBias(-1.337);
qtensor->Resize(std::vector<int>{2, 3});
// "Randomly" set bits.
srand(0);
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 5; ++j) {
qtensor->SetBitAtIndex(j, i, rand() % 2);
}
}
string serialized = blob.Serialize("test");
BlobProto proto;
CHECK(proto.ParseFromString(serialized));
EXPECT_EQ(proto.name(), "test");
EXPECT_EQ(proto.type(), "QTensor");
EXPECT_TRUE(proto.has_qtensor());
const QTensorProto& qtensor_proto = proto.qtensor();
EXPECT_EQ(qtensor_proto.precision(), qtensor->precision());
EXPECT_EQ(qtensor_proto.scale(), qtensor->scale());
EXPECT_EQ(qtensor_proto.bias(), qtensor->bias());
EXPECT_EQ(qtensor_proto.is_signed(), qtensor->is_signed());
Blob new_blob;
new_blob.Deserialize(serialized);
EXPECT_TRUE(new_blob.IsType<QTensor<CPUContext>>());
const QTensor<CPUContext>& new_qtensor = blob.Get<QTensor<CPUContext>>();
EXPECT_EQ(new_qtensor.ndim(), 2);
EXPECT_EQ(new_qtensor.dim32(0), 2);
EXPECT_EQ(new_qtensor.dim32(1), 3);
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 5; ++j) {
EXPECT_EQ(qtensor->GetBitAtIndex(j, i), new_qtensor.GetBitAtIndex(j, i));
}
}
}
using StringMap = std::vector<std::pair<string, string>>;
class VectorCursor : public db::Cursor {
public:
explicit VectorCursor(StringMap* data) : data_(data) {
pos_ = 0;
}
~VectorCursor() {}
void Seek(const string& /* unused */) override {}
void SeekToFirst() override {}
void Next() override {
++pos_;
}
string key() override {
return (*data_)[pos_].first;
}
string value() override {
return (*data_)[pos_].second;
}
bool Valid() override {
return pos_ < data_->size();
}
private:
StringMap* data_ = nullptr;
size_t pos_ = 0;
};
class VectorDB : public db::DB {
public:
VectorDB(const string& source, db::Mode mode)
: DB(source, mode), name_(source) {}
~VectorDB() {
data_.erase(name_);
}
void Close() override {}
std::unique_ptr<db::Cursor> NewCursor() override {
return make_unique<VectorCursor>(getData());
}
std::unique_ptr<db::Transaction> NewTransaction() override {
CAFFE_THROW("Not implemented");
}
static void registerData(const string& name, StringMap&& data) {
std::lock_guard<std::mutex> guard(dataRegistryMutex_);
data_[name] = std::move(data);
}
private:
StringMap* getData() {
auto it = data_.find(name_);
CAFFE_ENFORCE(it != data_.end(), "Can't find ", name_);
return &(it->second);
}
private:
string name_;
static std::mutex dataRegistryMutex_;
static std::map<string, StringMap> data_;
};
std::mutex VectorDB::dataRegistryMutex_;
std::map<string, StringMap> VectorDB::data_;
REGISTER_CAFFE2_DB(vector_db, VectorDB);
template <typename TypeParam>
class TypedTensorTest : public ::testing::Test {};
typedef ::testing::
Types<float, bool, double, int, int8_t, int16_t, uint8_t, uint16_t, int64_t>
TensorDataTypes;
TYPED_TEST_CASE(TypedTensorTest, TensorDataTypes);
TYPED_TEST(TypedTensorTest, BigTensorSerialization) {
int64_t d1 = 2;
int64_t d2 = FLAGS_caffe2_test_big_tensor_size
? FLAGS_caffe2_test_big_tensor_size / d1
: static_cast<int64_t>(std::numeric_limits<int>::max()) + 1;
int64_t size = d1 * d2;
string db_source = (string)std::tmpnam(nullptr);
VLOG(1) << "db_source: " << db_source;
{
VLOG(1) << "Test begin";
Blob blob;
TensorCPU* tensor = blob.GetMutable<TensorCPU>();
VLOG(1) << "Allocating blob";
tensor->Resize(d1, d2);
auto mutableData = tensor->mutable_data<TypeParam>();
VLOG(1) << "Filling out the blob";
for (int64_t i = 0; i < size; ++i) {
mutableData[i] = static_cast<TypeParam>(i);
}
StringMap data;
std::mutex mutex;
/*auto db = CreateDB("minidb", db_source, WRITE);*/
auto acceptor = [&](const std::string& key, const std::string& value) {
std::lock_guard<std::mutex> guard(mutex);
/*db->NewTransaction()->Put(key, value);*/
data.emplace_back(key, value);
};
blob.Serialize("test", acceptor);
VectorDB::registerData(db_source, std::move(data));
VLOG(1) << "finished writing to DB";
}
{
DeviceOption option;
option.set_device_type(CPU);
Argument db_type_arg = MakeArgument<string>("db_type", "vector_db");
Argument absolute_path_arg = MakeArgument<bool>("absolute_path", true);
Argument db_source_arg = MakeArgument<string>("db", db_source);
auto op_def = CreateOperatorDef(
"Load",
"",
std::vector<string>{},
std::vector<string>({"test"}),
std::vector<Argument>{db_type_arg, db_source_arg, absolute_path_arg},
option,
"DUMMY_ENGINE");
Workspace ws;
auto load_op = CreateOperator(op_def, &ws);
EXPECT_TRUE(load_op != nullptr);
VLOG(1) << "Running operator";
load_op->Run();
VLOG(1) << "Reading blob from workspace";
auto new_blob = ws.GetBlob("test");
EXPECT_TRUE(new_blob->IsType<TensorCPU>());
const auto& new_tensor = new_blob->Get<TensorCPU>();
EXPECT_EQ(new_tensor.ndim(), d1);
EXPECT_EQ(new_tensor.dim(0), d1);
EXPECT_EQ(new_tensor.dim(1), d2);
for (int64_t i = 0; i < size; ++i) {
EXPECT_EQ(static_cast<TypeParam>(i), new_tensor.data<TypeParam>()[i]);
}
}
}
struct DummyType {
/* This struct is used to test serialization and deserialization of huge
* blobs, that are not tensors.
*/
/* implicit */ DummyType(int n_chunks_init = 0) : n_chunks(n_chunks_init) {}
std::string serialize(const std::string& name, const int32_t chunk_id) const {
BlobProto blobProto;
blobProto.set_name(name);
blobProto.set_type("DummyType");
std::string content("");
blobProto.set_content(content);
blobProto.set_content_num_chunks(n_chunks);
blobProto.set_content_chunk_id(chunk_id);
return blobProto.SerializeAsString();
}
void deserialize(const BlobProto& /* unused */) {
++n_chunks;
}
int n_chunks;
};
class DummyTypeSerializer : public BlobSerializerBase {
public:
DummyTypeSerializer() {}
~DummyTypeSerializer() {}
void Serialize(
const Blob& blob,
const string& name,
SerializationAcceptor acceptor) override {
CAFFE_ENFORCE(blob.IsType<DummyType>());
const auto& container = blob.template Get<DummyType>();
for (int k = 0; k < container.n_chunks; ++k) {
std::string serialized_chunk = container.serialize(name, k);
acceptor(MakeString(name, kChunkIdSeparator, k), serialized_chunk);
}
}
};
class DummyTypeDeserializer : public BlobDeserializerBase {
public:
void Deserialize(const BlobProto& proto, Blob* blob) override {
auto* container = blob->GetMutable<DummyType>();
container->deserialize(proto);
}
};
}
CAFFE_KNOWN_TYPE(DummyType);
namespace {
REGISTER_BLOB_SERIALIZER((TypeMeta::Id<DummyType>()), DummyTypeSerializer);
CAFFE_REGISTER_TYPED_CLASS(
BlobDeserializerRegistry,
"DummyType",
DummyTypeDeserializer);
TEST(ContentChunks, Serialization) {
string db_source = (string)std::tmpnam(nullptr);
VLOG(1) << "db_source: " << db_source;
{
VLOG(1) << "Test begin";
Blob blob;
DummyType* container = blob.GetMutable<DummyType>();
VLOG(1) << "Allocating blob";
container->n_chunks = 10;
VLOG(1) << "Filling out the blob";
StringMap data;
std::mutex mutex;
auto acceptor = [&](const std::string& key, const std::string& value) {
std::lock_guard<std::mutex> guard(mutex);
data.emplace_back(key, value);
};
blob.Serialize("test", acceptor);
VectorDB::registerData(db_source, std::move(data));
VLOG(1) << "finished writing to DB";
}
{
DeviceOption option;
option.set_device_type(CPU);
Argument db_type_arg = MakeArgument<string>("db_type", "vector_db");
Argument absolute_path_arg = MakeArgument<bool>("absolute_path", true);
Argument db_source_arg = MakeArgument<string>("db", db_source);
auto op_def = CreateOperatorDef(
"Load",
"",
std::vector<string>{},
std::vector<string>({"test"}),
std::vector<Argument>{db_type_arg, db_source_arg, absolute_path_arg},
option,
"DUMMY_ENGINE");
Workspace ws;
auto load_op = CreateOperator(op_def, &ws);
EXPECT_TRUE(load_op != nullptr);
VLOG(1) << "Running operator";
load_op->Run();
VLOG(1) << "Reading blob from workspace";
auto new_blob = ws.GetBlob("test");
EXPECT_TRUE(new_blob->IsType<DummyType>());
const auto& container = new_blob->Get<DummyType>();
EXPECT_EQ(container.n_chunks, 10);
}
}
TEST(CustomChunkSize, BigTensorSerialization) {
int64_t d1 = 2;
int64_t d2 = FLAGS_caffe2_test_big_tensor_size
? FLAGS_caffe2_test_big_tensor_size / d1
: static_cast<int64_t>(std::numeric_limits<int>::max()) + 1;
int64_t size = d1 * d2;
Blob blob;
TensorCPU* tensor = blob.GetMutable<TensorCPU>();
tensor->Resize(d1, d2);
tensor->mutable_data<float>();
std::mutex mutex;
int counter = 0;
auto acceptor = [&](const std::string& /*key*/,
const std::string& /*value*/) {
std::lock_guard<std::mutex> guard(mutex);
counter++;
};
blob.Serialize("test", acceptor, size);
EXPECT_EQ(counter, 1);
counter = 0;
blob.Serialize("test", acceptor, (size / 2) + 1);
EXPECT_EQ(counter, 2);
counter = 0;
blob.Serialize("test", acceptor, kNoChunking);
EXPECT_EQ(counter, 1);
}
TEST(QTensor, QTensorSizingTest) {
vector<int> dims(3);
dims[0] = 2;
dims[1] = 3;
dims[2] = 5;
QTensor<CPUContext> qtensor(dims, 3);
EXPECT_TRUE(qtensor.mutable_data() != nullptr);
EXPECT_EQ(qtensor.nbytes(), 12);
EXPECT_EQ(qtensor.size(), 30);
}
} // namespace
} // namespace caffe2
|
/*
* @Author: tusikalanse
* @Date: 2021-07-12 15:29:10
* @LastEditTime: 2021-07-12 17:24:40
* @LastEditors: tusikalanse
* @Description:
*/
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
LL gcd(LL a, LL b) {
return b == 0 ? a : gcd(b, a % b);
}
const int INF = 0x3f3f3f3f;
const LL INFL = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
//-------------------end head--------------
const int N = 1e4 + 10;
int vis[N][10];
int rep[N];
void init(int x, int a, int b, int c) {
int i = 1, n = 0;
do {
vis[n][x] = 1;
vis[n][6] = 1;
rep[n] |= 1 << x;
n = (a * i * i + b * i) / c;
i++;
} while (n < 10000);
}
int p[10];
int used[N];
int ans = 0;
bool valid(vector<int> x) {
sort(x.begin(), x.end());
do {
bool flag = true;
for (int i = 0; i < 6; ++i)
flag &= (x[i] >> i) & 1;
if (flag)
return true;
} while (next_permutation(x.begin(), x.end()));
return false;
}
void dfs(int now, int mask) {
if (__builtin_popcount(mask) < now - 1)
return;
if (now == 6) {
if (vis[p[5] * 100 + p[0]][6]) {
ans = 0;
int mask = 0;
vector<int> v;
for (int i = 0; i < 6; ++i) {
mask |= rep[p[i] * 100 + p[(i + 1) % 6]];
v.push_back(rep[p[i] * 100 + p[(i + 1) % 6]]);
}
if (mask != (1 << 6) - 1)
return;
if (!valid(v))
return;
for (int i = 0; i < 6; ++i) {
ans += p[i] * 100 + p[(i + 1) % 6];
cout << p[i] * 100 + p[(i + 1) % 6] << " ";
}
cout << ans << endl;
}
return;
}
for (int i = 10; i <= 99; ++i) {
if (now == 0) {
p[now] = i;
dfs(now + 1, mask);
} else {
int x = p[now - 1] * 100 + i;
if (vis[x][6] == 0 || used[x])
continue;
p[now] = i;
used[x] = 1;
dfs(now + 1, mask | rep[x]);
used[x] = 0;
}
}
}
int main() {
init(0, 1, 1, 2);
init(1, 1, 0, 1);
init(2, 3, -1, 2);
init(3, 2, -1, 1);
init(4, 5, -3, 2);
init(5, 3, -2, 1);
dfs(0, 0);
return 0;
}
|
// Copyright (c) Jeremiah Z. Griffin <nokurn@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE NEGLIGENCE OR OTHER TORTIOUS ACTION,
// ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
// SOFTWARE.
#include "Evaluator.hpp"
#include <cmath>
#include <stdexcept>
Evaluator::Evaluator(std::deque<Node> nodes)
: _nodes{std::move(nodes)}
{
}
double Evaluator::evaluate()
{
while (!_nodes.empty()) {
step();
}
return _operands.top();
}
void Evaluator::step()
{
auto& n = _nodes.front();
switch (n.kind) {
case NodeKind::Number:
stepNumber(std::get<double>(n.value));
break;
case NodeKind::Operator:
stepOperator(std::get<OperatorKind>(n.value));
break;
}
_nodes.pop_front();
}
void Evaluator::stepNumber(double v)
{
_operands.push(v);
}
void Evaluator::stepOperator(OperatorKind k)
{
switch (k) {
case OperatorKind::Add:
stepAdd();
break;
case OperatorKind::Subtract:
stepSubtract();
break;
case OperatorKind::Multiply:
stepMultiply();
break;
case OperatorKind::Divide:
stepDivide();
break;
case OperatorKind::Power:
stepPower();
break;
default:
throw std::runtime_error{"Unknown evaluation operator"};
}
}
void Evaluator::stepAdd()
{
if (_operands.size() < 2) {
throw std::runtime_error{"Insufficient operands for addition"};
}
auto y = _operands.top();
_operands.pop();
auto x = _operands.top();
_operands.pop();
_operands.push(x + y);
}
void Evaluator::stepSubtract()
{
if (_operands.size() < 2) {
throw std::runtime_error{"Insufficient operands for subtraction"};
}
auto y = _operands.top();
_operands.pop();
auto x = _operands.top();
_operands.pop();
_operands.push(x - y);
}
void Evaluator::stepMultiply()
{
if (_operands.size() < 2) {
throw std::runtime_error{"Insufficient operands for multiplication"};
}
auto y = _operands.top();
_operands.pop();
auto x = _operands.top();
_operands.pop();
_operands.push(x * y);
}
void Evaluator::stepDivide()
{
if (_operands.size() < 2) {
throw std::runtime_error{"Insufficient operands for division"};
}
auto y = _operands.top();
_operands.pop();
auto x = _operands.top();
_operands.pop();
_operands.push(x / y);
}
void Evaluator::stepPower()
{
if (_operands.size() < 2) {
throw std::runtime_error{"Insufficient operands for power"};
}
auto y = _operands.top();
_operands.pop();
auto x = _operands.top();
_operands.pop();
_operands.push(std::pow(x, y));
}
|
// This file is part of snark, a generic and flexible library for robotics research
// Copyright (c) 2018 The University of Sydney
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the University of Sydney nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
// GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
// HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ocular-thermal.h"
#include <RobotEye.h>
#include <comma/base/exception.h>
#include <comma/application/verbose.h>
#include <opencv2/core.hpp>
namespace snark { namespace ocular { namespace roboteye {
::ocular::ocular_error_t check_status( ::ocular::ocular_error_t status, const std::string& msg )
{
if( status != ::ocular::NO_ERR )
{
std::cerr << comma::verbose.app_name() << ": " << msg << ( msg.empty() ? "" : ": " )
<< ::ocular::RobotEye::GetErrorString( status ) << std::endl;
}
return status;
}
::ocular::dev_status_t check_dev_status( ::ocular::dev_status_t status, const std::string& msg )
{
if( status.devCode != ::ocular::NO_ERR )
{
std::cerr << comma::verbose.app_name() << ": " << msg << ( msg.empty() ? "" : ": " )
<< ::ocular::RobotEyeThermal::GetErrorString( status ) << std::endl;
}
return status;
}
int pixel_type_to_opencv( uint8_t pixel_type )
{
switch( pixel_type )
{
case ::ocular::thermal::PIXELTYPE_MONO_8: return CV_8UC1;
case ::ocular::thermal::PIXELTYPE_MONO_14: return CV_16UC1;
default: COMMA_THROW( comma::exception, "unsupported pixel type " << pixel_type );
}
}
} } } //namespace snark { namespace ocular { namespace roboteye {
|
// REQUIRES: lld
// RUN: clang -g -c -o %t-1.o --target=x86_64-pc-linux -mllvm -accel-tables=Disable %s
// RUN: clang -g -c -o %t-2.o --target=x86_64-pc-linux -mllvm -accel-tables=Disable %S/Inputs/find-variable-file-2.cpp
// RUN: ld.lld %t-1.o %t-2.o -o %t
// RUN: lldb-test symbols --file=find-variable-file.cpp --find=variable %t | \
// RUN: FileCheck --check-prefix=ONE %s
// RUN: lldb-test symbols --file=find-variable-file-2.cpp --find=variable %t | \
// RUN: FileCheck --check-prefix=TWO %s
// RUN: clang -g -c -o %t-1.o --target=x86_64-pc-linux -mllvm -accel-tables=Dwarf %s
// RUN: clang -g -c -o %t-2.o --target=x86_64-pc-linux -mllvm -accel-tables=Dwarf %S/Inputs/find-variable-file-2.cpp
// RUN: ld.lld %t-1.o %t-2.o -o %t
// RUN: lldb-test symbols --file=find-variable-file.cpp --find=variable %t | \
// RUN: FileCheck --check-prefix=ONE %s
// RUN: lldb-test symbols --file=find-variable-file-2.cpp --find=variable %t | \
// RUN: FileCheck --check-prefix=TWO %s
// ONE: Found 1 variables:
namespace one {
int foo;
// ONE-DAG: name = "foo", type = {{.*}} (int), {{.*}} decl = find-variable-file.cpp:[[@LINE-1]]
} // namespace one
extern "C" void _start() {}
// TWO: Found 1 variables:
// TWO-DAG: name = "foo", {{.*}} decl = find-variable-file-2.cpp:2
|
#include <iostream>
using integer = long long;
void answer(integer v)
{
std::cout << v << '\n';
}
void solve(integer x1, integer y1, integer x2, integer y2)
{
const integer dx = abs(x1 - x2);
const integer dy = abs(y1 - y2);
answer(std::max(dx, dy));
}
int main()
{
integer x1, y1;
std::cin >> x1 >> y1;
integer x2, y2;
std::cin >> x2 >> y2;
solve(x1, y1, x2, y2);
return 0;
}
|
#define EPI_DEBUG
#include "../../include/epiworld/epiworld.hpp"
int main()
{
// Setting up model --------------------------------------------------------
epiworld::Model<> model;
model.add_status("Susceptible", epiworld::default_update_susceptible<>);
model.add_status("Exposed", epiworld::default_update_exposed<>);
model.add_status("Removed");
model.set_user_data({"agent_id", "virus_id"});
model.agents_from_adjlist(
epiworld::rgraph_smallworld(200, 5, .1, false, model)
);
model.add_param(.9, "infectiousness");
model.add_param(.3, "recovery");
// Setting up virus --------------------------------------------------------
epiworld::Virus<> v("covid");
v.set_status(1,2,2);
EPI_NEW_POSTRECOVERYFUN_LAMBDA(immunity, int)
{
// Post immunity
auto Tpr = m->get_tools()[1u];
p->add_tool(Tpr);
m->add_user_data({
static_cast< epiworld_double >(p->get_id()),
static_cast< epiworld_double >(v.get_id())
});
};
v.set_post_recovery(immunity);
v.set_prob_infecting(&model("infectiousness"));
// Setting up tool ---------------------------------------------------------
epiworld::Tool<> is("immune system");
is.set_susceptibility_reduction(.3);
is.set_death_reduction(.9);
is.set_recovery_enhancer(&model("recovery"));
epiworld::Tool<> postImm("post immunity");
postImm.set_susceptibility_reduction(1.0);
model.add_tool(is, 1.0);
model.add_tool_n(postImm, 0u);
model.add_virus_n(v, 5);
model.init(112, 30);
model.run();
model.print();
model.get_user_data().print();
model.get_user_data().write("user-data.txt");
}
|
// Copyright 2019 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 "components/offline_pages/task/sql_store_base.h"
#include <iterator>
#include <utility>
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/task/sequenced_task_runner.h"
#include "base/trace_event/trace_event.h"
namespace offline_pages {
namespace {
bool PrepareDirectory(const base::FilePath& path) {
base::File::Error error = base::File::FILE_OK;
if (!base::DirectoryExists(path.DirName())) {
if (!base::CreateDirectoryAndGetError(path.DirName(), &error)) {
DLOG(ERROR) << "Failed to create prefetch db directory: "
<< base::File::ErrorToString(error);
return false;
}
}
return true;
}
// TODO(fgorski): This function and this part of the system in general could
// benefit from a better status code reportable through UMA to better capture
// the reason for failure, aiding the process of repeated attempts to
// open/initialize the database.
bool InitializeSync(
sql::Database* db,
const base::FilePath& path,
const std::string& histogram_tag,
base::OnceCallback<bool(sql::Database*)> initialize_schema) {
db->set_histogram_tag(histogram_tag);
const bool in_memory = path.empty();
if (!in_memory && !PrepareDirectory(path))
return false;
bool open_db_result = false;
if (in_memory)
open_db_result = db->OpenInMemory();
else
open_db_result = db->Open(path);
if (!open_db_result) {
DLOG(ERROR) << "Failed to open database, in memory: " << in_memory;
return false;
}
db->Preload();
return std::move(initialize_schema).Run(db);
}
void CloseDatabaseSync(
sql::Database* db,
scoped_refptr<base::SingleThreadTaskRunner> callback_runner,
base::OnceClosure callback) {
if (db)
db->Close();
callback_runner->PostTask(FROM_HERE, std::move(callback));
}
} // namespace
// static
constexpr base::TimeDelta SqlStoreBase::kClosingDelay;
SqlStoreBase::SqlStoreBase(
const std::string& histogram_tag,
scoped_refptr<base::SequencedTaskRunner> background_task_runner,
const base::FilePath& file_path)
: background_task_runner_(background_task_runner),
histogram_tag_(histogram_tag),
db_file_path_(file_path),
db_(nullptr, base::OnTaskRunnerDeleter(background_task_runner_)) {}
SqlStoreBase::~SqlStoreBase() = default;
void SqlStoreBase::SetInitializationStatusForTesting(
InitializationStatus initialization_status,
bool reset_db) {
initialization_status_ = initialization_status;
if (reset_db)
db_.reset(nullptr);
}
void SqlStoreBase::Initialize(base::OnceClosure pending_command) {
OnOpenStart(last_closing_time_);
DCHECK_EQ(initialization_status_, InitializationStatus::kNotInitialized);
initialization_status_ = InitializationStatus::kInProgress;
// This is how we reset a pointer and provide deleter. This is necessary to
// ensure that we can close the store more than once.
db_ = DatabaseUniquePtr(new sql::Database({// These values are default.
.exclusive_locking = true,
.page_size = 4096,
.cache_size = 500}),
base::OnTaskRunnerDeleter(background_task_runner_));
base::PostTaskAndReplyWithResult(
background_task_runner_.get(), FROM_HERE,
base::BindOnce(&InitializeSync, db_.get(), db_file_path_, histogram_tag_,
GetSchemaInitializationFunction()),
base::BindOnce(&SqlStoreBase::InitializeDone,
weak_ptr_factory_.GetWeakPtr(),
std::move(pending_command)));
}
void SqlStoreBase::InitializeDone(base::OnceClosure pending_command,
bool success) {
DCHECK_EQ(initialization_status_, InitializationStatus::kInProgress);
if (success) {
initialization_status_ = InitializationStatus::kSuccess;
} else {
initialization_status_ = InitializationStatus::kFailure;
db_.reset();
}
CHECK(!pending_command.is_null());
std::move(pending_command).Run();
for (auto command_iter = std::make_move_iterator(pending_commands_.begin());
command_iter != std::make_move_iterator(pending_commands_.end());
++command_iter) {
(*command_iter).Run();
}
pending_commands_.clear();
// Once pending commands are empty, we get back to kNotInitialized state, to
// make it possible to retry initialization next time a DB operation is
// attempted.
if (initialization_status_ == InitializationStatus::kFailure)
initialization_status_ = InitializationStatus::kNotInitialized;
OnOpenDone(success);
}
void SqlStoreBase::ExecuteInternal(base::OnceClosure command) {
if (initialization_status_ == InitializationStatus::kInProgress) {
pending_commands_.push_back(std::move(command));
return;
}
if (initialization_status_ == InitializationStatus::kNotInitialized) {
Initialize(std::move(command));
return;
}
std::move(command).Run();
}
sql::Database* SqlStoreBase::ExecuteBegin() {
OnTaskBegin(initialization_status_ == InitializationStatus::kSuccess);
// Ensure that any scheduled close operations are canceled.
closing_weak_ptr_factory_.InvalidateWeakPtrs();
return initialization_status_ == InitializationStatus::kSuccess ? db_.get()
: nullptr;
}
void SqlStoreBase::CloseInternal() {
OnCloseStart(initialization_status_);
last_closing_time_ = base::TimeTicks::Now();
initialization_status_ = InitializationStatus::kNotInitialized;
background_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&CloseDatabaseSync, db_.get(), base::ThreadTaskRunnerHandle::Get(),
base::BindOnce(&SqlStoreBase::CloseInternalDone,
weak_ptr_factory_.GetWeakPtr(), std::move(db_))));
}
void SqlStoreBase::RescheduleClosingBefore() {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&SqlStoreBase::CloseInternal,
closing_weak_ptr_factory_.GetWeakPtr()),
kClosingDelay);
// Note: the time recorded for this trace step will include thread hop wait
// times to the background thread and back.
OnTaskRunComplete();
}
void SqlStoreBase::CloseInternalDone(DatabaseUniquePtr db) {
db.reset();
OnCloseComplete();
}
} // namespace offline_pages
|
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <utility.h>
#include <window.h>
using namespace luminate;
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods){
Window* luminate_window = (Window*)glfwGetWindowUserPointer(window);
luminate_window->notifyMouseHandlers(window, button, action, mods);
};
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods){
Window* luminate_window = (Window*)glfwGetWindowUserPointer(window);
luminate_window->notifyKeyHandlers(window, key, scancode, action, mods);
};
Window::Window(int width, int height, const char* title){
this->stay_open = false;
this->width = width;
this->height = height;
this->title = title;
};
void Window::addWidget(Widget* widget){
this->widgets.push_back(widget);
};
void Window::addKeyHandler(KeyHandler* key_handler){
this->key_handlers.push_back(key_handler);
};
void Window::addMouseHandler(MouseHandler* mouse_handler){
this->mouse_handlers.push_back(mouse_handler);
};
void Window::notifyKeyHandlers(GLFWwindow* window, int key, int scancode, int action, int mods){
std::vector<KeyHandler*>::iterator it;
for(it = this->key_handlers.begin(); it != this->key_handlers.end(); it++){
(*it)->key_handler(window, key, scancode, action, mods);
}
};
void Window::notifyMouseHandlers(GLFWwindow* window, int button, int action, int mods){
std::vector<MouseHandler*>::iterator it;
for(it = this->mouse_handlers.begin(); it != this->mouse_handlers.end(); it++){
(*it)->mouse_handler(window, button, action, mods);
}
};
void Window::initialise(){
glewExperimental = true;
if( !glfwInit() ){
fprintf( stderr, "Failed to initialize GLFW\n" );
return;
}
glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // We don't want the old OpenGL
GLFWwindow* glfw_window;
glfw_window = glfwCreateWindow(this->width, this->height, this->title, NULL, NULL);
if( glfw_window == NULL ){
fprintf( stderr, "Failed to open GLFW window.\n" );
glfwTerminate();
return;
}
glfwSetWindowUserPointer(glfw_window, this);
glfwSetKeyCallback(glfw_window, key_callback);
glfwSetMouseButtonCallback(glfw_window, mouse_button_callback);
glfwMakeContextCurrent(glfw_window);
glewExperimental = true;
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
return;
}
glfwSetInputMode(glfw_window, GLFW_STICKY_KEYS, GL_TRUE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
GLuint program_ID = LoadShaders("shaders/SimpleVertexShader.glsl", "shaders/SimpleFragmentShader.glsl");
glUseProgram(program_ID);
// glm::mat4 projection = glm::mat4(1.0f);
glm::mat4 projection = glm::ortho(0.0f, (float)this->width, (float)this->height, 0.0f, -1.0f, 1.0f);
GLint projection_loc = glGetUniformLocation(program_ID, "projection");
glUniformMatrix4fv(projection_loc, 1, GL_FALSE, &projection[0][0]);
this->glfw_window = glfw_window;
this->shader_program_id = shader_program_id;
};
void Window::run(){
std::vector<Widget*>::iterator it;
for(it = this->widgets.begin(); it != this->widgets.end(); it++){
(*it)->drawSetup();
}
do{
this->update();
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glUseProgram(this->shader_program_id);
this->draw();
// Swap buffers
glfwSwapBuffers(this->glfw_window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while( glfwGetKey(this->glfw_window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
glfwWindowShouldClose(this->glfw_window) == 0 );
}
void Window::draw(){
std::vector<Widget*>::iterator it;
for(it = this->widgets.begin(); it != this->widgets.end(); it++){
(*it)->draw();
}
};
void Window::update(){
std::vector<Widget*>::iterator it;
for(it = this->widgets.begin(); it != this->widgets.end(); it++){
(*it)->update();
}
};
void Window::closeWindow(){
this->stay_open = false;
};
|
// Copyright 2014, Yahoo! Inc.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "yahoo/cnet/android/response_completion_adapter.h"
// Generated headers
#include "jni/ResponseCompletion_jni.h"
namespace cnet {
namespace android {
bool ResponseCompletionRegisterJni(JNIEnv* j_env) {
// Register the generated JNI methods.
return RegisterNativesImpl(j_env);
}
jboolean InvokeFetcherResponseCompletion(JNIEnv* j_env, jobject j_completion,
jobject j_fetcher, jobject j_response) {
return Java_ResponseCompletion_onBackgroundComplete(j_env, j_completion,
j_fetcher, j_response);
}
} // namespace android
} // namespace cnet
|
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// 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.
//
// @@@ END COPYRIGHT @@@
********************************************************************/
//
// MODULE: SrvrOther.cpp
//
// PURPOSE: Implements the following methods
// odbc_SQLSvc_Prepare_sme_
// odbc_SQLSvc_ExecuteN_sme_
// odbc_SQLSvc_Close_sme_
// odbc_SQLSvc_FetchN_sme_
// odbc_SQLSvc_EndTransaction_sme_
// odbc_SQLSvc_ExecuteCall_sme_
//
#include <platform_ndcs.h>
#include <platform_utils.h>
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <string>
// Used to disable and enable dumps via setrlimit in a release env.
#ifndef _DEBUG
#include <sys/resource.h>
#endif
#include <sql.h>
#include <sqlext.h>
#include "odbcCommon.h"
#include "odbc_sv.h"
#include "srvrcommon.h"
#include "sqlinterface.h"
#include "srvrkds.h"
#include "SQLWrapper.h"
#include "CommonDiags.h"
#include "tdm_odbcSrvrMsg.h"
#include "ResStatistics.h"
#include "ResStatisticsSession.h"
#include "ResStatisticsStatement.h"
#include "NskUtil.h"
// reserved names for seabase metadata where SQL table information is kept
#ifndef SEABASE_MD_SCHEMA
#define SEABASE_MD_SCHEMA "\"_MD_\""
#define SEABASE_MD_CATALOG "TRAFODION"
#define SEABASE_COLUMNS "COLUMNS"
#define SEABASE_DEFAULTS "DEFAULTS"
#define SEABASE_INDEXES "INDEXES"
#define SEABASE_KEYS "KEYS"
#define SEABASE_OBJECTS "OBJECTS"
#define SEABASE_OBJECTUID "OBJECTUID"
#define SEABASE_TABLES "TABLES"
#define SEABASE_VIEWS "VIEWS"
#define SEABASE_VIEWS_USAGE "VIEWS_USAGE"
#define SEABASE_VERSIONS "VERSIONS"
#endif
//#include "zmxocfg.h" //aruna
#include <dlfcn.h>
#include "sqlcli.h"
#include "TransportBase.h"
// #ifdef _TMP_SQ_SECURITY
#include "secsrvrmxo.h"
#include "dbUserAuth.h"
// #endif
#define SQL_API_TBLSYNONYM 1917
#define SQL_API_TBLMVS 1918
using namespace SRVR;
bool rePrepare2WouldLikeToExecute(Long stmtHandle
, Int32 *returnCode
, Int32 *sqlWarningOrErrorLength
, char *&sqlWarningOrError);
short qrysrvcExecuteFinished(
const char *stmtLabel
, const Long stmtHandle
, const bool bCheckSqlQueryType
, const short error_code
, const bool bFetch
, const bool bException
, const bool bErase);
void AllocateAdaptiveSegment(SRVR_STMT_HDL *pSrvrStmt);
void DeallocateAdaptiveSegment(SRVR_STMT_HDL *pSrvrStmt);
void ClearAdaptiveSegment(short adapiveSeg = -1);
static void setAuthenticationError(
bool & bSQLMessageSet,
odbc_SQLSvc_SQLError * SQLError,
const char * externalUsername,
bool isInternalError);
// Internal calls - Defined in libcli.so
int SQL_EXEC_AssignParserFlagsForExSqlComp_Internal( /*IN*/ unsigned int flagbits);
int SQL_EXEC_GetParserFlagsForExSqlComp_Internal( /*IN*/ unsigned int &flagbits);
void SQL_EXEC_SetParserFlagsForExSqlComp_Internal( /*IN*/ unsigned int flagbits);
#define INTERNAL_QUERY_FROM_EXEUTIL 0x20000
//#define SRVR_PERFORMANCE
SMD_SELECT_TABLE SQLCommitStmt[] = {
{ STRING_TYPE, "COMMIT WORK"},
{ END_OF_TABLE}
};
SMD_SELECT_TABLE SQLRollbackStmt[] = {
{ STRING_TYPE, "ROLLBACK WORK"},
{ END_OF_TABLE}
};
SMD_QUERY_TABLE tranQueryTable[] = {
{"SQL_COMMIT", SQLCommitStmt, TYPE_UNKNOWN, FALSE, FALSE},
{"SQL_ROLLBACK", SQLRollbackStmt, TYPE_UNKNOWN, FALSE, FALSE},
{NULL}
};
#define SQL_API_JDBC 9999
#define SQL_API_SQLTABLES_JDBC SQL_API_SQLTABLES + SQL_API_JDBC
#define SQL_API_SQLGETTYPEINFO_JDBC SQL_API_SQLGETTYPEINFO + SQL_API_JDBC
#define SQL_API_SQLCOLUMNS_JDBC SQL_API_SQLCOLUMNS + SQL_API_JDBC
#define SQL_API_SQLSPECIALCOLUMNS_JDBC SQL_API_SQLSPECIALCOLUMNS + SQL_API_JDBC
#define SQL_API_SQLPROCEDURES_JDBC SQL_API_SQLPROCEDURES + SQL_API_JDBC
#define SQL_API_SQLPROCEDURECOLUMNS_JDBC SQL_API_SQLPROCEDURECOLUMNS + SQL_API_JDBC
// The value represents SQL version, MXCS module major version and MXCS module minor version.
#define MODULE_RELEASE_VERSION 200
#define MODULE_MAJOR_VERSION 400
#define MODULE_MINOR_VERSION 000
#define SQL_INVALID_USER_CODE -8837
// ResStatistics
ResStatisticsSession *resStatSession;
ResStatisticsStatement *resStatStatement;
BOOL resStatCollectorError = false;
struct collect_info setinit;
Int32 inState = STMTSTAT_NONE;
short inSqlStmtType = TYPE_UNKNOWN;
double inEstimatedCost = 0;
char *inQueryId = NULL;
char *inSqlString = NULL;
Int32 inErrorStatement = 0;
Int32 inWarningStatement = 0;
int64 inRowCount = 0;
Int32 inErrorCode = 0;
Int32 inSqlQueryType = 0;
Int32 inSqlNewQueryType = 0;
char *inSqlError = NULL;
Int32 inSqlErrorLength = 0;
bool setStatisticsFlag = FALSE;
// end ResStatistics
char b[317];
bool securitySetup = false;
//char QueryQueue[1024];
//int64 queryId;
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_Prepare'
*/
extern "C" void
odbc_SQLSvc_Prepare_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_Prepare_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ const IDL_char *stmtLabel
, /* In */ const IDL_char *stmtExplainLabel
, /* In */ IDL_short stmtType
, /* In */ IDL_string sqlString
, /* In */ IDL_short sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* Out */ Int32 *estimatedCost
, /* Out */ SQLItemDescList_def *inputDesc
, /* Out */ SQLItemDescList_def *outputDesc
, /* Out */ ERROR_DESC_LIST_def *sqlWarning)
{
SRVRTRACE_ENTER(FILE_SME+1)
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQL_QUERY_COST_INFO cost_info;
SQL_QUERY_COMPILER_STATS_INFO comp_stats_info;
SQLRETURN rc = PROGRAM_ERROR;
Int32 holdestimatedCost;
bool flag_21036 = false;
if (sqlString == NULL)
{
exception_->exception_nr = odbc_SQLSvc_Prepare_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_NULL_SQL_STMT;
}
// resource statistics
if (resStatStatement != NULL && stmtType == EXTERNAL_STMT)
{
inState = STMTSTAT_PREPARE;
inSqlStmtType = TYPE_UNKNOWN;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlQueryType = SQL_UNKNOWN;
inSqlNewQueryType = SQL_UNKNOWN;
inSqlError = NULL;
inSqlErrorLength = 0;
bzero(&cost_info, sizeof(cost_info));
resStatStatement->start(inState,
inSqlQueryType,
stmtLabel,
NULL,
inEstimatedCost,
&flag_21036,
sqlString);
}
if (exception_->exception_nr == 0)
{
if (stmtType != TYPE_SMD)
{
if ((pSrvrStmt = getSrvrStmt(stmtLabel, FALSE)) != NULL)
{
pSrvrStmt->cleanupAll();
pSrvrStmt->currentMethod = odbc_SQLSvc_Close_ldx_;
pSrvrStmt->freeResourceOpt = SQL_DROP;
FREESTATEMENT(pSrvrStmt);
}
// Need to validate the stmtLabel
// Given a label find out the SRVR_STMT_HDL
if ((pSrvrStmt = getSrvrStmt(stmtLabel, TRUE)) == NULL)
{
exception_->exception_nr = odbc_SQLSvc_Prepare_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
if (exception_->exception_nr == 0)
{
if (resStatStatement != NULL && stmtType == EXTERNAL_STMT)
pSrvrStmt->inState = inState;
rc = SQL_SUCCESS;
if (!pSrvrStmt->isReadFromModule)
{
// cleanup all memory allocated in the previous operations
pSrvrStmt->cleanupAll();
pSrvrStmt->sqlStringLen = strlen(sqlString);
pSrvrStmt->sqlString = new char[pSrvrStmt->sqlStringLen+1];
if (pSrvrStmt->sqlString == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "Prepare");
exit(0);
}
strcpy(pSrvrStmt->sqlString, sqlString);
pSrvrStmt->stmtType = stmtType;
pSrvrStmt->currentMethod = odbc_SQLSvc_Prepare_ldx_;
rc = PREPARE(pSrvrStmt);
switch (rc)
{
case SQL_SUCCESS:
break;
case SQL_SUCCESS_WITH_INFO:
GETSQLWARNING(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlWarning);
break;
case SQL_ERROR:
GETSQLERROR(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError);
break;
case ODBC_RG_WARNING:
// if there is RG_WARNING, we don't pass SQL Warning to the application
// Hence, we need to clear any warnings
// call SQL_EXEC_ClearDiagnostics
// CLEARDIAGNOSTICS(pSrvrStmt);
rc = SQL_SUCCESS_WITH_INFO;
case ODBC_SERVER_ERROR:
case ODBC_RG_ERROR:
default:
break;
}
}
}
}
/* else // added for user module support
{
char *sqltoken;
char sqlseps[] = " \t\n{(";
int ch = '.';
int TknLen = 0;
int SStrLen = 0;
char VariableValue[1000];
VariableValue[0] = '\0';
strcpy(VariableValue,sqlString);
sqltoken = strtok(VariableValue, sqlseps);
if (_stricmp(sqltoken, "SMD") == 0)
{
sqltoken = strtok(NULL, sqlseps);
if (sqltoken != NULL)
{
UserModuleName[0] = '\0';
UserStatementName[0] = '\0';
TknLen = strrchr(sqltoken, ch) - sqltoken + 1;
SStrLen = strlen(sqltoken);
strncpy(UserModuleName,sqltoken, TknLen-1);
UserModuleName[TknLen-1] = '\0';
strncpy(UserStatementName,sqltoken + TknLen, SStrLen);
UserStatementName[SStrLen-TknLen+1] = '\0';
// Need to validate the stmtLabel
// Given a label find out the SRVR_STMT_HDL
pSrvrStmt = getSrvrStmt(UserStatementName, TRUE);
strcpy(pSrvrStmt->stmtName, UserStatementName);
strcpy(pSrvrStmt->cursorName, UserStatementName);
pSrvrStmt->stmtType = stmtType;
user_module.module_name = UserModuleName;
user_module.module_name_len = strlen(UserModuleName);
user_module.charset = "ISO88591";
user_module.creation_timestamp = 1234567890;
rc = pSrvrStmt->PrepareUserModule();
}
else
{
// Return Error Invalid Module Name.
}
sqltoken = strtok(NULL, sqlseps);
if (sqltoken != NULL)
{
// Return Error Invalid Module Name.
}
}
else
{
// Return Error Invalid Call.
}
}
*/
if (exception_->exception_nr == 0)
{
switch (rc)
{
case SQL_SUCCESS:
case SQL_SUCCESS_WITH_INFO:
exception_->exception_nr = 0;
// Copy all the output parameters
// Vijay - Changes to support not to parse tokens for statement type SELECT
holdestimatedCost = (Int32)pSrvrStmt->cost_info.totalTime; // SQL returns cost in a strcuture - cost.totalTime
if ((pSrvrStmt->sqlQueryType == SQL_SELECT_NON_UNIQUE) || (pSrvrStmt->sqlQueryType == SQL_SELECT_UNIQUE))
pSrvrStmt->sqlStmtType = TYPE_SELECT;
*estimatedCost = pSrvrStmt->sqlQueryType;
inputDesc->_length = pSrvrStmt->inputDescList._length;
inputDesc->_buffer = pSrvrStmt->inputDescList._buffer;
outputDesc->_length = pSrvrStmt->outputDescList._length;
outputDesc->_buffer = pSrvrStmt->outputDescList._buffer;
sqlWarning->_length = pSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = pSrvrStmt->sqlWarning._buffer;
break;
case SQL_STILL_EXECUTING:
exception_->exception_nr = odbc_SQLSvc_Prepare_SQLStillExecuting_exn_;
break;
case ODBC_RG_ERROR:
case SQL_ERROR:
ERROR_DESC_def *error_desc_def;
error_desc_def = pSrvrStmt->sqlError.errorList._buffer;
if (pSrvrStmt->sqlError.errorList._length != 0 && error_desc_def->sqlcode == -8007)
{
exception_->exception_nr = odbc_SQLSvc_Prepare_SQLQueryCancelled_exn_;
exception_->u.SQLQueryCancelled.sqlcode = error_desc_def->sqlcode;
}
else
{
exception_->exception_nr = odbc_SQLSvc_Prepare_SQLError_exn_;
exception_->u.SQLError.errorList._length = pSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = pSrvrStmt->sqlError.errorList._buffer;
}
break;
case PROGRAM_ERROR:
exception_->exception_nr = odbc_SQLSvc_Prepare_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_PREPARE_FAILED;
default:
break;
}
}
}
// resource statistics
if (resStatStatement != NULL && stmtType == EXTERNAL_STMT)
{
if (exception_->exception_nr != 0 && exception_->u.SQLError.errorList._buffer != NULL)
{
inErrorStatement ++;
ERROR_DESC_def *p_buffer = exception_->u.SQLError.errorList._buffer;
inErrorCode = p_buffer->sqlcode;
inSqlError = p_buffer->errorText;
inSqlErrorLength = strlen(p_buffer->errorText);
}
if (sqlWarning->_length != 0)
inWarningStatement ++;
if (sqlString == NULL)
sqlString = "";
inSqlString = new char[strlen(sqlString) + 1];
if (inSqlString == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "inSqlString");
exit(0);
}
strcpy(inSqlString,sqlString);
if (pSrvrStmt != NULL)
{
inEstimatedCost = pSrvrStmt->cost_info.totalTime; // res stat reports estimated cost as double
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
inSqlNewQueryType = pSrvrStmt->sqlNewQueryType;
}
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&flag_21036,
inSqlNewQueryType);
delete inSqlString;
}
//end rs
pSrvrStmt->m_need_21036_end_msg = flag_21036;
SRVRTRACE_EXIT(FILE_SME+1);
return;
}
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_ExecuteN'
*/
extern "C" void
odbc_SQLSvc_ExecuteN_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_ExecuteN_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ const IDL_char *stmtLabel
, /* In */ IDL_string cursorName
, /* In */ IDL_short sqlStmtType
, /* In */ Int32 inputRowCnt
, /* In */ const SQLValueList_def *inputValueList
, /* In */ IDL_short sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* Out */ Int32 *rowsAffected
, /* Out */ ERROR_DESC_LIST_def *sqlWarning)
{
SRVRTRACE_ENTER(FILE_SME+2);
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQLRETURN rc = SQL_SUCCESS;
bool bWMAutoCommitOff = false;
if (inputRowCnt < 0)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_ROW_COUNT;
}
else
{
if (sqlStmtType == TYPE_SELECT && inputRowCnt > 1)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_ROW_COUNT_AND_SELECT;
}
else
{
if ((pSrvrStmt = getSrvrStmt(stmtLabel, FALSE)) == NULL)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
}
}
if (exception_->exception_nr == 0)
{
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->inState = inState = STMTSTAT_EXECUTE;
inSqlStmtType = sqlStmtType;
inEstimatedCost = pSrvrStmt->cost_info.totalTime;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlError = NULL;
inSqlErrorLength = 0;
/*resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt->sqlUniqueQueryID,
pSrvrStmt->cost_info,
pSrvrStmt->comp_stats_info,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg,
false,
pSrvrStmt->sqlString); */
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlString);
}
//end rs
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if(pSrvrStmt->bSQLValueListSet)
pSrvrStmt->cleanupSQLValueList();
pSrvrStmt->inputRowCnt = inputRowCnt;
pSrvrStmt->sqlStmtType = sqlStmtType;
if (cursorName != NULL && cursorName[0] != '\0')
{
pSrvrStmt->cursorNameLen = strlen(cursorName);
pSrvrStmt->cursorNameLen = pSrvrStmt->cursorNameLen < sizeof(pSrvrStmt->cursorName)? pSrvrStmt->cursorNameLen : sizeof(pSrvrStmt->cursorName);
strncpy(pSrvrStmt->cursorName, cursorName, sizeof(pSrvrStmt->cursorName));
pSrvrStmt->cursorName[sizeof(pSrvrStmt->cursorName)-1] = 0;
}
else
pSrvrStmt->cursorName[0] = '\0';
pSrvrStmt->inputValueList._buffer = inputValueList->_buffer;
pSrvrStmt->inputValueList._length = inputValueList->_length;
pSrvrStmt->currentMethod = odbc_SQLSvc_ExecuteN_ldx_;
// batch job support for T4
// Fix for transaction issue 20/09/06
if ((WSQL_EXEC_Xact(SQLTRANS_STATUS,NULL) != 0) && srvrGlobal->bAutoCommitOn == TRUE && sqlStmtType != TYPE_SELECT)
{
bWMAutoCommitOff = true;
SRVR_STMT_HDL *TranOffSrvrStmt;
if ((TranOffSrvrStmt = getSrvrStmt("STMT_TRANS_OFF_1", FALSE)) == NULL)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
else
{
SQLValueList_def *inValueList;
markNewOperator,inValueList = new SQLValueList_def();
if (inValueList == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "odbc_SQLSvc_ExecuteN_sme_");
exit(0);
}
inValueList->_buffer = NULL;
inValueList->_length = 0;
rc = TranOffSrvrStmt->Execute(NULL,1,TYPE_UNKNOWN,inValueList,SQL_ASYNC_ENABLE_OFF,0);
if (rc == SQL_ERROR)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_SQLError_exn_;
exception_->u.SQLError.errorList._length = TranOffSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = TranOffSrvrStmt->sqlError.errorList._buffer;
}
else if (rc != SQL_SUCCESS)
{
exception_->exception_nr = 0;
sqlWarning->_length = TranOffSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = TranOffSrvrStmt->sqlWarning._buffer;
}
delete inValueList;
}
}
if (exception_->exception_nr == 0)
{
rc = EXECUTE(pSrvrStmt);
switch (rc)
{
case ODBC_RG_WARNING:
// if there is RG_WARNING, we don't pass SQL Warning to the application
// Hence, we need to clear any warnings
// call SQL_EXEC_ClearDiagnostics
// CLEARDIAGNOSTICS(pSrvrStmt);
rc = SQL_SUCCESS_WITH_INFO;
case SQL_SUCCESS_WITH_INFO:
GETSQLWARNING(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlWarning);
case SQL_SUCCESS:
exception_->exception_nr = 0;
// Copy the output values
*rowsAffected = pSrvrStmt->rowsAffected;
sqlWarning->_length = pSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = pSrvrStmt->sqlWarning._buffer;
break;
case SQL_STILL_EXECUTING:
exception_->exception_nr = odbc_SQLSvc_ExecuteN_SQLStillExecuting_exn_;
break;
case SQL_INVALID_HANDLE:
exception_->exception_nr = odbc_SQLSvc_ExecuteN_SQLInvalidHandle_exn_;
break;
case SQL_NEED_DATA:
exception_->exception_nr = odbc_SQLSvc_ExecuteN_SQLNeedData_exn_;
break;
case SQL_ERROR:
GETSQLERROR(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError);
case ODBC_SERVER_ERROR:
if (rc == ODBC_SERVER_ERROR)
{
// Allocate Error Desc
kdsCreateSQLErrorException(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError, 1);
// Add SQL Error
kdsCopySQLErrorException(&pSrvrStmt->sqlError, NULL_VALUE_ERROR, NULL_VALUE_ERROR_SQLCODE,
NULL_VALUE_ERROR_SQLSTATE);
}
ERROR_DESC_def *error_desc_def;
error_desc_def = pSrvrStmt->sqlError.errorList._buffer;
if (pSrvrStmt->sqlError.errorList._length != 0 && error_desc_def->sqlcode == -8007)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_SQLQueryCancelled_exn_;
exception_->u.SQLQueryCancelled.sqlcode = error_desc_def->sqlcode;
}
else
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_SQLError_exn_;
exception_->u.SQLError.errorList._length = pSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = pSrvrStmt->sqlError.errorList._buffer;
}
break;
case -8814:
case 8814:
rc = SQL_RETRY_COMPILE_AGAIN;
exception_->exception_nr = odbc_SQLSvc_ExecuteN_SQLRetryCompile_exn_;
break;
case PROGRAM_ERROR:
exception_->exception_nr = odbc_SQLSvc_ExecuteN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECUTE_FAILED;
default:
break;
}
if (resStatStatement != NULL)
{
resStatStatement->setStatistics(pSrvrStmt);
}
// batch job support for T4
// Fix for transaction issue 20/09/06
if ( bWMAutoCommitOff )
{
SQLValueList_def *inValueList;
markNewOperator,inValueList = new SQLValueList_def();
if (inValueList == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "odbc_SQLSvc_ExecuteN_sme_");
exit(0);
}
inValueList->_buffer = NULL;
inValueList->_length = 0;
if(WSQL_EXEC_Xact(SQLTRANS_STATUS,NULL) == 0)
{
SRVR_STMT_HDL *RbwSrvrStmt;
SRVR_STMT_HDL *CmwSrvrStmt;
if (exception_->exception_nr != 0)
{
RbwSrvrStmt = getSrvrStmt("STMT_ROLLBACK_1", FALSE);
rc = RbwSrvrStmt->Execute(NULL,1,TYPE_UNKNOWN,inValueList,SQL_ASYNC_ENABLE_OFF,0);
}
else
{
CmwSrvrStmt = getSrvrStmt("STMT_COMMIT_1", FALSE);
rc = CmwSrvrStmt->Execute(NULL,1,TYPE_UNKNOWN,inValueList,SQL_ASYNC_ENABLE_OFF,0);
if (rc == SQL_ERROR)
{
ERROR_DESC_def *error_desc_def = CmwSrvrStmt->sqlError.errorList._buffer;
if (CmwSrvrStmt->sqlError.errorList._length != 0 )
{
if(error_desc_def->sqlcode != -8605 )
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_ParamError_exn_;
if (CEE_TMP_ALLOCATE(call_id_, 50, (void **)&(exception_->u.ParamError.ParamDesc)) == CEE_SUCCESS)
sprintf(exception_->u.ParamError.ParamDesc, "%s (%d)",SQLSVC_EXCEPTION_EXECUTE_FAILED, error_desc_def->sqlcode);
else
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECUTE_FAILED;
}
else
rc = SQL_SUCCESS;
}
else
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECUTE_FAILED;
}
}
else if (rc != SQL_SUCCESS)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECUTE_FAILED;
}
}
}
// reset back to original setting
SRVR_STMT_HDL *TranOnSrvrStmt;
if ((TranOnSrvrStmt = getSrvrStmt("STMT_TRANS_ON_1", FALSE)) == NULL)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
rc = TranOnSrvrStmt->Execute(NULL,1,TYPE_UNKNOWN,inValueList,SQL_ASYNC_ENABLE_OFF,0);
if (rc == SQL_ERROR)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteN_SQLError_exn_;
exception_->u.SQLError.errorList._length = TranOnSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = TranOnSrvrStmt->sqlError.errorList._buffer;
}
else if (rc != SQL_SUCCESS)
{
exception_->exception_nr = 0;
sqlWarning->_length = TranOnSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = TranOnSrvrStmt->sqlWarning._buffer;
}
delete inValueList;
}
}
}
// resource statistics
if (resStatStatement != NULL && pSrvrStmt != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
if (exception_->exception_nr != 0 && exception_->u.SQLError.errorList._buffer != NULL)
{
inErrorStatement ++;
ERROR_DESC_def *p_buffer = exception_->u.SQLError.errorList._buffer;
inErrorCode = p_buffer->sqlcode;
inSqlError = p_buffer->errorText;
inSqlErrorLength = strlen(p_buffer->errorText);
}
if (sqlWarning->_length != 0)
inWarningStatement ++;
inRowCount = *rowsAffected;
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlNewQueryType,
pSrvrStmt->isClosed);
}
//end rs
SRVRTRACE_EXIT(FILE_SME+2);
return;
}
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_Prepare2'
*/
extern "C" void
odbc_SQLSvc_Prepare2_sme_(
/* In */ Int32 inputRowCnt
, /* In */ Int32 sqlStmtType
, /* In */ const IDL_char *stmtLabel
, /* In */ IDL_string sqlString
, /* In */ Int32 holdableCursor
, /* Out */ Int32 *returnCode
, /* Out */ Int32 *sqlWarningOrErrorLength
, /* Out */ BYTE *&sqlWarningOrError
, /* Out */ Int32 *sqlQueryType
, /* Out */ Long *stmtHandle
, /* Out */ Int32 *estimatedCost
, /* Out */ Int32 *inputDescLength
, /* Out */ BYTE *&inputDesc
, /* Out */ Int32 *outputDescLength
, /* Out */ BYTE *&outputDesc
, /* In */ bool isFromExecDirect = false)
{
SRVRTRACE_ENTER(FILE_SME+18);
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQL_QUERY_COST_INFO cost_info;
SQL_QUERY_COMPILER_STATS_INFO comp_stats_info;
SQLRETURN rc = SQL_SUCCESS;
bool bSkipWouldLikeToExecute = false; // some queries have to skip Would Like To Execute
bool flag_21036 = false;
if (sqlString == NULL)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY090", "Invalid SQL String.", sqlWarningOrErrorLength, sqlWarningOrError);
}
else
{
// resource statistics
if (resStatStatement != NULL)
{
inState = STMTSTAT_PREPARE;
inSqlStmtType = TYPE_UNKNOWN;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlQueryType = SQL_UNKNOWN;
inSqlNewQueryType = SQL_UNKNOWN;
inSqlError = NULL;
inSqlErrorLength = 0;
bzero(&cost_info, sizeof(cost_info));
resStatStatement->start(inState,
inSqlQueryType,
stmtLabel,
NULL,
inEstimatedCost,
&flag_21036,
sqlString);
}
if ((pSrvrStmt = getSrvrStmt(stmtLabel, FALSE)) != NULL)
{
bSkipWouldLikeToExecute = pSrvrStmt->m_bSkipWouldLikeToExecute;
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if(pSrvrStmt->bSQLValueListSet)
pSrvrStmt->cleanupSQLValueList();
pSrvrStmt->currentMethod = odbc_SQLSvc_Close_ldx_;
pSrvrStmt->freeResourceOpt = SQL_DROP;
FREESTATEMENT(pSrvrStmt);
}
// Need to validate the stmtLabel
// Given a label find out the SRVR_STMT_HDL
if ((pSrvrStmt = getSrvrStmt(stmtLabel, TRUE)) == NULL)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Statement Label could not be allocated.", sqlWarningOrErrorLength, sqlWarningOrError);
}
}
if (*returnCode == 0)
{
pSrvrStmt->m_bSkipWouldLikeToExecute = bSkipWouldLikeToExecute;
*stmtHandle = (Long)pSrvrStmt;
// cleanup all memory allocated in the previous operations
pSrvrStmt->cleanupAll();
if (resStatStatement != NULL)
pSrvrStmt->inState = inState;
pSrvrStmt->sqlStringLen = strlen(sqlString) + 1;
pSrvrStmt->sqlString = new char[pSrvrStmt->sqlStringLen];
if (pSrvrStmt->sqlString == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "Prepare2");
exit(0);
}
strncpy(pSrvrStmt->sqlString, sqlString, pSrvrStmt->sqlStringLen);
pSrvrStmt->sqlStmtType = (short)sqlStmtType;
pSrvrStmt->maxRowsetSize = inputRowCnt;
if (pSrvrStmt->maxRowsetSize == ROWSET_NOT_DEFINED) pSrvrStmt->maxRowsetSize = DEFAULT_ROWSET_SIZE;
if (srvrGlobal->srvrType == CORE_SRVR)
AllocateAdaptiveSegment(pSrvrStmt);
pSrvrStmt->currentMethod = odbc_SQLSvc_PrepareRowset_ldx_;
pSrvrStmt->holdableCursor = holdableCursor;
rc = PREPARE2(pSrvrStmt,isFromExecDirect);
if (srvrGlobal->srvrType == CORE_SRVR && rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
DeallocateAdaptiveSegment(pSrvrStmt);
switch (rc)
{
case ODBC_RG_WARNING:
case SQL_SHAPE_WARNING:
case SQL_SUCCESS_WITH_INFO:
*returnCode = SQL_SUCCESS_WITH_INFO;
*estimatedCost = (Int32)pSrvrStmt->cost_info.totalTime; // SQL returns cost in a strcuture - cost.totalTime == estimatedCost
*sqlQueryType = pSrvrStmt->sqlQueryType;
*inputDescLength = pSrvrStmt->inputDescBufferLength;
inputDesc = pSrvrStmt->inputDescBuffer;
*outputDescLength = pSrvrStmt->outputDescBufferLength;
outputDesc = pSrvrStmt->outputDescBuffer;
if (rc == SQL_SUCCESS_WITH_INFO)
{
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
else if (rc == SQL_SHAPE_WARNING)
{
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
else
{
char *RGWarningOrError;
RGWarningOrError = new char[256];
sprintf(b,"%lf",pSrvrStmt->cost_info.totalTime);
sprintf(RGWarningOrError, "The query's estimated cost: %.50s exceeded resource management attribute limit set.", b);
GETMXCSWARNINGORERROR(1, "01000", RGWarningOrError, sqlWarningOrErrorLength, sqlWarningOrError);
delete RGWarningOrError;
}
break;
case SQL_SUCCESS:
*estimatedCost = (Int32)pSrvrStmt->cost_info.totalTime; // SQL returns cost in a strcuture - cost.totalTime == estimatedCost
*sqlQueryType = pSrvrStmt->sqlQueryType;
*inputDescLength = pSrvrStmt->inputDescBufferLength;
inputDesc = pSrvrStmt->inputDescBuffer;
*outputDescLength = pSrvrStmt->outputDescBufferLength;
outputDesc = pSrvrStmt->outputDescBuffer;
break;
case SQL_ERROR:
case ODBC_RG_ERROR:
*returnCode = SQL_ERROR;
if (rc == SQL_ERROR)
{
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
else
{
char *RGWarningOrError;
RGWarningOrError = new char[256];
sprintf(b,"%lf",pSrvrStmt->cost_info.totalTime);
sprintf(RGWarningOrError, "The query's estimated cost: %.50s exceeded resource management attribute limit set.", b);
GETMXCSWARNINGORERROR(-1, "HY000", RGWarningOrError, sqlWarningOrErrorLength, sqlWarningOrError);
delete RGWarningOrError;
}
break;
case PROGRAM_ERROR:
GETMXCSWARNINGORERROR(-1, "HY000", SQLSVC_EXCEPTION_PREPARE_FAILED, sqlWarningOrErrorLength, sqlWarningOrError);
break;
case INFOSTATS_SYNTAX_ERROR:
case INFOSTATS_STMT_NOT_FOUND:
*returnCode = SQL_ERROR;
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
break;
default:
break;
}
}
// resource statistics
if (resStatStatement != NULL)
{
if (*returnCode == SQL_ERROR && pSrvrStmt != NULL && pSrvrStmt->sqlWarningOrError != NULL)
{
inErrorCode = *(Int32 *)(pSrvrStmt->sqlWarningOrError+8);
inErrorStatement ++;
inSqlError = (char*)pSrvrStmt->sqlWarningOrError + 16;
inSqlErrorLength =*(Int32 *)(pSrvrStmt->sqlWarningOrError + 12);
}
if (*returnCode == SQL_SUCCESS_WITH_INFO)
inWarningStatement ++;
if (sqlString == NULL)
sqlString = "";
if (pSrvrStmt != NULL)
{
inSqlString = new char[pSrvrStmt->sqlStringLen];
if (inSqlString == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "inSqlString");
exit(0);
}
strncpy(inSqlString,sqlString,pSrvrStmt->sqlStringLen);
inEstimatedCost = pSrvrStmt->cost_info.totalTime; // res stat reports estimated cost as double
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
inSqlNewQueryType = pSrvrStmt->sqlNewQueryType;
}
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&flag_21036,
inSqlNewQueryType);
if(inSqlString != NULL)
delete inSqlString;
}
//end rs
if(pSrvrStmt != NULL)
pSrvrStmt->m_need_21036_end_msg = flag_21036;
SRVRTRACE_EXIT(FILE_SME+18);
return;
}
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_Prepare2withRowsets'
*/
extern "C" void
odbc_SQLSvc_Prepare2withRowsets_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ Int32 sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* In */ Int32 inputRowCnt
, /* In */ Int32 sqlStmtType
, /* In */ Int32 stmtLength
, /* In */ const IDL_char *stmtLabel
, /* In */ Int32 stmtLabelCharset
, /* In */ Int32 cursorLength
, /* In */ IDL_string cursorName
, /* In */ Int32 cursorCharset
, /* In */ Int32 moduleNameLength
, /* In */ const IDL_char *moduleName
, /* In */ Int32 moduleCharset
, /* In */ int64 moduleTimestamp
, /* In */ Int32 sqlStringLength
, /* In */ IDL_string sqlString
, /* In */ Int32 sqlStringCharset
, /* In */ Int32 setStmtOptionsLength
, /* In */ IDL_string setStmtOptions
, /* In */ Int32 holdableCursor
, /* Out */ Int32 *returnCode
, /* Out */ Int32 *sqlWarningOrErrorLength
, /* Out */ BYTE *&sqlWarningOrError
, /* Out */ Int32 *sqlQueryType
, /* Out */ Long *stmtHandle
, /* Out */ Int32 *estimatedCost
, /* Out */ Int32 *inputDescLength
, /* Out */ BYTE *&inputDesc
, /* Out */ Int32 *outputDescLength
, /* Out */ BYTE *&outputDesc)
{
SRVRTRACE_ENTER(FILE_SME+18);
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQL_QUERY_COST_INFO cost_info;
SQL_QUERY_COMPILER_STATS_INFO comp_stats_info;
SQLRETURN rc = SQL_SUCCESS;
bool flag_21036 = false;
if (sqlString == NULL)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY090", "Invalid SQL String.", sqlWarningOrErrorLength, sqlWarningOrError);
}
else
{
// resource statistics
if (resStatStatement != NULL)
{
inState = STMTSTAT_PREPARE;
inSqlStmtType = TYPE_UNKNOWN;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlQueryType = SQL_UNKNOWN;
inSqlNewQueryType = SQL_UNKNOWN;
inSqlError = NULL;
inSqlErrorLength = 0;
bzero(&cost_info, sizeof(cost_info));
resStatStatement->start(inState,
inSqlQueryType,
stmtLabel,
NULL,
inEstimatedCost,
&flag_21036,
sqlString);
}
if ((pSrvrStmt = getSrvrStmt(stmtLabel, FALSE)) != NULL)
{
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if(pSrvrStmt->bSQLValueListSet)
pSrvrStmt->cleanupSQLValueList();
pSrvrStmt->currentMethod = odbc_SQLSvc_Close_ldx_;
pSrvrStmt->freeResourceOpt = SQL_DROP;
FREESTATEMENT(pSrvrStmt);
}
// Need to validate the stmtLabel
// Given a label find out the SRVR_STMT_HDL
if ((pSrvrStmt = getSrvrStmt(stmtLabel, TRUE)) == NULL)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Statement Label not found.", sqlWarningOrErrorLength, sqlWarningOrError);
}
}
if (*returnCode == 0)
{
*stmtHandle = (Long)pSrvrStmt;
// cleanup all memory allocated in the previous operations
pSrvrStmt->cleanupAll();
if (resStatStatement != NULL)
pSrvrStmt->inState = inState;
pSrvrStmt->sqlStringLen = sqlStringLength;
pSrvrStmt->sqlString = new char[sqlStringLength];
if (pSrvrStmt->sqlString == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "Prepare2");
exit(0);
}
strncpy(pSrvrStmt->sqlString, sqlString, sqlStringLength);
pSrvrStmt->sqlStmtType = (short)sqlStmtType;
pSrvrStmt->maxRowsetSize = inputRowCnt;
if (pSrvrStmt->maxRowsetSize == ROWSET_NOT_DEFINED) pSrvrStmt->maxRowsetSize = DEFAULT_ROWSET_SIZE;
// this part is for NAR (not Atomic Rowset Recovery)
if (pSrvrStmt->maxRowsetSize > 1
&& (pSrvrStmt->sqlStmtType == TYPE_INSERT_PARAM))
// || pSrvrStmt->sqlStmtType == TYPE_UPDATE
// || pSrvrStmt->sqlStmtType == TYPE_DELETE))
{
if (srvrGlobal->EnvironmentType & MXO_ROWSET_ERROR_RECOVERY)
rc = WSQL_EXEC_SetStmtAttr(&pSrvrStmt->stmt, SQL_ATTR_ROWSET_ATOMICITY, SQL_NOT_ATOMIC,0);
else
rc = WSQL_EXEC_SetStmtAttr(&pSrvrStmt->stmt, SQL_ATTR_ROWSET_ATOMICITY, SQL_ATOMIC, 0);
if (rc < 0)
{
GETSQLERROR(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError);
return;
}
}
if (srvrGlobal->srvrType == CORE_SRVR)
AllocateAdaptiveSegment(pSrvrStmt);
pSrvrStmt->currentMethod = odbc_SQLSvc_PrepareRowset_ldx_;
pSrvrStmt->holdableCursor = holdableCursor;
rc = PREPARE2withRowsets(pSrvrStmt);
if (srvrGlobal->srvrType == CORE_SRVR && rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
DeallocateAdaptiveSegment(pSrvrStmt);
switch (rc)
{
case ODBC_RG_WARNING:
case SQL_SHAPE_WARNING:
case SQL_SUCCESS_WITH_INFO:
*returnCode = SQL_SUCCESS_WITH_INFO;
*estimatedCost = (Int32)pSrvrStmt->cost_info.totalTime; // SQL returns cost in a strcuture - cost.totalTime == estimatedCost
if (pSrvrStmt->sqlBulkFetchPossible && pSrvrStmt->sqlQueryType == SQL_SELECT_NON_UNIQUE)
*sqlQueryType = 10000;
else
*sqlQueryType = pSrvrStmt->sqlQueryType;
*inputDescLength = pSrvrStmt->inputDescBufferLength;
inputDesc = pSrvrStmt->inputDescBuffer;
*outputDescLength = pSrvrStmt->outputDescBufferLength;
outputDesc = pSrvrStmt->outputDescBuffer;
if (rc == SQL_SUCCESS_WITH_INFO)
{
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
else if (rc == SQL_SHAPE_WARNING)
{
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
else
{
char RGWarningOrError[256];
sprintf(b,"%lf",pSrvrStmt->cost_info.totalTime);
sprintf(RGWarningOrError, "The query's estimated cost: %.50s exceeded resource management attribute limit set.", b);
GETMXCSWARNINGORERROR(1, "01000", RGWarningOrError, sqlWarningOrErrorLength, sqlWarningOrError);
}
break;
case SQL_SUCCESS:
*estimatedCost = (Int32)pSrvrStmt->cost_info.totalTime; // SQL returns cost in a strcuture - cost.totalTime == estimatedCost
if (pSrvrStmt->sqlBulkFetchPossible && pSrvrStmt->sqlQueryType == SQL_SELECT_NON_UNIQUE)
*sqlQueryType = 10000;
else
*sqlQueryType = pSrvrStmt->sqlQueryType;
*inputDescLength = pSrvrStmt->inputDescBufferLength;
inputDesc = pSrvrStmt->inputDescBuffer;
*outputDescLength = pSrvrStmt->outputDescBufferLength;
outputDesc = pSrvrStmt->outputDescBuffer;
break;
case SQL_ERROR:
case ODBC_RG_ERROR:
*returnCode = SQL_ERROR;
if (rc == SQL_ERROR)
{
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
else
{
char *RGWarningOrError;
RGWarningOrError = new char[256];
sprintf(b,"%lf",pSrvrStmt->cost_info.totalTime);
sprintf(RGWarningOrError, "The query's estimated cost: %.50s exceeded resource management attribute limit set.", b);
GETMXCSWARNINGORERROR(-1, "HY000", RGWarningOrError, sqlWarningOrErrorLength, sqlWarningOrError);
delete RGWarningOrError;
}
break;
case PROGRAM_ERROR:
GETMXCSWARNINGORERROR(-1, "HY000", SQLSVC_EXCEPTION_PREPARE_FAILED, sqlWarningOrErrorLength, sqlWarningOrError);
break;
default:
break;
}
}
// resource statistics
if (resStatStatement != NULL)
{
if (*returnCode == SQL_ERROR && pSrvrStmt != NULL && pSrvrStmt->sqlWarningOrError != NULL)
{
inErrorCode = *(Int32 *)(pSrvrStmt->sqlWarningOrError+8);
inErrorStatement ++;
inSqlError = (char*)pSrvrStmt->sqlWarningOrError + 16;
inSqlErrorLength =*(Int32 *)(pSrvrStmt->sqlWarningOrError + 12);
}
if (*returnCode == SQL_SUCCESS_WITH_INFO)
inWarningStatement ++;
if (sqlString == NULL)
sqlString = "";
inSqlString = new char[sqlStringLength];
if (inSqlString == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "inSqlString");
exit(0);
}
strncpy(inSqlString,sqlString,sqlStringLength);
if (pSrvrStmt != NULL)
{
inEstimatedCost = pSrvrStmt->cost_info.totalTime; // res stat reports estimated cost as double
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
inSqlNewQueryType = pSrvrStmt->sqlNewQueryType;
}
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&flag_21036,
inSqlNewQueryType);
delete inSqlString;
}
//end rs
pSrvrStmt->m_need_21036_end_msg = flag_21036;
SRVRTRACE_EXIT(FILE_SME+18);
return;
} // end SQLSvc_Prepare2withRowsets_sme
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_Execute2'
*/
extern "C" void
odbc_SQLSvc_Execute2_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ Int32 sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* In */ Int32 inputRowCnt
, /* In */ Int32 sqlStmtType
, /* In */ Long stmtHandle
, /* In */ Int32 cursorLength
, /* In */ IDL_string cursorName
, /* In */ Int32 cursorCharset
, /* In */ Int32 holdableCursor
, /* In */ Int32 inValuesLength
, /* In */ BYTE *inValues
, /* Out */ Int32 *returnCode
, /* Out */ Int32 *sqlWarningOrErrorLength
, /* Out */ BYTE *&sqlWarningOrError
, /* Out */ Int32 *rowsAffected
, /* Out */ Int32 *outValuesLength
, /* Out */ BYTE *&outValues)
{
SRVRTRACE_ENTER(FILE_SME+19);
bool bRePrepare2 = false;
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQLRETURN rc = SQL_SUCCESS;
if ((pSrvrStmt = (SRVR_STMT_HDL *)stmtHandle) == NULL)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Statement Label not found.", sqlWarningOrErrorLength, sqlWarningOrError);
}
else
{
if (pSrvrStmt->current_holdableCursor != holdableCursor)
{
rePrepare2( pSrvrStmt
, sqlStmtType
, inputRowCnt
, holdableCursor
, &rc
, returnCode
, sqlWarningOrErrorLength
, sqlWarningOrError
);
bRePrepare2 = true;
}
if (*returnCode == 0 || *returnCode == 1)
{
// resource statistics
// generate the actual start message after reprepare, if any.
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->inState = inState = STMTSTAT_EXECUTE;
inSqlStmtType = sqlStmtType;
inEstimatedCost = pSrvrStmt->cost_info.totalTime;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlError = NULL;
inSqlErrorLength = 0;
// For UPSERT statements force it as INSERT if the driver has sent a unknown type.
if( inSqlStmtType == TYPE_UNKNOWN && (pSrvrStmt->sqlQueryType == SQL_INSERT_UNIQUE || pSrvrStmt->sqlQueryType == SQL_INSERT_NON_UNIQUE) )
inSqlStmtType = TYPE_INSERT;
}
//end rs
if (inputRowCnt < 0)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Invalid Row Count.", sqlWarningOrErrorLength, sqlWarningOrError);
}
else
{
if (sqlStmtType == TYPE_SELECT && inputRowCnt > 1)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Invalid Row Count.", sqlWarningOrErrorLength, sqlWarningOrError);
}
}
if (*returnCode == 0 || *returnCode == 1)
{
if ((*returnCode == 0) && (pSrvrStmt->sqlWarningOrErrorLength > 0)) // To preserve warning returned at prepare time
{
if (pSrvrStmt->sqlWarningOrError != NULL)
delete pSrvrStmt->sqlWarningOrError;
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
pSrvrStmt->inputRowCnt = inputRowCnt;
pSrvrStmt->sqlStmtType = (short)sqlStmtType;
if (cursorLength > 0)
{
pSrvrStmt->cursorNameLen = cursorLength;
memcpy(pSrvrStmt->cursorName, cursorName, cursorLength);
pSrvrStmt->cursorName[cursorLength] = '\0';
}
else
pSrvrStmt->cursorName[0] = '\0';
if (pSrvrStmt->sqlQueryType == SQL_RWRS_SPECIAL_INSERT)
{
//memcpy(pSrvrStmt->inputDescVarBuffer, (void *)&pSrvrStmt->inputRowCnt , sizeof(pSrvrStmt->inputRowCnt) );
//memcpy(pSrvrStmt->inputDescVarBuffer+4, (void *)&pSrvrStmt->maxRowLen, sizeof(pSrvrStmt->maxRowLen) );
*((Int32 *)pSrvrStmt->inputDescVarBuffer) = pSrvrStmt->inputRowCnt;
*((Int32 *)(pSrvrStmt->inputDescVarBuffer+4)) = pSrvrStmt->maxRowLen;
//*((Int32)pSrvrStmt->inputDescVarBuffer+8) = inValues ;
*((BYTE **)(pSrvrStmt->inputDescVarBuffer+8)) = inValues ;
}
else
{
if (pSrvrStmt->inputDescVarBufferLen == inValuesLength)
memcpy(pSrvrStmt->inputDescVarBuffer, inValues, inValuesLength);
else
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY090", "Invalid param Values.", sqlWarningOrErrorLength, sqlWarningOrError);
}
}
if (bRePrepare2)
{
rc = rePrepare2WouldLikeToExecute((Long)pSrvrStmt, (Int32*)returnCode, (Int32*)sqlWarningOrErrorLength, (char*&)sqlWarningOrError);
if (rc == false)
{
*rowsAffected = -1;
if ((resStatStatement != NULL) && (pSrvrStmt->stmtType == EXTERNAL_STMT))
{
// generate 21036 start message
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
pSrvrStmt->stmtName,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlString);
}
goto out0;
}
}
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
pSrvrStmt->stmtName,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlString);
}
pSrvrStmt->currentMethod = odbc_SQLSvc_ExecuteN_ldx_;
rc = EXECUTE2(pSrvrStmt);
// char tmpString[32];
// tmpString[0] = '\0';
// sprintf(tmpString, "e: %Ld", pSrvrStmt->cliElapseTime);
// SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
// srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
// srvrGlobal->srvrObjRef, 1, tmpString);
switch (rc)
{
case SQL_SUCCESS_WITH_INFO:
*returnCode = SQL_SUCCESS_WITH_INFO;
*rowsAffected = pSrvrStmt->rowsAffected;
if ( pSrvrStmt->sqlQueryType == SQL_SELECT_UNIQUE
|| pSrvrStmt->sqlStmtType == TYPE_CALL)
{
*outValuesLength = pSrvrStmt->outputDescVarBufferLen;
outValues = pSrvrStmt->outputDescVarBuffer;
}
else
{
if (pSrvrStmt->sqlQueryType == SQL_RWRS_SPECIAL_INSERT)
{
if (inValues != NULL)
*pSrvrStmt->inputDescVarBuffer = NULL;
}
*outValuesLength = 0;
outValues = 0;
}
if (pSrvrStmt->sqlWarningOrErrorLength > 0) // overwriting warning returned at prepare time
{
if (pSrvrStmt->sqlWarningOrError != NULL)
delete pSrvrStmt->sqlWarningOrError;
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
break;
case SQL_SUCCESS:
*returnCode = SQL_SUCCESS;
*rowsAffected = pSrvrStmt->rowsAffected;
if ( pSrvrStmt->sqlQueryType == SQL_SELECT_UNIQUE
|| pSrvrStmt->sqlStmtType == TYPE_CALL)
{
*outValuesLength = pSrvrStmt->outputDescVarBufferLen;
outValues = pSrvrStmt->outputDescVarBuffer;
}
else
{
if (pSrvrStmt->sqlQueryType == SQL_RWRS_SPECIAL_INSERT)
{
if (inValues != NULL)
*pSrvrStmt->inputDescVarBuffer = NULL;
}
*outValuesLength = 0;
outValues = 0;
}
break;
case SQL_NO_DATA_FOUND:
*returnCode = SQL_NO_DATA_FOUND;
break;
case SQL_INVALID_HANDLE:
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Invalid Statement Handle.", sqlWarningOrErrorLength, sqlWarningOrError);
break;
case SQL_ERROR:
if (pSrvrStmt->sqlWarningOrErrorLength > 0) // Overwriting warning returned at prepare time
{
if (pSrvrStmt->sqlWarningOrError != NULL)
delete pSrvrStmt->sqlWarningOrError;
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
GETSQLWARNINGORERROR2(pSrvrStmt);
*returnCode = SQL_ERROR;
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
break;
default:
break;
}
if (resStatStatement != NULL)
{
// Should avoid collecting statistics for
// statement types that do not fetch until end of data or close the stmt
// during execute since it's causing issues in RMS.
if( pSrvrStmt->sqlQueryType != SQL_SELECT_NON_UNIQUE && pSrvrStmt->sqlQueryType != SQL_CALL_WITH_RESULT_SETS)
resStatStatement->setStatistics(pSrvrStmt);
}
}
out0:
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
if (*returnCode == SQL_ERROR && pSrvrStmt->sqlWarningOrError != NULL)
{
inErrorCode = *(Int32 *)(pSrvrStmt->sqlWarningOrError+8);
inErrorStatement ++;
inSqlError = (char*)pSrvrStmt->sqlWarningOrError + 16;
inSqlErrorLength =*(Int32 *)(pSrvrStmt->sqlWarningOrError + 12);
}
if (*returnCode == SQL_SUCCESS_WITH_INFO)
inWarningStatement ++;
if (pSrvrStmt->rowsAffectedHigherBytes != 0)
inRowCount = -1;
else
inRowCount = *rowsAffected;
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlNewQueryType,
pSrvrStmt->isClosed);
}
//end rs
}
}
SRVRTRACE_EXIT(FILE_SME+19);
return;
}
//--------------------------------------------------------------------------------
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_Execute2withRowsets'
*/
extern "C" void
odbc_SQLSvc_Execute2withRowsets_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ Int32 sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* In */ Int32 inputRowCnt
, /* In */ Int32 sqlStmtType
, /* In */ Long stmtHandle
, /* In */ Int32 cursorLength
, /* In */ IDL_string cursorName
, /* In */ Int32 cursorCharset
, /* In */ Int32 holdableCursor
, /* In */ Int32 inValuesLength
, /* In */ BYTE *inValues
, /* Out */ Int32 *returnCode
, /* Out */ Int32 *sqlWarningOrErrorLength
, /* Out */ BYTE *&sqlWarningOrError
, /* Out */ Int32 *rowsAffected
, /* Out */ Int32 *outValuesLength
, /* Out */ BYTE *&outValues)
{
SRVRTRACE_ENTER(FILE_SME+19);
bool bRePrepare2 = false;
/*
* The performance team wanted to be able to stub out the actual inserts
* to measure the contributions of individual components to the overall
* load times. If the env variable mxosrvr-stubout-EXECUTE2withRowsets
* is set in ms.env, we will skip over the call to EXECUTE2withRowsets
* and return sql_success, and rowsAffected = input row count
*/
static bool bCheckStubExecute2WithRowsets = true;
static bool bStubExecute2WithRowsets = false;
if(bCheckStubExecute2WithRowsets)
{
char *env = getenv("mxosrvr-stubout-EXECUTE2withRowsets");
if (env != NULL && strcmp(env,"true") == 0)
bStubExecute2WithRowsets = true;
bCheckStubExecute2WithRowsets = false;
}
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQLRETURN rc = SQL_SUCCESS;
if ((pSrvrStmt = (SRVR_STMT_HDL *)stmtHandle) == NULL)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Statement Label not found.", sqlWarningOrErrorLength, sqlWarningOrError);
}
else
{
*returnCode = SQL_SUCCESS;
if (inputRowCnt < 0)
{
}
else if (sqlStmtType == TYPE_SELECT && inputRowCnt > 1)
{
}
else if ((pSrvrStmt->maxRowsetSize < inputRowCnt) || (pSrvrStmt->current_holdableCursor != holdableCursor))
{
rePrepare2( pSrvrStmt
, sqlStmtType
, inputRowCnt
, holdableCursor
,&rc
, returnCode
, sqlWarningOrErrorLength
, sqlWarningOrError
);
bRePrepare2 = true;
}
if (*returnCode == 0 || *returnCode == 1)
{
// resource statistics
// generate the actual start message after reprepare, if any.
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->inState = inState = STMTSTAT_EXECUTE;
inSqlStmtType = sqlStmtType;
inEstimatedCost = pSrvrStmt->cost_info.totalTime;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlError = NULL;
inSqlErrorLength = 0;
}
//end rs
if (inputRowCnt < 0)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Invalid Row Count.", sqlWarningOrErrorLength, sqlWarningOrError);
}
else
{
if (sqlStmtType == TYPE_SELECT && inputRowCnt > 1)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Invalid Row Count.", sqlWarningOrErrorLength, sqlWarningOrError);
}
}
if (*returnCode == 0 || *returnCode == 1)
{
// Fix for CR 5763/6389 - added additional checks to make sure the warnings, if any, are not lost from the
// rePrepare2() call in SrvrConnect.cpp (returnCode could be 0).
if ((*returnCode == 0) && (pSrvrStmt->sqlWarningOrErrorLength > 0) && pSrvrStmt->reprepareWarn == FALSE) // To preserve warning returned at prepare time
{
if (pSrvrStmt->sqlWarningOrError != NULL)
delete pSrvrStmt->sqlWarningOrError;
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if(pSrvrStmt->bSQLValueListSet)
pSrvrStmt->cleanupSQLValueList();
if ( (*returnCode == 0 && rc == 0) || (*returnCode == 1 && rc == 1) )
{
pSrvrStmt->inputRowCnt = inputRowCnt;
pSrvrStmt->sqlStmtType = (short)sqlStmtType;
if (cursorLength > 0)
{
pSrvrStmt->cursorNameLen = cursorLength;
memcpy(pSrvrStmt->cursorName, cursorName, cursorLength);
}
else
pSrvrStmt->cursorName[0] = '\0';
if (pSrvrStmt->preparedWithRowsets == TRUE)
{
pSrvrStmt->transportBuffer = inValues;
pSrvrStmt->transportBufferLen = inValuesLength;
}
else if (pSrvrStmt->inputDescVarBufferLen == inValuesLength)
memcpy(pSrvrStmt->inputDescVarBuffer, inValues, inValuesLength);
else
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR( -1
, "HY090"
, "Invalid param Values."
, sqlWarningOrErrorLength
, sqlWarningOrError
);
goto out;
}
if (bRePrepare2)
{
// Note: The below method ends in a dummy call in CommonNSKFunctions.cpp. CR 5763 takes care of this.
rc = rePrepare2WouldLikeToExecute((Long)pSrvrStmt, (Int32*)returnCode, (Int32*)sqlWarningOrErrorLength, (char*&)sqlWarningOrError);
if (rc == false)
{
*rowsAffected = -1;
if ((resStatStatement != NULL) && (pSrvrStmt->stmtType == EXTERNAL_STMT))
{
// generate 21036 start message
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
pSrvrStmt->stmtName,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlString);
}
goto out;
}
}
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
pSrvrStmt->stmtName,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlString);
}
//end rs
pSrvrStmt->currentMethod = odbc_SQLSvc_ExecuteN_ldx_;
if(!bStubExecute2WithRowsets)
rc = EXECUTE2withRowsets(pSrvrStmt);
else {
rc = SQL_SUCCESS;
pSrvrStmt->rowsAffected = inputRowCnt;
}
switch (rc)
{
case ROWSET_SQL_ERROR:
// Copy the output values
*rowsAffected = -1;
if (pSrvrStmt->sqlWarningOrErrorLength > 0) // Overwriting warning returned at prepare time
{
if (pSrvrStmt->sqlWarningOrError != NULL)
delete pSrvrStmt->sqlWarningOrError;
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
GETSQLWARNINGORERROR2forRowsets(pSrvrStmt);
*returnCode = SQL_ERROR;
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
break;
case SQL_SUCCESS_WITH_INFO:
*returnCode = SQL_SUCCESS_WITH_INFO;
*rowsAffected = pSrvrStmt->rowsAffected;
if ( pSrvrStmt->sqlQueryType == SQL_SELECT_UNIQUE
|| pSrvrStmt->sqlStmtType == TYPE_CALL)
{
*outValuesLength = pSrvrStmt->outputDescVarBufferLen;
outValues = pSrvrStmt->outputDescVarBuffer;
}
else
{
*outValuesLength = 0;
outValues = 0;
}
if (pSrvrStmt->sqlWarningOrErrorLength > 0) // Overwriting warning returned at prepare time
{
if (pSrvrStmt->sqlWarningOrError != NULL)
delete pSrvrStmt->sqlWarningOrError;
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
if (pSrvrStmt->sqlWarning._length > 0)
GETSQLWARNINGORERROR2forRowsets(pSrvrStmt);
else
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
break;
case SQL_SUCCESS:
*returnCode = SQL_SUCCESS;
*rowsAffected = pSrvrStmt->rowsAffected;
if (pSrvrStmt->sqlWarning._length > 0)
{
if (pSrvrStmt->sqlWarningOrErrorLength > 0) // Overwriting warning returned at prepare time
{
if (pSrvrStmt->sqlWarningOrError != NULL)
delete pSrvrStmt->sqlWarningOrError;
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
GETSQLWARNINGORERROR2forRowsets(pSrvrStmt);
*returnCode = SQL_SUCCESS_WITH_INFO; // We have warnings so return success witn info.
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
if (pSrvrStmt->sqlQueryType == SQL_SELECT_UNIQUE
|| pSrvrStmt->sqlStmtType == TYPE_CALL)
{
*outValuesLength = pSrvrStmt->outputDescVarBufferLen;
outValues = pSrvrStmt->outputDescVarBuffer;
}
else
{
*outValuesLength = 0;
outValues = 0;
}
break;
case SQL_NO_DATA_FOUND:
*returnCode = SQL_NO_DATA_FOUND;
break;
case SQL_INVALID_HANDLE:
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Invalid Statement Handle.", sqlWarningOrErrorLength, sqlWarningOrError);
break;
case SQL_ERROR:
if (pSrvrStmt->sqlWarningOrErrorLength > 0) // Overwriting warning returned at prepare time
{
if (pSrvrStmt->sqlWarningOrError != NULL)
delete pSrvrStmt->sqlWarningOrError;
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
GETSQLWARNINGORERROR2(pSrvrStmt);
*returnCode = SQL_ERROR;
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
break;
default:
break;
}
if (resStatStatement != NULL)
{
// We don't need a check here similar to odbc_SQLSvc_Execute2_sme_()
// since for rowsets we don't call
// WSQL_EXEC_Exec().
resStatStatement->setStatistics(pSrvrStmt);
}
//
// The following transaction check was taken from Zbig.
//
if ( sqlStmtType == TYPE_INSERT_PARAM
&& (srvrGlobal->EnvironmentType & MXO_ROWSET_ERROR_RECOVERY)
&& pSrvrStmt->NA_supported == false
&& srvrGlobal->bAutoCommitOn == true)
{
if (SQL_EXEC_Xact(SQLTRANS_STATUS,NULL) == 0)
{
// transaction is running - do commit/rollback
SQLValueList_def inValueList;
inValueList._buffer = NULL;
inValueList._length = 0;
if (rc == ROWSET_SQL_ERROR)
{
SRVR_STMT_HDL *RbwSrvrStmt = getSrvrStmt("STMT_ROLLBACK_1", FALSE);
RbwSrvrStmt->Execute(NULL,1,TYPE_UNKNOWN,&inValueList,SQL_ASYNC_ENABLE_OFF,0);
}
else
{
SRVR_STMT_HDL *CmwSrvrStmt = getSrvrStmt("STMT_COMMIT_1", FALSE);
CmwSrvrStmt->Execute(NULL,1,TYPE_UNKNOWN,&inValueList,SQL_ASYNC_ENABLE_OFF,0);
}
}
}
}
} // end if (*returnCode == 0 && rc == 0)
// resource statistics
out:
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
if (*returnCode == SQL_ERROR && pSrvrStmt->sqlWarningOrError != NULL)
{
inErrorCode = *(Int32 *)(pSrvrStmt->sqlWarningOrError+8);
inErrorStatement ++;
inSqlError = (char*)pSrvrStmt->sqlWarningOrError + 16;
inSqlErrorLength =*(Int32 *)(pSrvrStmt->sqlWarningOrError + 12);
}
if (*returnCode == SQL_SUCCESS_WITH_INFO)
inWarningStatement ++;
if (pSrvrStmt->rowsAffectedHigherBytes != 0)
inRowCount = -1;
else
inRowCount = *rowsAffected;
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlNewQueryType,
pSrvrStmt->isClosed);
}
}
} // end else
outout:
pSrvrStmt->returnCodeForDelayedError = *returnCode;
SRVRTRACE_EXIT(FILE_SME+19);
return;
} // end odbc_SQLSvc_Execute2withRowsets_sme_
//------------------------------------------------------------------------------
extern "C" void
rePrepare2( SRVR_STMT_HDL *pSrvrStmt
, Int32 sqlStmtType
, Int32 inputRowCnt
, Int32 holdableCursor
, SQLRETURN *rc
, Int32 *returnCode
, Int32 *sqlWarningOrErrorLength
, BYTE *&sqlWarningOrError
)
{
UInt32 tmpSqlStringLen = pSrvrStmt->sqlStringLen;
char *tmpSqlString;
short tmpStmtType = pSrvrStmt->stmtType;
short tmpSqlStmtType = sqlStmtType; // need to do this since PREPARE does not pass this from driver
Int32 tmpMaxRowsetSize = pSrvrStmt->maxRowsetSize;
Int32 sqlQueryType;
Int32 estimatedCost;
if (pSrvrStmt->sqlWarningOrErrorLength > 0) // To preserve warning returned at prepare time
{
if (pSrvrStmt->sqlWarningOrError != NULL)
delete pSrvrStmt->sqlWarningOrError;
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if(pSrvrStmt->bSQLValueListSet)
pSrvrStmt->cleanupSQLValueList();
tmpSqlString = new char[tmpSqlStringLen+1];
if (tmpSqlString == NULL)
{
SendEventMsg( MSG_MEMORY_ALLOCATION_ERROR
, EVENTLOG_ERROR_TYPE
, srvrGlobal->nskProcessInfo.processId
, ODBCMX_SERVER
, srvrGlobal->srvrObjRef
, 1
, "Execute2"
);
exit(0);
}
strcpy(tmpSqlString, pSrvrStmt->sqlString);
// cleanup all memory allocated in the previous operations
pSrvrStmt->cleanupAll();
pSrvrStmt->sqlStringLen = tmpSqlStringLen;
pSrvrStmt->sqlString = new char[pSrvrStmt->sqlStringLen+1];
if (pSrvrStmt->sqlString == NULL)
{
SendEventMsg( MSG_MEMORY_ALLOCATION_ERROR
, EVENTLOG_ERROR_TYPE
, srvrGlobal->nskProcessInfo.processId
, ODBCMX_SERVER
, srvrGlobal->srvrObjRef
, 1
, "Execute2"
);
exit(0);
}
strcpy(pSrvrStmt->sqlString, tmpSqlString);
pSrvrStmt->stmtType = tmpStmtType;
pSrvrStmt->sqlStmtType = tmpSqlStmtType;
pSrvrStmt->maxRowsetSize = inputRowCnt;
pSrvrStmt->holdableCursor= holdableCursor;
if (pSrvrStmt->maxRowsetSize == ROWSET_NOT_DEFINED)
pSrvrStmt->maxRowsetSize = DEFAULT_ROWSET_SIZE;
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->inState = inState = STMTSTAT_PREPARE;
inSqlStmtType = TYPE_UNKNOWN;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlQueryType = SQL_UNKNOWN;
inSqlNewQueryType = SQL_UNKNOWN;
inSqlError = NULL;
inSqlErrorLength = 0;
/*resStatStatement->start(inState,
inSqlQueryType,
pSrvrStmt->stmtName,
NULL,
pSrvrStmt->cost_info,
pSrvrStmt->comp_stats_info,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg,
false,
tmpSqlString);*/
resStatStatement->start(inState,
inSqlQueryType,
pSrvrStmt->stmtName,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg,
tmpSqlString);
}
*rc = REALLOCSQLMXHDLS(pSrvrStmt); // This is a workaround for executor when we switch between OLTP vs NON-OLTP
if (*rc < 0)
{
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
goto out;
}
if (pSrvrStmt->sqlStmtType == TYPE_INSERT_PARAM)
{
if (srvrGlobal->EnvironmentType & MXO_ROWSET_ERROR_RECOVERY)
*rc = WSQL_EXEC_SetStmtAttr(&pSrvrStmt->stmt, SQL_ATTR_ROWSET_ATOMICITY, SQL_NOT_ATOMIC,0);
else
*rc = WSQL_EXEC_SetStmtAttr(&pSrvrStmt->stmt, SQL_ATTR_ROWSET_ATOMICITY, SQL_ATOMIC, 0);
if (*rc < 0)
{
GETSQLWARNINGORERROR2(pSrvrStmt);
goto out;
}
WSQL_EXEC_ClearDiagnostics(&pSrvrStmt->stmt);
}
if (srvrGlobal->srvrType == CORE_SRVR)
AllocateAdaptiveSegment(pSrvrStmt);
pSrvrStmt->currentMethod = odbc_SQLSvc_PrepareRowset_ldx_; // KAS - bug. This should be Prepare2.
if(pSrvrStmt->maxRowsetSize > 1)
*rc = PREPARE2withRowsets(pSrvrStmt);
else
*rc = PREPARE2(pSrvrStmt);
if (srvrGlobal->srvrType == CORE_SRVR && *rc != SQL_SUCCESS && *rc != SQL_SUCCESS_WITH_INFO)
DeallocateAdaptiveSegment(pSrvrStmt);
switch (*rc)
{
case ODBC_RG_WARNING:
case SQL_SUCCESS_WITH_INFO:
*returnCode = SQL_SUCCESS_WITH_INFO;
estimatedCost = (Int32)pSrvrStmt->cost_info.totalTime; // change to double in future
sqlQueryType = pSrvrStmt->sqlQueryType;
if (*rc == SQL_SUCCESS_WITH_INFO)
{
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
else
{
char RGWarningOrError[256];
sprintf(b,"%lf",pSrvrStmt->cost_info.totalTime);
sprintf( RGWarningOrError
, "The query's estimated cost: %.50s exceeded resource management attribute limit set."
, b
);
GETMXCSWARNINGORERROR(1, "01000", RGWarningOrError, sqlWarningOrErrorLength, sqlWarningOrError);
}
break;
case SQL_SUCCESS:
WSQL_EXEC_ClearDiagnostics(&pSrvrStmt->stmt);
estimatedCost = (Int32)pSrvrStmt->cost_info.totalTime; // change to double in future
sqlQueryType = pSrvrStmt->sqlQueryType;
break;
case SQL_ERROR:
case ODBC_RG_ERROR:
*returnCode = SQL_ERROR;
if (*rc == SQL_ERROR)
{
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
else
{
char *RGWarningOrError;
RGWarningOrError = new char[256];
sprintf(b,"%lf",pSrvrStmt->cost_info.totalTime);
sprintf( RGWarningOrError
, "The query's estimated cost: %.50s exceeded resource management attribute limit set."
, b
);
GETMXCSWARNINGORERROR( -1
, "HY000"
, RGWarningOrError
, sqlWarningOrErrorLength
, sqlWarningOrError
);
delete RGWarningOrError;
}
break;
case PROGRAM_ERROR:
GETMXCSWARNINGORERROR( -1
, "HY000"
, SQLSVC_EXCEPTION_PREPARE_FAILED
, sqlWarningOrErrorLength
, sqlWarningOrError
);
break;
default:
break;
} // end switch
out:
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
if (*returnCode == SQL_ERROR && pSrvrStmt != NULL && pSrvrStmt->sqlWarningOrError != NULL)
{
inErrorCode = *(Int32 *)(pSrvrStmt->sqlWarningOrError+8);
inErrorStatement ++;
inSqlError = (char*)pSrvrStmt->sqlWarningOrError + 16;
inSqlErrorLength =*(Int32 *)(pSrvrStmt->sqlWarningOrError + 12);
}
if (*returnCode == SQL_SUCCESS_WITH_INFO)
inWarningStatement ++;
if (tmpSqlString == NULL)
tmpSqlString = "";
inSqlString = new char[pSrvrStmt->sqlStringLen];
if (inSqlString == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "inSqlString");
exit(0);
}
strncpy(inSqlString,tmpSqlString,pSrvrStmt->sqlStringLen);
if (pSrvrStmt != NULL)
{
inEstimatedCost = pSrvrStmt->cost_info.totalTime; // res stat reports estimated cost as double
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
inSqlNewQueryType = pSrvrStmt->sqlNewQueryType;
}
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
inSqlNewQueryType);
delete inSqlString;
delete tmpSqlString;
}
//end rs
} // end rePrepare2
//------------------------------------------------------------------------------
//LCOV_EXCL_START
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_Fetch2'
*/
extern "C" void
odbc_SQLSvc_Fetch2_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ Int32 sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* In */ Long stmtHandle
, /* In */ Int32 maxRowCnt
, /* In */ Int32 cursorLength
, /* In */ IDL_string cursorName
, /* In */ Int32 cursorCharset
, /* Out */ Int32 *returnCode
, /* Out */ Int32 *sqlWarningOrErrorLength
, /* Out */ BYTE *&sqlWarningOrError
, /* Out */ Int32 *rowsAffected
, /* Out */ Int32 *outValuesFormat
, /* Out */ Int32 *outValuesLength
, /* Out */ BYTE *&outValues)
{
SRVRTRACE_ENTER(FILE_SME+20);
SRVR_STMT_HDL *pSrvrStmt;
SQLRETURN rc = SQL_SUCCESS;
if ((pSrvrStmt = (SRVR_STMT_HDL *)stmtHandle) == NULL)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Statement Label not found.", sqlWarningOrErrorLength, sqlWarningOrError);
}
else if (maxRowCnt < 0)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Max row count < 0.", sqlWarningOrErrorLength, sqlWarningOrError);
}
else if (pSrvrStmt->isClosed)
*returnCode = SQL_NO_DATA_FOUND;
else
{
pSrvrStmt->maxRowCnt = maxRowCnt;
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->inState = inState = STMTSTAT_FETCH;
inSqlStmtType = TYPE_UNKNOWN;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlError = NULL;
inSqlErrorLength = 0;
/* resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
pSrvrStmt->stmtName,
pSrvrStmt->sqlUniqueQueryID,
pSrvrStmt->cost_info,
pSrvrStmt->comp_stats_info,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);*/
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
pSrvrStmt->stmtName,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);
} // end if resource statistics
if (pSrvrStmt->sqlWarningOrErrorLength > 0)
{
if (pSrvrStmt->sqlWarningOrError != NULL)
delete pSrvrStmt->sqlWarningOrError;
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
if (cursorLength > 0)
{
pSrvrStmt->cursorNameLen = cursorLength;
memcpy(pSrvrStmt->cursorName, cursorName, cursorLength);
}
else
pSrvrStmt->cursorName[0] = '\0';
pSrvrStmt->currentMethod = odbc_SQLSvc_FetchPerf_ldx_; // KAS - bug. Should be Fetch2
//
// We will either use fetch bulk (also known as fetch "row wise rowsets") or fetch rowsets
// (also known as fetch "column wise rowsets").
//
if (pSrvrStmt->sqlBulkFetchPossible && pSrvrStmt->sqlQueryType == SQL_SELECT_NON_UNIQUE)
{
if (pSrvrStmt->outputDataValue._buffer != NULL)
delete pSrvrStmt->outputDataValue._buffer;
pSrvrStmt->outputDataValue._buffer = NULL;
pSrvrStmt->outputDataValue._length = 0;
rc = FETCH2bulk(pSrvrStmt);
*outValuesFormat = ROWWISE_ROWSETS;
if (pSrvrStmt->rowsAffected > 0)
{
if (pSrvrStmt->outputDataValue._length == 0 && pSrvrStmt->outputDataValue._buffer == NULL)
{
outValues = pSrvrStmt->outputDescVarBuffer;
*outValuesLength = (Int32)(pSrvrStmt->outputDescVarBufferLen * pSrvrStmt->rowsAffected);
}
else
{
outValues = pSrvrStmt->outputDataValue._buffer;
*outValuesLength = (Int32)(pSrvrStmt->outputDataValue._length);
}
}
else
{
outValues = NULL;
*outValuesLength = 0;
}
}
else
rc = FETCH2(pSrvrStmt, outValuesFormat, outValuesLength, outValues);
switch (rc)
{
case SQL_SUCCESS_WITH_INFO:
*returnCode = SQL_SUCCESS_WITH_INFO;
*rowsAffected = pSrvrStmt->rowsAffected;
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
break;
case SQL_SUCCESS:
*returnCode = SQL_SUCCESS;
*rowsAffected = pSrvrStmt->rowsAffected;
break;
case SQL_NO_DATA_FOUND:
*returnCode = SQL_NO_DATA_FOUND;
break;
case SQL_INVALID_HANDLE:
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Invalid Statement Handle.", sqlWarningOrErrorLength, sqlWarningOrError);
break;
case SQL_ERROR:
GETSQLWARNINGORERROR2(pSrvrStmt);
*returnCode = SQL_ERROR;
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
break;
default:
break;
} // end switch
if (resStatStatement != NULL && (rc == SQL_NO_DATA_FOUND || (rc == SQL_SUCCESS && *rowsAffected < maxRowCnt)))
{
resStatStatement->setStatistics(pSrvrStmt);
}
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
if (*returnCode == SQL_ERROR && pSrvrStmt->sqlWarningOrError != NULL)
{
inErrorCode = *(Int32 *)(pSrvrStmt->sqlWarningOrError+8);
inErrorStatement ++;
inSqlError = (char*)pSrvrStmt->sqlWarningOrError + 16;
inSqlErrorLength =*(Int32 *)(pSrvrStmt->sqlWarningOrError + 12);
}
if (*returnCode == SQL_SUCCESS_WITH_INFO)
inWarningStatement ++;
inRowCount = *rowsAffected;
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlNewQueryType,
pSrvrStmt->isClosed);
} // end resStatStatement != NULL
} // end if ((pSrvrStmt = (SRVR_STMT_HDL *)stmtHandle) == NULL) else
SRVRTRACE_EXIT(FILE_SME+20);
return;
} // end odbc_SQLSvc_Fetch2_sme_
//LCOV_EXCL_STOP
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_Close'
*/
extern "C" void
odbc_SQLSvc_Close_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_Close_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ const IDL_char *stmtLabel
, /* In */ IDL_unsigned_short freeResourceOpt
, /* Out */ Int32 *rowsAffected
, /* Out */ ERROR_DESC_LIST_def *sqlWarning
)
{
SRVRTRACE_ENTER(FILE_SME+3);
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQLRETURN rc = SQL_SUCCESS;
if (freeResourceOpt != SQL_CLOSE && freeResourceOpt != SQL_DROP &&
freeResourceOpt != SQL_UNBIND && freeResourceOpt != SQL_RESET_PARAMS)
{
exception_->exception_nr = odbc_SQLSvc_Close_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_RESOURCE_OPT_CLOSE;
}
else
{
if ((pSrvrStmt = getSrvrStmt(stmtLabel, FALSE)) == NULL)
goto ret; // Statement was never allocated.
if (freeResourceOpt == SQL_CLOSE && pSrvrStmt->isClosed)
goto ret;
}
if (exception_->exception_nr == 0)
{
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->inState = inState = STMTSTAT_CLOSE;
inSqlStmtType = TYPE_UNKNOWN;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlError = NULL;
inSqlErrorLength = 0;
/*resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt->sqlUniqueQueryID,
pSrvrStmt->cost_info,
pSrvrStmt->comp_stats_info,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);*/
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);
// if SQLClose is called after SQLExecute/SQLExecdirect of select stmt,
// END:SQLFetch/END:QueryExecution still needs to be generated
// if (pSrvrStmt->isClosed == FALSE) pSrvrStmt->bFetchStarted = TRUE;
if (pSrvrStmt->isClosed == FALSE)
{
pSrvrStmt->bFetchStarted = FALSE;
if (exception_->exception_nr != 0 && exception_->u.SQLError.errorList._buffer != NULL)
{
inErrorStatement ++;
ERROR_DESC_def *p_buffer = exception_->u.SQLError.errorList._buffer;
inErrorCode = p_buffer->sqlcode;
inSqlError = p_buffer->errorText;
inSqlErrorLength = strlen(p_buffer->errorText);
}
inQueryId=pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlNewQueryType,
pSrvrStmt->isClosed);
}
}
//end rs
rc = SQL_SUCCESS;
if (pSrvrStmt->stmtType != INTERNAL_STMT)
{
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if(pSrvrStmt->bSQLValueListSet)
pSrvrStmt->cleanupSQLValueList();
pSrvrStmt->freeResourceOpt = freeResourceOpt;
pSrvrStmt->currentMethod = odbc_SQLSvc_Close_ldx_;
if (pSrvrStmt->sqlQueryType == SQL_SP_RESULT_SET)
{
// The result set can not be re-used, so remove it completely.
freeResourceOpt = SQL_DROP;
pSrvrStmt->freeResourceOpt = freeResourceOpt;
delete [] pSrvrStmt->SpjProxySyntaxString;
pSrvrStmt->SpjProxySyntaxString = NULL;
pSrvrStmt->SpjProxySyntaxStringLen = 0;
// remove the result set from the call statement
SRVR_STMT_HDL *prev = pSrvrStmt->previousSpjRs;
SRVR_STMT_HDL *next = pSrvrStmt->nextSpjRs;
prev->nextSpjRs = next;
if (next != NULL)
next->previousSpjRs = prev;
// If prev is the call statement itself, and the call statement has no more
// result sets, then close the call statement.
if (prev->sqlQueryType == SQL_CALL_WITH_RESULT_SETS && prev->nextSpjRs == NULL)
rc = FREESTATEMENT(prev);
}
rc = FREESTATEMENT(pSrvrStmt);
// Return back immediately since the pSrvrStmt is deleted and return SQL_SUCCESS always
if (freeResourceOpt == SQL_DROP)
{
rc = SQL_SUCCESS;
}
else
{
switch (rc)
{
case SQL_SUCCESS:
break;
case SQL_SUCCESS_WITH_INFO:
GETSQLWARNING(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlWarning);
break;
case SQL_ERROR:
GETSQLERROR(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError);
break;
case ODBC_RG_WARNING:
// if there is RG_WARNING, we don't pass SQL Warning to the application
// Hence, we need to clear any warnings
// call SQL_EXEC_ClearDiagnostics
// CLEARDIAGNOSTICS(pSrvrStmt);
rc = SQL_SUCCESS_WITH_INFO;
case ODBC_SERVER_ERROR:
case ODBC_RG_ERROR:
default:
break;
}
}
}
switch (rc)
{
case SQL_SUCCESS:
case SQL_SUCCESS_WITH_INFO:
exception_->exception_nr = 0;
if (freeResourceOpt != SQL_DROP)
{
*rowsAffected = pSrvrStmt->rowsAffected;
sqlWarning->_length = pSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = pSrvrStmt->sqlWarning._buffer;
}
else
{
*rowsAffected = 0;
sqlWarning->_length = 0;
sqlWarning->_buffer = NULL;
}
break;
case SQL_ERROR:
exception_->exception_nr = odbc_SQLSvc_Close_SQLError_exn_;
exception_->u.SQLError.errorList._length = pSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = pSrvrStmt->sqlError.errorList._buffer;
break;
case PROGRAM_ERROR:
exception_->exception_nr = odbc_SQLSvc_Close_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_CLOSE_FAILED;
default:
break;
}
}
ret:
/* This code is moved to the begining of this method since pSrvrStmt is deleted in case of a
SQL_DROP.
// resource statistics
if (resStatStatement != NULL && pSrvrStmt != NULL && pSrvrStmt->isClosed == TRUE && pSrvrStmt->bFetchStarted == TRUE && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->bFetchStarted = FALSE;
if (exception_->exception_nr != 0 && exception_->u.SQLError.errorList._buffer != NULL)
{
inErrorStatement ++;
inErrorCode = exception_->u.SQLError.errorList._buffer->sqlcode;
}
inQueryId=pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
resStatStatement->end(inState,inSqlQueryType,inSqlStmtType,inQueryId,inEstimatedCost,inSqlString,inErrorStatement,inWarningStatement,inRowCount,inErrorCode,resStatSession,pSrvrStmt->isClosed);
}
*/
SRVRTRACE_EXIT(FILE_SME+3);
return;
}
//------------------------------------------------------------------------------
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_Close'
*/
extern "C" void
odbc_SQLSrvr_Close_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ const IDL_char *stmtLabel
, /* In */ IDL_unsigned_short freeResourceOpt
, /* Out */ Int32 *rowsAffected
, /* Out */ Int32 *returnCode
, /* Out */ Int32 *sqlWarningOrErrorLength
, /* Out */ BYTE *&sqlWarningOrError
)
{
SRVRTRACE_ENTER(FILE_SME+3);
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQLRETURN rc = SQL_SUCCESS;
if (freeResourceOpt != SQL_CLOSE && freeResourceOpt != SQL_DROP &&
freeResourceOpt != SQL_UNBIND && freeResourceOpt != SQL_RESET_PARAMS)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", SQLSVC_EXCEPTION_INVALID_RESOURCE_OPT_CLOSE, sqlWarningOrErrorLength, sqlWarningOrError);
}
else
{
pSrvrStmt = getSrvrStmt(stmtLabel, FALSE);
if(pSrvrStmt == NULL)
goto ret; // Statement was never allocated.
else
{
if (pSrvrStmt->sqlWarningOrErrorLength > 0 &&
pSrvrStmt->sqlWarningOrError != NULL)
{
delete pSrvrStmt->sqlWarningOrError;
}
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
if (freeResourceOpt == SQL_CLOSE && pSrvrStmt->isClosed)
goto ret;
}
if (*returnCode == SQL_SUCCESS)
{
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->inState = inState = STMTSTAT_CLOSE;
pSrvrStmt->m_bqueryFinish = true;
inSqlStmtType = TYPE_UNKNOWN;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlError = NULL;
inSqlErrorLength = 0;
/*resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt->sqlUniqueQueryID,
pSrvrStmt->cost_info,
pSrvrStmt->comp_stats_info,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);*/
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);
if (pSrvrStmt->isClosed == FALSE)
{
pSrvrStmt->bFetchStarted = FALSE;
if (*returnCode == SQL_ERROR && pSrvrStmt != NULL && pSrvrStmt->sqlWarningOrError != NULL)
{
inErrorStatement ++;
inErrorCode = *(Int32 *)(pSrvrStmt->sqlWarningOrError+8);
inSqlError = (char*)pSrvrStmt->sqlWarningOrError + 16;
inSqlErrorLength =*(Int32 *)(pSrvrStmt->sqlWarningOrError + 12);
}
inQueryId=pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
if (pSrvrStmt->m_need_21036_end_msg)
{
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlNewQueryType,
pSrvrStmt->isClosed);
}
}
}
//end rs
qrysrvcExecuteFinished(NULL, (Long)pSrvrStmt, false, *returnCode, false, false, true);
if ((resStatStatement != NULL) && (pSrvrStmt->stmtType == EXTERNAL_STMT)) // if statement is on
{
resStatStatement->endRepository(pSrvrStmt,
inSqlErrorLength,
(BYTE*)inSqlError,
true);
}
rc = SQL_SUCCESS;
if (pSrvrStmt->stmtType != INTERNAL_STMT)
{
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if(pSrvrStmt->bSQLValueListSet)
pSrvrStmt->cleanupSQLValueList();
pSrvrStmt->freeResourceOpt = freeResourceOpt;
pSrvrStmt->currentMethod = odbc_SQLSvc_Close_ldx_;
if (pSrvrStmt->sqlQueryType == SQL_SP_RESULT_SET)
{
// The result set can not be re-used, so remove it completely.
freeResourceOpt = SQL_DROP;
pSrvrStmt->freeResourceOpt = freeResourceOpt;
// Added deletion of proxy syntax
delete [] pSrvrStmt->SpjProxySyntaxString;
pSrvrStmt->SpjProxySyntaxString = NULL;
pSrvrStmt->SpjProxySyntaxStringLen = 0;
// remove the result set from the call statement
SRVR_STMT_HDL *prev = pSrvrStmt->previousSpjRs;
SRVR_STMT_HDL *next = pSrvrStmt->nextSpjRs;
prev->nextSpjRs = next;
if (next != NULL)
next->previousSpjRs = prev;
// If prev is the call statement itself, and the call statement has no more
// result sets, then close the call statement.
if (prev->sqlQueryType == SQL_CALL_WITH_RESULT_SETS && prev->nextSpjRs == NULL)
rc = FREESTATEMENT(prev);
}
rc = FREESTATEMENT(pSrvrStmt);
// Return back immediately since the pSrvrStmt is deleted and return SQL_SUCCESS always
if (freeResourceOpt == SQL_DROP)
{
rc = SQL_SUCCESS;
}
else
{
if(rc == SQL_SUCCESS_WITH_INFO ||
rc == SQL_ERROR )
{
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
}
}
switch (rc)
{
case SQL_SUCCESS:
*returnCode = SQL_SUCCESS;
if (freeResourceOpt != SQL_DROP)
*rowsAffected = pSrvrStmt->rowsAffected;
else
*rowsAffected = 0;
break;
case SQL_SUCCESS_WITH_INFO:
*returnCode = SQL_SUCCESS_WITH_INFO;
if (freeResourceOpt != SQL_DROP)
*rowsAffected = pSrvrStmt->rowsAffected;
else
*rowsAffected = 0;
break;
case SQL_ERROR:
*returnCode = SQL_ERROR;
break;
default:
break;
}
}
ret:
/* This code is moved to the begining of this method since pSrvrStmt is deleted in case of a
SQL_DROP.
// resource statistics
if (resStatStatement != NULL && pSrvrStmt != NULL && pSrvrStmt->isClosed == TRUE && pSrvrStmt->bFetchStarted == TRUE && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->bFetchStarted = FALSE;
if (*returnCode == SQL_ERROR && pSrvrStmt != NULL && pSrvrStmt->sqlWarningOrError != NULL)
{
inErrorStatement ++;
inErrorCode = *(Int32 *)(pSrvrStmt->sqlWarningOrError+8);
}
inQueryId=pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
resStatStatement->end(inState,inSqlQueryType,inSqlStmtType,inQueryId,inEstimatedCost,inSqlString,inErrorStatement,inWarningStatement,inRowCount,inErrorCode,resStatSession,pSrvrStmt->isClosed);
}
*/
SRVRTRACE_EXIT(FILE_SME+3);
return;
} /* odbc_SQLSrvr_Close_sme_() */
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_FetchN'
*/
extern "C" void
odbc_SQLSvc_FetchN_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_FetchN_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ const IDL_char *stmtLabel
, /* In */ Int32 maxRowCnt
, /* In */ Int32 maxRowLen
, /* In */ IDL_short sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* Out */ Int32 *rowsAffected
, /* Out */ SQLValueList_def *outputValueList
, /* Out */ ERROR_DESC_LIST_def *sqlWarning
)
{
SRVRTRACE_ENTER(FILE_SME+4);
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQLRETURN rc = SQL_SUCCESS;
if (maxRowCnt < 0)
{
exception_->exception_nr = odbc_SQLSvc_FetchN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_ROW_COUNT;
}
else
{
if ((pSrvrStmt = getSrvrStmt(stmtLabel, FALSE)) == NULL)
{
exception_->exception_nr = odbc_SQLSvc_FetchN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
}
if (exception_->exception_nr == 0)
{
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->isClosed == FALSE && pSrvrStmt->bFetchStarted == FALSE && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->bFetchStarted = TRUE;
pSrvrStmt->inState = inState = STMTSTAT_FETCH;
inSqlStmtType = TYPE_UNKNOWN;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlError = NULL;
inSqlErrorLength = 0;
/*resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt->sqlUniqueQueryID,
pSrvrStmt->cost_info,
pSrvrStmt->comp_stats_info,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);*/
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);
}
//end rs
rc = SQL_SUCCESS;
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if (pSrvrStmt->outputValueList._buffer == NULL || pSrvrStmt->maxRowCnt < maxRowCnt)
{
if(pSrvrStmt->bSQLValueListSet)
pSrvrStmt->cleanupSQLValueList();
rc = AllocAssignValueBuffer(pSrvrStmt->bSQLValueListSet,&pSrvrStmt->outputDescList,
&pSrvrStmt->outputValueList, pSrvrStmt->outputDescVarBufferLen,
maxRowCnt, pSrvrStmt->outputValueVarBuffer);
}
else
// Reset the length to 0, but the _buffer points to array of required SQLValue_defs
pSrvrStmt->outputValueList._length = 0;
if (rc == SQL_SUCCESS)
{
pSrvrStmt->maxRowCnt = maxRowCnt;
pSrvrStmt->maxRowLen = maxRowLen;
pSrvrStmt->currentMethod = odbc_SQLSvc_FetchN_ldx_;
rc = FETCH(pSrvrStmt);
switch (rc)
{
case SQL_SUCCESS:
break;
case SQL_SUCCESS_WITH_INFO:
GETSQLWARNING(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlWarning);
break;
case SQL_ERROR:
GETSQLERROR(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError);
break;
case ODBC_RG_WARNING:
// if there is RG_WARNING, we don't pass SQL Warning to the application
// Hence, we need to clear any warnings
// call SQL_EXEC_ClearDiagnostics
// CLEARDIAGNOSTICS(pSrvrStmt);
rc = SQL_SUCCESS_WITH_INFO;
case ODBC_SERVER_ERROR:
case ODBC_RG_ERROR:
default:
break;
}
}
switch (rc)
{
case SQL_SUCCESS:
case SQL_SUCCESS_WITH_INFO:
exception_->exception_nr = 0;
*rowsAffected = pSrvrStmt->rowsAffected;
outputValueList->_length = pSrvrStmt->outputValueList._length;
outputValueList->_buffer = pSrvrStmt->outputValueList._buffer;
sqlWarning->_length = pSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = pSrvrStmt->sqlWarning._buffer;
break;
case SQL_STILL_EXECUTING:
exception_->exception_nr = odbc_SQLSvc_FetchN_SQLStillExecuting_exn_;
break;
case SQL_INVALID_HANDLE:
exception_->exception_nr = odbc_SQLSvc_FetchN_SQLInvalidHandle_exn_;
break;
case SQL_NO_DATA_FOUND:
exception_->exception_nr = odbc_SQLSvc_FetchN_SQLNoDataFound_exn_;
break;
case SQL_ERROR:
ERROR_DESC_def *error_desc_def;
error_desc_def = pSrvrStmt->sqlError.errorList._buffer;
if (pSrvrStmt->sqlError.errorList._length != 0 && error_desc_def->sqlcode == -8007)
{
exception_->exception_nr = odbc_SQLSvc_FetchN_SQLQueryCancelled_exn_;
exception_->u.SQLQueryCancelled.sqlcode = error_desc_def->sqlcode;
}
else
{
exception_->exception_nr = odbc_SQLSvc_FetchN_SQLError_exn_;
exception_->u.SQLError.errorList._length = pSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = pSrvrStmt->sqlError.errorList._buffer;
}
break;
case PROGRAM_ERROR:
exception_->exception_nr = odbc_SQLSvc_FetchN_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_FETCH_FAILED;
default:
break;
}
if (resStatStatement != NULL && (rc == SQL_NO_DATA_FOUND || rc == SQL_ERROR || ((rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) && *rowsAffected < maxRowCnt)))
resStatStatement->setStatistics(pSrvrStmt);
}
//resource statistics
if (resStatStatement != NULL && pSrvrStmt != NULL && pSrvrStmt->isClosed == TRUE && pSrvrStmt->bFetchStarted == TRUE && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
if (rc == SQL_ERROR && exception_->u.SQLError.errorList._buffer != NULL)
{
ERROR_DESC_def *p_buffer = exception_->u.SQLError.errorList._buffer;
inErrorCode = p_buffer->sqlcode;
inSqlError = p_buffer->errorText;
inSqlErrorLength = strlen(p_buffer->errorText);
}
pSrvrStmt->bFetchStarted = FALSE;
Int32 inMaxRowCnt = 0;
Int32 inMaxRowLen = 0;
inMaxRowCnt = maxRowCnt;
inMaxRowLen = maxRowLen;
if (exception_->exception_nr != 0)
inErrorStatement ++;
else
setStatisticsFlag = FALSE;
if (sqlWarning->_length != 0)
inWarningStatement ++;
if (exception_->exception_nr == 5)
{
inErrorStatement = 0;
inWarningStatement = 0;
setStatisticsFlag = TRUE;
}
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
resStatStatement->setStatisticsFlag(setStatisticsFlag);
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlNewQueryType,
pSrvrStmt->isClosed);
}
// end rs
SRVRTRACE_EXIT(FILE_SME+4);
return;
}
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_EndTransaction'
*/
extern "C" void
odbc_SQLSvc_EndTransaction_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_EndTransaction_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ IDL_unsigned_short transactionOpt
, /* Out */ ERROR_DESC_LIST_def *sqlWarning
)
{
SRVRTRACE_ENTER(FILE_SME+5);
char stmtLabel[MAX_STMT_LABEL_LEN+1];
Int32 rc = SQL_SUCCESS;
SRVR_STMT_HDL *pSrvrStmt = NULL;
switch (transactionOpt) {
case SQL_COMMIT:
pSrvrStmt = getSrvrStmt("STMT_COMMIT_1", FALSE);
break;
case SQL_ROLLBACK:
pSrvrStmt = getSrvrStmt("STMT_ROLLBACK_1", FALSE);
break;
default:
exception_->exception_nr = odbc_SQLSvc_EndTransaction_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_TRANSACT_OPT;
return;
}
if (pSrvrStmt == NULL)
{
exception_->exception_nr = odbc_SQLSvc_EndTransaction_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
else
{
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if(pSrvrStmt->bSQLValueListSet)
pSrvrStmt->cleanupSQLValueList();
pSrvrStmt->inputRowCnt = 1;
pSrvrStmt->sqlStmtType = TYPE_UNKNOWN;
pSrvrStmt->cursorName[0] = '\0';
pSrvrStmt->cursorNameLen = 0;
pSrvrStmt->inputValueList._buffer = NULL;
pSrvrStmt->inputValueList._length = 0;
pSrvrStmt->currentMethod = odbc_SQLSvc_ExecuteN_ldx_;
rc = EXECUTE(pSrvrStmt);
if (rc == SQL_ERROR)
{
GETSQLERROR(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError);
ERROR_DESC_def *error_desc_def = pSrvrStmt->sqlError.errorList._buffer;
if (pSrvrStmt->sqlError.errorList._length != 0 )
{
if (error_desc_def != NULL && (error_desc_def->sqlcode == -8605 || error_desc_def->sqlcode == -8607 || error_desc_def->sqlcode == -8609))
{
exception_->exception_nr = 0;
sqlWarning->_length = 0;
sqlWarning->_buffer = NULL;
}
else
{
exception_->exception_nr = odbc_SQLSvc_EndTransaction_SQLError_exn_;
exception_->u.SQLError.errorList._length = pSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = pSrvrStmt->sqlError.errorList._buffer;
}
}
else
{
exception_->exception_nr = odbc_SQLSvc_EndTransaction_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_TRANSACT_OPT;
}
}
else if (rc != SQL_SUCCESS)
{
GETSQLWARNING(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlWarning);
exception_->exception_nr = 0;
sqlWarning->_length = pSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = pSrvrStmt->sqlWarning._buffer;
}
}
SRVRTRACE_EXIT(FILE_SME+5);
return;
}
//LCOV_EXCL_START
/*
* Synchronous method function prototype for
* operation 'odbc_SQLSvc_ExecDirect'
*/
extern "C" void
odbc_SQLSvc_ExecDirect_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_ExecDirect_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ const IDL_char *stmtLabel
, /* In */ IDL_string cursorName
, /* In */ const IDL_char *stmtExplainLabel
, /* In */ IDL_short stmtType
, /* In */ IDL_short sqlStmtType
, /* In */ IDL_string sqlString
, /* In */ IDL_short sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* Out */ Int32 *estimatedCost
, /* Out */ SQLItemDescList_def *outputDesc
, /* Out */ Int32 *rowsAffected
, /* Out */ ERROR_DESC_LIST_def *sqlWarning)
{
SRVRTRACE_ENTER(FILE_SME+6);
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQLRETURN rc = SQL_SUCCESS;
Int32 holdestimatedCost;
if (sqlString == NULL)
{
exception_->exception_nr = odbc_SQLSvc_ExecDirect_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_NULL_SQL_STMT;
}
else
{
// resource statistics
if (resStatStatement != NULL && stmtType == EXTERNAL_STMT)
{
inState = STMTSTAT_EXECDIRECT;
inSqlStmtType = sqlStmtType;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlError = NULL;
inSqlErrorLength = 0;
// resStatStatement->start(inState, stmtLabel, NULL, inEstimatedCost, sqlString); called in EXECDIRECT
}
//end rs
if ((pSrvrStmt = getSrvrStmt(stmtLabel, FALSE)) != NULL)
{
pSrvrStmt->cleanupAll();
pSrvrStmt->currentMethod = odbc_SQLSvc_Close_ldx_;
pSrvrStmt->freeResourceOpt = SQL_DROP;
FREESTATEMENT(pSrvrStmt);
}
// Need to validate the stmtLabel
// Given a label find out the SRVR_STMT_HDL
if ((pSrvrStmt = getSrvrStmt(stmtLabel, TRUE)) == NULL)
{
exception_->exception_nr = odbc_SQLSvc_ExecDirect_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
}
if (exception_->exception_nr == 0)
{
pSrvrStmt->cleanupAll();
if (resStatStatement != NULL && stmtType == EXTERNAL_STMT)
pSrvrStmt->inState = inState;
pSrvrStmt->sqlStringLen = strlen(sqlString);
pSrvrStmt->sqlString = new char[pSrvrStmt->sqlStringLen+1];
if (pSrvrStmt->sqlString == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "ExecDirect");
exit(0);
}
strcpy(pSrvrStmt->sqlString, sqlString);
pSrvrStmt->sqlStmtType = sqlStmtType;
if (exception_->exception_nr == 0)
{
pSrvrStmt->stmtType = stmtType;
if (cursorName != NULL && cursorName[0] != '\0')
{
pSrvrStmt->cursorNameLen = strlen(cursorName);
pSrvrStmt->cursorNameLen = pSrvrStmt->cursorNameLen < sizeof(pSrvrStmt->cursorName)? pSrvrStmt->cursorNameLen : sizeof(pSrvrStmt->cursorName);
strncpy(pSrvrStmt->cursorName, cursorName, sizeof(pSrvrStmt->cursorName));
pSrvrStmt->cursorName[sizeof(pSrvrStmt->cursorName)-1] = 0;
}
else
pSrvrStmt->cursorName[0] = '\0';
pSrvrStmt->currentMethod = odbc_SQLSvc_ExecDirect_ldx_;
rc = EXECDIRECT(pSrvrStmt);
switch (rc)
{
case SQL_SUCCESS:
break;
case SQL_SUCCESS_WITH_INFO:
GETSQLWARNING(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlWarning);
break;
case SQL_ERROR:
GETSQLERROR(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError);
break;
case ODBC_RG_WARNING:
// if there is RG_WARNING, we don't pass SQL Warning to the application
// Hence, we need to clear any warnings
// call SQL_EXEC_ClearDiagnostics
// CLEARDIAGNOSTICS(pSrvrStmt);
rc = SQL_SUCCESS_WITH_INFO;
case ODBC_SERVER_ERROR:
case ODBC_RG_ERROR:
default:
break;
}
switch (rc)
{
case SQL_SUCCESS:
case SQL_SUCCESS_WITH_INFO:
break;
default:
break;
}
switch (rc)
{
case SQL_SUCCESS:
case SQL_SUCCESS_WITH_INFO:
exception_->exception_nr = 0;
// Vijay - Changes to support not to parse tokens for statement type SELECT
holdestimatedCost = (Int32)pSrvrStmt->cost_info.totalTime; // SQL returns cost in a strcuture - cost.totalTime
if ((pSrvrStmt->sqlQueryType == SQL_SELECT_NON_UNIQUE) || (pSrvrStmt->sqlQueryType == SQL_SELECT_UNIQUE))
pSrvrStmt->sqlStmtType = TYPE_SELECT;
*estimatedCost = pSrvrStmt->sqlQueryType;
*rowsAffected = pSrvrStmt->rowsAffected;
outputDesc->_length = pSrvrStmt->outputDescList._length;
outputDesc->_buffer = pSrvrStmt->outputDescList._buffer;
sqlWarning->_length = pSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = pSrvrStmt->sqlWarning._buffer;
break;
case SQL_STILL_EXECUTING:
exception_->exception_nr = odbc_SQLSvc_ExecDirect_SQLStillExecuting_exn_;
break;
case ODBC_RG_ERROR:
case SQL_ERROR:
case INFOSTATS_STMT_NOT_FOUND:
ERROR_DESC_def *error_desc_def;
error_desc_def = pSrvrStmt->sqlError.errorList._buffer;
if (pSrvrStmt->sqlError.errorList._length != 0 && error_desc_def->sqlcode == -8007)
{
exception_->exception_nr = odbc_SQLSvc_ExecDirect_SQLQueryCancelled_exn_;
exception_->u.SQLQueryCancelled.sqlcode = error_desc_def->sqlcode;
}
else
{
exception_->exception_nr = odbc_SQLSvc_ExecDirect_SQLError_exn_;
exception_->u.SQLError.errorList._length = pSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = pSrvrStmt->sqlError.errorList._buffer;
}
break;
case PROGRAM_ERROR:
exception_->exception_nr = odbc_SQLSvc_ExecDirect_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECDIRECT_FAILED;
break;
default:
break;
}
if (resStatStatement != NULL)
resStatStatement->setStatistics(pSrvrStmt);
}
}
// resource statistics
if (resStatStatement != NULL && stmtType == EXTERNAL_STMT)
{
if (exception_->exception_nr != 0 && exception_->u.SQLError.errorList._buffer != NULL)
{
inErrorStatement ++;
ERROR_DESC_def *p_buffer = exception_->u.SQLError.errorList._buffer;
inErrorCode = p_buffer->sqlcode;
inSqlError = p_buffer->errorText;
inSqlErrorLength = strlen(p_buffer->errorText);
}
if (sqlWarning->_length != 0)
inWarningStatement ++;
inRowCount = *rowsAffected;
if (sqlString == NULL)
sqlString = "";
inSqlString = new char[strlen(sqlString) + 1];
if (inSqlString == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "inSqlString");
exit(0);
}
strcpy(inSqlString,sqlString);
if (pSrvrStmt != NULL)
{
if (holdestimatedCost == -1)
inEstimatedCost = 0;
else
inEstimatedCost = pSrvrStmt->cost_info.totalTime; // res stat reports estimated cost as double
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
inSqlNewQueryType = pSrvrStmt->sqlNewQueryType;
}
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
inSqlNewQueryType,
pSrvrStmt->isClosed);
delete inSqlString;
}
//end rs
SRVRTRACE_EXIT(FILE_SME+6);
return;
}
//LCOV_EXCL_STOP
//LCOV_EXCL_START
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_FetchPerf'
*/
extern "C" void
odbc_SQLSvc_FetchPerf_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_FetchPerf_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ const IDL_char *stmtLabel
, /* In */ Int32 maxRowCnt
, /* In */ Int32 maxRowLen
, /* In */ IDL_short sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* Out */ Int32 *rowsAffected
, /* Out */ SQL_DataValue_def *outputDataValue
, /* Out */ ERROR_DESC_LIST_def *sqlWarning)
{
SRVRTRACE_ENTER(FILE_SME+8);
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQLRETURN rc = SQL_SUCCESS;
if (maxRowCnt < 0)
{
exception_->exception_nr = odbc_SQLSvc_FetchPerf_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_ROW_COUNT;
}
else
{
if ((pSrvrStmt = getSrvrStmt(stmtLabel, FALSE)) == NULL)
{
exception_->exception_nr = odbc_SQLSvc_FetchPerf_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
}
if (exception_->exception_nr == 0)
{
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->isClosed == FALSE && pSrvrStmt->bFetchStarted == FALSE && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->bFetchStarted = TRUE;
pSrvrStmt->inState = inState = STMTSTAT_FETCH;
inSqlStmtType = TYPE_UNKNOWN;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlError = NULL;
inSqlErrorLength = 0;
/*resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt->sqlUniqueQueryID,
pSrvrStmt->cost_info,
pSrvrStmt->comp_stats_info,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);*/
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);
}
// end rs
if (pSrvrStmt->sqlStmtType != TYPE_SELECT_CATALOG)
{
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
pSrvrStmt->outputDataValue._length = 0;
pSrvrStmt->outputDataValue._buffer = 0;
if (pSrvrStmt->isClosed)
{
exception_->exception_nr = odbc_SQLSvc_FetchPerf_SQLNoDataFound_exn_;
goto ret;
}
pSrvrStmt->currentMethod = odbc_SQLSvc_FetchPerf_ldx_;
if (pSrvrStmt->sqlBulkFetchPossible && pSrvrStmt->sqlQueryType == SQL_SELECT_NON_UNIQUE)
{
if (pSrvrStmt->outputDataValue._buffer != NULL)
delete pSrvrStmt->outputDataValue._buffer;
pSrvrStmt->outputDataValue._buffer = NULL;
pSrvrStmt->outputDataValue._length = 0;
rc = FETCH2bulk(pSrvrStmt);
if (pSrvrStmt->rowsAffected > 0)
{
if(pSrvrStmt->outputDataValue._length == 0 && pSrvrStmt->outputDataValue._buffer == NULL)
{
outputDataValue->_buffer = pSrvrStmt->outputDescVarBuffer;
outputDataValue->_length = pSrvrStmt->outputDescVarBufferLen*pSrvrStmt->rowsAffected;
}
else
{
outputDataValue->_buffer = pSrvrStmt->outputDataValue._buffer;
outputDataValue->_length = pSrvrStmt->outputDataValue._length;
}
}
else
{
outputDataValue->_buffer = NULL;
outputDataValue->_length = 0;
}
// if (pSrvrStmt->PerfFetchRetcode == SQL_NO_DATA_FOUND)
// {
// char tmpString[32];
// tmpString[0] = '\0';
// sprintf(tmpString, "f: %Ld %d", pSrvrStmt->cliElapseTime, pSrvrStmt->rowsAffected);
// SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
// srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
// srvrGlobal->srvrObjRef, 1, tmpString);
// }
}
else
{
pSrvrStmt->maxRowCnt = maxRowCnt;
pSrvrStmt->maxRowLen = maxRowLen;
rc = FETCHPERF(pSrvrStmt, outputDataValue);
}
switch (rc)
{
case ODBC_SERVER_ERROR:
case ODBC_RG_ERROR:
default:
break;
}
switch (rc)
{
case ODBC_RG_WARNING:
// if there is RG_WARNING, we don't pass SQL Warning to the application
// Hence, we need to clear any warnings
// call SQL_EXEC_ClearDiagnostics
// CLEARDIAGNOSTICS(pSrvrStmt);
rc = SQL_SUCCESS_WITH_INFO;
case SQL_SUCCESS_WITH_INFO:
GETSQLWARNING(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlWarning);
case SQL_SUCCESS:
exception_->exception_nr = 0;
*rowsAffected = pSrvrStmt->rowsAffected;
sqlWarning->_length = pSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = pSrvrStmt->sqlWarning._buffer;
break;
case SQL_STILL_EXECUTING:
exception_->exception_nr = odbc_SQLSvc_FetchPerf_SQLStillExecuting_exn_;
break;
case SQL_INVALID_HANDLE:
exception_->exception_nr = odbc_SQLSvc_FetchPerf_SQLInvalidHandle_exn_;
break;
case SQL_NO_DATA_FOUND:
exception_->exception_nr = odbc_SQLSvc_FetchPerf_SQLNoDataFound_exn_;
break;
case SQL_ERROR:
GETSQLERROR(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError);
ERROR_DESC_def *error_desc_def;
error_desc_def = pSrvrStmt->sqlError.errorList._buffer;
if (pSrvrStmt->sqlError.errorList._length != 0 && error_desc_def->sqlcode == -8007)
{
exception_->exception_nr = odbc_SQLSvc_FetchPerf_SQLQueryCancelled_exn_;
exception_->u.SQLQueryCancelled.sqlcode = error_desc_def->sqlcode;
}
else
{
exception_->exception_nr = odbc_SQLSvc_FetchPerf_SQLError_exn_;
exception_->u.SQLError.errorList._length = pSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = pSrvrStmt->sqlError.errorList._buffer;
}
break;
case PROGRAM_ERROR:
exception_->exception_nr = odbc_SQLSvc_FetchPerf_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_FETCH_FAILED;
default:
break;
}
}
else
{ // Catalog APIs
pSrvrStmt->maxRowCnt = maxRowCnt;
pSrvrStmt->maxRowLen = maxRowLen;
rc = FETCHPERF(pSrvrStmt, outputDataValue);
if (pSrvrStmt->sqlError.errorList._buffer != NULL)
{
rc = SQL_ERROR;
ERROR_DESC_def *error_desc_def;
error_desc_def = pSrvrStmt->sqlError.errorList._buffer;
if (pSrvrStmt->sqlError.errorList._length != 0 && error_desc_def->sqlcode == -8007)
{
exception_->exception_nr = odbc_SQLSvc_FetchPerf_SQLQueryCancelled_exn_;
exception_->u.SQLQueryCancelled.sqlcode = error_desc_def->sqlcode;
}
else
{
exception_->exception_nr = odbc_SQLSvc_FetchPerf_SQLError_exn_;
exception_->u.SQLError.errorList._length = pSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = pSrvrStmt->sqlError.errorList._buffer;
}
}
else if (pSrvrStmt->rowsAffected == 0 || pSrvrStmt->rowsAffected == -1)
{
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
pSrvrStmt->outputDataValue._length = 0;
pSrvrStmt->outputDataValue._buffer = 0;
pSrvrStmt->InternalStmtClose(SQL_CLOSE);
rc = SQL_NO_DATA_FOUND;
exception_->exception_nr = odbc_SQLSvc_FetchPerf_SQLNoDataFound_exn_;
}
else
{
exception_->exception_nr = 0;
*rowsAffected = pSrvrStmt->rowsAffected;
outputDataValue->_length = pSrvrStmt->outputDataValue._length;
outputDataValue->_buffer = pSrvrStmt->outputDataValue._buffer;
sqlWarning->_length = pSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = pSrvrStmt->sqlWarning._buffer;
if (pSrvrStmt->sqlWarning._length != 0)
rc = SQL_SUCCESS_WITH_INFO;
else
rc = SQL_SUCCESS;
pSrvrStmt->rowsAffected = 0;
}
}
ret:
if (exception_->exception_nr != 0)
{
if (pSrvrStmt->outputDataValue._buffer != NULL)
delete pSrvrStmt->outputDataValue._buffer;
pSrvrStmt->outputDataValue._length = 0;
pSrvrStmt->outputDataValue._buffer = NULL;
}
if (resStatStatement != NULL && pSrvrStmt->bFetchStarted == TRUE &&
(rc == SQL_NO_DATA_FOUND || rc == SQL_ERROR ||
((rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) && *rowsAffected < maxRowCnt)))
{
resStatStatement->setStatistics(pSrvrStmt);
}
}
// resource statistics
if (resStatStatement != NULL && pSrvrStmt != NULL && pSrvrStmt->isClosed == TRUE && pSrvrStmt->bFetchStarted == TRUE && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
if (rc == SQL_ERROR && exception_->u.SQLError.errorList._buffer != NULL)
{
ERROR_DESC_def *p_buffer = exception_->u.SQLError.errorList._buffer;
inErrorCode = p_buffer->sqlcode;
inSqlError = p_buffer->errorText;
inSqlErrorLength = strlen(p_buffer->errorText);
}
pSrvrStmt->bFetchStarted = FALSE;
Int32 inMaxRowCnt = 0;
Int32 inMaxRowLen = 0;
inMaxRowCnt = maxRowCnt;
inMaxRowLen = maxRowLen;
if (exception_->exception_nr != 0)
inErrorStatement ++;
else
setStatisticsFlag = FALSE;
if (sqlWarning->_length != 0)
inWarningStatement ++;
if (exception_->exception_nr == 5)
{
inErrorStatement = 0;
inWarningStatement = 0;
setStatisticsFlag = TRUE;
}
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
resStatStatement->setStatisticsFlag(setStatisticsFlag);
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlNewQueryType,
pSrvrStmt->isClosed);
}
//end rs
SRVRTRACE_EXIT(FILE_SME+8);
return;
}
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_ExecuteCall'
*/
extern "C" void
odbc_SQLSvc_ExecuteCall_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_ExecuteCall_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ const IDL_char *stmtLabel
, /* In */ IDL_string cursorName
, /* In */ IDL_short sqlStmtType
, /* In */ Int32 inputRowCnt
, /* In */ const SQLValueList_def *inputValueList
, /* In */ IDL_short sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* Out */ SQLValueList_def *outputValueList
, /* Out */ Int32 *rowsAffected
, /* Out */ ERROR_DESC_LIST_def *sqlWarning)
{
SRVRTRACE_ENTER(FILE_SME+13);
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQLRETURN rc = SQL_SUCCESS;
/*
// resource statistics
inState = STMTSTAT_EXECUTE;
inSqlStmtType = sqlStmtType;
inEstimatedCost = 0;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
if (resStatStatement != NULL)
resStatStatement->start(inState, stmtLabel);
//end rs
*/
if ((pSrvrStmt = getSrvrStmt(stmtLabel, FALSE)) == NULL)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteCall_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
return;
}
if (exception_->exception_nr == 0)
{
rc = SQL_SUCCESS;
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if(pSrvrStmt->bSQLValueListSet)
pSrvrStmt->cleanupSQLValueList();
pSrvrStmt->inputValueList._buffer = inputValueList->_buffer;
pSrvrStmt->inputValueList._length = inputValueList->_length;
if (pSrvrStmt->outputValueList._buffer == NULL)
{
rc = AllocAssignValueBuffer(pSrvrStmt->bSQLValueListSet,&pSrvrStmt->outputDescList,
&pSrvrStmt->outputValueList, pSrvrStmt->outputDescVarBufferLen,
1, pSrvrStmt->outputValueVarBuffer);
}
else
pSrvrStmt->outputValueList._length = 0;
if (rc == SQL_SUCCESS)
{
pSrvrStmt->currentMethod = odbc_SQLSvc_ExecuteCall_ldx_;
rc = EXECUTECALL(pSrvrStmt);
switch (rc)
{
case SQL_SUCCESS:
break;
case SQL_SUCCESS_WITH_INFO:
GETSQLWARNING(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlWarning);
break;
case SQL_ERROR:
GETSQLERROR(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError);
break;
case ODBC_RG_WARNING:
// if there is RG_WARNING, we don't pass SQL Warning to the application
// Hence, we need to clear any warnings
// call SQL_EXEC_ClearDiagnostics
// CLEARDIAGNOSTICS(pSrvrStmt);
rc = SQL_SUCCESS_WITH_INFO;
case ODBC_SERVER_ERROR:
case ODBC_RG_ERROR:
default:
break;
}
switch (rc)
{
case SQL_SUCCESS:
case SQL_SUCCESS_WITH_INFO:
break;
case ODBC_SERVER_ERROR:
// Allocate Error Desc
kdsCreateSQLErrorException(pSrvrStmt->bSQLMessageSet, &pSrvrStmt->sqlError, 1);
// Add SQL Error
kdsCopySQLErrorException(&pSrvrStmt->sqlError, NULL_VALUE_ERROR, NULL_VALUE_ERROR_SQLCODE,
NULL_VALUE_ERROR_SQLSTATE);
break;
case -8814:
case 8814:
rc = SQL_RETRY_COMPILE_AGAIN;
break;
default:
break;
}
}
switch (rc)
{
case SQL_SUCCESS:
case SQL_SUCCESS_WITH_INFO:
exception_->exception_nr = 0;
// Copy the output values
*rowsAffected = 0;
outputValueList->_length = pSrvrStmt->outputValueList._length;
outputValueList->_buffer = pSrvrStmt->outputValueList._buffer;
sqlWarning->_length = pSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = pSrvrStmt->sqlWarning._buffer;
break;
case SQL_STILL_EXECUTING:
exception_->exception_nr = odbc_SQLSvc_ExecuteCall_SQLStillExecuting_exn_;
break;
case SQL_INVALID_HANDLE:
exception_->exception_nr = odbc_SQLSvc_ExecuteCall_SQLInvalidHandle_exn_;
break;
case SQL_NO_DATA_FOUND:
// Added this for JDBC T4 driver since its uses this interface to get zero or one row
// for select statement besides CALL statement.
exception_->exception_nr = 100;
break;
case SQL_NEED_DATA:
exception_->exception_nr = odbc_SQLSvc_ExecuteCall_SQLNeedData_exn_;
break;
case ODBC_SERVER_ERROR:
case SQL_ERROR:
ERROR_DESC_def *error_desc_def;
error_desc_def = pSrvrStmt->sqlError.errorList._buffer;
if (pSrvrStmt->sqlError.errorList._length != 0 && error_desc_def->sqlcode == -8007)
{
exception_->exception_nr = odbc_SQLSvc_ExecuteCall_SQLQueryCancelled_exn_;
exception_->u.SQLQueryCancelled.sqlcode = error_desc_def->sqlcode;
}
else
{
exception_->exception_nr = odbc_SQLSvc_ExecuteCall_SQLError_exn_;
exception_->u.SQLError.errorList._length = pSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = pSrvrStmt->sqlError.errorList._buffer;
}
break;
case -8814:
case 8814:
exception_->exception_nr = odbc_SQLSvc_ExecuteCall_SQLRetryCompile_exn_;
break;
case PROGRAM_ERROR:
exception_->exception_nr = odbc_SQLSvc_ExecuteCall_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECUTE_FAILED;
default:
break;
}
/* SQL doesn't return statistics for Call statement?
if (resStatStatement != NULL && (srvrGlobal->resourceStatistics & STMTSTAT_EXECUTE))
resStatStatement->setStatistics(pSrvrStmt);
*/
}
/* SQL doesn't return statistics for Call statement?
// resource statistics
if (exception_.exception_nr != 0 && exception_.u.SQLError.errorList._buffer != NULL)
{
inErrorCode = exception_.u.SQLError.errorList._buffer->sqlcode;
inErrorStatement ++;
}
if (sqlWarning._length != 0)
inWarningStatement ++;
inRowCount = rowsAffected;
if (resStatStatement != NULL)
resStatStatement->end(inState,inSqlStmtType,inEstimatedCost,inSqlString,inErrorStatement,inWarningStatement,inRowCount,inErrorCode, resStatSession);
//end rs
*/
SRVRTRACE_EXIT(FILE_SME+13);
return;
}
//LCOV_EXCL_STOP
/*
* * Synchronous method function prototype for
* * operation 'odbc_SQLSvc_GetSQLCatalogs'
* */
extern "C" void
odbc_SQLSvc_GetSQLCatalogs_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_GetSQLCatalogs_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ const IDL_char *stmtLabel
, /* In */ IDL_short APIType
, /* In */ const IDL_char *catalogNm
, /* In */ const IDL_char *schemaNm
, /* In */ const IDL_char *tableNm
, /* In */ const IDL_char *tableTypeList
, /* In */ const IDL_char *columnNm
, /* In */ Int32 columnType
, /* In */ Int32 rowIdScope
, /* In */ Int32 nullable
, /* In */ Int32 uniqueness
, /* In */ Int32 accuracy
, /* In */ IDL_short sqlType
, /* In */ UInt32 metadataId
, /* In */ const IDL_char *fkcatalogNm
, /* In */ const IDL_char *fkschemaNm
, /* In */ const IDL_char *fktableNm
, /* Out */ IDL_char *catStmtLabel
, /* Out */ SQLItemDescList_def *outputDesc
, /* Out */ ERROR_DESC_LIST_def *sqlWarning
)
{
SRVRTRACE_ENTER(FILE_SME+14);
enum CATAPI_TABLE_INDEX {
COLUMNS = 0,
DEFAULTS,
INDEXES,
KEYS,
OBJECTS,
OBJECTUID,
TABLES,
VIEWS,
VIEWS_USAGE,
VERSIONS
};
char *smdCatAPITablesList[] = {
"COLUMNS",
"DEFAULTS",
"INDEXES",
"KEYS",
"OBJECTS",
"OBJECTUID",
"TABLES",
"VIEWS",
"VIEWS_USAGE",
"VERSIONS"
};
char CatalogQuery[20000];
SRVR_STMT_HDL *QryCatalogSrvrStmt = NULL;
odbc_SQLSvc_Prepare_exc_ prepareException;
odbc_SQLSvc_ExecuteN_exc_ executeException;
char *inputParam[16];
char *tableParam[20];
short retCode;
char RequestError[200 + 1];
char ConvertAPITypeToString[30];
Int32 curRowNo = 0;
Int32 numOfCols = 0;
Int32 curColNo = 0;
Int32 rowsAffected = 0;
Int32 rowsFetched;
char SQLObjType[2];
short EnvSetting = 0;
char MapDataType[2] = "0";
short retcode = 0;
char tmpBuf[20];
char odbcAppVersion[20];
char lc_tableTypeList[MAX_ANSI_NAME_LEN+1];
char *token;
char* saveptr;
odbc_SQLSvc_FetchN_exc_ fetchException;
odbc_SQLSvc_Close_exc_ CloseException;
CloseException.exception_nr=0;
fetchException.exception_nr=0;
if (resStatSession != NULL)
resStatSession->totalCatalogStatements++;
char catalogNmNoEsc[MAX_ANSI_NAME_LEN+1];
char schemaNmNoEsc[MAX_ANSI_NAME_LEN+1];
char tableNmNoEsc[MAX_ANSI_NAME_LEN+1];
char columnNmNoEsc[MAX_ANSI_NAME_LEN+1];
char expCatalogNm[MAX_ANSI_NAME_LEN+1];
char expSchemaNm[MAX_ANSI_NAME_LEN+1];
char expTableNm[MAX_ANSI_NAME_LEN+1];
char expColumnNm[MAX_ANSI_NAME_LEN+1];
char tableName1[MAX_ANSI_NAME_LEN+MAX_ANSI_NAME_LEN+MAX_ANSI_NAME_LEN+3];
char tableName2[MAX_ANSI_NAME_LEN+MAX_ANSI_NAME_LEN+MAX_ANSI_NAME_LEN+3];
char tableName3[MAX_ANSI_NAME_LEN+MAX_ANSI_NAME_LEN+MAX_ANSI_NAME_LEN+3];
_itoa(srvrGlobal->appVersion.majorVersion, odbcAppVersion, 10);
if(diagnostic_flags)
{
switch (APIType)
{
case SQL_API_SQLTABLES:
sprintf(ConvertAPITypeToString, "SQLTables (%d)", SQL_API_SQLTABLES);
break;
case SQL_API_SQLCOLUMNS:
sprintf(ConvertAPITypeToString, "SQLColumns (%d)", SQL_API_SQLCOLUMNS);
break;
case SQL_API_SQLCOLUMNPRIVILEGES:
sprintf(ConvertAPITypeToString, "SQLColumnPrivileges (%d)", SQL_API_SQLCOLUMNPRIVILEGES);
break;
case SQL_API_SQLFOREIGNKEYS:
sprintf(ConvertAPITypeToString, "SQLForeignKeys (%d)", SQL_API_SQLFOREIGNKEYS);
break;
case SQL_API_SQLPRIMARYKEYS:
sprintf(ConvertAPITypeToString, "SQLPrimaryKeys (%d)", SQL_API_SQLPRIMARYKEYS);
break;
case SQL_API_SQLSPECIALCOLUMNS:
sprintf(ConvertAPITypeToString, "SQLSpecialColumns (%d)", SQL_API_SQLSPECIALCOLUMNS);
break;
case SQL_API_SQLSTATISTICS:
sprintf(ConvertAPITypeToString, "SQLStatistics (%d)", SQL_API_SQLSTATISTICS);
break;
case SQL_API_SQLTABLEPRIVILEGES:
sprintf(ConvertAPITypeToString, "SQLTablePrivileges (%d)", SQL_API_SQLTABLEPRIVILEGES);
break;
case SQL_API_SQLGETTYPEINFO:
sprintf(ConvertAPITypeToString, "SQLGetTypeInfo (%d)", SQL_API_SQLGETTYPEINFO);
break;
case SQL_API_SQLPROCEDURES:
sprintf(ConvertAPITypeToString, "SQLProcedures (%d)", SQL_API_SQLPROCEDURES);
break;
case SQL_API_SQLPROCEDURECOLUMNS:
sprintf(ConvertAPITypeToString, "SQLProcedureColumns (%d)", SQL_API_SQLPROCEDURECOLUMNS);
break;
case SQL_API_TBLSYNONYM:
sprintf(ConvertAPITypeToString, "SQLTblsynonym (%d)", SQL_API_TBLSYNONYM);
break;
case SQL_API_TBLMVS:
sprintf(ConvertAPITypeToString, "SQLTblMvs (%d)", SQL_API_TBLMVS);
break;
default:
sprintf(ConvertAPITypeToString, "Invalid Catalog API (%d)", APIType);
break;
}
TraceOut(TR_SRVR_KRYPTON_API,"odbc_SQLSvc_GetSQLCatalogs_sme_(%#x, %#x, %#x, %ld, %s, %s, %s, %s, %s, %s, %s, %ld, %ld, %ld, %ld, %ld, %d, %s, %#x, %#x)",
objtag_,
call_id_,
exception_,
dialogueId,
stmtLabel,
ConvertAPITypeToString,
catalogNm,
schemaNm,
tableNm,
tableTypeList,
columnNm,
columnType,
rowIdScope,
nullable,
uniqueness,
accuracy,
sqlType,
fkcatalogNm,
fkschemaNm,
fktableNm,
catStmtLabel,
outputDesc,
sqlWarning);
}
if (stmtLabel != NULL)
odbc_SQLSvc_Close_sme_(objtag_, call_id_, &CloseException, dialogueId, stmtLabel,
SQL_DROP, &rowsAffected, sqlWarning);
if ((tableNm[0] == '\0') && (columnNm[0] == '\0') && (metadataId == 1))
metadataId = 0;
if (APIType != SQL_API_SQLTABLES && APIType != SQL_API_SQLTABLES_JDBC)
{
if (tableNm[0] == '\0')
strcpy((char *)tableNm,"%");
if (columnNm[0] == '\0')
strcpy((char *)columnNm,"%");
}
exception_->exception_nr = 0;
CatalogQuery[0] = '\0';
strcpy(catStmtLabel, stmtLabel);
switch(APIType)
{
case SQL_API_SQLTABLES :
case SQL_API_SQLTABLES_JDBC :
if ((strcmp(catalogNm,"%") == 0) && (strcmp(schemaNm,"") == 0) && (strcmp(tableNm,"") == 0))
{
strcpy(catalogNmNoEsc, SEABASE_MD_CATALOG);
inputParam[0] = catalogNmNoEsc;
inputParam[1] = inputParam[0];
inputParam[2] = NULL;
if (APIType == SQL_API_SQLTABLES)
{
// strcpy((char *)catStmtLabel, "SQL_TABLES_ANSI_Q1");
snprintf(CatalogQuery, sizeof(CatalogQuery),
"select distinct(cast('%s' as varchar(128))) TABLE_CAT, "
"cast(NULL as varchar(128) ) TABLE_SCHEM, "
"cast(NULL as varchar(128) ) TABLE_NAME, "
"cast(NULL as varchar(128) ) TABLE_TYPE, "
"cast(NULL as varchar(128)) REMARKS "
"from TRAFODION.\"_MD_\".objects "
"where CATALOG_NAME = '%s' "
"FOR READ UNCOMMITTED ACCESS ORDER BY 4,1,2,3;",
inputParam[0], inputParam[1]);
}
else
{
// strcpy((char *)catStmtLabel, "SQL_JAVA_TABLES_ANSI_Q1");
snprintf(CatalogQuery, sizeof(CatalogQuery),
"select distinct(cast('%s' as varchar(128) )) TABLE_CAT "
"from TRAFODION.\"_MD_\".objects "
"where CATALOG_NAME = '%s' "
"FOR READ UNCOMMITTED ACCESS ORDER BY 1;",
inputParam[0], inputParam[1]);
}
}
else
if ((strcmp(catalogNm,"") == 0) && (strcmp(schemaNm,"%") == 0) && (strcmp(tableNm,"") == 0))
{
convertWildcard(metadataId, TRUE, schemaNm, expSchemaNm);
strcpy(catalogNmNoEsc, SEABASE_MD_CATALOG);
inputParam[0] = catalogNmNoEsc;
inputParam[1] = inputParam[0];
inputParam[2] = (char*) schemaNm;
inputParam[3] = expSchemaNm;
inputParam[4] = NULL;
if (APIType == SQL_API_SQLTABLES)
{
// strcpy((char *)catStmtLabel, "SQL_TABLES_ANSI_Q2");
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select distinct cast(NULL as varchar(128) ) TABLE_CAT, "
"cast(trim(SCHEMA_NAME) as varchar(128) ) TABLE_SCHEM, "
"cast(NULL as varchar(128) ) TABLE_NAME, "
"cast(NULL as varchar(128) ) TABLE_TYPE, "
"cast(NULL as varchar(128)) REMARKS "
"from TRAFODION.\"_MD_\".objects "
"where "
"(CATALOG_NAME = '%s' or "
" CATALOG_NAME LIKE '%s' ESCAPE '\\') "
"and (SCHEMA_NAME = '%s' or "
"SCHEMA_NAME LIKE '%s' ESCAPE '\\') "
"FOR READ UNCOMMITTED ACCESS ORDER BY 4,1,2,3;",
inputParam[0], inputParam[1], inputParam[2],
inputParam[3]);
}
else
{
// strcpy((char *)catStmtLabel, "SQL_JAVA_TABLES_ANSI_Q2");
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select distinct "
"cast(trim(SCHEMA_NAME) as varchar(128) ) TABLE_SCHEM, "
"cast(trim(CATALOG_NAME) as varchar(128) ) TABLE_CATALOG "
"from TRAFODION.\"_MD_\".objects "
"where "
"(CATALOG_NAME = '%s' or "
" CATALOG_NAME LIKE '%s' ESCAPE '\\') "
"and (SCHEMA_NAME = '%s' or "
"SCHEMA_NAME LIKE '%s' ESCAPE '\\') "
"FOR READ UNCOMMITTED ACCESS ORDER BY 2;",
inputParam[0], inputParam[1], inputParam[2],
inputParam[3]);
}
}
else
if ((strcmp(catalogNm,"") == 0) && (strcmp(schemaNm,"")
== 0) && (strcmp(tableNm,"") == 0) && (strcmp(tableTypeList,"%") == 0))
{
strcpy(catalogNmNoEsc, "%");
strcpy(schemaNmNoEsc, "%");
strcpy(tableNmNoEsc, "%");
// strcpy((char *)catStmtLabel, "SQL_TABLES_ANSI_Q4");
tableParam[0] = NULL;
inputParam[0] = NULL;
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select cast(NULL as varchar(128) ) TABLE_CAT,"
"cast(NULL as varchar(128) ) TABLE_SCHEM, "
"cast(NULL as varchar(128) ) TABLE_NAME,"
"trim(TABLE_TYPE) TABLE_TYPE,"
"cast(NULL as varchar(128)) REMARKS "
" from (VALUES "
"('TABLE'),"
"('SYSTEM TABLE'),"
"('VIEW'))"
" tp (\"TABLE_TYPE\")"
" FOR READ UNCOMMITTED ACCESS ORDER BY 4,1,2,3;");
}
else
{
if (tableNm[0] == '\0')
strcpy((char *)tableNmNoEsc,"%");
if (! checkIfWildCard(catalogNm, expCatalogNm))
{
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_WILDCARD_NOT_SUPPORTED;
goto MapException;
}
if (strcmp(catalogNm,"") == 0) // If catalog empty default to system catalog
strcpy(tableName1,SEABASE_MD_CATALOG);
else
{
strncpy(tableName1,catalogNm, sizeof(tableName1));
tableName1[sizeof(tableName1)-1] = 0;
}
tableParam[0] = tableName1;
tableParam[1] = NULL;
convertWildcardNoEsc(metadataId, TRUE, schemaNm,schemaNmNoEsc);
convertWildcard(metadataId, TRUE, schemaNm, expSchemaNm);
if (tableNm[0] == '\0')
{
convertWildcardNoEsc(metadataId, TRUE, tableNmNoEsc, tableNmNoEsc);
convertWildcard(metadataId, TRUE, tableNmNoEsc, expTableNm);
}
else
{
convertWildcardNoEsc(metadataId, TRUE, tableNm, tableNmNoEsc);
convertWildcard(metadataId, TRUE, tableNm, expTableNm);
}
inputParam[0] = schemaNmNoEsc;
inputParam[1] = expSchemaNm;
inputParam[2] = tableNmNoEsc;
inputParam[3] = expTableNm;
if (tableTypeList == NULL || strlen(tableTypeList) == 0 || strcmp(tableTypeList,"%") == 0)
{
inputParam[4] = "UT"; // User Table
inputParam[5] = "BT";
inputParam[6] = "VI";
inputParam[7] = "SM"; // System MetaData
inputParam[8] = "BT";
inputParam[9] = NULL;
}
else
{
inputParam[4] = "";
inputParam[5] = "";
inputParam[6] = "";
inputParam[7] = "";
inputParam[8] = "";
inputParam[9] = NULL;
strncpy(lc_tableTypeList, tableTypeList, sizeof(lc_tableTypeList));
lc_tableTypeList[sizeof(lc_tableTypeList)-1] = 0;
token = strtok_r(lc_tableTypeList, " ,'", &saveptr);
while (token != NULL)
{
if (strcmp(token, "SYSTEM") == 0
)
{
token = strtok_r(NULL, ",'", &saveptr);
if (token != NULL && strcmp(token, "TABLE") == 0)
{
inputParam[7] = "SM";
inputParam[8] = "BT";
}
else
continue;
}
else
if (strcmp(token, "TABLE") == 0) {
inputParam[4] = "UT";
inputParam[5] = "BT";
}
else
if (strcmp(token, "VIEW") == 0)
{
inputParam[4] = "UT";
inputParam[6] = "VI";
}
token = strtok_r(NULL, " ,'", &saveptr);
}
}
if (APIType == SQL_API_SQLTABLES)
{
// strcpy((char *)catStmtLabel, "SQL_TABLES_ANSI_Q7");
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select cast('%s' as varchar(128) ) TABLE_CAT,"
"cast(trim(SCHEMA_NAME) as varchar(128) ) TABLE_SCHEM,"
"cast(trim(OBJECT_NAME) as varchar(128) ) TABLE_NAME,"
"trim(case OBJECT_TYPE "
"when 'BT' then 'TABLE' "
"when 'VI' then 'VIEW' "
"end) TABLE_TYPE,"
"cast(NULL as varchar(128)) REMARKS "
" from TRAFODION.\"_MD_\".OBJECTS "
" where (SCHEMA_NAME = '%s' or "
" trim(SCHEMA_NAME) LIKE '%s' ESCAPE '\\')"
" and (OBJECT_NAME = '%s' or"
" trim(OBJECT_NAME) LIKE '%s' ESCAPE '\\')"
" and ((SCHEMA_NAME <> '_MD_' and '%s'='UT' and OBJECT_TYPE in ('%s', '%s'))"
" or (SCHEMA_NAME = '_MD_' and '%s'='SM' and OBJECT_TYPE in ('%s')))"
" FOR READ UNCOMMITTED ACCESS ORDER BY 4, 1, 2, 3 ;",
tableParam[0], inputParam[0], inputParam[1],
inputParam[2], inputParam[3], inputParam[4],
inputParam[5], inputParam[6], inputParam[7],
inputParam[8]);
}
else
{
// strcpy((char *)catStmtLabel, "SQL_JAVA_TABLES_ANSI_Q7");
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select cast('%s' as varchar(128) ) TABLE_CAT,"
"cast(trim(SCHEMA_NAME) as varchar(128) ) TABLE_SCHEM,"
"cast(trim(OBJECT_NAME) as varchar(128) ) TABLE_NAME,"
"trim(case OBJECT_TYPE "
"when 'BT' then 'TABLE' "
"when 'VI' then 'VIEW' "
"end) TABLE_TYPE,"
"cast(NULL as varchar(128)) REMARKS, "
"cast(NULL as varchar(128)) TYPE_CAT,"
"cast(NULL as varchar(128)) TYPE_SCHEM, "
"cast(NULL as varchar(128)) TYPE_NAME,"
"cast(NULL as varchar(128)) SELF_REFERENCING_COL_NAME, "
"cast(NULL as varchar(128)) REF_GENERATION"
" from TRAFODION.\"_MD_\".OBJECTS "
" where (SCHEMA_NAME = '%s' or "
" trim(SCHEMA_NAME) LIKE '%s' ESCAPE '\\')"
" and (OBJECT_NAME = '%s' or"
" trim(OBJECT_NAME) LIKE '%s' ESCAPE '\\')"
" and ((SCHEMA_NAME <> '_MD_' and '%s'='UT' and OBJECT_TYPE in ('%s', '%s'))"
" or (SCHEMA_NAME = '_MD_' and '%s'='SM' and OBJECT_TYPE in ('%s')))"
" FOR READ UNCOMMITTED ACCESS ORDER BY 4, 1, 2, 3 ;",
tableParam[0], inputParam[0], inputParam[1],
inputParam[2], inputParam[3], inputParam[4],
inputParam[5], inputParam[6], inputParam[7],
inputParam[8]);
}
}
break;
case SQL_API_SQLGETTYPEINFO :
{
char condExpression[20] = {0};
switch(sqlType) {
case SQL_DATE:
sqlType == SQL_TYPE_DATE;
break;
case SQL_TIME:
sqlType == SQL_TYPE_TIME;
break;
case SQL_TIMESTAMP:
sqlType == SQL_TYPE_TIMESTAMP;
break;
default:
break;
}
if(sqlType == SQL_ALL_TYPES)
sprintf(condExpression, "1=1");
else
sprintf(condExpression, "DATA_TYPE=%d", sqlType);
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select distinct TYPE_NAME TYPE_NAME,"
"DATA_TYPE DATA_TYPE,PREC COLUMN_SIZE,"
"LITERAL_PREFIX LITERAL_PREFIX,"
"LITERAL_SUFFIX LITERAL_SUFFIX,"
"CREATE_PARAMS CREATE_PARAMS,"
"IS_NULLABLE NULLABLE,"
"CASE_SENSITIVE CASE_SENSITIVE,"
"SEARCHABLE SEARCHABLE,"
"UNSIGNED_ATTRIBUTE UNSIGNED_ATTRIBUTE,"
"FIXED_PREC_SCALE FIXED_PREC_SCALE,"
"AUTO_UNIQUE_VALUE AUTO_UNIQUE_VALUE,"
"LOCAL_TYPE_NAME LOCAL_TYPE_NAME,"
"MINIMUM_SCALE MINIMUM_SCALE,"
"MAXIMUM_SCALE MAXIMUM_SCALE,"
"SQL_DATA_TYPE SQL_DATA_TYPE,"
"SQL_DATETIME_SUB SQL_DATETIME_SUB,"
"NUM_PREC_RADIX NUM_PREC_RADIX,"
"INTERVAL_PRECISION INTERVAL_PRECISION "
" from "
" (VALUES "
"(cast('BIGINT' as varchar(128)),cast(-5 as smallint), cast(19 as integer), cast (NULL as varchar(128)), cast (NULL as varchar(128)),"
"cast (NULL as varchar(128)), cast(1 as smallint), cast(0 as smallint), cast(2 as smallint) , cast(0 as smallint), cast(0 as smallint),"
"cast(0 as smallint), cast('LARGEINT' as varchar(128)), cast(NULL as smallint), cast(NULL as smallint), cast('LARGEINT' as varchar(128)),"
"cast(10 as smallint), cast(19 as integer), cast(20 as integer), cast(-402 as smallint), cast(NULL as smallint), cast(NULL as smallint),"
"cast(0 as smallint), cast(0 as smallint), cast(3 as smallint), cast(0 as smallint)),"
"('BIGINT SIGNED', -5, 19, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'LARGEINT', NULL, NULL, 'SIGNED LARGEINT', 19, 19, -1, -5, NULL, NULL, 0, 0, 3, 0),"
"('BIGINT UNSIGNED', -5, 20, NULL, NULL, NULL, 1, 0, 2, 1, 0, 0, 'LARGEINT', NULL, NULL, 'UNSIGNED LARGEINT', 20, 20, -1, -405, NULL, NULL, 0, 0, 3, 0),"
"('CHAR', 1, 32000, '''', '''', 'max length', 1, 1, 3, NULL, 0, NULL, 'CHARACTER', NULL, NULL, 'CHARACTER', NULL, -1, -1, 1, NULL, NULL, 0, 0, 3, 0),"
"('NCHAR', -8, 32000, '''', '''', 'max length', 1, 1, 3, NULL, 0, NULL, 'WCHAR', NULL, NULL, 'WCHAR', NULL, -1, -1, -8, NULL, NULL, 0, 0, 3, 0),"
"('NCHAR VARYING', -9, 32000, '''', '''', 'max length', 1, 1, 3, NULL, 0, NULL, 'WCHAR VARYING', NULL, NULL, 'VARWCHAR', NULL, -1, -1, -9, NULL, NULL, 0, 0, 3, 0),"
"('DATE', 91, 10, '{d ''', '''}', NULL, 1, 0, 2, NULL, 0, NULL, 'DATE', NULL, NULL, 'DATE', NULL, 10, 6, 9, 1, NULL, 1, 3, 3, 0),"
"('DECIMAL', 3, 18, NULL, NULL, 'precision,scale', 1, 0, 2, 0, 0, 0, 'DECIMAL', 0, 18, 'DECIMAL', 10, -2, -3, 3, NULL, NULL, 0, 0, 3, 0),"
"('DECIMAL SIGNED', 3, 18, NULL, NULL, 'precision,scale', 1, 0, 2, 0, 0, 0, 'DECIMAL', 0, 18, 'SIGNED DECIMAL', 10, -2, -3, 3, NULL, NULL, 0, 0, 3, 0),"
"('DECIMAL UNSIGNED', 3, 18, NULL, NULL, 'precision,scale', 1, 0, 2, 1, 0, 0, 'DECIMAL', 0, 18, 'UNSIGNED DECIMAL', 10, -2, -3, -301, NULL, NULL, 0, 0, 3, 0),"
"('DOUBLE PRECISION', 8, 15, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'DOUBLE', NULL, NULL, 'DOUBLE PRECISION', 2, 54, -1, 8, NULL, NULL, 0, 0, 3, 0),"
"('DOUBLE PRECISION', 8, 15, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'DOUBLE', NULL, NULL, 'DOUBLE', 2, 54, -1, 8, NULL, NULL, 0, 0, 3, 0),"
"('FLOAT', 6, 15, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'FLOAT', NULL, NULL, 'FLOAT', 2, -2, -1, 6, NULL, NULL, 0, 0, 3, 0),"
"('INTEGER', 4, 9, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'INTEGER', NULL, NULL, 'INTEGER', 9, 9, -1, 4, NULL, NULL, 0, 0, 3, 0),"
"('INTEGER SIGNED', 4, 9, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'INTEGER', NULL, NULL, 'SIGNED INTEGER', 9, 9, -1, 4, NULL, NULL, 0, 0, 3, 0),"
"('INTEGER UNSIGNED', 4, 10, NULL, NULL, NULL, 1, 0, 2, 1, 0, 0, 'INTEGER', NULL, NULL, 'UNSIGNED INTEGER', 10, 10, -1, -401, NULL, NULL, 0, 0, 3, 0),"
"('INTERVAL', 113, 0, '{INTERVAL ''', ''' MINUTE TO SECOND}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 3, 34, 100, 13, 2, 5, 6, 3, 0),"
"('INTERVAL', 105, 0, '{INTERVAL ''', ''' MINUTE}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 0, 34, 100, 5, 2, 5, 5, 3, 0),"
"('INTERVAL', 101, 0, '{INTERVAL ''', ''' YEAR}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 0, 34, 100, 1, 2, 1, 1, 3, 0),"
"('INTERVAL', 106, 0, '{INTERVAL ''', ''' SECOND}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 0, 34, 100, 6, 2, 6, 6, 3, 0),"
"('INTERVAL', 104, 0, '{INTERVAL ''', ''' HOUR}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 0, 34, 100, 4, 2, 4, 4, 3, 0),"
"('INTERVAL', 107, 0, '{INTERVAL ''', ''' YEAR TO MONTH}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 3, 34, 100, 7, 2, 1, 2, 3, 0),"
"('INTERVAL', 108, 0, '{INTERVAL ''', ''' DAY TO HOUR}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 3, 34, 100, 8, 2, 3, 4, 3, 0),"
"('INTERVAL', 102, 0, '{INTERVAL ''', ''' MONTH}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 0, 34, 100, 2, 2, 2, 2, 3, 0),"
"('INTERVAL', 111, 0, '{INTERVAL ''', ''' HOUR TO MINUTE}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 3, 34, 100, 11, 2, 4, 5, 3, 0),"
"('INTERVAL', 112, 0, '{INTERVAL ''', ''' HOUR TO SECOND}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 6, 34, 100, 12, 2, 4, 6, 3, 0),"
"('INTERVAL', 110, 0, '{INTERVAL ''', ''' DAY TO SECOND}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 9, 34, 100, 10, 2, 3, 6, 3, 0),"
"('INTERVAL', 109, 0, '{INTERVAL ''', ''' DAY TO MINUTE}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 6, 34, 100, 9, 2, 3, 5, 3, 0),"
"('INTERVAL', 103, 0, '{INTERVAL ''', ''' DAY}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', NULL, 0, 34, 100, 3, 2, 3, 3, 3, 0),"
"('NUMERIC', 2, 128, NULL, NULL, 'precision,scale', 1, 0, 2, 0, 0, 0, 'NUMERIC', 0, 128, 'NUMERIC', 10, -2, -3, 2, NULL, NULL, 0, 0, 3, 0),"
"('NUMERIC SIGNED', 2, 128, NULL, NULL, 'precision,scale', 1, 0, 2, 0, 0, 0, 'NUMERIC', 0, 128, 'SIGNED NUMERIC', 10, -2, -3, 2, NULL, NULL, 0, 0, 3, 0),"
"('NUMERIC UNSIGNED', 2, 128, NULL, NULL, 'precision,scale', 1, 0, 2, 1, 0, 0, 'NUMERIC', 0, 128, 'UNSIGNED NUMERIC', 10, -2, -3, 2, NULL, NULL, 0, 0, 3, 0),"
"('REAL', 7, 7, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'REAL', NULL, NULL, 'REAL', 2, 22, -1, 7, NULL, NULL, 0, 0, 3, 0),"
"('SMALLINT', 5, 5, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'SMALLINT', NULL, NULL, 'SMALLINT', 5, 5, -1, 5, NULL, NULL, 0, 0, 3, 0),"
"('SMALLINT SIGNED', 5, 5, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'SMALLINT', NULL, NULL, 'SIGNED SMALLINT', 5, 5, -1, 5, NULL, NULL, 0, 0, 3, 0),"
"('SMALLINT UNSIGNED', 5, 5, NULL, NULL, NULL, 1, 0, 2, 1, 0, 0, 'SMALLINT', NULL, NULL, 'UNSIGNED SMALLINT', 5, 5, -1, -502, NULL, NULL, 0, 0, 3, 0),"
"('TIME', 92, 8, '{t ''', '''}', NULL, 1, 0, 2, NULL, 0, NULL, 'TIME', NULL, NULL, 'TIME', NULL, 8, 6, 9, 2, NULL, 4, 6, 3, 0),"
"('TIMESTAMP', 93, 26, '{ts ''', '''}', NULL, 1, 0, 2, NULL, 0, NULL, 'TIMESTAMP', 0, 6, 'TIMESTAMP', NULL, 19, 16, 9, 3, NULL, 1, 6, 3, 0),"
"('VARCHAR', 12, 32000, '''', '''', 'max length', 1, 1, 3, NULL, 0, NULL, 'VARCHAR', NULL, NULL, 'VARCHAR', NULL, -1, -1, 12, NULL, NULL, 0, 0, 3, 0),"
"('LONG VARCHAR', -1, 2000, '''', '''', 'max length', 1, 1, 3, NULL, 0, NULL, 'LONG VARCHAR', NULL, NULL, 'VARCHAR', NULL, -1, -1, -1, NULL, NULL, 0, 0, 3, 0),"
"('TINYINT', -6, 3, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'TINYINT', NULL, NULL, 'TINYINT', 3, 3, -1, 4, NULL, NULL, 0, 0, 3, 0),"
"('TINYINT SIGNED', -6, 3, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'TINYINT', NULL, NULL, 'SIGNED TINYINT', 3, 3, -1, 4, NULL, NULL, 0, 0, 3, 0),"
"('TINYINT UNSIGNED', -6, 3, NULL, NULL, NULL, 1, 0, 2, 1, 0, 0, 'TINYINT', NULL, NULL, 'UNSIGNED TINYINT', 3, 3, -1, -404, NULL, NULL, 0, 0, 3, 0)"
" ) "
" dt(\"TYPE_NAME\", \"DATA_TYPE\", \"PREC\", \"LITERAL_PREFIX\", \"LITERAL_SUFFIX\", \"CREATE_PARAMS\", \"IS_NULLABLE\", \"CASE_SENSITIVE\", \"SEARCHABLE\","
"\"UNSIGNED_ATTRIBUTE\", \"FIXED_PREC_SCALE\", \"AUTO_UNIQUE_VALUE\", \"LOCAL_TYPE_NAME\", \"MINIMUM_SCALE\", \"MAXIMUM_SCALE\", \"SQL_TYPE_NAME\","
"\"NUM_PREC_RADIX\", \"USEPRECISION\", \"USELENGTH\", \"SQL_DATA_TYPE\", \"SQL_DATETIME_SUB\", \"INTERVAL_PRECISION\", \"DATETIMESTARTFIELD\","
"\"DATETIMEENDFIELD\", \"APPLICATION_VERSION\", \"TRANSLATION_ID\")"
" WHERE %s"
" ORDER BY 2,1 FOR READ UNCOMMITTED ACCESS ;", condExpression);
break;
}
case SQL_API_SQLPROCEDURES :
case SQL_API_SQLPROCEDURES_JDBC:
// strcpy((char *)catStmtLabel, "SQL_PROCEDURES_ANSI_Q4");
if (!checkIfWildCard(catalogNm, expCatalogNm) && !metadataId)
{
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_WILDCARD_NOT_SUPPORTED;
goto MapException;
}
if (strcmp(catalogNm,"") == 0)
strcpy(tableName1,SEABASE_MD_CATALOG);
else
strcpy(tableName1,catalogNm);
tableParam[0] = tableName1;
tableParam[1] = NULL;
convertWildcardNoEsc(metadataId, TRUE, schemaNm, schemaNmNoEsc);
convertWildcard(metadataId, TRUE, schemaNm, expSchemaNm);
convertWildcardNoEsc(metadataId, TRUE, tableNm, tableNmNoEsc);
convertWildcard(metadataId, TRUE, tableNm, expTableNm);
inputParam[0] = schemaNmNoEsc;
inputParam[1] = expSchemaNm;
inputParam[2] = tableNmNoEsc;
inputParam[3] = expTableNm;
inputParam[4] = NULL;
if( APIType == SQL_API_SQLPROCEDURES )
{
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select "
"cast('%s' as varchar(128) ) PROCEDURE_CAT, "
"cast(trim(SCHEMA_NAME) as varchar(128) ) PROCEDURE_SCHEM, "
"cast(trim(OBJECT_NAME) as varchar(128) ) PROCEDURE_NAME, "
"cast (NULL as smallint) NUM_INPUT_PARAMS, "
"cast (NULL as smallint) NUM_OUTPUT_PARAMS, "
"cast (NULL as smallint) NUM_RESULT_SETS, "
"cast (NULL as varchar(128)) REMARKS, "
"(case OBJECT_TYPE "
"when 'UR' then cast(1 as smallint) "
"else cast(0 as smallint) end) PROCEDURE_TYPE "
"from "
"TRAFODION.\"_MD_\".OBJECTS "
"where (SCHEMA_NAME = '%s' "
"or trim(SCHEMA_NAME) LIKE '%s' ESCAPE '\\') "
"and (OBJECT_NAME = '%s' "
"or trim(OBJECT_NAME) LIKE '%s' ESCAPE '\\') "
"and OBJECT_TYPE = 'UR' "
"FOR READ UNCOMMITTED ACCESS ORDER BY 4, 1, 2, 3 ;",
tableParam[0], inputParam[0], inputParam[1],
inputParam[2], inputParam[3]);
}
else
{
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select "
"obj.CATALOG_NAME PROCEDURE_CAT, obj.SCHEMA_NAME PROCEDURE_SCHEMA,"
"obj.OBJECT_NAME PROCEDURE_NAME, cast(NULL as varchar(10)) R1,cast(NULL as varchar(10)) R2,"
"cast(NULL as varchar(10)) R3, cast(NULL as varchar(10)) REMARKS,"
"cast(case when routines.UDR_TYPE = 'P' then 1"
" when routines.UDR_TYPE = 'F' or routines.UDR_TYPE = 'T'"
" then 2 else 0 end as smallint) PROCEDURE_TYPE,"
"obj.OBJECT_NAME SPECIFIC_NAME "
"from "
"TRAFODION.\"_MD_\".OBJECTS obj "
"left join TRAFODION.\"_MD_\".ROUTINES routines on obj.OBJECT_UID = routines.UDR_UID "
"where (obj.SCHEMA_NAME = '%s' "
"or trim(obj.SCHEMA_NAME) LIKE '%s' ESCAPE '\\') "
"and (obj.OBJECT_NAME = '%s' "
"or trim(obj.OBJECT_NAME) LIKE '%s' ESCAPE '\\') "
"and obj.OBJECT_TYPE = 'UR' "
"FOR READ UNCOMMITTED ACCESS ORDER BY 4, 1, 2, 3 ;",
inputParam[0], inputParam[1],
inputParam[2], inputParam[3]);
}
break;
case SQL_API_SQLPROCEDURECOLUMNS:
case SQL_API_SQLPROCEDURECOLUMNS_JDBC:
if (!checkIfWildCard(catalogNm, expCatalogNm) && !metadataId)
{
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_WILDCARD_NOT_SUPPORTED;
goto MapException;
}
if (strcmp(catalogNm,"") == 0)
strcpy(tableName1,SEABASE_MD_CATALOG);
else
strcpy(tableName1,catalogNm);
tableParam[0] = tableName1;
tableParam[1] = NULL;
convertWildcardNoEsc(metadataId, TRUE, schemaNm, schemaNmNoEsc);
convertWildcard(metadataId, TRUE, schemaNm, expSchemaNm);
convertWildcardNoEsc(metadataId, TRUE, tableNm, tableNmNoEsc);
convertWildcard(metadataId, TRUE, tableNm, expTableNm);
convertWildcardNoEsc(metadataId, TRUE, columnNm, columnNmNoEsc);
convertWildcard(metadataId, TRUE, columnNm, expColumnNm);
inputParam[0] = schemaNmNoEsc;
inputParam[1] = expSchemaNm;
inputParam[2] = tableNmNoEsc;
inputParam[3] = expTableNm;
inputParam[4] = columnNmNoEsc;
inputParam[5] = expColumnNm;
inputParam[6] = NULL;
if( APIType == SQL_API_SQLPROCEDURECOLUMNS )
{
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select obj.CATALOG_NAME PROCEDURE_CAT, obj.SCHEMA_NAME PROCEDURE_SCHEM,"
"obj.OBJECT_NAME PROCEDURE_NAME, cols.COLUMN_NAME COLUMN_NAME,"
"cast((case when cols.DIRECTION='I' then 1 when cols.DIRECTION='N' "
"then 2 when cols.DIRECTION='O' then 3 else 0 end) as smallint) COLUMN_TYPE,"
"cols.FS_DATA_TYPE DATA_TYPE, cols.SQL_DATA_TYPE TYPE_NAME,"
"cols.COLUMN_PRECISION \"PRECISION\", cols.COLUMN_SIZE LENGTH, cols.COLUMN_SCALE SCALE,"
"cast(1 as smallint) RADIX, cols.NULLABLE NULLABLE, cast(NULL as varchar(10)) REMARKS,"
"cols.DEFAULT_VALUE COLUMN_DEF, cols.FS_DATA_TYPE SQL_DATA_TYPE, cast(0 as smallint) SQL_DATETIME_SUB,"
"cols.COLUMN_SIZE CHAR_OCTET_LENGTH, cols.COLUMN_NUMBER ORDINAL_POSITION,"
"cols.NULLABLE IS_NULLABLE"
" from TRAFODION.\"_MD_\".OBJECTS obj"
" left join TRAFODION.\"_MD_\".COLUMNS cols on obj.OBJECT_UID=cols.OBJECT_UID"
" where"
" (obj.SCHEMA_NAME = '%s' or trim(obj.SCHEMA_NAME) LIKE '%s' ESCAPE '\\') "
" and (obj.OBJECT_NAME = '%s' or trim(obj.OBJECT_NAME) LIKE '%s' ESCAPE '\\')"
" and (cols.COLUMN_NAME = '%s' or trim(cols.COLUMN_NAME) LIKE '%s' ESCAPE '\\')"
" order by PROCEDURE_CAT, PROCEDURE_SCHEM, PROCEDURE_NAME, ORDINAL_POSITION"
" FOR READ UNCOMMITTED ACCESS",
inputParam[0], inputParam[1],
inputParam[2], inputParam[3],
inputParam[4], inputParam[5]);
}
else
{
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select obj.CATALOG_NAME PROCEDURE_CAT, obj.SCHEMA_NAME PROCEDURE_SCHEM,"
"obj.OBJECT_NAME PROCEDURE_NAME, cols.COLUMN_NAME COLUMN_NAME,"
"cast((case when cols.DIRECTION='I' then 1 when cols.DIRECTION='N' then 2 when cols.DIRECTION='O' then 3 else 0 end) as smallint) COLUMN_TYPE,"
"cols.FS_DATA_TYPE DATA_TYPE, cols.SQL_DATA_TYPE TYPE_NAME,"
"cols.COLUMN_PRECISION \"PRECISION\", cols.COLUMN_SIZE LENGTH, cols.COLUMN_SCALE SCALE,"
"cast(1 as smallint) RADIX, cols.NULLABLE NULLABLE, cast(NULL as varchar(10)) REMARKS,"
"cols.DEFAULT_VALUE COLUMN_DEF, cols.FS_DATA_TYPE SQL_DATA_TYPE, cast(0 as smallint) SQL_DATETIME_SUB,"
"cols.COLUMN_SIZE CHAR_OCTET_LENGTH, cols.COLUMN_NUMBER ORDINAL_POSITION,"
"cols.NULLABLE IS_NULLABLE, cols.COLUMN_NAME SPECIFIC_NAME"
" from TRAFODION.\"_MD_\".OBJECTS obj"
" left join TRAFODION.\"_MD_\".COLUMNS cols on obj.OBJECT_UID=cols.OBJECT_UID"
" where"
" (obj.SCHEMA_NAME = '%s' or trim(obj.SCHEMA_NAME) LIKE '%s' ESCAPE '\\') "
" and (obj.OBJECT_NAME = '%s' or trim(obj.OBJECT_NAME) LIKE '%s' ESCAPE '\\')"
" and (cols.COLUMN_NAME = '%s' or trim(cols.COLUMN_NAME) LIKE '%s' ESCAPE '\\')"
" order by PROCEDURE_CAT, PROCEDURE_SCHEM, PROCEDURE_NAME, ORDINAL_POSITION"
" FOR READ UNCOMMITTED ACCESS",
inputParam[0], inputParam[1],
inputParam[2], inputParam[3],
inputParam[4], inputParam[5]);
}
break;
case SQL_API_SQLCOLUMNS :
case SQL_API_SQLCOLUMNS_JDBC :
if (!checkIfWildCard(catalogNm, catalogNmNoEsc) && !metadataId)
{
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_WILDCARD_NOT_SUPPORTED;
goto MapException;
}
if (tableNm[0] != '$' && tableNm[0] != '\\')
{
if (strcmp(catalogNm,"") == 0)
strcpy(tableName1,SEABASE_MD_CATALOG);
else
strcpy(tableName1, catalogNm);
/*
if (APIType == SQL_API_SQLCOLUMNS)
strcpy((char *)catStmtLabel, "SQL_COLUMNS_UNICODE_Q4");
else
strcpy((char *)catStmtLabel, "SQL_JAVA_COLUMNS_ANSI_Q4");
*/
tableParam[0] = tableName1;
convertWildcard(metadataId, TRUE, schemaNm, expSchemaNm);
convertWildcardNoEsc(metadataId, TRUE, schemaNm, schemaNmNoEsc);
convertWildcard(metadataId, TRUE, tableNm, expTableNm);
convertWildcardNoEsc(metadataId, TRUE, tableNm, tableNmNoEsc);
convertWildcard(metadataId, TRUE, columnNm, expColumnNm);
convertWildcardNoEsc(metadataId, TRUE, columnNm, columnNmNoEsc);
inputParam[0] = schemaNmNoEsc;
inputParam[1] = expSchemaNm;
inputParam[2] = tableNmNoEsc;
inputParam[3] = expTableNm;
inputParam[4] = columnNmNoEsc;
inputParam[5] = expColumnNm;
inputParam[6] = odbcAppVersion;
inputParam[7] = NULL;
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select "
"cast('%s' as varchar(128) ) TABLE_CAT, "
"cast(trim(ob.SCHEMA_NAME) as varchar(128) ) TABLE_SCHEM, "
"cast(trim(ob.OBJECT_NAME) as varchar(128) ) TABLE_NAME, "
"cast(trim(co.COLUMN_NAME) as varchar(128) ) COLUMN_NAME, "
"cast((case when co.FS_DATA_TYPE = 0 and co.character_set = 'UCS2' then -8 "
"when co.FS_DATA_TYPE = 64 and co.character_set = 'UCS2' then -9 else dt.DATA_TYPE end) as smallint) DATA_TYPE, "
"trim(dt.TYPE_NAME) TYPE_NAME, "
"cast((case when co.FS_DATA_TYPE = 0 and co.character_set = 'UCS2' then co.COLUMN_SIZE/2 "
"when co.FS_DATA_TYPE = 64 and co.character_set = 'UCS2' then co.COLUMN_SIZE/2 "
"when dt.USEPRECISION = -1 then co.COLUMN_SIZE when dt.USEPRECISION = -2 then co.COLUMN_PRECISION "
"when co.FS_DATA_TYPE = 192 then dt.USEPRECISION + 1 "
"when co.FS_DATA_TYPE >= 195 and co.FS_DATA_TYPE <= 207 then dt.USEPRECISION + 1 "
"else dt.USEPRECISION end) as integer) COLUMN_SIZE, "
"cast((case when dt.USELENGTH = -1 then co.COLUMN_SIZE when dt.USELENGTH = -2 then co.COLUMN_PRECISION "
"when dt.USELENGTH = -3 then co.COLUMN_PRECISION + 2 "
"else dt.USELENGTH end) as integer) BUFFER_LENGTH, "
"cast(co.COLUMN_SCALE as smallint) DECIMAL_DIGITS, "
"cast(dt.NUM_PREC_RADIX as smallint) NUM_PREC_RADIX, "
"cast(co.NULLABLE as smallint) NULLABLE, "
"cast('' as varchar(128)) REMARKS, "
"trim(co.DEFAULT_VALUE) COLUMN_DEF, "
"cast((case when co.FS_DATA_TYPE = 0 and co.character_set = 'UCS2' then -8 "
"when co.FS_DATA_TYPE = 64 and co.character_set = 'UCS2' then -9 else dt.SQL_DATA_TYPE end) as smallint) SQL_DATA_TYPE, "
"cast(dt.SQL_DATETIME_SUB as smallint) SQL_DATETIME_SUB, cast((case dt.DATA_TYPE when 1 then co.COLUMN_SIZE "
"when -1 then co.COLUMN_SIZE when 12 then co.COLUMN_SIZE else NULL end) as integer) CHAR_OCTET_LENGTH, "
"cast((case when (trim(co1.COLUMN_CLASS) <> 'S') then co.column_number+1 else "
"co.column_number end) as integer) ORDINAL_POSITION, "
"cast((case when co.NULLABLE = 0 then 'NO' else 'YES' end) as varchar(3)) IS_NULLABLE "
"from "
"TRAFODION.\"_MD_\".objects ob, "
"TRAFODION.\"_MD_\".columns co, "
"TRAFODION.\"_MD_\".columns co1, "
"(VALUES ("
"cast('BIGINT' as varchar(128)),cast(-5 as smallint), cast(19 as integer), cast (NULL as varchar(128)), cast (NULL as varchar(128)), "
"cast (NULL as varchar(128)), cast(1 as smallint), cast(0 as smallint), cast(2 as smallint) , cast(0 as smallint), cast(0 as smallint), "
"cast(0 as smallint), cast('LARGEINT' as varchar(128)), cast(NULL as smallint), cast(NULL as smallint), cast('SIGNED LARGEINT' as varchar(128)), cast(134 as integer), "
"cast(10 as smallint), cast(19 as integer), cast(20 as integer), cast(-402 as smallint), cast(NULL as smallint), cast(NULL as smallint), "
"cast(0 as smallint), cast(0 as smallint), cast(3 as smallint), cast(0 as smallint)), "
"('CHAR', 1, 32000, '''', '''', 'max length', 1, 1, 3, NULL, 0, NULL, 'CHARACTER', NULL, NULL, 'CHARACTER', 0, NULL, -1, -1, 1, NULL, NULL, 0, 0, 3, 0), "
"('DATE', 91, 10, '{d ''', '''}', NULL, 1, 0, 2, NULL, 0, NULL, 'DATE', NULL, NULL, 'DATE', 192, NULL, 10, 6, 9, 1, NULL, 1, 3, 3, 0), "
"('DECIMAL', 3, 18, NULL, NULL, 'precision,scale', 1, 0, 2, 0, 0, 0, 'DECIMAL', 0, 18, 'SIGNED DECIMAL', 152, 10, -2, -3, 3, NULL, NULL, 0, 0, 3, 0), "
"('DECIMAL UNSIGNED', 3, 18, NULL, NULL, 'precision,scale', 1, 0, 2, 1, 0, 0, 'DECIMAL', 0, 18, 'UNSIGNED DECIMAL', 150, 10, -2, -3, -301, NULL, NULL, 0, 0, 3, 0), "
"('DOUBLE PRECISION', 8, 15, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'DOUBLE', NULL, NULL, 'DOUBLE', 143, 2, 54, -1, 8, NULL, NULL, 0, 0, 3, 0), "
"('INTEGER', 4, 10, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'INTEGER', NULL, NULL, 'SIGNED INTEGER', 132, 10, 10, -1, 4, NULL, NULL, 0, 0, 3, 0), "
"('INTEGER UNSIGNED', 4, 10, NULL, NULL, NULL, 1, 0, 2, 1, 0, 0, 'INTEGER', NULL, NULL, 'UNSIGNED INTEGER', 133, 10, 10, -1, -401, NULL, NULL, 0, 0, 3, 0), "
"('INTERVAL', 113, 0, '{INTERVAL ''', ''' MINUTE TO SECOND}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 205, NULL, 3, 34, 100, 13, 2, 5, 6, 3, 0), "
"('INTERVAL', 105, 0, '{INTERVAL ''', ''' MINUTE}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 201, NULL, 0, 34, 100, 5, 2, 5, 5, 3, 0), "
"('INTERVAL', 101, 0, '{INTERVAL ''', ''' YEAR}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 195, NULL, 0, 34, 100, 1, 2, 1, 1, 3, 0), "
"('INTERVAL', 106, 0, '{INTERVAL ''', ''' SECOND}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 204, NULL, 0, 34, 100, 6, 2, 6, 6, 3, 0), "
"('INTERVAL', 104, 0, '{INTERVAL ''', ''' HOUR}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 199, NULL, 0, 34, 100, 4, 2, 4, 4, 3, 0), "
"('INTERVAL', 107, 0, '{INTERVAL ''', ''' YEAR TO MONTH}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 197, NULL, 3, 34, 100, 7, 2, 1, 2, 3, 0), "
"('INTERVAL', 108, 0, '{INTERVAL ''', ''' DAY TO HOUR}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 200, NULL, 3, 34, 100, 8, 2, 3, 4, 3, 0), "
"('INTERVAL', 102, 0, '{INTERVAL ''', ''' MONTH}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 196, NULL, 0, 34, 100, 2, 2, 2, 2, 3, 0), "
"('INTERVAL', 111, 0, '{INTERVAL ''', ''' HOUR TO MINUTE}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 202, NULL, 3, 34, 100, 11, 2, 4, 5, 3, 0), "
"('INTERVAL', 112, 0, '{INTERVAL ''', ''' HOUR TO SECOND}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 206, NULL, 6, 34, 100, 12, 2, 4, 6, 3, 0), "
"('INTERVAL', 110, 0, '{INTERVAL ''', ''' DAY TO SECOND}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 207, NULL, 9, 34, 100, 10, 2, 3, 6, 3, 0), "
"('INTERVAL', 109, 0, '{INTERVAL ''', ''' DAY TO MINUTE}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 203, NULL, 6, 34, 100, 9, 2, 3, 5, 3, 0), "
"('INTERVAL', 103, 0, '{INTERVAL ''', ''' DAY}', NULL, 1, 0, 2, 0, 0, NULL, 'INTERVAL', 0, 0, 'INTERVAL', 198, NULL, 0, 34, 100, 3, 2, 3, 3, 3, 0), "
"('NUMERIC', 2, 128, NULL, NULL, 'precision,scale', 1, 0, 2, 0, 0, 0, 'NUMERIC', 0, 128, 'SIGNED NUMERIC', 156, 10, -2, -3, 2, NULL, NULL, 0, 0, 3, 0), "
"('NUMERIC UNSIGNED', 2, 128, NULL, NULL, 'precision,scale', 1, 0, 2, 1, 0, 0, 'NUMERIC', 0, 128, 'UNSIGNED NUMERIC', 155, 10, -2, -3, 2, NULL, NULL, 0, 0, 3, 0), "
"('REAL', 7, 7, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'REAL', NULL, NULL, 'REAL', 142, 2, 22, -1, 7, NULL, NULL, 0, 0, 3, 0), "
"('SMALLINT', 5, 5, NULL, NULL, NULL, 1, 0, 2, 0, 0, 0, 'SMALLINT', NULL, NULL, 'SIGNED SMALLINT', 130, 10, 5, -1, 5, NULL, NULL, 0, 0, 3, 0), "
"('SMALLINT UNSIGNED', 5, 5, NULL, NULL, NULL, 1, 0, 2, 1, 0, 0, 'SMALLINT', NULL, NULL, 'UNSIGNED SMALLINT', 131, 10, 5, -1, -502, NULL, NULL, 0, 0, 3, 0), "
"('TIME', 92, 8, '{t ''', '''}', NULL, 1, 0, 2, NULL, 0, NULL, 'TIME', NULL, NULL, 'TIME', 192, NULL, 8, 6, 9, 2, NULL, 4, 6, 3, 0), "
"('TIMESTAMP', 93, 26, '{ts ''', '''}', NULL, 1, 0, 2, NULL, 0, NULL, 'TIMESTAMP', 0, 6, 'TIMESTAMP', 192, NULL, 19, 16, 9, 3, NULL, 1, 6, 3, 0), "
"('VARCHAR', 12, 32000, '''', '''', 'max length', 1, 1, 3, NULL, 0, NULL, 'VARCHAR', NULL, NULL, 'VARCHAR', 64, NULL, -1, -1, 12, NULL, NULL, 0, 0, 3, 0) "
" ) "
"dt(\"TYPE_NAME\", \"DATA_TYPE\", \"PREC\", \"LITERAL_PREFIX\", \"LITERAL_SUFFIX\", \"CREATE_PARAMS\", \"IS_NULLABLE\", \"CASE_SENSITIVE\", \"SEARCHABLE\", "
"\"UNSIGNED_ATTRIBUTE\", \"FIXED_PREC_SCALE\", \"AUTO_UNIQUE_VALUE\", \"LOCAL_TYPE_NAME\", \"MINIMUM_SCALE\", \"MAXIMUM_SCALE\", \"SQL_TYPE_NAME\", \"FS_DATA_TYPE\", "
"\"NUM_PREC_RADIX\", \"USEPRECISION\", \"USELENGTH\", \"SQL_DATA_TYPE\", \"SQL_DATETIME_SUB\", \"INTERVAL_PRECISION\", \"DATETIMESTARTFIELD\", "
"\"DATETIMEENDFIELD\", \"APPLICATION_VERSION\", \"TRANSLATION_ID\") "
"where ob.OBJECT_UID = co.OBJECT_UID "
"and dt.FS_DATA_TYPE = co.FS_DATA_TYPE "
"and co.OBJECT_UID = co1.OBJECT_UID and co1.COLUMN_NUMBER = 0 "
"and (dt.DATETIMESTARTFIELD = co.DATETIME_START_FIELD) "
"and (dt.DATETIMEENDFIELD = co.DATETIME_END_FIELD) "
"and (ob.SCHEMA_NAME = '%s' or trim(ob.SCHEMA_NAME) LIKE '%s' ESCAPE '\\') "
"and (ob.OBJECT_NAME = '%s' or trim(ob.OBJECT_NAME) LIKE '%s' ESCAPE '\\') "
"and (co.COLUMN_NAME = '%s' or trim(co.COLUMN_NAME) LIKE '%s' ESCAPE '\\') "
"and (ob.OBJECT_TYPE in ('BT' , 'VI') ) "
"and (trim(co.COLUMN_CLASS) not in ('S', 'M')) "
"and dt.APPLICATION_VERSION = %s "
"FOR READ UNCOMMITTED ACCESS order by 1, 2, 3, co.COLUMN_NUMBER ; ",
tableParam[0], inputParam[0], inputParam[1],
inputParam[2], inputParam[3], inputParam[4],
inputParam[5], inputParam[6]);
}
break;
case SQL_API_SQLPRIMARYKEYS :
if ((!checkIfWildCard(catalogNm, catalogNmNoEsc) || !checkIfWildCard(schemaNm, schemaNmNoEsc) || !checkIfWildCard(tableNm, tableNmNoEsc)) && !metadataId)
{
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_WILDCARD_NOT_SUPPORTED;
goto MapException;
}
// strcpy((char *)catStmtLabel, "SQL_PRIMARYKEYS_ANSI_Q4");
if (strcmp(catalogNm,"") == 0)
strcpy(tableName1,SEABASE_MD_CATALOG);
else
strcpy(tableName1, catalogNm);
tableParam[0] = tableName1;
/*
strcpy(tableName2, SEABASE_MD_CATALOG);
strcat(tableName2, ".");
strcat(tableName2, SEABASE_MD_SCHEMA);
strcat(tableName2, ".");
strcat(tableName2, smdCatAPITablesList[OBJECTS]);
tableParam[1] = tableName2;
strcpy(tableName3, SEABASE_MD_CATALOG);
strcat(tableName3, ".");
strcat(tableName3, SEABASE_MD_SCHEMA);
strcat(tableName3, ".");
strcat(tableName3, smdCatAPITablesList[KEYS]);
tableParam[2] = tableName3;
tableParam[3] = NULL;
*/
convertWildcard(metadataId, TRUE, schemaNm, expSchemaNm);
convertWildcardNoEsc(metadataId, TRUE, schemaNm, schemaNmNoEsc);
convertWildcard(metadataId, TRUE, tableNm, expTableNm);
convertWildcardNoEsc(metadataId, TRUE, tableNm, tableNmNoEsc);
inputParam[0] = schemaNmNoEsc;
inputParam[1] = expSchemaNm;
inputParam[2] = tableNmNoEsc;
inputParam[3] = expTableNm;
inputParam[4] = NULL;
snprintf(CatalogQuery,sizeof(CatalogQuery),
"select "
"cast('%s' as varchar(128) ) TABLE_CAT,"
"cast(trim(ob.SCHEMA_NAME) as varchar(128) ) TABLE_SCHEM,"
"cast(trim(ob.OBJECT_NAME) as varchar(128) ) TABLE_NAME,"
"trim(ky.COLUMN_NAME) COLUMN_NAME,"
"cast((ky.keyseq_number) as smallint) KEY_SEQ,"
"trim(ob.OBJECT_NAME) PK_NAME "
" from TRAFODION.\"_MD_\".OBJECTS ob, "
"TRAFODION.\"_MD_\".KEYS ky "
" where (ob.SCHEMA_NAME = '%s' or "
" trim(ob.SCHEMA_NAME) LIKE '%s' ESCAPE '\\') "
" and (ob.OBJECT_NAME = '%s' or "
" trim(ob.OBJECT_NAME) LIKE '%s' ESCAPE '\\') "
" and ob.OBJECT_UID = ky.OBJECT_UID and ky.COLUMN_NAME <> '_SALT_' "
" FOR READ UNCOMMITTED ACCESS order by 1, 2, 3, 5 ;",
tableParam[0], inputParam[0], inputParam[1],
inputParam[2], inputParam[3]);
break;
case SQL_API_SQLFOREIGNKEYS:
if ((!checkIfWildCard(catalogNm, catalogNmNoEsc) ||
!checkIfWildCard(schemaNm, schemaNmNoEsc) ||
!checkIfWildCard(tableNm, tableNmNoEsc)) &&
!metadataId)
{
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_WILDCARD_NOT_SUPPORTED;
goto MapException;
}
convertWildcard(metadataId, TRUE, schemaNm, expSchemaNm);
convertWildcardNoEsc(metadataId, TRUE, schemaNm, schemaNmNoEsc);
convertWildcard(metadataId, TRUE, tableNm, expTableNm);
convertWildcardNoEsc(metadataId, TRUE, tableNm, tableNmNoEsc);
char fkcatalogNmNoEsc[MAX_ANSI_NAME_LEN + 1];
char fkschemaNmNoEsc[MAX_ANSI_NAME_LEN + 1];
char fktableNmNoEsc[MAX_ANSI_NAME_LEN + 1];
char fkexpCatalogNm[MAX_ANSI_NAME_LEN + 1];
char fkexpSchemaNm[MAX_ANSI_NAME_LEN + 1];
char fkexpTableNm[MAX_ANSI_NAME_LEN + 1];
if (strcmp(fktableNm, "") == 0)
strcpy((char *)fktableNm, "%");
if (strcmp(fkschemaNm, "") == 0)
strcpy((char *)fkschemaNm, "%");
convertWildcard(metadataId, TRUE, fkcatalogNm, fkexpCatalogNm);
convertWildcardNoEsc(metadataId, TRUE, fkcatalogNm, fkcatalogNmNoEsc);
convertWildcard(metadataId, TRUE, fkschemaNm, fkexpSchemaNm);
convertWildcardNoEsc(metadataId, TRUE, fkschemaNm, fkschemaNmNoEsc);
convertWildcard(metadataId, TRUE, fktableNm, fkexpTableNm);
convertWildcardNoEsc(metadataId, TRUE, fktableNm, fktableNmNoEsc);
snprintf(CatalogQuery, sizeof(CatalogQuery),
"select "
"cast(PKCO.CATALOG_NAME as varchar(128)) PKTABLE_CAT, "
"cast(PKCO.SCHEMA_NAME as varchar(128)) PKTABLE_SCHEM, "
"cast(PKCO.TABLE_NAME as varchar(128)) PKTABLE_NAME, "
"cast(PKCO.COLUMN_NAME as varchar(128)) PKCOLUMN_NAME, "
"cast(FKCO.CATALOG_NAME as varchar(128)) FKTABLE_CAT, "
"cast(PKCO.SCHEMA_NAME as varchar(128)) FKTABLE_SCHEM, "
"cast(FKCO.TABLE_NAME as varchar(128)) FKTABLE_NAME, "
"cast(FKCO.COLUMN_NAME as varchar(128)) FKCOLUMN_NAME, "
"cast(FKKV.ORDINAL_POSITION as smallint) KEY_SEQ, "
"cast(0 as smallint) update_rule, " // not support
"cast(0 as smallint) delete_rule, " // not support
"cast(FKKV.CONSTRAINT_NAME as varchar(128)) FK_NAME, "
"cast(PKKV.CONSTRAINT_NAME as varchar(128)) PK_NAME, "
"cast(0 as smallint) DEFERRABILITY " // not support
"from "
"TRAFODION.\"_MD_\".REF_CONSTRAINTS_VIEW rcv, "
"TRAFODION.\"_MD_\".KEYS_VIEW PKKV, "
"TRAFODION.\"_MD_\".KEYS_VIEW FKKV, "
"TRAFODION.\"_MD_\".COLUMNS_VIEW PKCO, "
"TRAFODION.\"_MD_\".COLUMNS_VIEW FKCO "
"where "
"FKKV.CONSTRAINT_NAME = rcv.CONSTRAINT_NAME "
"and PKKV.CONSTRAINT_NAME = rcv.UNIQUE_CONSTRAINT_NAME "
"and PKCO.TABLE_NAME = PKKV.TABLE_NAME "
"and FKCO.TABLE_NAME = FKKV.TABLE_NAME "
"and PKCO.COLUMN_NAME = PKKV.COLUMN_NAME "
"and FKCO.COLUMN_NAME = FKKV.COLUMN_NAME "
"and (PKCO.SCHEMA_NAME = '%s' or trim(PKCO.SCHEMA_NAME) LIKE '%s' ESCAPE '\\') "
"and (PKCO.TABLE_NAME = '%s' or trim(PKCO.TABLE_NAME) LIKE '%s' ESCAPE '\\') "
"and (FKCO.SCHEMA_NAME = '%s' or trim(FKCO.SCHEMA_NAME) LIKE '%s' ESCAPE '\\') "
"and (FKCO.TABLE_NAME = '%s' or trim(FKCO.TABLE_NAME) LIKE '%s' ESCAPE '\\') "
"FOR READ UNCOMMITTED ACCESS ORDER BY 1, 2, 3, 5, 6, 7, 9;",
schemaNmNoEsc, expSchemaNm,
tableNmNoEsc, expTableNm,
fkschemaNmNoEsc, fkexpSchemaNm,
fktableNmNoEsc, fkexpTableNm
);
break;
case SQL_API_SQLSTATISTICS:
if (!checkIfWildCard(catalogNm, catalogNmNoEsc) && !metadataId)
{
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_WILDCARD_NOT_SUPPORTED;
}
if (tableNm[0] != '$' && tableNm[0] != '\\')
{
if (strcmp(catalogNm, "") == 0)
strcpy(tableName1, SEABASE_MD_CATALOG);
else
strcpy(tableName1, catalogNm);
}
tableParam[0] = tableName1;
convertWildcard(metadataId, TRUE, schemaNm, expSchemaNm);
convertWildcardNoEsc(metadataId, TRUE, schemaNm, schemaNmNoEsc);
convertWildcard(metadataId, TRUE, tableNm, expTableNm);
convertWildcardNoEsc(metadataId, TRUE, tableNm, tableNmNoEsc);
inputParam[0] = schemaNmNoEsc;
inputParam[1] = expSchemaNm;
inputParam[2] = tableNmNoEsc;
inputParam[3] = expTableNm;
snprintf(CatalogQuery, sizeof(CatalogQuery),
"select "
"cast('%s' as varchar(128)) TABLE_CAT, "
"cast(trim(ob.SCHEMA_NAME) as varchar(128)) TABLE_SCHEM, "
"cast(trim(ob.OBJECT_NAME) as varchar(128)) TABLE_NAME, "
"cast(NULL as smallint) NON_UNIQUE, " // return NULL if TYPE is SQL_TABLE_STAT
"cast(NULL as varchar(128)) INDEX_QUALIFIER, " // return NULL if TYPE is SQL_TABLE_STAT
"cast(NULL as varchar(128)) INDEX_NAME, " // return NULL if TYPE is SQL_TABLE_STAT
"cast(0 as smallint) TYPE, " // TYPE is SQL_TABLE_STAT
"cast(NULL as smallint) ORDINAL_POSITION, " // return NULL if TYPE is SQL_TABLE_STAT
"cast(trim(co.COLUMN_NAME) as varchar(128)) COLUMN_NAME, "
"cast(NULL as char(1)) ASC_OR_DESC, " // return NULL if TYPE is SQL_TABLE_STAT
"cast(sb.rowcount as integer) CARDINALITY, " // number of rows
"cast(NULL as integer) PAGES, " // not support
"cast(NULL as varchar(128)) FILTER_CONDITION " // not support
"from "
"TRAFODION.\"_MD_\".OBJECTS ob, "
"TRAFODION.\"_MD_\".COLUMNS co, "
"TRAFODION.%s.sb_histograms sb "
"where "
"ob.OBJECT_UID = co.OBJECT_UID "
"and co.OBJECT_UID = sb.TABLE_UID "
"and co.COLUMN_NUMBER = sb.COLUMN_NUMBER "
"and sb.colcount = 1 "
"and (ob.SCHEMA_NAME = '%s' or trim(ob.SCHEMA_NAME) LIKE '%s' ESCAPE '\\') "
"and (ob.OBJECT_NAME = '%s' or trim(ob.OBJECT_NAME) LIKE '%s' ESCAPE '\\') "
"and (ob.OBJECT_TYPE in ('BT', 'VI')) "
"and (trim(co.COLUMN_CLASS) not in('S', 'M')) "
"union "
"select "
"cast('%s' as varchar(128)) TABLE_CAT, "
"cast(trim(ob_table.SCHEMA_NAME) as varchar(128)) TABLE_SCHEM, "
"cast(trim(ob_table.OBJECT_NAME) as varchar(128)) TABLE_NAME, "
"cast(case when idx.is_unique = 1 then 0 else 1 end as smallint) NON_UNIQUE, "
"cast(NULL as varchar(128)) INDEX_QUALIFIER, " // not support
"cast(trim(ob.OBJECT_NAME) as varchar(128)) INDEX_NAME, "
"cast(3 as smallint) TYPE, " // SQL_INDEX_OTHER
"cast(0 as smallint) ORDINAL_POSITION, "
"cast('' as varchar(128)) COLUMN_NAME, " // return an empty string if the expression cannot be determined.
"cast(NULL as char(1)) ASC_OR_DESC, " // not subsequent
"cast(NULL as integer) CARDINALITY, "
"cast(NULL as integer) PAGES, "
"cast(NULL as varchar(128)) FILTER_CONDITION "
"from "
"TRAFODION.\"_MD_\".OBJECTS ob, "
"TRAFODION.\"_MD_\".INDEXES idx, "
"TRAFODION.\"_MD_\".OBJECTS ob_table, "
"TRAFODION.\"_MD_\".TABLES tb "
"where "
"idx.BASE_TABLE_UID=tb.TABLE_UID "
"and idx.INDEX_UID=ob.OBJECT_UID "
"and idx.BASE_TABLE_UID=ob_table.OBJECT_UID "
"and (ob_table.SCHEMA_NAME = '%s' or trim(ob_table.SCHEMA_NAME) LIKE '%s' ESCAPE '\\') "
"and (ob_table.OBJECT_NAME = '%s' or trim(ob_table.OBJECT_NAME) LIKE '%s' ESCAPE '\\') "
"and (ob_table.OBJECT_TYPE in ('BT', 'VI')) "
"%s "
"ORDER BY 1, 2, 3, 7, 9, 6 ;",
tableParam[0],
inputParam[0],
inputParam[0], inputParam[1],
inputParam[2], inputParam[3],
tableParam[0],
inputParam[0], inputParam[1],
inputParam[2], inputParam[3],
uniqueness == 1 ? "" : "and idx.is_unique=1"
);
break;
default :
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNSUPPORTED_SMD_API_TYPE;
break;
}
if (exception_->exception_nr == 0)
{
if ((QryCatalogSrvrStmt = getSrvrStmt(catStmtLabel, TRUE)) == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
2,
"CATALOG APIs",
"Allocate Statement");
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
else
{
// Temporary solution - bypass checks on metadata tables
unsigned int savedParserFlags = 0;
SQL_EXEC_GetParserFlagsForExSqlComp_Internal(savedParserFlags);
try
{
SQL_EXEC_SetParserFlagsForExSqlComp_Internal(INTERNAL_QUERY_FROM_EXEUTIL);
retcode = QryCatalogSrvrStmt->ExecDirect(NULL, CatalogQuery, EXTERNAL_STMT, TYPE_SELECT, SQL_ASYNC_ENABLE_OFF, 0);
SQL_EXEC_AssignParserFlagsForExSqlComp_Internal(savedParserFlags);
if (retcode == SQL_ERROR)
{
ERROR_DESC_def *p_buffer = QryCatalogSrvrStmt->sqlError.errorList._buffer;
strncpy(RequestError, p_buffer->errorText,sizeof(RequestError) -1);
RequestError[sizeof(RequestError) - 1] = '\0';
SendEventMsg(MSG_SQL_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
2,
p_buffer->sqlcode,
RequestError);
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.SQLError.errorList._length = QryCatalogSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = QryCatalogSrvrStmt->sqlError.errorList._buffer;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECDIRECT_FAILED;
}
} //try
catch (...)
{
SQL_EXEC_AssignParserFlagsForExSqlComp_Internal(savedParserFlags);
SendEventMsg(MSG_PROGRAMMING_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
1,
"Exception in executing Catalog API");
exception_->exception_nr = odbc_SQLSvc_GetSQLCatalogs_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECDIRECT_FAILED;
} // catch
}
}
if (exception_->exception_nr == 0)
{
QryCatalogSrvrStmt->sqlStmtType = TYPE_SELECT_CATALOG;
outputDesc->_length = QryCatalogSrvrStmt->outputDescList._length;
outputDesc->_buffer = QryCatalogSrvrStmt->outputDescList._buffer;
}
MapException:
// resource statistics
if (resStatSession != NULL)
{
if (exception_->exception_nr != 0)
resStatSession->totalCatalogErrors ++;
if (sqlWarning->_length != 0)
resStatSession->totalCatalogWarnings ++;
}
if (resStatStatement != NULL)
resStatStatement->catFlagOn = FALSE;
if (exception_->exception_nr != 0)
{
SRVR_STMT_HDL *pSrvrStmt = NULL;
if ((pSrvrStmt = getSrvrStmt(catStmtLabel, FALSE)) != NULL)
{
exception_->exception_nr = 0;
exception_->exception_detail = 0;
pSrvrStmt->rowsAffected = 0;
// CLEARDIAGNOSTICS(pSrvrStmt);
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
}
}
SRVRTRACE_EXIT(FILE_SME+14);
return;
}
/*
* Synchronous method function prototype for
* operation 'odbc_SQLSvc_InitializeDialogue'
*/
extern "C" void
odbc_SQLSvc_InitializeDialogue_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_InitializeDialogue_exc_ *exception_
, /* In */ const USER_DESC_def *userDesc
, /* In */ const CONNECTION_CONTEXT_def *inContext
, /* In */ DIALOGUE_ID_def dialogueId
, /* Out */ OUT_CONNECTION_CONTEXT_def *outContext
)
{
SRVRTRACE_ENTER(FILE_SME+15);
exception_->exception_nr = 0;
Int32 retcode = SQL_SUCCESS;
char userSid[MAX_TEXT_SID_LEN+1];
char pwd[387];
pwd[0] = '\0';
__int64 julian = 0;
char primary_rolename[MAX_ROLENAME_LEN+1];
char logon_rolename[MAX_ROLENAME_LEN+1];
short logon_roleLen = 0;
__int64 redefTime = 0;
Int32 authIDType = 0;
int encryption = 1;
int refresh = 0;
char* pPWD = (char*)userDesc->password._buffer;
bzero(primary_rolename, sizeof(primary_rolename));
// volatile int done = 0;
// while (!done) {
// sleep(10);
// }
userSid[0] = 0;
// #ifdef _TMP_SQ_SECURITY
UA_Status authErrorDetail;
DBUserAuth *userSession = DBUserAuth::GetInstance();
size_t passwordLen = 0;
CLIENT_INFO client_info;
PERFORMANCE_INFO performanceInfo;
AUTHENTICATION_INFO authenticationInfo;
if (userDesc->userDescType != AUTHENTICATED_USER_TYPE)
{
srvrGlobal->QSRoleName[0] = '\0';
int64 tempStartTime, tempEndTime = 0;
int64 loginStartTime = JULIANTIMESTAMP();
client_info.client_name = setinit.clientId;
client_info.client_user_name = setinit.clientUserName;
client_info.application_name = setinit.applicationId;
#ifndef _DEBUG
// Disable generation of cores in release version
struct rlimit rlim;
int limit, ret_rlimit;
// Get the current limit and save.
ret_rlimit = getrlimit(RLIMIT_CORE, &rlim);
limit = rlim.rlim_cur;
// Set the current limit to 0, disabling generation of core
rlim.rlim_cur = 0;
ret_rlimit = setrlimit(RLIMIT_CORE, &rlim);
#endif
retcode = decrypt_message(pPWD,primary_rolename);
tempStartTime = JULIANTIMESTAMP() ;
if (retcode == SECMXO_NO_ERROR)
{
size_t length = strlen(userDesc->userName);
for (size_t i = 0; i < length; i++)
userDesc->userName[i] = toupper(userDesc->userName[i]);
retcode = userSession->verify(userDesc->userName
,pPWD
,authErrorDetail
,authenticationInfo
,client_info
,performanceInfo
);
}
if (retcode == 0)
{
srvrGlobal->redefTime = authenticationInfo.usersInfo.redefTime;
strcpy(srvrGlobal->QSRoleName, "NONE");
}
#ifndef _DEBUG
// Revert to the previous setting for core generation
rlim.rlim_cur = limit;
ret_rlimit = setrlimit(RLIMIT_CORE, &rlim);
#endif
tempEndTime = JULIANTIMESTAMP();
setinit.ldapLoginTime = tempEndTime - tempStartTime;
setinit.totalLoginTime = tempEndTime - loginStartTime;
setinit.sqlUserTime = performanceInfo.sqlUserTime;
setinit.searchConnectionTime = performanceInfo.searchConnectionTime;
setinit.searchTime = performanceInfo.searchTime;
setinit.authenticationConnectionTime = performanceInfo.authenticationConnectionTime;
setinit.authenticationTime = performanceInfo.authenticationTime;
if (retcode != SECMXO_NO_ERROR)
{
exception_->exception_detail = retcode;
exception_->exception_nr = odbc_SQLSvc_InitializeDialogue_SQLError_exn_;
srvrGlobal->QSRoleName[0] = '\0';
SETSECURITYERROR(retcode, &exception_->u.SQLError.errorList);
SRVRTRACE_EXIT(FILE_SME+15);
if (retcode == SECMXO_INTERNAL_ERROR_FATAL)
{
SendEventMsg(MSG_PROGRAMMING_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER, srvrGlobal->srvrObjRef,
1, "Security layer returned fatal error. Server exiting.");
exit(0);
}
return;
}
tempEndTime = JULIANTIMESTAMP();
setinit.totalLoginTime = tempEndTime - loginStartTime;
if (authenticationInfo.error == 0)
retcode = WSQL_EXEC_SetAuthID(userDesc->userName,
authenticationInfo.usersInfo.databaseUsername,
authenticationInfo.tokenKey,
authenticationInfo.tokenKeySize,
authenticationInfo.usersInfo.effectiveUserID,
authenticationInfo.usersInfo.sessionUserID);
else
{
bool bSQLMessageSet;
exception_->exception_detail = -8837;
if (authenticationInfo.errorDetail == 1)
{
setAuthenticationError(bSQLMessageSet,&(exception_->u.SQLError),userDesc->userName,false);
exception_->exception_nr = odbc_SQLSvc_InitializeDialogue_InvalidUser_exn_;
}
else
{
setAuthenticationError(bSQLMessageSet,&(exception_->u.SQLError),userDesc->userName,true);
exception_->exception_nr = odbc_SQLSvc_InitializeDialogue_SQLError_exn_;
ERROR_DESC_def *sqlError = exception_->u.SQLError.errorList._buffer;
SendEventMsg(MSG_SQL_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER, srvrGlobal->srvrObjRef,
3, ODBCMX_SERVER, sqlError->sqlstate, sqlError->errorText);
}
}
}
SRVRTRACE_EXIT(FILE_SME+15);
return;
}
/*
* Synchronous method function for
* operation 'odbc_SQLSvc_TerminateDialogue'
*/
extern "C" void
odbc_SQLSvc_TerminateDialogue_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_TerminateDialogue_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
)
{
SRVRTRACE_ENTER(FILE_SME+16);
exception_->exception_nr = 0;
//odbc_SQLSvc_EndTransaction_exc_ endTransactionException;
//ERROR_DESC_LIST_def sqlWarning;
// Rollback the transaction, Don't bother to check if autocommit is on or off, since SQL
// doesn't check for it
// When there is no transaction outstanding, SQL would give an error and ignore this error.
if (WSQL_EXEC_Xact(SQLTRANS_STATUS,NULL) == 0)
EXECDIRECT("ROLLBACK WORK");
//odbc_SQLSvc_EndTransaction_sme_(objtag_, call_id_, &endTransactionException,
// dialogueId, SQL_ROLLBACK
// ,&sqlWarning
// );
// resource statistics resStatSession->end() is called in SRVR::BreakDialogue()
//if (resStatSession != NULL)
// resStatSession->end();
//end rs
SRVRTRACE_EXIT(FILE_SME+16);
return;
}
/*
*
* Synchronous method function for
* operation 'odbc_SQLSvc_SetConnectionOption'
*/
extern "C" void
odbc_SQLSvc_SetConnectionOption_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLSvc_SetConnectionOption_exc_ *exception_
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ IDL_short connectionOption
, /* In */ Int32 optionValueNum
, /* In */ IDL_string optionValueStr
, /* Out */ ERROR_DESC_LIST_def *sqlWarning
)
{
SRVRTRACE_ENTER(FILE_SME+17);
char stmtLabel[MAX_STMT_LABEL_LEN+1];
char sqlString[256];
Int32 retcode = 0;
bool sqlStringNeedsExecution = true;
SRVR_STMT_HDL *pSrvrStmt = NULL;
SRVR_STMT_HDL *resStmt;
int64 local_xid;
UINT xid_length = sizeof(local_xid);
char buffer[100];
char valueStr[MAX_SQL_IDENTIFIER_LEN+1];
char schemaValueStr[MAX_SQL_IDENTIFIER_LEN+MAX_SQL_IDENTIFIER_LEN+5+1]; // 5 for quotes + dot
char *CatalogNameTypeStr = '\0';
char *endPtr;
exception_->exception_nr = CEE_SUCCESS;
sqlWarning->_length = 0;
sqlWarning->_buffer = NULL;
memset(sqlString, 0, 256);
// Given a label find out the SRVR_STMT_HDL
if ((pSrvrStmt = getSrvrStmt("STMT_INTERNAL_1", TRUE)) == NULL)
{
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
return;
}
// clientLCID = srvrGlobal->clientLCID, is done during the creation of statement
// handle. However, the in InitializeDialog(), the correct value of
// srvrGlobal->clientLCID is set only after the creation of statement handle.
// This causes an incorrect clientLCID value (the initalized value zero) to
// be set on pSrvrStmt. This value dectates the character set translations.
// An incorrect value of clientLCID causes incorrect translations for all the
// executions on that statement. The fix is to set the correct value after the
// creation of the statement.
pSrvrStmt->setclientLCID(srvrGlobal->clientLCID);
switch (connectionOption) {
//Special Case//
case SQL_ACCESSMODE_AND_ISOLATION:
switch (optionValueNum) {
case SQL_TXN_READ_UNCOMMITTED:
//Modified it, since on setting at DS level to uncommitted the subsequent connections were not going through.
strcpy(sqlString, "SET TRANSACTION READ ONLY, ISOLATION LEVEL READ UNCOMMITTED");
break;
case SQL_TXN_READ_COMMITTED:
//Modified it, since on setting at DS level to uncommitted the subsequent connections were not going through.
strcpy(sqlString, "SET TRANSACTION READ WRITE, ISOLATION LEVEL READ COMMITTED");
break;
default:
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_OPTION_VALUE_NUM;
return;
}
break;
//Special Case//
case SQL_ACCESS_MODE:
strcpy(sqlString, "SET TRANSACTION ");
switch (optionValueNum) {
case SQL_MODE_READ_WRITE:
strcat(sqlString, "READ WRITE");
break;
case SQL_MODE_READ_ONLY:
if ((srvrGlobal->EnvironmentType & MXO_MSACCESS_1997) || (srvrGlobal->EnvironmentType & MXO_MSACCESS_2000)) // change this to fix MS Access problem. Since it insert, update and delete while SQL_ACCESS_MODE is SQL_MODE_READ_ONLY.
strcat(sqlString, "READ WRITE");
else
strcat(sqlString, "READ ONLY");
break;
case SQL_MODE_NULL:
// Need to find out from profile what is the access Mode
// at present return ParamError. Note there is no break
default:
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_OPTION_VALUE_NUM;
return;
}
break;
case SQL_TXN_ISOLATION:
strcpy(sqlString, "SET TRANSACTION ISOLATION LEVEL ");
switch (optionValueNum) {
case SQL_TXN_READ_UNCOMMITTED:
strcat(sqlString, "READ UNCOMMITTED");
break;
case SQL_TXN_READ_COMMITTED:
strcat(sqlString, "READ COMMITTED");
break;
case SQL_TXN_REPEATABLE_READ:
strcat(sqlString, "REPEATABLE READ");
break;
case SQL_TXN_SERIALIZABLE:
strcat(sqlString, "SERIALIZABLE");
break;
default:
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_OPTION_VALUE_NUM;
return;
}
break;
case SQL_ATTR_ENLIST_IN_DTC:
#ifdef TIP_DEFINED
if (srvrGlobal->tip_gateway != NULL) {
tip_close(srvrGlobal->tip_gateway);
srvrGlobal->tip_gateway = NULL;
}
// Check for non-DTC transaction
if (optionValueNum == NULL){
SetTipUrl((IDL_char *)NULL);
SetLocalXid(NULL, 0);
exception_->exception_nr = 0;
sqlWarning->_length = 0;
sqlWarning->_buffer = NULL;
return;
}
// Check for previous DTC transaction
if(GetTipUrl() != (IDL_char *)NULL){
SetTipUrl((IDL_char *)NULL);
SetLocalXid(NULL, 0);
}
retcode = tip_open(&(srvrGlobal->tip_gateway));
if (retcode != TIPOK){
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_OPEN_TIP_GATEWAY_FAILED;
switch (retcode) {
case TIPNOTCONNECTED:
SendEventMsg (MSG_SRVR_DTC_TIP_NOTCONNECTED,
EVENTLOG_WARNING_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
0);
break;
case TIPNOTCONFIGURED:
SendEventMsg (MSG_SRVR_DTC_TIP_NOTCONFIGURED,
EVENTLOG_WARNING_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
0);
break;
default:
SendEventMsg (MSG_SRVR_DTC_TIP_ERROR,
EVENTLOG_WARNING_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
0);
break;
}
return;
}
strncpy(buffer, optionValueStr, sizeof(buffer));
buffer[sizeof(buffer)-1] = 0;
retcode = tip_pull(srvrGlobal->tip_gateway,
(IDL_char *)buffer,
&local_xid,
xid_length);
if (retcode != TIPOK){
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_PULL_TIP_FAILED;
switch (retcode) {
case TIPNOTCONNECTED:
SendEventMsg (MSG_SRVR_DTC_TIP_NOTCONNECTED,
EVENTLOG_WARNING_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
0);
break;
case TIPNOTCONFIGURED:
SendEventMsg (MSG_SRVR_DTC_TIP_NOTCONFIGURED,
EVENTLOG_WARNING_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
0);
break;
default:
SendEventMsg (MSG_SRVR_DTC_TIP_ERROR,
EVENTLOG_WARNING_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
0);
break;
}
return;
}
SetTipUrl((IDL_char *)buffer);
SetLocalXid(local_xid,
xid_length);
exception_->exception_nr = 0;
sqlWarning->_length = 0;
sqlWarning->_buffer = NULL;
#else
// RS we'll return an error just in case a user tries to use TIP until we get the libraries
sqlWarning->_length = 0;
sqlWarning->_buffer = NULL;
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_OPEN_TIP_GATEWAY_FAILED;
SendEventMsg (MSG_SRVR_DTC_TIP_ERROR,
EVENTLOG_WARNING_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
0);
#endif
return;
case SET_AUTOBEGIN:
strcpy(sqlString, "SET TRANSACTION AUTOBEGIN ON");
break;
case SQL_AUTOCOMMIT:
// if a change is required
sqlStringNeedsExecution = false;
if ( ((srvrGlobal->bAutoCommitOn == TRUE) && (optionValueNum == 0 ))
|| ((srvrGlobal->bAutoCommitOn == FALSE) && (optionValueNum == 1 )) )
{
//check for active txn, if yes commit them
if ((srvrGlobal->bAutoCommitOn == FALSE) && (WSQL_EXEC_Xact(SQLTRANS_STATUS,NULL) == 0))
retcode = pSrvrStmt->ExecDirect(NULL, "COMMIT WORK", INTERNAL_STMT, TYPE_UNKNOWN, SQL_ASYNC_ENABLE_OFF, 0);
if (retcode != SQL_ERROR)
{
if (optionValueNum)
{
if( SQL_SUCCESS == (retcode = pSrvrStmt->ExecDirect(NULL, "SET TRANSACTION AUTOCOMMIT ON", INTERNAL_STMT, TYPE_UNKNOWN, SQL_ASYNC_ENABLE_OFF, 0)))
srvrGlobal->bAutoCommitOn = TRUE;
}
else
{
if( SQL_SUCCESS == (retcode = pSrvrStmt->ExecDirect(NULL, "SET TRANSACTION AUTOCOMMIT OFF", INTERNAL_STMT, TYPE_UNKNOWN, SQL_ASYNC_ENABLE_OFF, 0)))
srvrGlobal->bAutoCommitOn = FALSE;
}
}
}
else
return;
break;
case SET_CATALOG:
case SQL_ATTR_CURRENT_CATALOG:
{
sqlStringNeedsExecution = false;
int len = 0;
bool defaultCatalog = false;
bool isDoubleQuoted = false;
char* tempSqlString = NULL;
if (optionValueStr == NULL || (optionValueStr != NULL && optionValueStr[0] == '\0'))
{
len = strlen(ODBCMX_DEFAULT_CATALOG);
defaultCatalog = true;
}
else
len = strlen(optionValueStr);
tempSqlString = new char[len+20];
if (tempSqlString == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR, EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, "SET CATALOG");
exit(0);
}
if (!defaultCatalog && optionValueStr[0] == '"' && optionValueStr[len-1] == '"')
isDoubleQuoted = true;
strcpy(tempSqlString, "SET CATALOG ");
if (!isDoubleQuoted)
strcat(tempSqlString, "'");
if (defaultCatalog)
strcat(tempSqlString, ODBCMX_DEFAULT_CATALOG);
else
strcat(tempSqlString, optionValueStr);
if (!isDoubleQuoted)
strcat(tempSqlString, "'");
if( SQL_SUCCESS == (retcode = pSrvrStmt->ExecDirect(NULL, tempSqlString, INTERNAL_STMT, TYPE_UNKNOWN, SQL_ASYNC_ENABLE_OFF, 0)))
{
if (defaultCatalog)
strcpy(srvrGlobal->DefaultCatalog, ODBCMX_DEFAULT_CATALOG);
else if (isDoubleQuoted)
{
strncpy(srvrGlobal->DefaultCatalog, optionValueStr+1, len-2);
srvrGlobal->DefaultCatalog[len-2] = '\0';
}
else
strcpy(srvrGlobal->DefaultCatalog, optionValueStr);
}
delete [] tempSqlString;
}
break;
case SET_SCHEMA:
{
if (optionValueStr == NULL || (optionValueStr != NULL && optionValueStr[0] == '\0'))
sprintf(schemaValueStr, "%s.%s", ODBCMX_DEFAULT_CATALOG, ODBCMX_DEFAULT_SCHEMA);
else
{
if (strlen(optionValueStr) < sizeof(schemaValueStr))
strcpy(schemaValueStr, optionValueStr);
else
{
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_OPTION_VALUE_STR;
return;
}
}
strcpy(sqlString, "SET SCHEMA ");
strncat(sqlString, schemaValueStr, sizeof(sqlString));
sqlString[sizeof(sqlString)-1] = 0;
}
break;
case RESET_DEFAULTS:
strcpy(sqlString, "CONTROL QUERY DEFAULT * RESET");
break;
case RESET_RESET_DEFAULTS:
strcpy(sqlString, "CONTROL QUERY DEFAULT * RESET RESET");
break;
case CUT_CONTROLQUERYSHAPE:
strcpy(sqlString, "CONTROL QUERY SHAPE CUT");
break;
case BEGIN_SESSION:
if(optionValueStr != NULL && strlen(optionValueStr) > 0)
sprintf(sqlString,"SET SESSION DEFAULT SQL_SESSION 'BEGIN:%0.200s';",optionValueStr);
else
strcpy(sqlString, "SET SESSION DEFAULT SQL_SESSION 'BEGIN';");
break;
// Added the below workaround for volatile table SQL problem
// Not called any more from initailizeDialog since executor fixed it.
case SET_SESSION_USERNAME:
sprintf( sqlString, "CONTROL QUERY DEFAULT session_id '%s'", srvrGlobal->sessionId );
break;
case END_SESSION:
strcpy(sqlString, "SET SESSION DEFAULT SQL_SESSION 'END'");
break;
case SET_CATALOGNAMETYPE:
strcpy(sqlString, "SET NAMETYPE ANSI");
break;
case SET_SETANDCONTROLSTMTS:
break;
case SET_ODBC_PROCESS:
strcpy(sqlString, "CONTROL QUERY DEFAULT ODBC_PROCESS 'TRUE'");
break;
case SET_JDBC_PROCESS:
strcpy(sqlString, "CONTROL QUERY DEFAULT JDBC_PROCESS 'TRUE'");
break;
case SET_INFER_NCHAR:
strcpy(sqlString, "CONTROL QUERY DEFAULT INFER_CHARSET 'ON'");
break;
case SET_EXPLAIN_PLAN:
strcpy(sqlString,"CONTROL QUERY DEFAULT GENERATE_EXPLAIN 'ON'");
break;
case SQL_ATTR_ROWSET_RECOVERY:
if (optionValueNum)
srvrGlobal->EnvironmentType |= MXO_ROWSET_ERROR_RECOVERY;
else
srvrGlobal->EnvironmentType &= (0xFFFF-MXO_ROWSET_ERROR_RECOVERY);
return;
case SQL_ATTR_CONCURRENCY:
strcpy(sqlString, "CONTROL QUERY DEFAULT READONLY_CURSOR ");
switch (optionValueNum)
{
case SQL_CONCUR_READ_ONLY:
strcat(sqlString, "'TRUE'");
break;
case SQL_CONCUR_LOCK:
case SQL_CONCUR_ROWVER:
case SQL_CONCUR_VALUES:
strcat(sqlString, "'FALSE'");
break;
default:
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_OPTION_VALUE_NUM;
return;
}
break;
case JDBC_ATTR_CONN_IDLE_TIMEOUT:
if (srvrGlobal->drvrVersion.componentId == JDBC_DRVR_COMPONENT)
{
if (optionValueNum > JDBC_DATASOURCE_CONN_IDLE_TIMEOUT)
srvrGlobal->javaConnIdleTimeout = optionValueNum;
else
srvrGlobal->javaConnIdleTimeout = JDBC_DATASOURCE_CONN_IDLE_TIMEOUT;
}
else
{
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_CONNECTION_OPTION;
}
return;
case CONN_IDLE_TIMER_RESET:
// this connection attribute is JDBC exclusive, NDCS just need to recognize it and does nothing
return;
break;
// Set priority of DP2 relative to master executor/ESPs
case CONTROL_TABLE_PRIORITY:
sprintf(sqlString,"CONTROL TABLE * PRIORITY_DELTA '%d'", optionValueNum);
break;
case SET_STATISTICS:
strcpy(sqlString,"CONTROL QUERY DEFAULT detailed_statistics 'PERTABLE'");
break;
// JDBC sets this connection attribute to set the Proxy syntax for SPJ result sets
case SET_SPJ_ENABLE_PROXY:
if(optionValueNum)
srvrGlobal->bSpjEnableProxy = true;
else
srvrGlobal->bSpjEnableProxy = false;
return;
break;
case SQL_ATTR_JOIN_UDR_TRANSACTION:
errno = 0;
endPtr = NULL;
srvrGlobal->spjTxnId = strtoll(optionValueStr, &endPtr, 10);
//srvrGlobal->spjTxnId = atoll(optionValueStr);
if( errno == 0 )
{
#ifdef SPJ_TXN_TEST
sprintf(msg, "SQL_ATTR_JOIN_UDR_TRANSACTION %lld", srvrGlobal->spjTxnId);
SendEventMsg(MSG_SERVER_TRACE_INFO, EVENTLOG_INFORMATION_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, msg);
#endif
retcode = JOINTRANSACTION( srvrGlobal->spjTxnId );
if(retcode != 0)
{
sprintf(buffer,"Transaction join failed with error %d",retcode);
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = buffer;
}
else
srvrGlobal->bspjTxnJoined = TRUE;
}
else
{
sprintf(buffer,"Unable to retrieve transaction ID. Error %d",errno);
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = buffer;
}
return;
break;
case SQL_ATTR_SUSPEND_UDR_TRANSACTION:
endPtr = NULL;
errno = 0;
srvrGlobal->spjTxnId = strtoll(optionValueStr, &endPtr, 10);
//srvrGlobal->spjTxnId = atoll(optionValueStr);
if( errno == 0 )
{
#ifdef SPJ_TXN_TEST
sprintf(msg, "SQL_ATTR_SUSPEND_UDR_TRANSACTION %lld", srvrGlobal->spjTxnId);
SendEventMsg(MSG_SERVER_TRACE_INFO, EVENTLOG_INFORMATION_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 1, msg);
#endif
retcode = SUSPENDTRANSACTION( (short*)&(srvrGlobal->spjTxnId) );
if(retcode != 0)
{
sprintf(buffer,"Transaction suspend failed with error %d",retcode);
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = buffer;
}
else
srvrGlobal->bspjTxnJoined = FALSE;
}
else
{
sprintf(buffer,"Unable to retrieve transaction ID. Error %d",errno);
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = buffer;
}
return;
break;
case SET_INPUT_CHARSET:
snprintf(sqlString,200,"CONTROL QUERY DEFAULT input_charset '%s'", getCharsetStr(srvrGlobal->clientLCID));
break;
case SET_TERMINAL_CHARSET:
snprintf(sqlString,200,"CONTROL QUERY DEFAULT terminal_charset '%s'", getCharsetStr(srvrGlobal->clientErrorLCID));
break;
case SET_NVCI_PROCESS:
sprintf(sqlString, "CONTROL QUERY DEFAULT NVCI_PROCESS 'ON'");
break;
case WMS_QUERY_MONITORING:
strcpy(sqlString, "CONTROL QUERY DEFAULT WMS_QUERY_MONITORING 'OFF'");
break;
default:
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_INVALID_CONNECTION_OPTION;
return;
}
if(sqlStringNeedsExecution)
{
if (connectionOption == SET_SETANDCONTROLSTMTS)
retcode = pSrvrStmt->ExecDirect(NULL, optionValueStr, INTERNAL_STMT, TYPE_UNKNOWN, SQL_ASYNC_ENABLE_OFF, 0);
else
retcode = pSrvrStmt->ExecDirect(NULL, sqlString, INTERNAL_STMT, TYPE_UNKNOWN, SQL_ASYNC_ENABLE_OFF, 0);
}
switch (retcode)
{
case SQL_SUCCESS:
exception_->exception_nr = 0;
// Ignore estimatedCost and rowsAffected
sqlWarning->_length = pSrvrStmt->sqlWarning._length;
sqlWarning->_buffer = pSrvrStmt->sqlWarning._buffer;
break;
case SQL_ERROR:
if(pSrvrStmt->sqlError.errorList._buffer->sqlcode == -15371) // Executor dev should be treated as warning.
{
exception_->exception_nr = 0;
SendEventMsg(MSG_SQL_WARNING, EVENTLOG_WARNING_TYPE,
srvrGlobal->nskProcessInfo.processId, ODBCMX_SERVER,
srvrGlobal->srvrObjRef, 3, "SQL/MX", "15371", sqlString);
}
else
{
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_SQLError_exn_;
exception_->u.SQLError.errorList._length = pSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = pSrvrStmt->sqlError.errorList._buffer;
}
break;
case PROGRAM_ERROR:
exception_->exception_nr = odbc_SQLSvc_SetConnectionOption_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_SETCONNECTOPTION_FAILED;
default:
break;
}
SRVRTRACE_EXIT(FILE_SME+17);
return;
}
extern "C" void
odbc_SQLSrvr_FetchPerf_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ Int32 *returnCode
, /* In */ DIALOGUE_ID_def dialogueId
, /* In */ const IDL_char *stmtLabel
, /* In */ Int32 maxRowCnt
, /* In */ Int32 maxRowLen
, /* In */ IDL_short sqlAsyncEnable
, /* In */ Int32 queryTimeout
, /* Out */ Int32 *rowsAffected
, /* Out */ Int32 *outValuesFormat
, /* Out */ SQL_DataValue_def *outputDataValue
, /* Out */ Int32 *sqlWarningOrErrorLength
, /* Out */ BYTE *&sqlWarningOrError
)
{
SRVRTRACE_ENTER(FILE_SME+8);
SRVR_STMT_HDL *pSrvrStmt = NULL;
SQLRETURN rc = SQL_SUCCESS;
int outputDataOffset = 0;
*returnCode = SQL_SUCCESS;
if (maxRowCnt < 0)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Invalid Row Count", sqlWarningOrErrorLength, sqlWarningOrError);
}
else
{
pSrvrStmt = getSrvrStmt(stmtLabel, FALSE);
if (pSrvrStmt == NULL)
{
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Statement Label not found", sqlWarningOrErrorLength, sqlWarningOrError);
}
else
{
if (pSrvrStmt->sqlWarningOrErrorLength > 0 &&
pSrvrStmt->sqlWarningOrError != NULL)
{
delete pSrvrStmt->sqlWarningOrError;
}
pSrvrStmt->sqlWarningOrErrorLength = 0;
pSrvrStmt->sqlWarningOrError = NULL;
}
}
if (*returnCode == SQL_SUCCESS)
{
// limit on maxRowsFetched from WMS
if (pSrvrStmt->sqlStmtType != TYPE_SELECT_CATALOG)
{
if (srvrGlobal->maxRowsFetched != 0 && pSrvrStmt->m_bDoneWouldLikeToExecute)
{
if (srvrGlobal->maxRowsFetched <= pSrvrStmt->m_curRowsFetched)
{
WSQL_EXEC_CloseStmt(&pSrvrStmt->stmt);
WSQL_EXEC_ClearDiagnostics(&pSrvrStmt->stmt);
pSrvrStmt->isClosed = true;
pSrvrStmt->bFirstSqlBulkFetch = false;
pSrvrStmt->m_curRowsFetched = 0;
// *returnCode = SQL_NO_DATA_FOUND;
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "The limit for maximum rows to be returned for a query, as set by the administrator, was exceeded", sqlWarningOrErrorLength, sqlWarningOrError);
goto ret;
}
else
{
if (pSrvrStmt->bFirstSqlBulkFetch == true)
pSrvrStmt->m_curRowsFetched = 0;
if (pSrvrStmt->m_curRowsFetched + maxRowCnt <= srvrGlobal->maxRowsFetched )
pSrvrStmt->maxRowCnt = maxRowCnt;
else
{
pSrvrStmt->maxRowCnt = srvrGlobal->maxRowsFetched - pSrvrStmt->m_curRowsFetched;
if (pSrvrStmt->maxRowCnt <= 0)
pSrvrStmt->maxRowCnt = 1;
}
}
}
else
pSrvrStmt->maxRowCnt = maxRowCnt;
}
else
pSrvrStmt->maxRowCnt = maxRowCnt;
pSrvrStmt->maxRowLen = maxRowLen;
// resource statistics
if (resStatStatement != NULL && pSrvrStmt->isClosed == FALSE && pSrvrStmt->bFetchStarted == FALSE && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
pSrvrStmt->bFetchStarted = TRUE;
pSrvrStmt->inState = inState = STMTSTAT_FETCH;
inSqlStmtType = TYPE_UNKNOWN;
inEstimatedCost = 0;
inQueryId = NULL;
inSqlString = NULL;
inErrorStatement = 0;
inWarningStatement = 0;
inRowCount = 0;
inErrorCode = 0;
inSqlError = NULL;
inSqlErrorLength = 0;
/*resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt->sqlUniqueQueryID,
pSrvrStmt->cost_info,
pSrvrStmt->comp_stats_info,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);*/
resStatStatement->start(inState,
pSrvrStmt->sqlQueryType,
stmtLabel,
pSrvrStmt,
inEstimatedCost,
&pSrvrStmt->m_need_21036_end_msg);
}
// end rs
if (pSrvrStmt->sqlStmtType != TYPE_SELECT_CATALOG)
{
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
if(pSrvrStmt->outputDataValue._length > 0 &&
pSrvrStmt->outputDataValue._buffer != NULL)
delete pSrvrStmt->outputDataValue._buffer;
pSrvrStmt->outputDataValue._length = 0;
pSrvrStmt->outputDataValue._buffer = NULL;
if (pSrvrStmt->isClosed)
{
pSrvrStmt->m_curRowsFetched = 0;
pSrvrStmt->bFirstSqlBulkFetch = false;
*returnCode = SQL_NO_DATA_FOUND;
goto ret;
}
pSrvrStmt->currentMethod = odbc_SQLSvc_FetchPerf_ldx_;
// if (pSrvrStmt->sqlBulkFetchPossible && (pSrvrStmt->sqlQueryType == SQL_SELECT_NON_UNIQUE || pSrvrStmt->sqlQueryType == SQL_SP_RESULT_SET))
if (srvrGlobal->drvrVersion.buildId & ROWWISE_ROWSET)
{
*outValuesFormat = ROWWISE_ROWSETS;
rc = FETCH2bulk(pSrvrStmt);
if (pSrvrStmt->rowsAffected > 0)
{
if(pSrvrStmt->outputDataValue._length == 0 && pSrvrStmt->outputDataValue._buffer == NULL)
{
outputDataValue->_buffer = pSrvrStmt->outputDescVarBuffer;
outputDataValue->_length = pSrvrStmt->outputDescVarBufferLen*pSrvrStmt->rowsAffected;
}
else
{
outputDataValue->_buffer = pSrvrStmt->outputDataValue._buffer;
outputDataValue->_length = pSrvrStmt->outputDataValue._length;
}
}
else
{
outputDataValue->_buffer = NULL;
outputDataValue->_length = 0;
}
}
else
{
*outValuesFormat = COLUMNWISE_ROWSETS;
//pSrvrStmt->maxRowCnt = maxRowCnt;
//pSrvrStmt->maxRowLen = maxRowLen;
rc = FETCHPERF(pSrvrStmt, outputDataValue);
}
switch (rc)
{
case ODBC_RG_WARNING:
case SQL_SUCCESS_WITH_INFO:
*returnCode = SQL_SUCCESS_WITH_INFO;
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
*rowsAffected = pSrvrStmt->rowsAffected;
if (*rowsAffected > 0)
pSrvrStmt->m_curRowsFetched += *rowsAffected;
break;
case SQL_SUCCESS:
*returnCode = SQL_SUCCESS;
*rowsAffected = pSrvrStmt->rowsAffected;
if (*rowsAffected > 0)
pSrvrStmt->m_curRowsFetched += *rowsAffected;
break;
case SQL_STILL_EXECUTING:
*returnCode = SQL_STILL_EXECUTING;
break;
case SQL_INVALID_HANDLE:
*returnCode = SQL_INVALID_HANDLE;
break;
case SQL_NO_DATA_FOUND:
pSrvrStmt->bFirstSqlBulkFetch = false;
*returnCode = SQL_NO_DATA_FOUND;
break;
case SQL_ERROR:
pSrvrStmt->bFirstSqlBulkFetch = false;
*returnCode = SQL_ERROR;
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
break;
case PROGRAM_ERROR:
pSrvrStmt->bFirstSqlBulkFetch = false;
*returnCode = SQL_ERROR;
GETMXCSWARNINGORERROR(-1, "HY000", "Fetch Failed", sqlWarningOrErrorLength, sqlWarningOrError);
break;
default:
break;
}
}
else
{ // Catalog APIs
outputDataOffset = *(int*)pSrvrStmt->outputDataValue.pad_to_offset_8_;
*outValuesFormat = COLUMNWISE_ROWSETS;
rc = FETCHPERF(pSrvrStmt, &pSrvrStmt->outputDataValue);
if (pSrvrStmt->sqlError.errorList._buffer != NULL)
{
*returnCode = SQL_ERROR;
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
if (pSrvrStmt->outputDataValue._buffer != NULL)
delete pSrvrStmt->outputDataValue._buffer;
pSrvrStmt->outputDataValue._buffer = NULL;
pSrvrStmt->outputDataValue._length = 0;
}
else if (pSrvrStmt->rowsAffected == 0 || pSrvrStmt->rowsAffected == -1)
{
if (pSrvrStmt->bSQLMessageSet)
pSrvrStmt->cleanupSQLMessage();
pSrvrStmt->outputDataValue._buffer = NULL;
pSrvrStmt->outputDataValue._length = 0;
*(int*)pSrvrStmt->outputDataValue.pad_to_offset_8_=0;
outputDataOffset = 0;
pSrvrStmt->InternalStmtClose(SQL_CLOSE);
*returnCode = SQL_NO_DATA_FOUND;
}
else
{
*rowsAffected = pSrvrStmt->rowsAffected;
if (pSrvrStmt->sqlWarning._length != 0)
{
*returnCode = SQL_SUCCESS_WITH_INFO;
GETSQLWARNINGORERROR2(pSrvrStmt);
*sqlWarningOrErrorLength = pSrvrStmt->sqlWarningOrErrorLength;
sqlWarningOrError = pSrvrStmt->sqlWarningOrError;
}
else
{
char *tmpByte = (char*)&pSrvrStmt->outputDataValue._length;
for(int i=0; i<sizeof(pSrvrStmt->outputDataValue.pad_to_offset_8_); i++) {
pSrvrStmt->outputDataValue.pad_to_offset_8_[i] = *tmpByte;
tmpByte++;
}
*returnCode = SQL_SUCCESS;
}
pSrvrStmt->rowsAffected = 0;
}
outputDataValue->_length = pSrvrStmt->outputDataValue._length - outputDataOffset;
outputDataValue->_buffer = pSrvrStmt->outputDataValue._buffer + outputDataOffset;
}
ret:
if (*returnCode != SQL_SUCCESS &&
*returnCode != SQL_SUCCESS_WITH_INFO)
{
if (pSrvrStmt->outputDataValue._buffer != NULL)
delete pSrvrStmt->outputDataValue._buffer;
pSrvrStmt->outputDataValue._length = 0;
pSrvrStmt->outputDataValue._buffer = NULL;
}
if (pSrvrStmt->sqlNewQueryType == SQL_SP_RESULT_SET)
{
if (pSrvrStmt->callStmtHandle->isClosed == true && *returnCode == SQL_NO_DATA_FOUND || *returnCode == SQL_ERROR)
{
pSrvrStmt->callStmtHandle->inState = STMTSTAT_CLOSE;
// Fix for CR 6059
if( resStatStatement != NULL )
resStatStatement->setStatistics(pSrvrStmt->callStmtHandle);
}
}
else if (resStatStatement != NULL && pSrvrStmt->bFetchStarted == TRUE &&
(*returnCode == SQL_NO_DATA_FOUND || *returnCode == SQL_ERROR ||
((*returnCode == SQL_SUCCESS || *returnCode == SQL_SUCCESS_WITH_INFO) && *rowsAffected < maxRowCnt)))
{
resStatStatement->setStatistics(pSrvrStmt);
}
}
// resource statistics
if (resStatStatement != NULL && pSrvrStmt != NULL && pSrvrStmt->isClosed == TRUE && pSrvrStmt->bFetchStarted == TRUE && pSrvrStmt->stmtType == EXTERNAL_STMT)
{
if (*returnCode == SQL_ERROR && pSrvrStmt->sqlWarningOrError != NULL)
{
inErrorCode = *(Int32 *)(pSrvrStmt->sqlWarningOrError+8);
inSqlError = (char*)pSrvrStmt->sqlWarningOrError + 16;
inSqlErrorLength =*(Int32 *)(pSrvrStmt->sqlWarningOrError + 12);
}
pSrvrStmt->bFetchStarted = FALSE;
Int32 inMaxRowCnt = 0;
Int32 inMaxRowLen = 0;
inMaxRowCnt = maxRowCnt;
inMaxRowLen = maxRowLen;
if (*returnCode != SQL_SUCCESS &&
*returnCode != SQL_SUCCESS_WITH_INFO)
inErrorStatement ++;
else
setStatisticsFlag = FALSE;
if (*returnCode == SQL_SUCCESS_WITH_INFO)
inWarningStatement ++;
if (*returnCode == SQL_NO_DATA_FOUND)
{
inErrorStatement = 0;
inWarningStatement = 0;
setStatisticsFlag = TRUE;
}
inQueryId = pSrvrStmt->sqlUniqueQueryID;
inSqlQueryType = pSrvrStmt->sqlQueryType;
resStatStatement->setStatisticsFlag(setStatisticsFlag);
resStatStatement->end(inState,
inSqlQueryType,
inSqlStmtType,
inQueryId,
inEstimatedCost,
inSqlString,
inErrorStatement,
inWarningStatement,
inRowCount,
inErrorCode,
resStatSession,
inSqlErrorLength,
inSqlError,
pSrvrStmt,
&pSrvrStmt->m_need_21036_end_msg,
pSrvrStmt->sqlNewQueryType,
pSrvrStmt->isClosed);
}
//end rs
SRVRTRACE_EXIT(FILE_SME+8);
return;
} // odbc_SQLSrvr_FetchPerf_sme_()
extern "C" void
odbc_SQLSrvr_ExtractLob_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def *call_id_
, /* Out */ odbc_SQLsrvr_ExtractLob_exc_ *exception_
, /* In */ IDL_long extractLobAPI
, /* In */ IDL_string lobHandle
, /* Out */ IDL_long_long &lobDataLen
, /* Out */ BYTE *& lobDataValue
)
{
char LobExtractQuery[1000];
char RequestError[200] = {0};
SRVR_STMT_HDL *QryLobExtractSrvrStmt = NULL;
if ((QryLobExtractSrvrStmt = getSrvrStmt("MXOSRVR_EXTRACRTLOB", TRUE)) == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
2,
"EXTRACT LOB APIs",
"Allocate Statement");
exception_->exception_nr = odbc_SQLsrvr_ExtractLob_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
snprintf(LobExtractQuery, sizeof(LobExtractQuery), "EXTRACT LOBLENGTH(LOB'%s') LOCATION %Ld", lobHandle, (Int64)&lobDataLen);
try
{
short retcode = QryLobExtractSrvrStmt->ExecDirect(NULL, LobExtractQuery, EXTERNAL_STMT, TYPE_CALL, SQL_ASYNC_ENABLE_OFF, 0);
if (retcode == SQL_ERROR)
{
ERROR_DESC_def *p_buffer = QryLobExtractSrvrStmt->sqlError.errorList._buffer;
strncpy(RequestError, p_buffer->errorText, sizeof(RequestError) - 1);
SendEventMsg(MSG_SQL_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
2,
p_buffer->sqlcode,
RequestError);
exception_->exception_nr = odbc_SQLsrvr_ExtractLob_ParamError_exn_;
exception_->u.SQLError.errorList._length = QryLobExtractSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = QryLobExtractSrvrStmt->sqlError.errorList._buffer;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECUTE_FAILED;
}
}
catch (...)
{
SendEventMsg(MSG_PROGRAMMING_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
1,
"Exception in executing EXTRACT LOBLENGTH");
exception_->exception_nr = odbc_SQLsrvr_ExtractLob_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECDIRECT_FAILED;
}
lobDataValue = new BYTE[lobDataLen + 1];
if (lobDataValue == NULL)
{
exception_->exception_nr = odbc_SQLsrvr_ExtractLob_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_BUFFER_ALLOC_FAILED;
}
memset(lobDataValue, 0, lobDataLen + 1);
memset(LobExtractQuery, 0, sizeof(LobExtractQuery));
snprintf(LobExtractQuery, sizeof(LobExtractQuery), "EXTRACT LOBTOBUFFER(LOB'%s', LOCATION %Ld, SIZE %Ld)", lobHandle, (Int64)lobDataValue, &lobDataLen);
if (exception_->exception_nr == 0)
{
try
{
short retcode = QryLobExtractSrvrStmt->ExecDirect(NULL, LobExtractQuery, EXTERNAL_STMT, TYPE_CALL, SQL_ASYNC_ENABLE_OFF, 0);
if (retcode == SQL_ERROR)
{
ERROR_DESC_def *p_buffer = QryLobExtractSrvrStmt->sqlError.errorList._buffer;
strncpy(RequestError, p_buffer->errorText, sizeof(RequestError) - 1);
SendEventMsg(MSG_SQL_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
2,
p_buffer->sqlcode,
RequestError);
exception_->exception_nr = odbc_SQLsrvr_ExtractLob_ParamError_exn_;
exception_->u.SQLError.errorList._length = QryLobExtractSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = QryLobExtractSrvrStmt->sqlError.errorList._buffer;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECUTE_FAILED;
}
}
catch (...)
{
SendEventMsg(MSG_PROGRAMMING_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
1,
"Exception in executing EXTRACT LOBTOBUFFER");
exception_->exception_nr = odbc_SQLsrvr_ExtractLob_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECDIRECT_FAILED;
}
if (exception_->exception_nr != 0) {
lobDataLen = 0;
delete [] lobDataValue;
lobDataValue = NULL;
}
}
}
extern "C" void
odbc_SQLSrvr_UpdateLob_sme_(
/* In */ CEE_tag_def objtag_
, /* In */ const CEE_handle_def * call_id_
, /* In */ odbc_SQLSvc_UpdateLob_exc_ * exception_
, /* In */ IDL_short lobUpdateType
, /* In */ IDL_string lobHandle
, /* In */ IDL_long_long totalLength
, /* In */ IDL_long_long offset
, /* In */ IDL_long_long length
, /* In */ BYTE * data)
{
char lobUpdateQuery[1000] = {0};
char RequestError[200] = {0};
SRVR_STMT_HDL * QryLobUpdateSrvrStmt = NULL;
if ((QryLobUpdateSrvrStmt = getSrvrStmt("MXOSRVR_UPDATELOB", TRUE)) == NULL)
{
SendEventMsg(MSG_MEMORY_ALLOCATION_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
2,
"LOB UPDATE APIs",
"Allocate Statement");
exception_->exception_nr = odbc_SQLSvc_UpdateLob_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_UNABLE_TO_ALLOCATE_SQL_STMT;
}
if (offset == 0)
{
snprintf(lobUpdateQuery, sizeof(lobUpdateQuery), "UPDATE LOB (LOB'%s', LOCATION %Ld, SIZE %Ld)", lobHandle, (Int64)data, length);
}
else
{
snprintf(lobUpdateQuery, sizeof(lobUpdateQuery), "UPDATE LOB (LOB'%s', LOCATION %Ld, SIZE %Ld, APPEND)", lobHandle, (Int64)data, length);
}
short retcode = 0;
try
{
retcode = QryLobUpdateSrvrStmt->ExecDirect(NULL, lobUpdateQuery, INTERNAL_STMT, TYPE_UNKNOWN, SQL_ASYNC_ENABLE_OFF, 0);
if (retcode == SQL_ERROR)
{
ERROR_DESC_def * p_buffer = QryLobUpdateSrvrStmt->sqlError.errorList._buffer;
strncpy(RequestError, p_buffer->errorText, sizeof(RequestError) - 1);
SendEventMsg(MSG_SQL_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
2,
p_buffer->sqlcode,
RequestError);
exception_->exception_nr = odbc_SQLSvc_UpdateLob_ParamError_exn_;
exception_->u.SQLError.errorList._length = QryLobUpdateSrvrStmt->sqlError.errorList._length;
exception_->u.SQLError.errorList._buffer = QryLobUpdateSrvrStmt->sqlError.errorList._buffer;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECUTE_FAILED;
}
}
catch (...)
{
SendEventMsg(MSG_PROGRAMMING_ERROR,
EVENTLOG_ERROR_TYPE,
srvrGlobal->nskProcessInfo.processId,
ODBCMX_SERVER,
srvrGlobal->srvrObjRef,
1,
"Exception in executing UPDATE_LOB");
exception_->exception_nr = odbc_SQLSvc_UpdateLob_ParamError_exn_;
exception_->u.ParamError.ParamDesc = SQLSVC_EXCEPTION_EXECUTE_FAILED;
}
}
//========================================================================
//LCOV_EXCL_START
short qrysrvc_GetAdaptiveSegment()
{
static ADAPTIVE_SEGMENT_DATA asd = {CATCHER, ASOPER_ALLOCATE, -1};
_cc_status cc;
short error;
//short pHandle[10];
TPT_DECL(pHandle);
unsigned short wcount;
SB_Tag_Type tag;
Int32 timeout = AS_TIMEOUT;
int size;
if (srvrGlobal->bWMS_AdaptiveSegment == false)
return -1;
if ((error = getProcessHandle(srvrGlobal->QSProcessName,
TPT_REF(pHandle))) != 0)
{
if (srvrGlobal->fnumAS != -1)
{
FILE_CLOSE_(srvrGlobal->fnumAS);
srvrGlobal->fnumAS = -1;
}
return -1;
}
if (srvrGlobal->fnumAS == -1 || 2 != PROCESSHANDLE_COMPARE_(TPT_REF(pHandle), TPT_REF(srvrGlobal->pASHandle)))
{
if (srvrGlobal->fnumAS != -1)
{
FILE_CLOSE_(srvrGlobal->fnumAS);
srvrGlobal->fnumAS = -1;
}
// bits <1> ON - nowait
short option = 0x4000;
error = FILE_OPEN_(srvrGlobal->QSProcessName
, strlen(srvrGlobal->QSProcessName)
, &srvrGlobal->fnumAS
, 0 //access
, 0 //exclusion
, 1 //nowait_depth
, 0 //sync-or-receive-depth
, option //options
);
if (error == 0)
{
cc = AWAITIOX(&srvrGlobal->fnumAS,OMITREF,OMITREF,OMITREF,timeout);
if (_status_lt(cc))
FILE_GETINFO_ (srvrGlobal->fnumAS, &error);
else
error = 0;
}
if (error == 0)
{
if ((error = getProcessHandle(srvrGlobal->QSProcessName,
TPT_REF(srvrGlobal->pASHandle))) != 0)
error = 1;
}
if (error)
{
if (srvrGlobal->fnumAS != -1) //timeout
FILE_CLOSE_(srvrGlobal->fnumAS);
srvrGlobal->fnumAS = -1;
return -1;
}
}
size = sizeof(asd);
short fnum = srvrGlobal->fnumAS;
cc = WRITEREADX( fnum,
(char*)&asd,
size,
size,
&wcount,
tag);
if (_status_lt(cc))
{
FILE_CLOSE_(srvrGlobal->fnumAS);
srvrGlobal->fnumAS = -1;
return -1;
}
cc = AWAITIOX(&fnum,OMITREF,&wcount,&tag,timeout);
if (_status_lt(cc))
{
FILE_CLOSE_(srvrGlobal->fnumAS);
srvrGlobal->fnumAS = -1;
return -1;
}
return asd.segment;
}
void AllocateAdaptiveSegment(SRVR_STMT_HDL *pSrvrStmt)
{
if (srvrGlobal->bWMS_AdaptiveSegment == false)
return;
if (pSrvrStmt->m_isAdaptiveSegmentAllocated)
{
if (pSrvrStmt->m_adaptive_segment != -1)
ClearAdaptiveSegment(pSrvrStmt->m_adaptive_segment);
}
pSrvrStmt->m_isAdaptiveSegmentAllocated = false;
pSrvrStmt->m_adaptive_segment = qrysrvc_GetAdaptiveSegment();
if (pSrvrStmt->m_adaptive_segment != -1)
pSrvrStmt->m_isAdaptiveSegmentAllocated = true;
if (pSrvrStmt->m_adaptive_segment != srvrGlobal->lastCQDAdaptiveSegment)
{
char AffinityCQD[64];
sprintf(AffinityCQD, "CONTROL QUERY DEFAULT AFFINITY_VALUE '%d'", pSrvrStmt->m_adaptive_segment);
EXECDIRECT(AffinityCQD);
srvrGlobal->lastCQDAdaptiveSegment = pSrvrStmt->m_adaptive_segment;
}
}
void DeallocateAdaptiveSegment(SRVR_STMT_HDL *pSrvrStmt)
{
if (srvrGlobal->bWMS_AdaptiveSegment == false)
return;
if (pSrvrStmt->m_isAdaptiveSegmentAllocated)
{
if (pSrvrStmt->m_adaptive_segment != -1)
ClearAdaptiveSegment(pSrvrStmt->m_adaptive_segment);
pSrvrStmt->m_isAdaptiveSegmentAllocated = false;
}
}
void ClearAdaptiveSegment(short adapiveSeg)
{
static ADAPTIVE_SEGMENT_DATA asd = {CATCHER, ASOPER_INIT, -1};
_cc_status cc;
short error;
//short pHandle[10];
TPT_DECL(pHandle);
unsigned short wcount;
SB_Tag_Type tag;
Int32 timeout = AS_TIMEOUT;
if (srvrGlobal->bWMS_AdaptiveSegment == false)
return;
if ((error = getProcessHandle(srvrGlobal->QSProcessName,
TPT_REF(pHandle))) != 0)
{
if (srvrGlobal->fnumAS != -1)
{
FILE_CLOSE_(srvrGlobal->fnumAS);
srvrGlobal->fnumAS = -1;
}
return;
}
if (adapiveSeg == -1)
{
asd.operation = ASOPER_DEALLOCATE_ALL;
}
else
{
asd.operation = ASOPER_DEALLOCATE;
asd.segment = adapiveSeg;
}
if (srvrGlobal->fnumAS == -1 || 2 != PROCESSHANDLE_COMPARE_(TPT_REF(pHandle),TPT_REF(srvrGlobal->pASHandle)))
{
if (srvrGlobal->fnumAS != -1)
{
FILE_CLOSE_(srvrGlobal->fnumAS);
srvrGlobal->fnumAS = -1;
}
// bits <1> ON - nowait
short option = 0x4000;
error = FILE_OPEN_(srvrGlobal->QSProcessName
, strlen(srvrGlobal->QSProcessName)
, &srvrGlobal->fnumAS
, 0 //access
, 0 //exclusion
, 1 //nowait_depth
, 0 //sync-or-receive-depth
, option //options
);
if (error == 0)
{
cc = AWAITIOX(&srvrGlobal->fnumAS,OMITREF,OMITREF,OMITREF,timeout);
if (_status_lt(cc))
FILE_GETINFO_ (srvrGlobal->fnumAS, &error);
else
error = 0;
}
if (error == 0)
{
if ((error = getProcessHandle(srvrGlobal->QSProcessName,
TPT_REF(srvrGlobal->pASHandle))) != 0)
error = 1;
}
if (error)
{
if (srvrGlobal->fnumAS != -1) //timeout
FILE_CLOSE_(srvrGlobal->fnumAS);
srvrGlobal->fnumAS = -1;
}
}
if (srvrGlobal->fnumAS != -1)
{
cc = WRITEREADX( srvrGlobal->fnumAS,
(char*)&asd,
sizeof(asd),
sizeof(asd),
&wcount,
tag);
if (_status_lt(cc))
{
FILE_CLOSE_(srvrGlobal->fnumAS);
srvrGlobal->fnumAS = -1;
return;
}
cc = AWAITIOX(&(srvrGlobal->fnumAS),OMITREF,&wcount,&tag,timeout);
if (_status_lt(cc))
{
FILE_CLOSE_(srvrGlobal->fnumAS);
srvrGlobal->fnumAS = -1;
}
}
}
//LCOV_EXCL_STOP
//==========================================================
static void setAuthenticationError(
bool & bSQLMessageSet,
odbc_SQLSvc_SQLError * SQLError,
const char * externalUsername,
bool isInternalError)
{
const char authErrorMessageHeader[] = "*** ERROR[8837] Invalid username or password";
const char authInternalErrorMessageHeader[] = "*** ERROR[8837] Internal error occurred";
char strNow[TIMEBUFSIZE + 1];
kdsCreateSQLErrorException(bSQLMessageSet,SQLError,1);
size_t messageHeaderLength;
if (isInternalError)
messageHeaderLength = strlen(authInternalErrorMessageHeader);
else
messageHeaderLength = strlen(authErrorMessageHeader);
size_t messageLength = (messageHeaderLength + 1) * 4 + TIMEBUFSIZE;
char *message = new char[messageLength];
if (isInternalError)
strcpy(message,authInternalErrorMessageHeader);
else
strcpy(message,authErrorMessageHeader);
strcat(message,". User: ");
strcat(message,externalUsername);
time_t now = time(NULL);
bzero(strNow,sizeof(strNow));
strftime(strNow,sizeof(strNow)," [%Y-%m-%d %H:%M:%S]", localtime(&now));
strcat(message,strNow);
kdsCopySQLErrorExceptionAndRowCount(SQLError,message,-8837," ",-1);
delete message;
}
|
// Copyright 2013 Olivier Gillet.
//
// Author: Olivier Gillet (ol.gillet@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// See http://creativecommons.org/licenses/MIT/ for more information.
//
// -----------------------------------------------------------------------------
//
// Driver for the ADD/DEL switches.
#include "frames/drivers/switches.h"
#include <string.h>
namespace frames {
void Switches::Init() {
memset(&switch_state_, 0xff, sizeof(switch_state_));
GPIO_InitTypeDef gpio_init;
gpio_init.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
gpio_init.GPIO_Speed = GPIO_Speed_10MHz;
gpio_init.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOB, &gpio_init);
}
void Switches::Debounce() {
switch_state_[0] = (switch_state_[0] << 1) | \
GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_10);
switch_state_[1] = (switch_state_[1] << 1) | \
GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11);
}
} // namespace frames
|
/*
Copyright 2017 Cory Sherman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef GLWRAPPER_HPP
#define GLWRAPPER_HPP
// profile.hpp is always included first (all headers require it)
// it verifies OpenGL headers are included, and defines Profile enum and getProfile()
#include "glwrapper/profile.hpp"
#include "glwrapper/attribute.hpp"
#include "glwrapper/buffer.hpp"
#include "glwrapper/error.hpp"
#include "glwrapper/profile.hpp"
#include "glwrapper/program.hpp"
#include "glwrapper/program_util.hpp"
#include "glwrapper/shader.hpp"
#include "glwrapper/shader_util.hpp"
#include "glwrapper/texture.hpp"
#include "glwrapper/uniform.hpp"
#include "glwrapper/vertex_array.hpp"
#endif // #ifndef GLWRAPPER_HPP
|
/**
* \file WznmRMSubsetMSubset_vecs.cpp
* database access for table TblWznmRMSubsetMSubset (implementation of vectors)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
class TblWznmRMSubsetMSubset::VecVReltype
******************************************************************************/
uint TblWznmRMSubsetMSubset::VecVReltype::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "ainb") return AINB;
if (s == "bina") return BINA;
if (s == "compl") return COMPL;
if (s == "disj") return DISJ;
if (s == "xsec") return XSEC;
return(0);
};
string TblWznmRMSubsetMSubset::VecVReltype::getSref(
const uint ix
) {
if (ix == AINB) return("ainb");
if (ix == BINA) return("bina");
if (ix == COMPL) return("compl");
if (ix == DISJ) return("disj");
if (ix == XSEC) return("xsec");
return("");
};
string TblWznmRMSubsetMSubset::VecVReltype::getTitle(
const uint ix
, const uint ixWznmVLocale
) {
if (ixWznmVLocale == 1) {
if (ix == AINB) return("a includes b");
if (ix == BINA) return("b includes a");
if (ix == COMPL) return("complement");
if (ix == DISJ) return("disjointedness");
if (ix == XSEC) return("intersection");
return(getSref(ix));
};
return("");
};
void TblWznmRMSubsetMSubset::VecVReltype::fillFeed(
const uint ixWznmVLocale
, Feed& feed
) {
feed.clear();
for (unsigned int i = 1; i <= 5; i++) feed.appendIxSrefTitles(i, getSref(i), getTitle(i, ixWznmVLocale));
};
|
// Copyright (c) 2012-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dbwrapper.h"
#include "fs.h"
#include "random.h"
#include "util.h"
#include <algorithm>
#include <leveldb/cache.h>
#include <leveldb/env.h>
#include <leveldb/filter_policy.h>
#include <memenv.h>
#include <stdint.h>
class CBitcoinArrayLevelDBLogger : public leveldb::Logger
{
public:
// This code is adapted from posix_logger.h, which is why it is using vsprintf.
// Please do not do this in normal code
virtual void Logv(const char* format, va_list ap) override
{
if (!LogAcceptCategory(BCLog::LEVELDB)) {
return;
}
char buffer[500];
for (int iter = 0; iter < 2; iter++) {
char* base;
int bufsize;
if (iter == 0) {
bufsize = sizeof(buffer);
base = buffer;
} else {
bufsize = 30000;
base = new char[bufsize];
}
char* p = base;
char* limit = base + bufsize;
// Print the message
if (p < limit) {
va_list backup_ap;
va_copy(backup_ap, ap);
// Do not use vsnprintf elsewhere in bitcoinarray source code, see above.
p += vsnprintf(p, limit - p, format, backup_ap);
va_end(backup_ap);
}
// Truncate to available space if necessary
if (p >= limit) {
if (iter == 0) {
continue; // Try again with larger buffer
} else {
p = limit - 1;
}
}
// Add newline if necessary
if (p == base || p[-1] != '\n') {
*p++ = '\n';
}
assert(p <= limit);
base[std::min(bufsize - 1, (int)(p - base))] = '\0';
LogPrintStr(base);
if (base != buffer) {
delete[] base;
}
break;
}
}
};
static leveldb::Options GetOptions(size_t nCacheSize)
{
leveldb::Options options;
options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
options.compression = leveldb::kNoCompression;
options.max_open_files = 64;
options.info_log = new CBitcoinArrayLevelDBLogger();
if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
// LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
// on corruption in later versions.
options.paranoid_checks = true;
}
return options;
}
CDBWrapper::CDBWrapper(const fs::path& path, size_t nCacheSize, bool fMemory, bool fWipe, bool obfuscate)
{
penv = nullptr;
readoptions.verify_checksums = true;
iteroptions.verify_checksums = true;
iteroptions.fill_cache = false;
syncoptions.sync = true;
options = GetOptions(nCacheSize);
options.create_if_missing = true;
if (fMemory) {
penv = leveldb::NewMemEnv(leveldb::Env::Default());
options.env = penv;
} else {
if (fWipe) {
LogPrintf("Wiping LevelDB in %s\n", path.string());
leveldb::Status result = leveldb::DestroyDB(path.string(), options);
dbwrapper_private::HandleError(result);
}
TryCreateDirectories(path);
LogPrintf("Opening LevelDB in %s\n", path.string());
}
leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
dbwrapper_private::HandleError(status);
LogPrintf("Opened LevelDB successfully\n");
if (gArgs.GetBoolArg("-forcecompactdb", false)) {
LogPrintf("Starting database compaction of %s\n", path.string());
pdb->CompactRange(nullptr, nullptr);
LogPrintf("Finished database compaction of %s\n", path.string());
}
// The base-case obfuscation key, which is a noop.
obfuscate_key = std::vector<unsigned char>(OBFUSCATE_KEY_NUM_BYTES, '\000');
bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key);
if (!key_exists && obfuscate && IsEmpty()) {
// Initialize non-degenerate obfuscation if it won't upset
// existing, non-obfuscated data.
std::vector<unsigned char> new_key = CreateObfuscateKey();
// Write `new_key` so we don't obfuscate the key with itself
Write(OBFUSCATE_KEY_KEY, new_key);
obfuscate_key = new_key;
LogPrintf("Wrote new obfuscate key for %s: %s\n", path.string(), HexStr(obfuscate_key));
}
LogPrintf("Using obfuscation key for %s: %s\n", path.string(), HexStr(obfuscate_key));
}
CDBWrapper::~CDBWrapper()
{
delete pdb;
pdb = nullptr;
delete options.filter_policy;
options.filter_policy = nullptr;
delete options.info_log;
options.info_log = nullptr;
delete options.block_cache;
options.block_cache = nullptr;
delete penv;
options.env = nullptr;
}
bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
{
leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
dbwrapper_private::HandleError(status);
return true;
}
// Prefixed with null character to avoid collisions with other keys
//
// We must use a string constructor which specifies length so that we copy
// past the null-terminator.
const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);
const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;
/**
* Returns a string (consisting of 8 random bytes) suitable for use as an
* obfuscating XOR key.
*/
std::vector<unsigned char> CDBWrapper::CreateObfuscateKey() const
{
unsigned char buff[OBFUSCATE_KEY_NUM_BYTES];
GetRandBytes(buff, OBFUSCATE_KEY_NUM_BYTES);
return std::vector<unsigned char>(&buff[0], &buff[OBFUSCATE_KEY_NUM_BYTES]);
}
bool CDBWrapper::IsEmpty()
{
std::unique_ptr<CDBIterator> it(NewIterator());
it->SeekToFirst();
return !(it->Valid());
}
CDBIterator::~CDBIterator() { delete piter; }
bool CDBIterator::Valid() { return piter->Valid(); }
void CDBIterator::SeekToFirst() { piter->SeekToFirst(); }
void CDBIterator::Next() { piter->Next(); }
namespace dbwrapper_private
{
void HandleError(const leveldb::Status& status)
{
if (status.ok())
return;
LogPrintf("%s\n", status.ToString());
if (status.IsCorruption())
throw dbwrapper_error("Database corrupted");
if (status.IsIOError())
throw dbwrapper_error("Database I/O error");
if (status.IsNotFound())
throw dbwrapper_error("Database entry missing");
throw dbwrapper_error("Unknown database error");
}
const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper& w)
{
return w.obfuscate_key;
}
} // namespace dbwrapper_private
|
// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify -fopenmp -fnoopenmp-use-tls -ferror-limit 100 -emit-llvm -o - %s
// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify -fopenmp -ferror-limit 100 -emit-llvm -o - %s
#pragma omp threadprivate // expected-error {{expected '(' after 'threadprivate'}}
#pragma omp threadprivate( // expected-error {{expected identifier}} expected-error {{expected ')'}} expected-note {{to match this '('}}
#pragma omp threadprivate() // expected-error {{expected identifier}}
#pragma omp threadprivate(1) // expected-error {{expected unqualified-id}}
struct CompleteSt{
int a;
};
struct CompleteSt1{
#pragma omp threadprivate(1) // expected-error {{expected unqualified-id}}
int a;
} d; // expected-note {{'d' defined here}}
int a; // expected-note {{'a' defined here}}
#pragma omp threadprivate(a)
#pragma omp threadprivate(u) // expected-error {{use of undeclared identifier 'u'}}
#pragma omp threadprivate(d, a)
int foo() { // expected-note {{declared here}}
static int l;
#pragma omp threadprivate(l)) // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}}
return (a);
}
#pragma omp threadprivate (a) (
// expected-warning@-1 {{extra tokens at the end of '#pragma omp threadprivate' are ignored}}
#pragma omp threadprivate (a) [ // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}}
#pragma omp threadprivate (a) { // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}}
#pragma omp threadprivate (a) ) // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}}
#pragma omp threadprivate (a) ] // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}}
#pragma omp threadprivate (a) } // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}}
#pragma omp threadprivate a // expected-error {{expected '(' after 'threadprivate'}}
#pragma omp threadprivate(d // expected-error {{expected ')'}} expected-note {{to match this '('}}
#pragma omp threadprivate(d)) // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}}
int x, y;
#pragma omp threadprivate(x)) // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}}
#pragma omp threadprivate(y)),
// expected-warning@-1 {{extra tokens at the end of '#pragma omp threadprivate' are ignored}}
#pragma omp threadprivate(a,d)
#pragma omp threadprivate(d.a) // expected-error {{expected identifier}}
#pragma omp threadprivate((float)a) // expected-error {{expected unqualified-id}}
int foa; // expected-note {{'foa' declared here}}
#pragma omp threadprivate(faa) // expected-error {{use of undeclared identifier 'faa'; did you mean 'foa'?}}
#pragma omp threadprivate(foo) // expected-error {{'foo' is not a global variable, static local variable or static data member}}
#pragma omp threadprivate (int a=2) // expected-error {{expected unqualified-id}}
struct IncompleteSt; // expected-note {{forward declaration of 'IncompleteSt'}}
extern IncompleteSt e;
#pragma omp threadprivate (e) // expected-error {{threadprivate variable with incomplete type 'IncompleteSt'}}
int &f = a; // expected-note {{'f' defined here}}
#pragma omp threadprivate (f) // expected-error {{arguments of '#pragma omp threadprivate' cannot be of reference type 'int &'}}
class TestClass {
private:
int a; // expected-note {{declared here}}
static int b; // expected-note {{'b' declared here}}
TestClass() : a(0){}
public:
TestClass (int aaa) : a(aaa) {}
#pragma omp threadprivate (b, a) // expected-error {{'a' is not a global variable, static local variable or static data member}}
} g(10);
#pragma omp threadprivate (b) // expected-error {{use of undeclared identifier 'b'}}
#pragma omp threadprivate (TestClass::b) // expected-error {{'#pragma omp threadprivate' must appear in the scope of the 'TestClass::b' variable declaration}}
#pragma omp threadprivate (g)
namespace ns {
int m;
#pragma omp threadprivate (m)
}
#pragma omp threadprivate (m) // expected-error {{use of undeclared identifier 'm'}}
#pragma omp threadprivate (ns::m)
#pragma omp threadprivate (ns:m) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'?}}
const int h = 12;
const volatile int i = 10;
#pragma omp threadprivate (h, i)
template <class T>
class TempClass {
private:
T a;
TempClass() : a(){}
public:
TempClass (T aaa) : a(aaa) {}
static T s;
#pragma omp threadprivate (s)
};
#pragma omp threadprivate (s) // expected-error {{use of undeclared identifier 's'}}
static __thread int t; // expected-note {{'t' defined here}}
#pragma omp threadprivate (t) // expected-error {{variable 't' cannot be threadprivate because it is thread-local}}
// Register "0" is currently an invalid register for global register variables.
// Use "esp" instead of "0".
// register int reg0 __asm__("0");
register int reg0 __asm__("esp"); // expected-note {{'reg0' defined here}}
#pragma omp threadprivate (reg0) // expected-error {{variable 'reg0' cannot be threadprivate because it is a global named register variable}}
int o; // expected-note {{candidate found by name lookup is 'o'}}
#pragma omp threadprivate (o)
namespace {
int o; // expected-note {{candidate found by name lookup is '(anonymous namespace)::o'}}
#pragma omp threadprivate (o)
#pragma omp threadprivate (o)
}
#pragma omp threadprivate (o) // expected-error {{reference to 'o' is ambiguous}}
#pragma omp threadprivate (::o)
int main(int argc, char **argv) { // expected-note {{'argc' defined here}}
int x, y = argc; // expected-note 2 {{'y' defined here}}
static double d1;
static double d2;
static double d3; // expected-note {{'d3' defined here}}
static TestClass LocalClass(y); // expected-error {{variable with local storage in initial value of threadprivate variable}}
#pragma omp threadprivate(LocalClass)
d.a = a;
d2++;
;
#pragma omp threadprivate(argc+y) // expected-error {{expected identifier}}
#pragma omp threadprivate(argc,y) // expected-error 2 {{arguments of '#pragma omp threadprivate' must have static storage duration}}
#pragma omp threadprivate(d2) // expected-error {{'#pragma omp threadprivate' must precede all references to variable 'd2'}}
#pragma omp threadprivate(d1)
{
++a;d2=0;
#pragma omp threadprivate(d3) // expected-error {{'#pragma omp threadprivate' must appear in the scope of the 'd3' variable declaration}}
}
#pragma omp threadprivate(d3)
#pragma omp threadprivate(a) // expected-error {{'#pragma omp threadprivate' must appear in the scope of the 'a' variable declaration}}
return (y);
#pragma omp threadprivate(d) // expected-error {{'#pragma omp threadprivate' must appear in the scope of the 'd' variable declaration}}
}
|
#pragma once
#include "workspace/command.hpp"
#include "workspace/configuration.hpp"
#include "workspace/folders.hpp"
#include "workspace/fswatch.hpp"
#include "workspace/operations.hpp"
#include "workspace/symbols.hpp"
|
#include "../../../include/odfaeg/Driver/pipeline.hpp"
namespace odfaeg {
namespace driver {
Pipeline::Pipeline() t(run) {
pipelineStages[0] = std::make_unique<TransformVertices>();
pipelineStages[1] = std::make_unique<DriverGeometry>();
pipelineStages[2] = std::make_unique<Rasterizer>;
pipelineStages[3] = std::make_unique<Blending>;
finished.store(false);
}
void Pipeline::setVertexArrayPointer(void* pointer) {
vertexArrayPointer = pointer;
}
void Pipeline::setColorArrayPointer(void* pointer) {
colorArrayPointer = pointer;
}
void Pipeline::setTexcoordsArrayPointer(void* pointer) {
texCoordsArrayPointer = pointer;
}
void Pipeline::setDataSize(unsigned int dataSize) {
this->dataSize = dataSize;
}
void Pipeline::drawVertexArray(float* transfomMatrix, float* viewMatrix, float* projMatrix, float* textureMatrix, float* viewportMatrix, unsigned int first, unsigned int mode, unsigned int vertexCount) {
VertexArray va;
for (unsigned int i = first; i < vertexCount; i++) {
Vector3f position (vertexArrayPointer[i * dataSize], vertexArrayPointer[i*dataSize + 1], vertexArrayPointer[i*dataSize + 2]);
Color color (colorArrayPointer[i*dataSize], colorArrayPointer[i*dataSize+1], colorArrayPointer[i*dataSize+2], colorArrayPointer[i*dataSize+3]);
Vector2f texCoords(texCoordsArrayPointer[i*dataSize], texCoordsArrayPointer[i*dataSize+1]);
va.append(Vertex(position, color, texCoords));
}
pipelineStages[0]->setTransformMatrix(transformMatrix);
pipelineStages[0]->setViewMatrix(viewMatrix);
pipelineStages[0]->setProjMatrix(projMatrix);
pipelineStages[0]->setTextureMatrix(textureMatrix);
pipelineStages[0]->setViewportMatrix(viewportMatrix);
vertexBlocks.push_back(va);
}
void Pipeline::run() {
running.store(true);
while (running) {
if (finished.load()) {
pipelineStages[0]->load(vertexBlocks.back());
finished.store(false)
}
for (unsigned int i = 1; i < 4; i++) {
if (pipelineStages[i-1]->done()) {
pipelineStages[i]->load(pipelineStages[i-1]->getResults());
}
}
if (pipelineStages[4]->done()) {
finished.store(true);
}
}
}
}
}
|
// jms_x.cpp : common millisecond time functions
//
// Written by Jonathan H. Connell, jconnell@alum.mit.edu
//
///////////////////////////////////////////////////////////////////////////
//
// Copyright 2017-2019 IBM Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////
// Build.Settings.Link.General must have library winmm.lib
#pragma comment(lib, "winmm.lib")
#include <windows.h>
#include <stdio.h>
#include "Interface/jms_x.h"
//= Persistent synchronization object for more precise sleep.
static HANDLE wait = CreateWaitableTimer(NULL, TRUE, NULL);
///////////////////////////////////////////////////////////////////////////
// Elapsed Time //
///////////////////////////////////////////////////////////////////////////
//= Sleep for a certain number of milliseconds (BLOCKS).
void jms_sleep (int ms)
{
if (ms > 0)
Sleep(ms);
/*
LARGE_INTEGER due;
// figure out time to sleep in 100ns ticks
if (ms <= 0)
return;
due.QuadPart = -10LL * ms;
// wait at least the amount requested
timeBeginPeriod(1);
if (SetWaitableTimer(wait, &due, 0, NULL, NULL, 0))
WaitForSingleObject(wait, INFINITE);
timeEndPeriod(1);
*/
}
//= Tell number of milliseconds elapsed since power-on.
// never returns special value of 0 (usually means uninitialized)
// Note: wraps around roughly every 50 days
UL32 jms_now ()
{
UL32 now = timeGetTime();
return __max(1, now);
}
//= Returns elapsed milliseconds from "before" to "now".
// handles 50 day wraparound, so max of 24.8 days (0x7FFFFFF = 2,147,483.647 secs)
// NOTE: "now" must actually represent a later time than "before"
int jms_diff (UL32 now, UL32 before)
{
if (now >= before)
return((int)(now - before));
return((int)(~(before - now) + 1));
}
//= Block until "delay" milliseconds after "tref" time.
// returns time when function is exited
UL32 jms_wait (UL32 tref, int delay)
{
UL32 now;
int passed = 0, dslop = delay - 1; // tends to oversleep
// see if time already expired
if (tref != 0)
{
now = jms_now();
passed = jms_diff(now, tref);
if (passed >= dslop)
return now;
}
// wait remainder of time
jms_sleep(dslop - passed);
return jms_now();
}
//= Sleep until a specific time has come.
// good for long term pacing by constantly incrementing "cont"
// always returns 0 for convenience
int jms_resume (UL32 cont)
{
if (cont != 0)
jms_sleep(jms_diff(cont, jms_now()) - 1);
return 0;
}
//= Gives string with elapsed time in hrs:min:sec.ms from base time.
char *jms_elapsed (char *dest, UL32 tref, int ssz)
{
int h, m, s, ms = jms_diff(jms_now(), tref);
h = ms / 3600000;
ms -= h * 3600000;
m = ms / 60000;
ms -= m * 60000;
s = ms / 1000;
ms -= s * 1000;
sprintf_s(dest, ssz, "%d:%02d:%02d.%03d", h, m, s, ms);
return dest;
}
///////////////////////////////////////////////////////////////////////////
// Absolute Time //
///////////////////////////////////////////////////////////////////////////
//= Generate a date string with optional time (down to seconds).
// res: -1 gives 110717 just date
// 0 gives 110717_1027 with minutes (24 hr format)
// 1 gives 110717_102736 with minutes and seconds
// useful for labelling log files
char *jms_date (char *dest, int res, int ssz)
{
SYSTEMTIME t;
GetLocalTime(&t);
if (res < 0)
sprintf_s(dest, ssz, "%02d%02d%02d",
t.wMonth, t.wDay, t.wYear % 100);
else if (res == 0)
sprintf_s(dest, ssz, "%02d%02d%02d_%02d%02d",
t.wMonth, t.wDay, t.wYear % 100, t.wHour, t.wMinute);
else
sprintf_s(dest, ssz, "%02d%02d%02d_%02d%02d%02d",
t.wMonth, t.wDay, t.wYear % 100, t.wHour, t.wMinute, t.wSecond);
return dest;
}
//= Generate a time string (with optional milliseconds).
// res: 0 gives 10:27:36 time with seconds
// 1 gives 10:27:36.145 time with milliseconds
// useful for tagging events
char *jms_time (char *dest, int res, int ssz)
{
SYSTEMTIME t;
GetLocalTime(&t);
if (res <= 0)
sprintf_s(dest, ssz, "%02d:%02d:%02d",
t.wHour, t.wMinute, t.wSecond);
else
sprintf_s(dest, ssz, "%02d:%02d:%02d.%03d",
t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
return dest;
}
//= Tells whether current local date is outside specified window.
// years must be 4 digit, ignores start month and year if zero
bool jms_expired (int mon, int yr, int smon, int syr)
{
SYSTEMTIME t;
int cmon, cyr;
GetLocalTime(&t);
cmon = t.wMonth;
cyr = t.wYear;
return( (cyr > yr) ||
((cyr == yr) && (cmon > mon)) ||
((syr > 0) && (cyr < syr)) ||
((syr > 0) && (cyr == syr) && (smon > 0) && (cmon < smon)));
}
|
#include <iostream>
#include "udp.h"
using namespace std;
int main(int argc,char*args[])
{
if(argc>1)
socket_send(args[1]);
else
socket_recv();
return 0;
}
|
// merge-sort.hpp
//
// Phi Luu
//
// Data Structures and Algorithms: Merge Sort
//
// This implementation serves as one of many ways to refine skills in
// data structures and algorithms.
//
// Sorts an array by dividing it into two halves and sorting each half, then
// merging two halves back into a sorted array (merge sort).
#ifndef INCLUDE_MERGESORT_HPP_
#define INCLUDE_MERGESORT_HPP_
#include <cstddef>
#include <utility>
#include <vector>
namespace dsa {
// Internal helpers
namespace {
template <class Comparable>
void Merge(Comparable* array, size_t begin, size_t middle, size_t end) {
Comparable merged[end - begin]; // temporary array holding merged halves
size_t i = begin, j = middle, k = 0;
// put the smallest of the current elements of two halves first
while (i < middle && j < end) {
if (array[i] < array[j])
merged[k++] = array[i++];
else
merged[k++] = array[j++];
}
// if there are any remaining elements, put them all in the merged array
while (i < middle) merged[k++] = array[i++];
while (j < end) merged[k++] = array[j++];
// move all merged elements to the real array
for (size_t t = 0; t < k; t++) array[t + begin] = std::move(merged[t]);
}
template <class Comparable>
void MergeSort(Comparable* array, size_t begin, size_t end) {
// array is already sorted if it has 1 element or 0 elements
if (end - begin < 2) return;
// sort left and right halves, then merge them back
size_t middle = (begin + end) / 2;
MergeSort(array, begin, middle);
MergeSort(array, middle, end);
Merge(array, begin, middle, end);
}
template <class Comparable>
void Merge(std::vector<Comparable>& array, size_t begin, size_t middle,
size_t end) {
// temporary array holding merged halves
std::vector<Comparable> merged(end - begin);
size_t i = begin, j = middle, k = 0;
// put the smallest of the current elements of two halves first
while (i < middle && j < end) {
if (array[i] < array[j])
merged[k++] = array[i++];
else
merged[k++] = array[j++];
}
// if there are any remaining elements, put them all in the merged array
while (i < middle) merged[k++] = array[i++];
while (j < end) merged[k++] = array[j++];
// move all merged elements to the real array
for (size_t t = 0; t < k; t++) array[t + begin] = std::move(merged[t]);
}
template <class Comparable>
void MergeSort(std::vector<Comparable>& array, size_t begin, size_t end) {
// array is already sorted if it has 1 element or 0 elements
if (end - begin < 2) return;
// sort left and right halves, then merge them back
size_t middle = (begin + end) / 2;
MergeSort(array, begin, middle);
MergeSort(array, middle, end);
Merge(array, begin, middle, end);
}
} // namespace
// Interface
template <class Comparable>
void MergeSort(Comparable* array, size_t size) {
MergeSort(array, 0, size);
}
template <class Comparable>
void MergeSort(std::vector<Comparable>& array) {
MergeSort(array, 0, array.size());
}
} // namespace dsa
#endif // #ifndef INCLUDE_MERGESORT_HPP_
|
// Copyright © 2017 ChaiShushan <chaishushan{AT}gmail.com>.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
#include <iostream>
void SayHello() {
std::cout << "Hello, World!" << std::endl;
}
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
#ifndef __PROCESS_FIREWALL_HPP__
#define __PROCESS_FIREWALL_HPP__
#include <string>
#include <process/http.hpp>
#include <process/socket.hpp>
#include <stout/error.hpp>
#include <stout/hashset.hpp>
#include <stout/option.hpp>
namespace process {
namespace firewall {
/**
* A 'FirewallRule' describes an interface which provides control
* over incoming HTTP requests while also taking the underlying
* connection into account.
*
* Concrete classes based on this interface must implement the
* 'apply' method.
*
* Rules can be installed using the free function
* 'process::firewall::install()' defined in 'process.hpp'.
*/
class FirewallRule
{
public:
FirewallRule() {}
virtual ~FirewallRule() {}
/**
* Verify rule by applying it to an HTTP request and its underlying
* socket connection.
*
* @param socket Socket used to deliver the HTTP request.
* @param request HTTP request made by the client to libprocess.
* @return If the rule verification fails, i.e. the rule didn't
* match, the returned error is set with an explanation for the
* failure. Otherwise None is returned.
*/
virtual Option<Error> apply(
const network::Socket& socket,
const http::Request& request) = 0;
};
/**
* Simple firewall rule to forbid any HTTP request to a path
* in the provided list of endpoints.
*
* Matches are required to be exact, no substrings nor wildcards are
* considered for a match.
*/
class DisabledEndpointsFirewallRule : public FirewallRule
{
public:
explicit DisabledEndpointsFirewallRule(const hashset<std::string>& _paths)
: paths(_paths) {}
virtual ~DisabledEndpointsFirewallRule() {}
virtual Option<Error> apply(
const network::Socket&,
const http::Request& request)
{
if (paths.contains(request.path)) {
return Error("'" + request.path + "' is disabled");
}
return None();
}
private:
hashset<std::string> paths;
};
} // namespace firewall {
} // namespace process {
#endif // __PROCESS_FIREWALL_HPP__
|
////////////////////////////////////////////////////////////////////////////
// Name: rfc2231.cpp
// Purpose: This class implements the rfc2047 norm
// Author: Brice André
// Created: 2010/12/12
// RCS-ID: $Id: mycomp.cpp 505 2007-03-31 10:31:46Z frm $
// Copyright: (c) 2010 Brice André
// Licence: wxWidgets licence
/////////////////////////////////////////////////////////////////////////////
// Note __VISUALC__ is defined by wxWidgets, not by MSVC IDE
// and thus won't be defined until some wxWidgets headers are included
#if defined( _MSC_VER )
# if defined ( _DEBUG )
// this statement NEEDS to go BEFORE all headers
# define _CRTDBG_MAP_ALLOC
# endif
#endif
#include "wxMsPreProcDefsh.h" // needs to be first
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
// includes
#ifndef WX_PRECOMP
// here goes the #include <wx/abc.h> directives for those
// files which are not included by wxprec.h
#include "wx/wx.h"
#endif
#include "wx/regex.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "rfc2047.h"
#include "charsetconv.h"
// ------------------------------------------------------------------
// Note __VISUALC__ is defined by wxWidgets, not by MSVC IDE
// and thus won't be defined until some wxWidgets headers are included
#if defined( _MSC_VER )
// this block needs to go AFTER all headers
#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif
#endif
// ------------------------------------------------------------------
wxString wxRfc2047::Decode(const wxString& encoded_str)
{
/* Initialise decoded string */
wxString decoded_str = encoded_str;
/* Remove all white spaces between encoded parts, if any */
{
wxRegEx pattern(
_T("(=\\077[[:alnum:].\\055_]+\\077[qQbB]\\077[^\\077]*\\077=)[[:blank:]]+\
(=\\077[[:alnum:].\\055_]+\\077[qQbB]\\077[^\\077]*\\077=)"), wxRE_ADVANCED);
pattern.ReplaceAll(&decoded_str, _T("\\1\\2"));
}
/* Perform Q decoding */
{
/* Check if we have pattern */
wxRegEx pattern(
_T("=\\077([[:alnum:].\\055_]+)\\077[qQ]\\077([^\\077]*)\\077="),
wxRE_ADVANCED);
while ((pattern.Matches(decoded_str)) &&
(pattern.GetMatchCount() == 3))
{
/* Extract the encoded string */
wxString str_content = pattern.GetMatch(decoded_str, 2);
/* Replace all spaces */
str_content.Replace(_T("_"), _T(" "));
/* Handle all =xx paterns */
int index;
while (((index = str_content.Find(_T("="))) != wxNOT_FOUND) &&
(index < int(str_content.length()-2)))
{
unsigned long val_long;
str_content.Mid(index+1, 2).ToULong(&val_long, 16);
char val[2];
*((unsigned char*)val) = (unsigned char)val_long;
val[1] = 0;
str_content = str_content.Mid(0,index) << wxString(val, wxConvLocal) <<
str_content.Mid(index+3);
}
/* Convert to local charset, if necessary */
str_content = wxCharsetConverter::ConvertCharset(str_content,
pattern.GetMatch(decoded_str, 1));
/* Recode string before replacement */
str_content.Replace(_T("\\"), _T("\\\\"));
str_content.Replace(_T("&"), _T("\\&"));
/* Replace in result */
pattern.ReplaceFirst(&decoded_str, str_content);
}
}
/* Perform B decoding */
{
/* Check if we have pattern */
wxRegEx pattern(_T("=\\077([[:alnum:].\\055_]+)\\077[bB]\\077([^\\077]*)\\077="),
wxRE_ADVANCED);
// it seems we can have multiple 'B' strings - need to decode & concatenate them all
while ((pattern.Matches(decoded_str)) &&
(pattern.GetMatchCount() == 3))
{
/* Extract the encoded string */
wxString str_content = pattern.GetMatch(decoded_str, 2);
/* Perform a base64 decoding of the string */
std::vector<unsigned char> buffer;
std::string std_string = (const char*)str_content.mb_str(wxConvLocal);
mimetic::Base64::Decoder b64;
mimetic::decode(std_string.begin(),
std_string.end(),
b64,
std::back_inserter(buffer));
/* Flush content in a string */
str_content = _T("");
#if !defined( _MSC_VER )
unsigned int uiSize = buffer.size() - 1; // move calc'n outside of loop
char *pBuffer = (char *)calloc( uiSize + 5, sizeof( char) );
for (unsigned char* p = &buffer[0], i = 0; p <= &buffer[uiSize]; p++, i++)
{
pBuffer[i] = *p;
}
// str_content = wxString::FromUTF8( pBuf ); // does not work
wxString wsT1( pBuffer, wxConvUTF8 );
free( pBuffer );
str_content = wsT1;
/* Convert to local charset, if necessary */
wxString wsConvert = pattern.GetMatch(decoded_str, 1);
str_content = wxCharsetConverter::ConvertCharset(str_content,
pattern.GetMatch(decoded_str, 1));
#else
for (unsigned char* p = &buffer[0]; p <= &buffer[buffer.size()-1]; p++)
{
// complains because of hi bit set in some UTF-8 chars
// stops the rest from working - works OK on Windows/MSVC 2015
str_content.Append(*p, 1);
}
wxString wsConvert = pattern.GetMatch(decoded_str, 1);
/* Convert to local charset, if necessary */
str_content = wxCharsetConverter::ConvertCharset(str_content,
pattern.GetMatch(decoded_str, 1));
#endif
/* Recode string before replacement */
str_content.Replace(_T("\\"), _T("\\\\"));
str_content.Replace(_T("&"), _T("\\&"));
/* Replace in result */
pattern.ReplaceFirst(&decoded_str, str_content);
}
}
/* Return the decoded string */
return decoded_str;
}
// ------------------------------- eof ------------------------------
|
/*
Copyright 2005-2014 Intel Corporation. All Rights Reserved.
This file is part of Threading Building Blocks. Threading Building Blocks is free software;
you can redistribute it and/or modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation. Threading Building Blocks 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 Threading Building Blocks; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software library without
restriction. Specifically, if other files instantiate templates or use macros or inline
functions from this file, or you compile this file and link it with other files to produce
an executable, this file does not by itself cause the resulting executable to be covered
by the GNU General Public License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU General Public License.
*/
#include "harness_graph.h"
#include "harness_barrier.h"
#include "tbb/task_scheduler_init.h"
const int T = 4;
const int W = 4;
struct decrement_wait : NoAssign {
tbb::flow::graph * const my_graph;
bool * const my_done_flag;
decrement_wait( tbb::flow::graph &h, bool *done_flag ) : my_graph(&h), my_done_flag(done_flag) {}
void operator()(int i) const {
Harness::Sleep(10*i);
my_done_flag[i] = true;
my_graph->decrement_wait_count();
}
};
static void test_wait_count() {
tbb::flow::graph h;
for (int i = 0; i < T; ++i ) {
bool done_flag[W];
for (int j = 0; j < W; ++j ) {
for ( int w = 0; w < W; ++w ) done_flag[w] = false;
for ( int w = 0; w < j; ++w ) h.increment_wait_count();
NativeParallelFor( j, decrement_wait(h, done_flag) );
h.wait_for_all();
for ( int w = 0; w < W; ++w ) {
if ( w < j ) ASSERT( done_flag[w] == true, NULL );
else ASSERT( done_flag[w] == false, NULL );
}
}
}
}
const int F = 100;
#if __TBB_LAMBDAS_PRESENT
bool lambda_flag[F];
#endif
bool functor_flag[F];
struct set_functor {
int my_i;
set_functor( int i ) : my_i(i) {}
void operator()() { functor_flag[my_i] = true; }
};
struct return_functor {
int my_i;
return_functor( int i ) : my_i(i) {}
int operator()() { return my_i; }
};
static void test_run() {
tbb::flow::graph h;
for (int i = 0; i < T; ++i ) {
// Create receivers and flag arrays
#if __TBB_LAMBDAS_PRESENT
harness_mapped_receiver<int> lambda_r;
lambda_r.initialize_map( F, 1 );
#endif
harness_mapped_receiver<int> functor_r;
functor_r.initialize_map( F, 1 );
// Initialize flag arrays
for (int j = 0; j < F; ++j ) {
#if __TBB_LAMBDAS_PRESENT
lambda_flag[j] = false;
#endif
functor_flag[j] = false;
}
for ( int j = 0; j < F; ++j ) {
#if __TBB_LAMBDAS_PRESENT
h.run( [=]() { lambda_flag[j] = true; } );
h.run( lambda_r, [=]() { return j; } );
#endif
h.run( set_functor(j) );
h.run( functor_r, return_functor(j) );
}
h.wait_for_all();
for ( int j = 0; j < F; ++j ) {
#if __TBB_LAMBDAS_PRESENT
ASSERT( lambda_flag[i] == true, NULL );
#endif
ASSERT( functor_flag[i] == true, NULL );
}
#if __TBB_LAMBDAS_PRESENT
lambda_r.validate();
#endif
functor_r.validate();
}
}
// Encapsulate object we want to store in vector (because contained type must have
// copy constructor and assignment operator
class my_int_buffer {
tbb::flow::buffer_node<int> *b;
tbb::flow::graph& my_graph;
public:
my_int_buffer(tbb::flow::graph &g) : my_graph(g) { b = new tbb::flow::buffer_node<int>(my_graph); }
my_int_buffer(const my_int_buffer& other) : my_graph(other.my_graph) {
b = new tbb::flow::buffer_node<int>(my_graph);
}
~my_int_buffer() { delete b; }
my_int_buffer& operator=(const my_int_buffer& /*other*/) {
return *this;
}
};
// test the graph iterator, delete nodes from graph, test again
void test_iterator() {
tbb::flow::graph g;
my_int_buffer a_buffer(g);
my_int_buffer b_buffer(g);
my_int_buffer c_buffer(g);
my_int_buffer *d_buffer = new my_int_buffer(g);
my_int_buffer e_buffer(g);
std::vector< my_int_buffer > my_buffer_vector(10, c_buffer);
int count = 0;
for (tbb::flow::graph::iterator it = g.begin(); it != g.end(); ++it) {
count++;
}
ASSERT(count==15, "error in iterator count");
delete d_buffer;
count = 0;
for (tbb::flow::graph::iterator it = g.begin(); it != g.end(); ++it) {
count++;
}
ASSERT(count==14, "error in iterator count");
my_buffer_vector.clear();
count = 0;
for (tbb::flow::graph::iterator it = g.begin(); it != g.end(); ++it) {
count++;
}
ASSERT(count==4, "error in iterator count");
}
class AddRemoveBody : NoAssign {
tbb::flow::graph& g;
int nThreads;
Harness::SpinBarrier &barrier;
public:
AddRemoveBody(int nthr, Harness::SpinBarrier &barrier_, tbb::flow::graph& _g) :
g(_g), nThreads(nthr), barrier(barrier_)
{}
void operator()(const int /*threadID*/) const {
my_int_buffer b(g);
{
std::vector<my_int_buffer> my_buffer_vector(100, b);
barrier.wait(); // wait until all nodes are created
// now test that the proper number of nodes were created
int count = 0;
for (tbb::flow::graph::iterator it = g.begin(); it != g.end(); ++it) {
count++;
}
ASSERT(count==101*nThreads, "error in iterator count");
barrier.wait(); // wait until all threads are done counting
} // all nodes but for the initial node on this thread are deleted
barrier.wait(); // wait until all threads have deleted all nodes in their vectors
// now test that all the nodes were deleted except for the initial node
int count = 0;
for (tbb::flow::graph::iterator it = g.begin(); it != g.end(); ++it) {
count++;
}
ASSERT(count==nThreads, "error in iterator count");
barrier.wait(); // wait until all threads are done counting
} // initial node gets deleted
};
void test_parallel(int nThreads) {
tbb::flow::graph g;
Harness::SpinBarrier barrier(nThreads);
AddRemoveBody body(nThreads, barrier, g);
NativeParallelFor(nThreads, body);
}
int TestMain() {
if( MinThread<1 ) {
REPORT("number of threads must be positive\n");
exit(1);
}
for( int p=MinThread; p<=MaxThread; ++p ) {
tbb::task_scheduler_init init(p);
test_wait_count();
test_run();
test_iterator();
test_parallel(p);
}
return Harness::Done;
}
|
#pragma once
#include "Core/Core.hpp"
#include "Core/Image.hpp"
#include "Core/Task.hpp"
class Heightmap
{
public:
Heightmap() = default;
Heightmap(const Heightmap& other) = delete;
Heightmap(Heightmap&& other) noexcept;
~Heightmap();
int16* data = nullptr; // elevation in meters.
int32 width = 0;
int32 height = 0;
int16 minElevationInM = 0;
int16 maxElevationInM = 0;
float minElevationInKm = 0.f;
float maxElevationInKm = 0.f;
bool tryLoad(const wchar_t* mapName);
int64 getDataSize() const { return width * height * 2; }
private:
void reset();
};
// Holds data with lifetime of a map
struct Map
{
wchar_t name[64];
wchar_t directoryPath[128];
int64 widthInM = 1565430; // TODO: read these values from map.ini. Maybe using libconfini?
int64 heightInM = 1878516;
float widthInKm = 1565.430f;
float heightInKm = 1878.516f;
Heightmap heightmap;
float cameraZoomMin;
float cameraZoomMax;
float cameraNearPlane;
float cameraFarPlane;
bool tryLoad(const wchar_t* mapDirectoryPath, float verticalFieldOfViewRadians, float aspectRatio);
};
|
#include "cbase.h"
#include "asw_marine_resource.h"
#include "asw_marine_profile.h"
#include "asw_player.h"
#include "asw_marine.h"
#include "asw_hack.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
IMPLEMENT_SERVERCLASS_ST(CASW_Hack, DT_ASW_Hack)
SendPropEHandle (SENDINFO(m_hHackerMarineResource) ),
SendPropEHandle (SENDINFO(m_hHackTarget) ),
SendPropInt (SENDINFO(m_iShowOption)),
END_SEND_TABLE()
//---------------------------------------------------------
// Save/Restore
//---------------------------------------------------------
BEGIN_DATADESC( CASW_Hack )
DEFINE_FIELD( m_hHackerMarineResource, FIELD_EHANDLE ),
DEFINE_FIELD( m_hHackTarget, FIELD_EHANDLE ),
DEFINE_FIELD( m_hHackingPlayer, FIELD_EHANDLE ),
DEFINE_FIELD( m_hHackingMarine, FIELD_EHANDLE ),
END_DATADESC()
CASW_Hack::CASW_Hack()
{
}
bool CASW_Hack::InitHack(CASW_Player* pHackingPlayer, CASW_Marine* pHackingMarine, CBaseEntity* pHackTarget)
{
AddEFlags( EFL_FORCE_CHECK_TRANSMIT );
if (!pHackingPlayer || !pHackingMarine || !pHackTarget || !pHackingMarine->GetMarineResource())
{
return false;
}
m_hHackingPlayer = pHackingPlayer;
m_hHackingMarine = pHackingMarine;
m_hHackTarget = pHackTarget;
m_hHackerMarineResource = pHackingMarine->GetMarineResource();
pHackingMarine->m_hCurrentHack = this;
return true;
}
int CASW_Hack::UpdateTransmitState()
{
// ALWAYS transmit to all clients.
return SetTransmitState( FL_EDICT_ALWAYS );
}
CASW_Player* CASW_Hack::GetHackingPlayer()
{
return dynamic_cast<CASW_Player*>(m_hHackingPlayer.Get());
}
CASW_Marine* CASW_Hack::GetHackingMarine()
{
return dynamic_cast<CASW_Marine*>(m_hHackingMarine.Get());
}
void CASW_Hack::MarineStoppedUsing(CASW_Marine* pMarine)
{
if (pMarine->m_hCurrentHack.Get() == this)
{
pMarine->m_hCurrentHack = NULL;
}
// finish hacking
m_hHackingMarine = NULL;
m_hHackingPlayer = NULL;
m_hHackerMarineResource = NULL;
}
|
// Copyright (c) 2017 The Chromium Embedded Framework 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 "tests/ceftests/extensions/extension_test_handler.h"
#include "tests/ceftests/test_util.h"
#include "tests/shared/browser/extension_util.h"
#define STORAGE_TEST_GROUP_ALL(name, test_class) \
EXTENSION_TEST_GROUP_ALL(ChromeStorage##name, test_class)
#define STORAGE_TEST_GROUP_MINIMAL(name, test_class) \
EXTENSION_TEST_GROUP_MINIMAL(ChromeStorage##name, test_class)
namespace {
const char kExtensionPath[] = "storage-extension";
const char kSuccessMessage[] = "success";
// Base class for testing chrome.storage methods.
// See https://developer.chrome.com/extensions/storage
class StorageTestHandler : public ExtensionTestHandler {
public:
explicit StorageTestHandler(RequestContextType request_context_type)
: ExtensionTestHandler(request_context_type) {
// Only creating the extension browser.
set_create_main_browser(false);
}
// CefExtensionHandler methods:
void OnExtensionLoaded(CefRefPtr<CefExtension> extension) override {
EXPECT_TRUE(CefCurrentlyOn(TID_UI));
EXPECT_FALSE(got_loaded_);
got_loaded_.yes();
// Verify |extension| contents.
EXPECT_FALSE(extension->GetIdentifier().empty());
EXPECT_STREQ(("extensions/" + std::string(kExtensionPath)).c_str(),
client::extension_util::GetInternalExtensionResourcePath(
extension->GetPath())
.c_str());
TestDictionaryEqual(CreateManifest(), extension->GetManifest());
EXPECT_FALSE(extension_);
extension_ = extension;
CreateBrowserForExtension();
}
void OnExtensionUnloaded(CefRefPtr<CefExtension> extension) override {
EXPECT_TRUE(CefCurrentlyOn(TID_UI));
EXPECT_TRUE(extension_);
EXPECT_TRUE(extension_->IsSame(extension));
EXPECT_FALSE(got_unloaded_);
got_unloaded_.yes();
extension_ = nullptr;
// Execute asynchronously so call stacks have a chance to unwind.
// Will close the browser windows.
CefPostTask(TID_UI, base::Bind(&StorageTestHandler::DestroyTest, this));
}
// CefLoadHandler methods:
void OnLoadingStateChange(CefRefPtr<CefBrowser> browser,
bool isLoading,
bool canGoBack,
bool canGoForward) override {
CefRefPtr<CefExtension> extension = browser->GetHost()->GetExtension();
EXPECT_TRUE(extension);
EXPECT_TRUE(extension_->IsSame(extension));
if (isLoading) {
EXPECT_FALSE(extension_browser_);
extension_browser_ = browser;
} else {
EXPECT_TRUE(browser->IsSame(extension_browser_));
const std::string& url = browser->GetMainFrame()->GetURL();
EXPECT_STREQ(extension_url_.c_str(), url.c_str());
}
}
// CefResourceRequestHandler methods:
CefRefPtr<CefResourceHandler> GetResourceHandler(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request) override {
EXPECT_TRUE(browser->IsSame(extension_browser_));
CefRefPtr<CefExtension> extension = browser->GetHost()->GetExtension();
EXPECT_TRUE(extension);
EXPECT_TRUE(extension_->IsSame(extension));
const std::string& url = request->GetURL();
EXPECT_STREQ(extension_url_.c_str(), url.c_str());
EXPECT_FALSE(got_url_request_);
got_url_request_.yes();
// Handle the resource request.
return RoutingTestHandler::GetResourceHandler(browser, frame, request);
}
protected:
void OnLoadExtensions() override {
LoadExtension(kExtensionPath, CreateManifest());
}
bool OnMessage(CefRefPtr<CefBrowser> browser,
const std::string& message) override {
if (message == "extension_onload") {
// From body onLoad in the extension browser.
EXPECT_TRUE(browser->IsSame(extension_browser_));
EXPECT_FALSE(got_body_onload_);
got_body_onload_.yes();
TriggerStorageApiJSFunction();
return true;
}
EXPECT_TRUE(browser->IsSame(extension_browser_));
EXPECT_FALSE(got_success_message_);
got_success_message_.yes();
EXPECT_STREQ(kSuccessMessage, message.c_str());
TriggerDestroyTest();
return true;
}
void OnDestroyTest() override {
extension_browser_ = nullptr;
EXPECT_TRUE(got_loaded_);
EXPECT_TRUE(got_url_request_);
EXPECT_TRUE(got_body_onload_);
EXPECT_TRUE(got_trigger_api_function_);
EXPECT_TRUE(got_success_message_);
EXPECT_TRUE(got_unloaded_);
}
// Create a manifest that grants access to the storage API.
virtual CefRefPtr<CefDictionaryValue> CreateManifest() const {
ApiPermissionsList api_permissions;
api_permissions.push_back("storage");
return CreateDefaultManifest(api_permissions);
}
// Add resources in the extension browser.
virtual void OnAddExtensionResources(const std::string& origin) {
extension_url_ = origin + "extension.html";
AddResource(extension_url_, GetExtensionHTML(), "text/html");
}
// Returns the chrome.storage.* JS that is executed in the extension browser
// when the triggerStorageApi() JS function is called.
virtual std::string GetStorageApiJS() const = 0;
// Returns the JS that will be loaded in the extension browser. This
// implements the triggerStorageApi() JS function called from
// TriggerStorageApiJSFunction().
virtual std::string GetExtensionJS() const {
return "function triggerStorageApi() {" + GetStorageApiJS() + "}";
}
// Returns the HTML that will be loaded in the extension browser.
virtual std::string GetExtensionHTML() const {
return "<html><head><script>" + GetExtensionJS() +
"</script></head><body onLoad=" + GetMessageJS("extension_onload") +
">Extension</body></html>";
}
virtual void TriggerDestroyTest() {
// Execute asynchronously so call stacks have a chance to unwind.
CefPostTask(TID_UI, base::Bind(&StorageTestHandler::UnloadExtension, this,
extension_));
}
CefRefPtr<CefExtension> extension() const { return extension_; }
std::string extension_url() const { return extension_url_; }
CefRefPtr<CefBrowser> extension_browser() const { return extension_browser_; }
bool got_success_message() const { return got_success_message_; }
private:
void CreateBrowserForExtension() {
const std::string& identifier = extension_->GetIdentifier();
EXPECT_FALSE(identifier.empty());
const std::string& origin =
client::extension_util::GetExtensionOrigin(identifier);
EXPECT_FALSE(origin.empty());
// Add extension resources.
OnAddExtensionResources(origin);
// Create a browser to host the extension.
CreateBrowser(extension_url_, request_context());
}
void TriggerStorageApiJSFunction() {
EXPECT_FALSE(got_trigger_api_function_);
got_trigger_api_function_.yes();
extension_browser_->GetMainFrame()->ExecuteJavaScript(
"triggerStorageApi();", extension_url_, 0);
}
CefRefPtr<CefExtension> extension_;
std::string extension_url_;
CefRefPtr<CefBrowser> extension_browser_;
TrackCallback got_loaded_;
TrackCallback got_url_request_;
TrackCallback got_body_onload_;
TrackCallback got_trigger_api_function_;
TrackCallback got_success_message_;
TrackCallback got_unloaded_;
};
} // namespace
namespace {
// Test for chrome.storage.local.set(object items, function callback)
// and for chrome.storage.local.get(string or array of string or object keys,
// function callback)
class LocalStorageTestHandler : public StorageTestHandler {
public:
explicit LocalStorageTestHandler(RequestContextType request_context_type)
: StorageTestHandler(request_context_type) {}
protected:
std::string GetStorageApiJS() const override {
return "chrome.storage.local.set({\"local_key_1\": \"local_value_1\"}, "
"function() {"
"chrome.storage.local.get(\"local_key_1\", function (items) {"
"if(items[\"local_key_1\"] == \"local_value_1\") {" +
GetMessageJS(kSuccessMessage) +
"}});"
"});";
}
private:
IMPLEMENT_REFCOUNTING(LocalStorageTestHandler);
DISALLOW_COPY_AND_ASSIGN(LocalStorageTestHandler);
};
} // namespace
STORAGE_TEST_GROUP_ALL(LocalStorage, LocalStorageTestHandler)
namespace {
// Test for chrome.storage.local.getBytesInUse(string or array of string keys,
// function callback)
class LocalStorageGetBytesInUseTestHandler : public StorageTestHandler {
public:
explicit LocalStorageGetBytesInUseTestHandler(
RequestContextType request_context_type)
: StorageTestHandler(request_context_type) {}
protected:
std::string GetStorageApiJS() const override {
return "chrome.storage.local.set({\"local_key_2\": \"local_value_2\"}, "
"function() {"
"chrome.storage.local.getBytesInUse(\"local_key_2\", function "
"(bytesInUse) {"
"if (bytesInUse == 26) {" +
GetMessageJS(kSuccessMessage) +
"}});"
"});";
}
private:
IMPLEMENT_REFCOUNTING(LocalStorageGetBytesInUseTestHandler);
DISALLOW_COPY_AND_ASSIGN(LocalStorageGetBytesInUseTestHandler);
};
} // namespace
STORAGE_TEST_GROUP_MINIMAL(LocalStorageGetBytesInUse,
LocalStorageGetBytesInUseTestHandler)
namespace {
// Test for chrome.storage.local.remove(string or array of string keys, function
// callback)
class LocalStorageRemoveTestHandler : public StorageTestHandler {
public:
explicit LocalStorageRemoveTestHandler(
RequestContextType request_context_type)
: StorageTestHandler(request_context_type) {}
protected:
std::string GetStorageApiJS() const override {
return "chrome.storage.local.set({\"local_key_3\": \"local_value_3\"}, "
"function() {"
"chrome.storage.local.remove(\"local_key_3\", function () {"
"chrome.storage.local.get(\"local_key_3\", function(items) {"
"if (items[\"local_key_3\"] == undefined) {" +
GetMessageJS(kSuccessMessage) +
"}})})"
"});";
}
private:
IMPLEMENT_REFCOUNTING(LocalStorageRemoveTestHandler);
DISALLOW_COPY_AND_ASSIGN(LocalStorageRemoveTestHandler);
};
} // namespace
STORAGE_TEST_GROUP_MINIMAL(LocalStorageRemove, LocalStorageRemoveTestHandler)
namespace {
// Test for chrome.storage.local.clear(function callback)
class LocalStorageClearTestHandler : public StorageTestHandler {
public:
explicit LocalStorageClearTestHandler(RequestContextType request_context_type)
: StorageTestHandler(request_context_type) {}
protected:
std::string GetStorageApiJS() const override {
return "var value1Cleared = false;"
"var value2Cleared = false;"
"function checkCleared() {"
"if (value1Cleared && value2Cleared) {" +
GetMessageJS(kSuccessMessage) +
"}}"
"chrome.storage.local.set({\"local_key_4\": \"local_value_4\","
"\"local_key_5\": \"local_value_5\"}, function() {"
"chrome.storage.local.clear(function () {"
"chrome.storage.local.get(\"local_key_4\", function(items) {"
"if (items[\"local_key_4\"] == undefined) {"
"value1Cleared = true;"
"checkCleared();"
"}});"
"chrome.storage.local.get(\"local_key_5\", function(items) {"
"if (items[\"local_key_5\"] == undefined) {"
"value2Cleared = true;"
"checkCleared();"
"}});"
"})});";
}
private:
IMPLEMENT_REFCOUNTING(LocalStorageClearTestHandler);
DISALLOW_COPY_AND_ASSIGN(LocalStorageClearTestHandler);
};
} // namespace
STORAGE_TEST_GROUP_MINIMAL(LocalStorageClear, LocalStorageClearTestHandler)
namespace {
// Test for chrome.storage.sync.set(object items, function callback)
// and for chrome.storage.sync.get(string or array of string or object keys,
// function callback)
class SyncStorageTestHandler : public StorageTestHandler {
public:
explicit SyncStorageTestHandler(RequestContextType request_context_type)
: StorageTestHandler(request_context_type) {}
protected:
std::string GetStorageApiJS() const override {
return "chrome.storage.sync.set({\"sync_key_1\": \"sync_value_1\"}, "
"function() {"
"chrome.storage.sync.get(\"sync_key_1\", function (items) {"
"if (items[\"sync_key_1\"] == \"sync_value_1\") {" +
GetMessageJS(kSuccessMessage) +
"}});"
"});";
}
private:
IMPLEMENT_REFCOUNTING(SyncStorageTestHandler);
DISALLOW_COPY_AND_ASSIGN(SyncStorageTestHandler);
};
} // namespace
STORAGE_TEST_GROUP_ALL(SyncStorage, SyncStorageTestHandler)
namespace {
// Test for chrome.storage.sync.getBytesInUse(string or array of string keys,
// function callback)
class SyncStorageGetBytesInUseTestHandler : public StorageTestHandler {
public:
explicit SyncStorageGetBytesInUseTestHandler(
RequestContextType request_context_type)
: StorageTestHandler(request_context_type) {}
protected:
std::string GetStorageApiJS() const override {
return "chrome.storage.sync.set({\"sync_key_2\": \"sync_value_2\"}, "
"function() {"
"chrome.storage.sync.getBytesInUse(\"sync_key_2\", function "
"(bytesInUse) {"
"if (bytesInUse == 24) {" +
GetMessageJS(kSuccessMessage) +
"}});"
"});";
}
private:
IMPLEMENT_REFCOUNTING(SyncStorageGetBytesInUseTestHandler);
DISALLOW_COPY_AND_ASSIGN(SyncStorageGetBytesInUseTestHandler);
};
} // namespace
STORAGE_TEST_GROUP_MINIMAL(SyncStorageGetBytesInUse,
SyncStorageGetBytesInUseTestHandler)
namespace {
// Test for chrome.storage.sync.remove(string or array of string keys, function
// callback)
class SyncStorageRemoveTestHandler : public StorageTestHandler {
public:
explicit SyncStorageRemoveTestHandler(RequestContextType request_context_type)
: StorageTestHandler(request_context_type) {}
protected:
std::string GetStorageApiJS() const override {
return "chrome.storage.sync.set({\"sync_key_3\": \"sync_value_3\"}, "
"function() {"
"chrome.storage.sync.remove(\"sync_key_3\", function () {"
"chrome.storage.sync.get(\"sync_key_3\", function(items) {"
"if (items[\"sync_key_3\"] == undefined) {" +
GetMessageJS(kSuccessMessage) +
"}})})"
"});";
}
private:
IMPLEMENT_REFCOUNTING(SyncStorageRemoveTestHandler);
DISALLOW_COPY_AND_ASSIGN(SyncStorageRemoveTestHandler);
};
} // namespace
STORAGE_TEST_GROUP_MINIMAL(SyncStorageRemove, SyncStorageRemoveTestHandler)
namespace {
// Test for chrome.storage.sync.clear(function callback)
class SyncStorageClearTestHandler : public StorageTestHandler {
public:
explicit SyncStorageClearTestHandler(RequestContextType request_context_type)
: StorageTestHandler(request_context_type) {}
protected:
std::string GetStorageApiJS() const override {
return "var value1Cleared = false;"
"var value2Cleared = false;"
"function checkCleared() {"
"if (value1Cleared && value2Cleared) {" +
GetMessageJS(kSuccessMessage) +
"}}"
"chrome.storage.sync.set({\"sync_key_4\": \"sync_value_4\","
"\"sync_key_5\": \"sync_value_5\"}, function() {"
"chrome.storage.sync.clear(function () {"
"chrome.storage.sync.get(\"sync_key_4\", function(items) {"
"if (items[\"sync_key_4\"] == undefined) {"
"value1Cleared = true;"
"checkCleared();"
"}});"
"chrome.storage.sync.get(\"sync_key_5\", function(items) {"
"if (items[\"sync_key_5\"] == undefined) {"
"value2Cleared = true;"
"checkCleared();"
"}});"
"})});";
}
private:
IMPLEMENT_REFCOUNTING(SyncStorageClearTestHandler);
DISALLOW_COPY_AND_ASSIGN(SyncStorageClearTestHandler);
};
} // namespace
STORAGE_TEST_GROUP_MINIMAL(SyncStorageClear, SyncStorageClearTestHandler)
|
/* Copyright 2020 Google LLC
*
* 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
*
* https://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 "paragraph/translation/reducescatter/unidir_ring_reducescatter_translator.h"
#include <memory>
#include <string>
#include <utility>
#include "google/protobuf/text_format.h"
#include "google/protobuf/util/message_differencer.h"
#include "gtest/gtest.h"
#include "paragraph/shim/test_macros.h"
#include "paragraph/translation/translation_map.h"
// Tests expanding uni-directional ring reduce-scatter
TEST(UniDirRingReduceScatter, NoBarrier) {
auto graph = absl::make_unique<paragraph::Graph>("test_graph", 2);
auto sub = absl::make_unique<paragraph::Subroutine>(
"test_subroutine", graph.get());
auto sub_ptr = sub.get();
graph->SetEntrySubroutine(std::move(sub));
ASSERT_OK_AND_ASSIGN(auto instr_1, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "first_instruction", sub_ptr));
instr_1->SetOps(4);
ASSERT_OK_AND_ASSIGN(auto reducescatter,
paragraph::Instruction::Create(
paragraph::Opcode::kReduceScatter, "reduce-scatter", sub_ptr));
reducescatter->SetBytesOut(48);
paragraph::CommunicationGroup reducescatter_group = {0, 1, 2};
reducescatter->AppendCommunicationGroup(reducescatter_group);
auto reduction_sub = absl::make_unique<paragraph::Subroutine>(
"reduction_subroutine", graph.get());
auto reduction_ptr = reduction_sub.get();
ASSERT_OK_AND_ASSIGN(auto op1, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "op1", reduction_ptr));
op1->SetBytesOut(48);
ASSERT_OK_AND_ASSIGN(auto op2, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "op2", reduction_ptr));
op2->SetBytesOut(48);
ASSERT_OK_AND_ASSIGN(auto sum_op, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "sum", reduction_ptr, true));
sum_op->SetOps(96);
sum_op->AddOperand(op1);
sum_op->AddOperand(op2);
reducescatter->AppendInnerSubroutine(std::move(reduction_sub));
ASSERT_OK_AND_ASSIGN(auto instr_3, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "last_instruction", sub_ptr, true));
instr_3->SetOps(4);
nlohmann::json config = R"(
{
"reduce-scatter": {
"algorithm": "unidir-ring"
}
}
)"_json;
ASSERT_OK_AND_ASSIGN(auto translators, paragraph::CreateTranslators(
paragraph::TranslatorType::kCollective, config));
EXPECT_OK(translators["reduce-scatter"]->Translate(reducescatter));
paragraph::InstructionProto reducescatter_proto;
std::string reducescatter_str =
R"proto(
name: "reduce-scatter"
opcode: "reduce-scatter"
instruction_id: 2
bytes_out: 48
communication_groups {
group_ids: 0
group_ids: 1
group_ids: 2
}
inner_subroutines {
name: "reduce-scatter_unidir-ring"
subroutine_root_id: 13
execution_probability: 1
execution_count: 1
instructions {
name: "reduce-scatter_unidir-ring_sendrecv_1"
opcode: "sendrecv"
instruction_id: 7
bytes_in: 16
bytes_out: 16
communication_groups {
group_ids: 1
group_ids: 0
}
}
instructions {
name: "reduce-scatter_unidir-ring_reduction_1"
opcode: "call"
instruction_id: 8
operand_ids: 7
inner_subroutines {
name: "reduction_subroutine_phase_1"
subroutine_root_id: 11
execution_probability: 1
execution_count: 1
instructions {
name: "op1_phase_1"
opcode: "delay"
instruction_id: 9
bytes_out: 16
}
instructions {
name: "op2_phase_1"
opcode: "delay"
instruction_id: 10
bytes_out: 16
}
instructions {
name: "sum_phase_1"
opcode: "delay"
instruction_id: 11
ops: 32
operand_ids: 9
operand_ids: 10
}
}
}
instructions {
name: "reduce-scatter_unidir-ring_sendrecv_2"
opcode: "sendrecv"
instruction_id: 12
bytes_in: 16
bytes_out: 16
communication_groups {
group_ids: 1
group_ids: 0
}
operand_ids: 8
}
instructions {
name: "reduce-scatter_unidir-ring_reduction_2"
opcode: "call"
instruction_id: 13
operand_ids: 12
inner_subroutines {
name: "reduction_subroutine_phase_2"
subroutine_root_id: 16
execution_probability: 1
execution_count: 1
instructions {
name: "op1_phase_2"
opcode: "delay"
instruction_id: 14
bytes_out: 16
}
instructions {
name: "op2_phase_2"
opcode: "delay"
instruction_id: 15
bytes_out: 16
}
instructions {
name: "sum_phase_2"
opcode: "delay"
instruction_id: 16
ops: 32
operand_ids: 14
operand_ids: 15
}
}
}
}
)proto";
google::protobuf::TextFormat::ParseFromString(reducescatter_str,
&reducescatter_proto);
EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals(
reducescatter->ToProto().value(), reducescatter_proto));
}
// Tests expanding uni-directional ring reduce-scatter with barrier
TEST(UniDirRingReduceScatter, WithBarrier) {
auto graph = absl::make_unique<paragraph::Graph>("test_graph", 2);
auto sub = absl::make_unique<paragraph::Subroutine>(
"test_subroutine", graph.get());
auto sub_ptr = sub.get();
sub_ptr->SetId(3);
graph->SetEntrySubroutine(std::move(sub));
ASSERT_OK_AND_ASSIGN(auto instr_1, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "first_instruction", sub_ptr));
instr_1->SetOps(4);
ASSERT_OK_AND_ASSIGN(auto reducescatter,
paragraph::Instruction::Create(
paragraph::Opcode::kReduceScatter, "reduce-scatter", sub_ptr));
reducescatter->SetBytesOut(48);
paragraph::CommunicationGroup reducescatter_group = {0, 1, 2};
reducescatter->AppendCommunicationGroup(reducescatter_group);
auto reduction_sub = absl::make_unique<paragraph::Subroutine>(
"reduction_subroutine", graph.get());
auto reduction_ptr = reduction_sub.get();
ASSERT_OK_AND_ASSIGN(auto op1, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "op1", reduction_ptr));
op1->SetBytesOut(48);
ASSERT_OK_AND_ASSIGN(auto op2, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "op2", reduction_ptr));
op2->SetBytesOut(48);
ASSERT_OK_AND_ASSIGN(auto sum_op, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "sum", reduction_ptr, true));
sum_op->SetOps(96);
sum_op->AddOperand(op1);
sum_op->AddOperand(op2);
reducescatter->AppendInnerSubroutine(std::move(reduction_sub));
ASSERT_OK_AND_ASSIGN(auto instr_3, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "last_instruction", sub_ptr, true));
instr_3->SetOps(4);
nlohmann::json config = R"(
{
"reduce-scatter": {
"algorithm": "unidir-ring",
"barrier": {
"algorithm": "centralized"
}
}
}
)"_json;
ASSERT_OK_AND_ASSIGN(auto translators, paragraph::CreateTranslators(
paragraph::TranslatorType::kCollective, config));
EXPECT_OK(translators["reduce-scatter"]->Translate(reducescatter));
paragraph::InstructionProto reducescatter_proto;
std::string reducescatter_str =
R"proto(
name: "reduce-scatter"
opcode: "reduce-scatter"
instruction_id: 2
bytes_out: 48
communication_groups {
group_ids: 0
group_ids: 1
group_ids: 2
}
inner_subroutines {
name: "reduce-scatter_unidir-ring"
subroutine_root_id: 16
execution_probability: 1
execution_count: 1
instructions {
name: "reduce-scatter_unidir-ring_barrier"
opcode: "barrier"
instruction_id: 7
communication_groups {
group_ids: 0
group_ids: 1
group_ids: 2
}
inner_subroutines {
name: "reduce-scatter_unidir-ring_barrier_centralized"
subroutine_root_id: 9
execution_probability: 1
execution_count: 1
instructions {
name: "reduce-scatter_unidir-ring_barrier_centralized_send_to_0"
opcode: "send"
instruction_id: 8
communication_groups {
group_ids: 0
}
}
instructions {
name: "reduce-scatter_unidir-ring_barrier_centralized_recv_from_0"
opcode: "recv"
instruction_id: 9
communication_groups {
group_ids: 0
}
operand_ids: 8
}
}
}
instructions {
name: "reduce-scatter_unidir-ring_sendrecv_1"
opcode: "sendrecv"
instruction_id: 10
bytes_in: 16
bytes_out: 16
communication_groups {
group_ids: 1
group_ids: 0
}
operand_ids: 7
}
instructions {
name: "reduce-scatter_unidir-ring_reduction_1"
opcode: "call"
instruction_id: 11
operand_ids: 10
inner_subroutines {
name: "reduction_subroutine_phase_1"
subroutine_root_id: 14
execution_probability: 1
execution_count: 1
instructions {
name: "op1_phase_1"
opcode: "delay"
instruction_id: 12
bytes_out: 16
}
instructions {
name: "op2_phase_1"
opcode: "delay"
instruction_id: 13
bytes_out: 16
}
instructions {
name: "sum_phase_1"
opcode: "delay"
instruction_id: 14
ops: 32
operand_ids: 12
operand_ids: 13
}
}
}
instructions {
name: "reduce-scatter_unidir-ring_sendrecv_2"
opcode: "sendrecv"
instruction_id: 15
bytes_in: 16
bytes_out: 16
communication_groups {
group_ids: 1
group_ids: 0
}
operand_ids: 11
}
instructions {
name: "reduce-scatter_unidir-ring_reduction_2"
opcode: "call"
instruction_id: 16
operand_ids: 15
inner_subroutines {
name: "reduction_subroutine_phase_2"
subroutine_root_id: 19
execution_probability: 1
execution_count: 1
instructions {
name: "op1_phase_2"
opcode: "delay"
instruction_id: 17
bytes_out: 16
}
instructions {
name: "op2_phase_2"
opcode: "delay"
instruction_id: 18
bytes_out: 16
}
instructions {
name: "sum_phase_2"
opcode: "delay"
instruction_id: 19
ops: 32
operand_ids: 17
operand_ids: 18
}
}
}
}
)proto";
google::protobuf::TextFormat::ParseFromString(reducescatter_str,
&reducescatter_proto);
EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals(
reducescatter->ToProto().value(), reducescatter_proto));
}
// Tests expanding uni-directional ring reduce-scatter
TEST(UniDirRingReduceScatter, InconsecutiveProcessors) {
auto graph = absl::make_unique<paragraph::Graph>("test_graph", 2);
auto sub = absl::make_unique<paragraph::Subroutine>(
"test_subroutine", graph.get());
auto sub_ptr = sub.get();
graph->SetEntrySubroutine(std::move(sub));
ASSERT_OK_AND_ASSIGN(auto instr_1, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "first_instruction", sub_ptr));
instr_1->SetOps(4);
ASSERT_OK_AND_ASSIGN(auto reducescatter,
paragraph::Instruction::Create(
paragraph::Opcode::kReduceScatter, "reduce-scatter", sub_ptr));
reducescatter->SetBytesOut(48);
paragraph::CommunicationGroup reducescatter_group = {0, 2, 4};
reducescatter->AppendCommunicationGroup(reducescatter_group);
auto reduction_sub = absl::make_unique<paragraph::Subroutine>(
"reduction_subroutine", graph.get());
auto reduction_ptr = reduction_sub.get();
ASSERT_OK_AND_ASSIGN(auto op1, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "op1", reduction_ptr));
op1->SetBytesOut(48);
ASSERT_OK_AND_ASSIGN(auto op2, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "op2", reduction_ptr));
op2->SetBytesOut(48);
ASSERT_OK_AND_ASSIGN(auto sum_op, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "sum", reduction_ptr, true));
sum_op->SetOps(96);
sum_op->AddOperand(op1);
sum_op->AddOperand(op2);
reducescatter->AppendInnerSubroutine(std::move(reduction_sub));
ASSERT_OK_AND_ASSIGN(auto instr_3, paragraph::Instruction::Create(
paragraph::Opcode::kDelay, "last_instruction", sub_ptr, true));
instr_3->SetOps(4);
nlohmann::json config = R"(
{
"reduce-scatter": {
"algorithm": "unidir-ring"
}
}
)"_json;
ASSERT_OK_AND_ASSIGN(auto translators, paragraph::CreateTranslators(
paragraph::TranslatorType::kCollective, config));
EXPECT_OK(translators["reduce-scatter"]->Translate(reducescatter));
paragraph::InstructionProto reducescatter_proto;
std::string reducescatter_str =
R"proto(
name: "reduce-scatter"
opcode: "reduce-scatter"
instruction_id: 2
bytes_out: 48
communication_groups {
group_ids: 0
group_ids: 2
group_ids: 4
}
inner_subroutines {
name: "reduce-scatter_unidir-ring"
subroutine_root_id: 13
execution_probability: 1
execution_count: 1
instructions {
name: "reduce-scatter_unidir-ring_sendrecv_1"
opcode: "sendrecv"
instruction_id: 7
bytes_in: 16
bytes_out: 16
communication_groups {
group_ids: 0
group_ids: 4
}
}
instructions {
name: "reduce-scatter_unidir-ring_reduction_1"
opcode: "call"
instruction_id: 8
operand_ids: 7
inner_subroutines {
name: "reduction_subroutine_phase_1"
subroutine_root_id: 11
execution_probability: 1
execution_count: 1
instructions {
name: "op1_phase_1"
opcode: "delay"
instruction_id: 9
bytes_out: 16
}
instructions {
name: "op2_phase_1"
opcode: "delay"
instruction_id: 10
bytes_out: 16
}
instructions {
name: "sum_phase_1"
opcode: "delay"
instruction_id: 11
ops: 32
operand_ids: 9
operand_ids: 10
}
}
}
instructions {
name: "reduce-scatter_unidir-ring_sendrecv_2"
opcode: "sendrecv"
instruction_id: 12
bytes_in: 16
bytes_out: 16
communication_groups {
group_ids: 0
group_ids: 4
}
operand_ids: 8
}
instructions {
name: "reduce-scatter_unidir-ring_reduction_2"
opcode: "call"
instruction_id: 13
operand_ids: 12
inner_subroutines {
name: "reduction_subroutine_phase_2"
subroutine_root_id: 16
execution_probability: 1
execution_count: 1
instructions {
name: "op1_phase_2"
opcode: "delay"
instruction_id: 14
bytes_out: 16
}
instructions {
name: "op2_phase_2"
opcode: "delay"
instruction_id: 15
bytes_out: 16
}
instructions {
name: "sum_phase_2"
opcode: "delay"
instruction_id: 16
ops: 32
operand_ids: 14
operand_ids: 15
}
}
}
}
)proto";
google::protobuf::TextFormat::ParseFromString(reducescatter_str,
&reducescatter_proto);
EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals(
reducescatter->ToProto().value(), reducescatter_proto));
}
|
#include "program/program.hpp"
#include "program_visitor.hpp"
#include "symbol_visitor.hpp"
#include "ast/factory.hpp"
#include "parser.hpp"
#include "symbols.hpp"
#include "builtins.hpp"
namespace gorc {
class boc_shell_program : public program {
public:
std::string script_filename;
bool parse_only = false;
virtual void create_options(options &opts) override
{
opts.insert(make_value_option("script", script_filename));
opts.insert(make_switch_option("parse-only", parse_only));
opts.emplace_constraint<required_option>("script");
return;
}
virtual int run() override
{
register_builtins();
// Parse script file
ast_factory ast;
translation_unit *tu = parse_shell_script(script_filename, ast);
if(parse_only) {
return EXIT_SUCCESS;
}
ast_visit(symbol_visitor(true), tu);
program_visitor pg;
ast_visit(pg, tu);
return EXIT_SUCCESS;
}
};
}
MAKE_MAIN(gorc::boc_shell_program)
|
/*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "system_properties/contexts_split.h"
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <async_safe/log.h>
#include "system_properties/context_node.h"
#include "system_properties/system_properties.h"
class ContextListNode : public ContextNode {
public:
ContextListNode(ContextListNode* next, const char* context, const char* filename)
: ContextNode(strdup(context), filename), next(next) {
}
~ContextListNode() {
free(const_cast<char*>(context()));
}
ContextListNode* next;
};
struct PrefixNode {
PrefixNode(struct PrefixNode* next, const char* prefix, ContextListNode* context)
: prefix(strdup(prefix)), prefix_len(strlen(prefix)), context(context), next(next) {
}
~PrefixNode() {
free(prefix);
}
char* prefix;
const size_t prefix_len;
ContextListNode* context;
PrefixNode* next;
};
template <typename List, typename... Args>
static inline void ListAdd(List** list, Args... args) {
*list = new List(*list, args...);
}
static void ListAddAfterLen(PrefixNode** list, const char* prefix, ContextListNode* context) {
size_t prefix_len = strlen(prefix);
auto next_list = list;
while (*next_list) {
if ((*next_list)->prefix_len < prefix_len || (*next_list)->prefix[0] == '*') {
ListAdd(next_list, prefix, context);
return;
}
next_list = &(*next_list)->next;
}
ListAdd(next_list, prefix, context);
}
template <typename List, typename Func>
static void ListForEach(List* list, Func func) {
while (list) {
func(list);
list = list->next;
}
}
template <typename List, typename Func>
static List* ListFind(List* list, Func func) {
while (list) {
if (func(list)) {
return list;
}
list = list->next;
}
return nullptr;
}
template <typename List>
static void ListFree(List** list) {
while (*list) {
auto old_list = *list;
*list = old_list->next;
delete old_list;
}
}
// The below two functions are duplicated from label_support.c in libselinux.
// The read_spec_entries and read_spec_entry functions may be used to
// replace sscanf to read entries from spec files. The file and
// property services now use these.
// Read an entry from a spec file (e.g. file_contexts)
static inline int read_spec_entry(char** entry, char** ptr, int* len) {
*entry = nullptr;
char* tmp_buf = nullptr;
while (isspace(**ptr) && **ptr != '\0') (*ptr)++;
tmp_buf = *ptr;
*len = 0;
while (!isspace(**ptr) && **ptr != '\0') {
(*ptr)++;
(*len)++;
}
if (*len) {
*entry = strndup(tmp_buf, *len);
if (!*entry) return -1;
}
return 0;
}
// line_buf - Buffer containing the spec entries .
// num_args - The number of spec parameter entries to process.
// ... - A 'char **spec_entry' for each parameter.
// returns - The number of items processed.
//
// This function calls read_spec_entry() to do the actual string processing.
static int read_spec_entries(char* line_buf, int num_args, ...) {
char **spec_entry, *buf_p;
int len, rc, items, entry_len = 0;
va_list ap;
len = strlen(line_buf);
if (line_buf[len - 1] == '\n')
line_buf[len - 1] = '\0';
else
// Handle case if line not \n terminated by bumping
// the len for the check below (as the line is NUL
// terminated by getline(3))
len++;
buf_p = line_buf;
while (isspace(*buf_p)) buf_p++;
// Skip comment lines and empty lines.
if (*buf_p == '#' || *buf_p == '\0') return 0;
// Process the spec file entries
va_start(ap, num_args);
items = 0;
while (items < num_args) {
spec_entry = va_arg(ap, char**);
if (len - 1 == buf_p - line_buf) {
va_end(ap);
return items;
}
rc = read_spec_entry(spec_entry, &buf_p, &entry_len);
if (rc < 0) {
va_end(ap);
return rc;
}
if (entry_len) items++;
}
va_end(ap);
return items;
}
bool ContextsSplit::MapSerialPropertyArea(bool access_rw, bool* fsetxattr_failed) {
char filename[PROP_FILENAME_MAX];
int len = async_safe_format_buffer(filename, sizeof(filename), "%s/properties_serial", filename_);
if (len < 0 || len >= PROP_FILENAME_MAX) {
serial_prop_area_ = nullptr;
return false;
}
if (access_rw) {
serial_prop_area_ =
prop_area::map_prop_area_rw(filename, "u:object_r:properties_serial:s0", fsetxattr_failed);
} else {
serial_prop_area_ = prop_area::map_prop_area(filename);
}
return serial_prop_area_;
}
bool ContextsSplit::InitializePropertiesFromFile(const char* filename) {
FILE* file = fopen(filename, "re");
if (!file) {
return false;
}
char* buffer = nullptr;
size_t line_len;
char* prop_prefix = nullptr;
char* context = nullptr;
while (getline(&buffer, &line_len, file) > 0) {
int items = read_spec_entries(buffer, 2, &prop_prefix, &context);
if (items <= 0) {
continue;
}
if (items == 1) {
free(prop_prefix);
continue;
}
// init uses ctl.* properties as an IPC mechanism and does not write them
// to a property file, therefore we do not need to create property files
// to store them.
if (!strncmp(prop_prefix, "ctl.", 4)) {
free(prop_prefix);
free(context);
continue;
}
auto old_context = ListFind(
contexts_, [context](ContextListNode* l) { return !strcmp(l->context(), context); });
if (old_context) {
ListAddAfterLen(&prefixes_, prop_prefix, old_context);
} else {
ListAdd(&contexts_, context, filename_);
ListAddAfterLen(&prefixes_, prop_prefix, contexts_);
}
free(prop_prefix);
free(context);
}
free(buffer);
fclose(file);
return true;
}
bool ContextsSplit::InitializeProperties() {
// If we do find /property_contexts, then this is being
// run as part of the OTA updater on older release that had
// /property_contexts - b/34370523
if (InitializePropertiesFromFile("/property_contexts")) {
return true;
}
// Use property_contexts from /system & /vendor, fall back to those from /
if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
if (!InitializePropertiesFromFile("/system/etc/selinux/plat_property_contexts")) {
return false;
}
// Don't check for failure here, since we don't always have all of these partitions.
// E.g. In case of recovery, the vendor partition will not have mounted and we
// still need the system / platform properties to function.
if (access("/vendor/etc/selinux/vendor_property_contexts", R_OK) != -1) {
InitializePropertiesFromFile("/vendor/etc/selinux/vendor_property_contexts");
} else {
// Fallback to nonplat_* if vendor_* doesn't exist.
InitializePropertiesFromFile("/vendor/etc/selinux/nonplat_property_contexts");
}
} else {
if (!InitializePropertiesFromFile("/plat_property_contexts")) {
return false;
}
if (access("/vendor_property_contexts", R_OK) != -1) {
InitializePropertiesFromFile("/vendor_property_contexts");
} else {
// Fallback to nonplat_* if vendor_* doesn't exist.
InitializePropertiesFromFile("/nonplat_property_contexts");
}
}
return true;
}
bool ContextsSplit::Initialize(bool writable, const char* filename, bool* fsetxattr_failed) {
filename_ = filename;
if (!InitializeProperties()) {
return false;
}
if (writable) {
mkdir(filename_, S_IRWXU | S_IXGRP | S_IXOTH);
bool open_failed = false;
if (fsetxattr_failed) {
*fsetxattr_failed = false;
}
ListForEach(contexts_, [&fsetxattr_failed, &open_failed](ContextListNode* l) {
if (!l->Open(true, fsetxattr_failed)) {
open_failed = true;
}
});
if (open_failed || !MapSerialPropertyArea(true, fsetxattr_failed)) {
FreeAndUnmap();
return false;
}
} else {
if (!MapSerialPropertyArea(false, nullptr)) {
FreeAndUnmap();
return false;
}
}
return true;
}
PrefixNode* ContextsSplit::GetPrefixNodeForName(const char* name) {
auto entry = ListFind(prefixes_, [name](PrefixNode* l) {
return l->prefix[0] == '*' || !strncmp(l->prefix, name, l->prefix_len);
});
return entry;
}
prop_area* ContextsSplit::GetPropAreaForName(const char* name) {
auto entry = GetPrefixNodeForName(name);
if (!entry) {
return nullptr;
}
auto cnode = entry->context;
if (!cnode->pa()) {
// We explicitly do not check no_access_ in this case because unlike the
// case of foreach(), we want to generate an selinux audit for each
// non-permitted property access in this function.
cnode->Open(false, nullptr);
}
return cnode->pa();
}
void ContextsSplit::ForEach(void (*propfn)(const prop_info* pi, void* cookie), void* cookie) {
ListForEach(contexts_, [propfn, cookie](ContextListNode* l) {
if (l->CheckAccessAndOpen()) {
l->pa()->foreach (propfn, cookie);
}
});
}
void ContextsSplit::ResetAccess() {
ListForEach(contexts_, [](ContextListNode* l) { l->ResetAccess(); });
}
void ContextsSplit::FreeAndUnmap() {
ListFree(&prefixes_);
ListFree(&contexts_);
prop_area::unmap_prop_area(&serial_prop_area_);
}
|
// This block enables to compile the code with and without the likwid header in place
#ifdef LIKWID_PERFMON
#include <likwid-marker.h>
#else
#define LIKWID_MARKER_INIT
#define LIKWID_MARKER_THREADINIT
#define LIKWID_MARKER_SWITCH
#define LIKWID_MARKER_REGISTER(regionTag)
#define LIKWID_MARKER_START(regionTag)
#define LIKWID_MARKER_STOP(regionTag)
#define LIKWID_MARKER_CLOSE
#define LIKWID_MARKER_GET(regionTag, nevents, events, time, count)
#endif
#include <cstddef>
#include <cassert>
#include <iostream>
#include "vcl/vectorclass.h"
using VALUE_TYPE = double;
using VEC_TYPE = Vec4d;
constexpr std::size_t OBJ_COLS_TILING = 8192;
constexpr std::size_t OBJ_ROWS_TILING = 8;
constexpr std::size_t OBJ_LEVELS_TILING = 8;
constexpr std::size_t OBJ_COLS = 65536;
constexpr std::size_t OBJ_ROWS = 256;
constexpr std::size_t OBJ_LEVELS = 256;
constexpr VALUE_TYPE C = 1.0;
constexpr VALUE_TYPE H = 1.0;
constexpr VALUE_TYPE TAU = 1.0;
constexpr std::size_t RUNS = 1;
#include "c_linear_stencil_tiling.hpp"
template <template<typename ValueType, typename VecType> class OperatorType, typename ValueType, typename VecType>
void routine(std::size_t p_objCols,
std::size_t p_objRows,
std::size_t p_objLevels,
std::size_t p_objColsTiling,
std::size_t p_objRowsTiling,
std::size_t p_objLevelsTiling)
{
std::size_t l_objCells = p_objCols * p_objRows * p_objLevels;
std::cout << "objCols: " << p_objCols << std::endl;
std::cout << "objRows: " << p_objRows << std::endl;
std::cout << "objLevels: " << p_objLevels << std::endl;
std::cout << "objColsTiling: " << p_objColsTiling << std::endl;
std::cout << "objRowsTiling: " << p_objRowsTiling << std::endl;
std::cout << "objLevelsTiling: " << p_objLevelsTiling << std::endl;
std::cout << "objCells: " << l_objCells << std::endl;
std::cout << std::endl;
ValueType * l_x = new ValueType[l_objCells];
ValueType * l_y = new ValueType[l_objCells];
for (std::size_t i = 0; i < l_objCells; ++i)
{
l_x[i] = i;
}
OperatorType<ValueType,VecType> l_Op(
p_objCols,
p_objRows,
p_objLevels,
p_objColsTiling,
p_objRowsTiling,
p_objLevelsTiling,
C,
H,
TAU
);
LIKWID_MARKER_START("Apply");
for (std::size_t i = 0; i < RUNS; ++i)
{
l_Op.apply(l_x,l_y);
}
LIKWID_MARKER_STOP("Apply");
delete [] l_x;
delete [] l_y;
}
int main(int argc, char *argv[])
{
std::cout << "argc: " << argc << std::endl;
std::cout << "argv: [";
for (std::size_t i = 0; i < argc; ++i)
{
std::cout << argv[i];
if (i < argc - 1)
{
std::cout << ", ";
}
}
std::cout << "]" << std::endl;
if(argc != 1 && argc != 7)
{
std::cout << "INVALID INPUT: argc must be 0 or 7" << std::endl;
return 1;
}
LIKWID_MARKER_INIT;
LIKWID_MARKER_THREADINIT;
LIKWID_MARKER_REGISTER("Apply");
std::size_t l_objCols;
std::size_t l_objRows;
std::size_t l_objLevels;
std::size_t l_objColsTiling;
std::size_t l_objRowsTiling;
std::size_t l_objLevelsTiling;
if(argc == 1)
{
l_objCols = OBJ_COLS;
l_objRows = OBJ_ROWS;
l_objLevels = OBJ_LEVELS;
l_objColsTiling = OBJ_COLS_TILING;
l_objRowsTiling = OBJ_ROWS_TILING;
l_objLevelsTiling = OBJ_LEVELS_TILING;
}
else if (argc == 7)
{
l_objCols = atoi(argv[1]);
l_objRows = atoi(argv[2]);
l_objLevels = atoi(argv[3]);
l_objColsTiling = atoi(argv[4]);
l_objRowsTiling = atoi(argv[5]);
l_objLevelsTiling = atoi(argv[6]);
}
assert(l_objColsTiling%VEC_TYPE::size() == 0);
assert(l_objCols%l_objColsTiling == 0);
assert(l_objRows%l_objRowsTiling == 0);
assert(l_objLevels%l_objLevelsTiling == 0);
//
// NOTE: Edges
//
l_objCols += 2;
l_objRows += 2;
l_objLevels += 2;
routine<CLinearStencilTiling, VALUE_TYPE, VEC_TYPE>(
l_objCols,
l_objRows,
l_objLevels,
l_objColsTiling,
l_objRowsTiling,
l_objLevelsTiling
);
LIKWID_MARKER_CLOSE;
return 0;
}
|
#include "pch.h"
namespace UnitTests
{
class TimeTests : public ::testing::Test
{
protected:
DiseaseSpreadSimulation::TimeManager time;
std::vector<DiseaseSpreadSimulation::Day> weekdays{
DiseaseSpreadSimulation::Day::Monday,
DiseaseSpreadSimulation::Day::Tuesday,
DiseaseSpreadSimulation::Day::Wednesday,
DiseaseSpreadSimulation::Day::Thursday,
DiseaseSpreadSimulation::Day::Friday,
DiseaseSpreadSimulation::Day::Saturday,
DiseaseSpreadSimulation::Day::Sunday};
};
TEST_F(TimeTests, HourProgressTest)
{
for (size_t i = 0; i < 100; i++)
{
EXPECT_EQ(time.GetElapsedHours(), i);
time.Update();
}
}
TEST_F(TimeTests, DayProgressTest)
{
EXPECT_EQ(time.GetElapsedDays(), 0);
for (size_t i = 0; i < 24; i++)
{
EXPECT_EQ(time.GetElapsedDays(), 0);
time.Update();
}
EXPECT_EQ(time.GetElapsedDays(), 1);
for (size_t i = 0; i < 24; i++)
{
EXPECT_EQ(time.GetElapsedDays(), 1);
time.Update();
}
EXPECT_EQ(time.GetElapsedDays(), 2);
}
TEST_F(TimeTests, WeekdayTest)
{
for (auto& day : weekdays)
{
for (size_t i = 0; i < 24; i++)
{
EXPECT_EQ(time.GetCurrentDay(), day);
time.Update();
}
}
}
TEST_F(TimeTests, WorkdayTest)
{
for (size_t i = 0; i < weekdays.size() - 2; i++)
{
for (size_t i = 0; i < 24; i++)
{
EXPECT_TRUE(time.IsWorkday());
time.Update();
}
}
for (size_t i = weekdays.size() - 2; i < weekdays.size(); i++)
{
for (size_t i = 0; i < 24; i++)
{
EXPECT_FALSE(time.IsWorkday());
time.Update();
}
}
}
TEST_F(TimeTests, ClockTimeTest)
{
for (size_t i = 0; i < 100; i++)
{
for (size_t i = 0; i < 24; i++)
{
EXPECT_EQ(time.GetTime(), i);
time.Update();
}
}
}
} // namespace UnitTests
|
/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtGui module of the Qxt library.
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the Common Public License, version 1.0, as published
** by IBM, and/or under the terms of the GNU Lesser General Public License,
** version 2.1, as published by the Free Software Foundation.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL and the LGPL along with this
** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files
** included with the source distribution for more information.
** If you did not receive a copy of the licenses, contact the Qxt Foundation.
**
** <http://libqxt.org> <foundation@libqxt.org>
**
****************************************************************************/
#include "qxtconfirmationmessage.h"
#include <QCoreApplication>
#if QT_VERSION >= 0x040200
#include <QDialogButtonBox>
#endif // QT_VERSION
#include <QPushButton>
#include <QGridLayout>
#include <QCheckBox>
static const QLatin1String DEFAULT_ORGANIZATION("QxtGui");
static const QLatin1String DEFAULT_APPLICATION("QxtConfirmationMessage");
class QxtConfirmationMessagePrivate : public QxtPrivate<QxtConfirmationMessage>
{
public:
QXT_DECLARE_PUBLIC(QxtConfirmationMessage);
void init(const QString& message = QString());
QString key() const;
QString applicationName() const;
QString organizationName() const;
int showAgain();
void doNotShowAgain(int result);
void reset();
bool remember;
QCheckBox* confirm;
QString overrideApp;
QString overrideKey;
QString overrideOrg;
static QString path;
static QSettings::Scope scope;
static QSettings::Format format;
};
QString QxtConfirmationMessagePrivate::path;
QSettings::Scope QxtConfirmationMessagePrivate::scope = QSettings::UserScope;
QSettings::Format QxtConfirmationMessagePrivate::format = QSettings::NativeFormat;
void QxtConfirmationMessagePrivate::init(const QString& message)
{
remember = false;
#if QT_VERSION >= 0x040200
confirm = new QCheckBox(&qxt_p());
if (!message.isNull())
confirm->setText(message);
else
confirm->setText(QxtConfirmationMessage::tr("Do not show again."));
QGridLayout* grid = qobject_cast<QGridLayout*>(qxt_p().layout());
QDialogButtonBox* buttons = qFindChild<QDialogButtonBox*>(&qxt_p());
if (grid && buttons)
{
const int idx = grid->indexOf(buttons);
int row, column, rowSpan, columnSpan = 0;
grid->getItemPosition(idx, &row, &column, &rowSpan, &columnSpan);
QLayoutItem* buttonsItem = grid->takeAt(idx);
grid->addWidget(confirm, row, column, rowSpan, columnSpan, Qt::AlignLeft | Qt::AlignTop);
grid->addItem(buttonsItem, ++row, column, rowSpan, columnSpan);
}
#endif // QT_VERSION
}
QString QxtConfirmationMessagePrivate::key() const
{
QString value = overrideKey;
if (value.isEmpty())
{
const QString all = qxt_p().windowTitle() + qxt_p().text()
#if QT_VERSION >= 0x040200
+ qxt_p().informativeText()
#endif // QT_VERSION
;
const QByteArray data = all.toLocal8Bit();
value = QString::number(qChecksum(data.constData(), data.length()));
}
return value;
}
QString QxtConfirmationMessagePrivate::applicationName() const
{
QString name = overrideApp;
if (name.isEmpty())
name = QCoreApplication::applicationName();
if (name.isEmpty())
name = DEFAULT_APPLICATION;
return name;
}
QString QxtConfirmationMessagePrivate::organizationName() const
{
QString name = overrideOrg;
if (name.isEmpty())
name = QCoreApplication::organizationName();
if (name.isEmpty())
name = DEFAULT_ORGANIZATION;
return name;
}
int QxtConfirmationMessagePrivate::showAgain()
{
QSettings settings(format, scope, organizationName(), applicationName());
if (!path.isEmpty())
settings.beginGroup(path);
return settings.value(key(), -1).toInt();
}
void QxtConfirmationMessagePrivate::doNotShowAgain(int result)
{
QSettings settings(format, scope, organizationName(), applicationName());
if (!path.isEmpty())
settings.beginGroup(path);
settings.setValue(key(), result);
}
void QxtConfirmationMessagePrivate::reset()
{
QSettings settings(format, scope, organizationName(), applicationName());
if (!path.isEmpty())
settings.beginGroup(path);
settings.remove(key());
}
/*!
\class QxtConfirmationMessage QxtConfirmationMessage
\ingroup QxtGui
\brief A confirmation message.
QxtConfirmationMessage is a confirmation message with checkable
<b>"Do not show again."</b> option. A checked and accepted confirmation
message is no more shown until reseted.
Example usage:
\code
void MainWindow::closeEvent(QCloseEvent* event)
{
static const QString text(tr("Are you sure you want to quit?"));
if (QxtConfirmationMessage::confirm(this, tr("Confirm"), text) == QMessageBox::No)
event->ignore();
}
\endcode
\image html qxtconfirmationmessage.png "QxtConfirmationMessage in action."
\note \b QCoreApplication::organizationName and \b QCoreApplication::applicationName
are used for storing settings. In case these properties are empty, \b "QxtGui" and
\b "QxtConfirmationMessage" are used, respectively.
\note Requires Qt 4.2 or newer.
*/
/*!
Constructs a new QxtConfirmationMessage with \a parent.
*/
QxtConfirmationMessage::QxtConfirmationMessage(QWidget* parent)
: QMessageBox(parent)
{
QXT_INIT_PRIVATE(QxtConfirmationMessage);
qxt_d().init();
}
/*!
Constructs a new QxtConfirmationMessage with \a icon, \a title, \a text, \a confirmation, \a buttons, \a parent and \a flags.
*/
#if QT_VERSION >= 0x040200
QxtConfirmationMessage::QxtConfirmationMessage(QMessageBox::Icon icon, const QString& title, const QString& text, const QString& confirmation,
QMessageBox::StandardButtons buttons, QWidget* parent, Qt::WindowFlags flags)
: QMessageBox(icon, title, text, buttons, parent, flags)
{
QXT_INIT_PRIVATE(QxtConfirmationMessage);
qxt_d().init(confirmation);
}
#endif // QT_VERSION
/*!
Destructs the confirmation message.
*/
QxtConfirmationMessage::~QxtConfirmationMessage()
{}
// QMessageBox::StandardButton showNewMessageBox() (qmessagebox.cpp)
#if QT_VERSION >= 0x040200
QMessageBox::StandardButton QxtConfirmationMessage::confirm(QWidget* parent,
const QString& title, const QString& text, const QString& confirmation,
QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton)
{
QxtConfirmationMessage msgBox(QMessageBox::NoIcon, title, text, confirmation, QMessageBox::NoButton, parent);
QDialogButtonBox* buttonBox = qFindChild<QDialogButtonBox*>(&msgBox);
Q_ASSERT(buttonBox != 0);
uint mask = QMessageBox::FirstButton;
while (mask <= QMessageBox::LastButton)
{
uint sb = buttons & mask;
mask <<= 1;
if (!sb)
continue;
QPushButton* button = msgBox.addButton((QMessageBox::StandardButton)sb);
// Choose the first accept role as the default
if (msgBox.defaultButton())
continue;
if ((defaultButton == QMessageBox::NoButton && buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
|| (defaultButton != QMessageBox::NoButton && sb == uint(defaultButton)))
msgBox.setDefaultButton(button);
}
if (msgBox.exec() == -1)
return QMessageBox::Cancel;
return msgBox.standardButton(msgBox.clickedButton());
}
#endif // QT_VERSION
/*!
\property QxtConfirmationMessage::confirmationText
\brief This property holds the confirmation text
The default value is <b>"Do not show again."</b>
*/
QString QxtConfirmationMessage::confirmationText() const
{
return qxt_d().confirm->text();
}
void QxtConfirmationMessage::setConfirmationText(const QString& confirmation)
{
qxt_d().confirm->setText(confirmation);
}
/*!
\property QxtConfirmationMessage::overrideSettingsApplication
\brief This property holds the override application name used for settings
QCoreApplication::applicationName is used when no overrideSettingsApplication
has been set. The application name falls back to "QxtConfirmationMessage"
when no QCoreApplication::applicationName has been set.
The default value is an empty string.
*/
QString QxtConfirmationMessage::overrideSettingsApplication() const
{
return qxt_d().overrideApp;
}
void QxtConfirmationMessage::setOverrideSettingsApplication(const QString& application)
{
qxt_d().overrideApp = application;
}
/*!
\property QxtConfirmationMessage::overrideSettingsKey
\brief This property holds the override key used for settings
When no overrideSettingsKey has been set, the key is calculated with
qChecksum() based on title, text and confirmation message.
The default value is an empty string.
*/
QString QxtConfirmationMessage::overrideSettingsKey() const
{
return qxt_d().overrideKey;
}
void QxtConfirmationMessage::setOverrideSettingsKey(const QString& key)
{
qxt_d().overrideKey = key;
}
/*!
\property QxtConfirmationMessage::overrideSettingsOrganization
\brief This property holds the override organization name used for settings
QCoreApplication::organizationName is used when no overrideSettingsOrganization
has been set. The organization name falls back to "QxtGui" when no
QCoreApplication::organizationName has been set.
The default value is an empty string.
*/
QString QxtConfirmationMessage::overrideSettingsOrganization() const
{
return qxt_d().overrideOrg;
}
void QxtConfirmationMessage::setOverrideSettingsOrganization(const QString& organization)
{
qxt_d().overrideOrg = organization;
}
/*!
\property QxtConfirmationMessage::rememberOnReject
\brief This property holds whether <b>"Do not show again"</b>
option is stored even if the message box is rejected
(eg. user presses Cancel).
The default value is \b false.
*/
bool QxtConfirmationMessage::rememberOnReject() const
{
return qxt_d().remember;
}
void QxtConfirmationMessage::setRememberOnReject(bool remember)
{
qxt_d().remember = remember;
}
/*!
\return The format used for storing settings.
The default value is \b QSettings::NativeFormat.
*/
QSettings::Format QxtConfirmationMessage::settingsFormat()
{
return QxtConfirmationMessagePrivate::format;
}
/*!
Sets the format used for storing settings.
*/
void QxtConfirmationMessage::setSettingsFormat(QSettings::Format format)
{
QxtConfirmationMessagePrivate::format = format;
}
/*!
\return The scope used for storing settings.
The default value is \b QSettings::UserScope.
*/
QSettings::Scope QxtConfirmationMessage::settingsScope()
{
return QxtConfirmationMessagePrivate::scope;
}
/*!
Sets the scope used for storing settings.
*/
void QxtConfirmationMessage::setSettingsScope(QSettings::Scope scope)
{
QxtConfirmationMessagePrivate::scope = scope;
}
/*!
\return The path used for storing settings.
The default value is an empty string.
*/
QString QxtConfirmationMessage::settingsPath()
{
return QxtConfirmationMessagePrivate::path;
}
/*!
Sets the path used for storing settings.
*/
void QxtConfirmationMessage::setSettingsPath(const QString& path)
{
QxtConfirmationMessagePrivate::path = path;
}
/*!
Shows the confirmation message if necessary. The confirmation message is not
shown in case <b>"Do not show again."</b> has been checked while the same
confirmation message was earlierly accepted.
A confirmation message is identified by the combination of title,
\b QMessageBox::text and optional \b QMessageBox::informativeText.
A clicked button with role \b QDialogButtonBox::AcceptRole or
\b QDialogButtonBox::YesRole is considered as "accepted".
\warning This function does not reimplement but shadows \b QMessageBox::exec().
\sa QWidget::windowTitle, QMessageBox::text, QMessageBox::informativeText
*/
int QxtConfirmationMessage::exec()
{
int res = qxt_d().showAgain();
if (res == -1)
res = QMessageBox::exec();
return res;
}
/*!
\reimp
*/
void QxtConfirmationMessage::done(int result)
{
#if QT_VERSION >= 0x040200
QDialogButtonBox* buttons = qFindChild<QDialogButtonBox*>(this);
Q_ASSERT(buttons != 0);
int role = buttons->buttonRole(clickedButton());
if (qxt_d().confirm->isChecked() &&
(qxt_d().remember || role != QDialogButtonBox::RejectRole))
{
qxt_d().doNotShowAgain(result);
}
#endif // QT_VERSION
QMessageBox::done(result);
}
/*!
Resets this instance of QxtConfirmationMessage. A reseted confirmation
message is shown again until user checks <b>"Do not show again."</b> and
accepts the confirmation message.
*/
void QxtConfirmationMessage::reset()
{
#if QT_VERSION >= 0x040200
qxt_d().reset();
#endif // QT_VERSION
}
|
#include "../sigmaprimitives.h"
#include "../signaturebuilder.h"
#include "../../test/test_bitcoin.h"
#include "../../wallet/test/wallet_test_fixture.h"
#include <boost/test/unit_test.hpp>
namespace elysium {
class TestSignatureSigmaV1Builder : public SigmaV1SignatureBuilder
{
public:
TestSignatureSigmaV1Builder(
CBitcoinAddress const &receiver,
int64_t referenceAmount,
SigmaProof const &proof)
: SigmaV1SignatureBuilder(receiver, referenceAmount, proof)
{
}
public:
uint256 GetHash()
{
return hash;
}
};
struct SignatureBuilderSigmaV1Setup : BasicTestingSetup
{
public:
CBitcoinAddress address;
SigmaProof proof;
CKey secret;
CPubKey publicKey;
public:
SignatureBuilderSigmaV1Setup()
: address("a8ULhhDgfdSiXJhSZVdhb8EuDc6R3ogsaM"), proof(DefaultSigmaParams)
{
auto rawProof = ParseHex("0881ac0a8392734a66179ed5f06b0fcc90804776e2194e2537c83abab1b0a8cf01007fa57fdf9caecf435ad51f8fdd5062a3360063954098026efea1041d51843d7700005785485b9c61950299f98850894ee101497ff0c5e60f70ca6468dc05a2f6757c010045b2e2575c32363fdc7eb4c0fcfd925f4ca196b2e1a5e8bea76b34e819e4fcc7000015f0c997162cf54ca1ca376e5b417fe04c2900888fb50c70598ca5f11229afbdb1faa42ca7c5734730f9e733b010556592619f29730159d79985798db97d268f1a882c8947a0e2da27534490efa2021e51f8b398d2e3e7d07debd17fc76e599ce4f9ea28886054d00103f0764ad193c89eecdce65f53e4603db2bffe0c9beae474afa96fb8d23f17eef92b32b56bd44716b8393443c63b78f93ed42fb2a1b6df0e0eb5c799ba2cc8dfe4b92cbd98cc98e7d0f7b4370413b442b8421b8de820dafae6271b51ab8f923eead1f81e32f85ea9075d905523e25fa6bd64dbf5cfcf5fe3bdaa663c762179aeda6361edf17424c3d0e96ebd5d628d52fbcd6df294e178fd9a1ab33b36e66e294f551de6d0dda865b6556ce72eac65b31a96d30d0c2225e7491830ab8aae2d7323efebe503b6cd9b0f7a3c6780dc446c2a198d88d0f805fc7e0fef6bf04ba413360ed73a6957be311269aabe4a5193182a7e0fc7b332e5320faa7ec20ea29ac7d348f6c3fb997e0c916c2e249ba6a1677f7a464eb5db817a9a063e85f0a0017b6e90e2e9e5b668360d49420429750043cee9f2f4be8c89c9f3daa6e353e2b800f8ca530e924df891d6eb6a33897d4551440d721e808757eaa83747003479e6b1f19e5f7a1cc8bd4bf54008cad7ff49f8d53e232772a2fd30576115c3d10f941cb8a49fe4d144dc0977e6f7f197f25d39ebfd5333cdfd71bad101637e8470470dc1d59b21ef16b5bf3150473bc5736cff706c59c82363acadd0b6d311c12944692825ae6eded3b0ac92d333862f85a516b59dbdab6dcd858322907412b8301fd3e5a1a737e86734abb363cc1fdc33635776bcf5adb69e16fc02b00ccbd90e37178375934740a8daa986294a2f0f4f44a7a73ad57611dce568c1a4b51542c202019527b77d4231869c26f7b44e6190933ed372391dd7cf09c3c6a522cb7dcf09a1344b64c597ab887e3840c642a07e3561b8ead98f152eee2a120912e31eb75c337e16a57adfc6b48ceb4c887473756aeba1ca94040c9546b20756551df2f116695e9b1a00eb28ce357a3beaeb62006241fde992aa33b2fbfec20000bf44451073162633dd4c690b75aaf6fd796c5dea3f29e775e3739673e529abc90100ad4907d4dfb26812b29def0167b1234fcbfcbdbb4f6dda8e45322d4a32e0555a010091f92a2ae22c5a9e1c3bbd3a9ff1c4a5aec7718080cbe06601021e0a082e07970000d57157ea9edfc6165cb40d122b9967fc64fbd74c7b7edfa75d990475040e67f40000fb32e10c853f44b877693ddf55be4cca53a54209956f68dbfb77034f16348281000008515c1f54a4cfe87cc7d06c548cc0119b5c9e0e04b8b604cd35d069ebadf6ca000004a805cb321df988b32acda8d5c8e60b0d17e0df5fe3c577990eb873f47d46b7");
CDataStream ss(rawProof, SER_NETWORK, PROTOCOL_VERSION);
proof.Unserialize(ss, SER_NETWORK, PROTOCOL_VERSION);
std::array<uint8_t, 32> rawSecret;
std::fill(rawSecret.begin(), rawSecret.end(), 0x11);
secret.Set(rawSecret.begin(), rawSecret.end(), true);
auto rawPublicKey = ParseHex("034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa");
publicKey.Set(rawPublicKey.begin(), rawPublicKey.end());
}
public:
CKey GetKey()
{
return secret;
}
};
BOOST_FIXTURE_TEST_SUITE(elysium_signaturebuilder_sigmav1_tests, SignatureBuilderSigmaV1Setup)
BOOST_AUTO_TEST_CASE(construct_withvalidkey_verify_hash)
{
std::unique_ptr<TestSignatureSigmaV1Builder> builder;
BOOST_CHECK_NO_THROW(
builder.reset(new TestSignatureSigmaV1Builder(address, 10, proof)));
auto hash = builder->GetHash();
BOOST_CHECK_EQUAL(
"e8ab0af8c1d15d5ff2ced260b4082ac01ade457da4c29dc2b8a97144b6b9c4c0",
HexStr(hash.begin(), hash.end()));
}
BOOST_AUTO_TEST_CASE(sign)
{
TestSignatureSigmaV1Builder builder(address, 10, proof);
auto signer = GetKey();
auto signature = builder.Sign(signer);
BOOST_CHECK_EQUAL(
"181dad1d268f03d0a38beb34f6efa4ed12cbd6d00b62fc1d6094fa33746cdd0f73b3baa4d9cf699886fd448c0cd0ae7d1447e533fd6b5394f8f4fcd3c009de37",
HexStr(signature.GetCompact(ECDSAContext::CreateSignContext())));
}
BOOST_AUTO_TEST_CASE(verify)
{
auto context = ECDSAContext::CreateVerifyContext();
TestSignatureSigmaV1Builder builder(address, 10, proof);
ECDSASignature signature;
auto validSig = ParseHex("181dad1d268f03d0a38beb34f6efa4ed12cbd6d00b62fc1d6094fa33746cdd0f73b3baa4d9cf699886fd448c0cd0ae7d1447e533fd6b5394f8f4fcd3c009de37");
auto invalidSig = ParseHex("181dad1d268f03d0a38beb34f6efa4ed12cbd6d00b62fc1d6094fa33746cdd0f73b3baa4d9cf699886fd448c0cd0ae7d1447e533fd6b5394f8f4fcd3c009de38");
signature = ECDSASignature::Parse(context, validSig.data(), validSig.size());
BOOST_CHECK_EQUAL(true, builder.Verify(publicKey, signature));
// invalid signature
builder = TestSignatureSigmaV1Builder(address, 10, proof);
signature = ECDSASignature::Parse(context, invalidSig.data(), invalidSig.size());
BOOST_CHECK_EQUAL(false, builder.Verify(publicKey, signature));
// invalid content
signature = ECDSASignature::Parse(context, validSig.data(), validSig.size());
builder = TestSignatureSigmaV1Builder(CBitcoinAddress("aGXhTgKqDgdH9kHNTyg47TbwGfs54k2cQF"), 10, proof);
BOOST_CHECK_EQUAL(false, builder.Verify(publicKey, signature));
builder = TestSignatureSigmaV1Builder(address, 11, proof);
BOOST_CHECK_EQUAL(false, builder.Verify(publicKey, signature));
auto rawPublicKey = ParseHex("0277d283f21eb4b02d8d0d39494821b8684fc7c9507d81485847f15ed92311e66e");
CPubKey otherPublicKey(rawPublicKey);
builder = TestSignatureSigmaV1Builder(address, 11, proof);
BOOST_CHECK_EQUAL(false, builder.Verify(otherPublicKey, signature));
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace elysium
|
#include <cstdint>
#include <entity-system/EmptySystem.hpp>
#include <es-systems/SystemCore.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <es-fs/Filesystem.hpp>
#include <es-fs/fscomp/StaticFS.hpp>
#include <es-acorn/Acorn.hpp>
#include <es-general/comp/StaticObjRefID.hpp>
#include <es-general/comp/StaticCamera.hpp>
#include <es-general/comp/StaticOrthoCamera.hpp>
#include <es-general/comp/StaticKeyboardInput.hpp>
#include <es-general/comp/StaticMouseInput.hpp>
#include <es-general/comp/StaticScreenDims.hpp>
#include <es-general/comp/StaticGlobalTime.hpp>
#include <es-general/comp/StaticRandom.hpp>
#include <es-render/ShaderMan.hpp>
#include <es-render/comp/StaticShaderMan.hpp>
#include <es-render/comp/StaticVBOMan.hpp>
#include <es-render/comp/StaticIBOMan.hpp>
#include <es-render/comp/StaticTextureMan.hpp>
#include <es-render/comp/StaticFBOMan.hpp>
#include <es-render/comp/StaticGeomMan.hpp>
#include <es-render/comp/StaticFontMan.hpp>
#include <es-render/comp/StaticGLState.hpp>
#include "comp/RenderBasicGeom.h"
#include "comp/StaticWorldLight.h"
#include "comp/StaticClippingPlanes.h"
#include "systems/RenderBasicSys.h"
#include "systems/RenderTransBasicSys.h"
#include "systems/RenderTransText.h"
#include "CoreBootstrap.h"
#include "AssetBootstrap.h"
#include "Core.h"
namespace SCIRun {
namespace Render {
class CoreBootstrap : public spire::EmptySystem
{
public:
static const char* getName() {return "scirun:CoreBootstrap";}
void execute(spire::ESCoreBase& baseCore)
{
// Dynamic cast core into our core so that we have access to the systems
// factory.
ESCore* corePtr = dynamic_cast<ESCore*>(&baseCore);
if (corePtr == nullptr)
{
std::cerr << "ap bad cast." << std::endl;
return;
}
ESCore& core = *corePtr;
// Perform any caching or mandatory initialization. This bootstrap will
// only be called once.
// Add StaticObjRefID
gen::StaticObjRefID newObjRefID;
core.addStaticComponent(newObjRefID);
core.addExemptComponent<gen::StaticObjRefID>();
// Kernel file system.
core.addKernelSystem(spire::Filesystem::getFSSystemName());
// --== Base Rendering ==--
// Static shader man and associated systems. Only run GC every 5 minutes.
// The systems themselves will run GC at their own convenience.
core.addKernelSystem(ren::ShaderMan::getGCName(), 1000 * 60 * 5);
core.addKernelSystem(ren::TextureMan::getGCName(), 1000 * 60 * 5);
// -- Promise Fulfillment --
// Run shader promise fulfillment 5 times a second.
core.addKernelSystem(ren::ShaderMan::getPromiseVFFulfillmentName(), 200);
core.addKernelSystem(ren::TextureMan::getPromiseSystemName(), 200, 0, 50);
core.addKernelSystem(ren::GeomMan::getPromiseSystemName(), 200, 0, 100);
core.addKernelSystem(ren::FontMan::getPromiseSystemName(), 200, 0, 150);
// -- Garbage Collection --
core.addGarbageCollectorSystem(ren::ShaderMan::getGCName());
core.addGarbageCollectorSystem(ren::TextureMan::getGCName());
core.addGarbageCollectorSystem(ren::GeomMan::getGCName());
core.addGarbageCollectorSystem(ren::FontMan::getGCName());
core.addGarbageCollectorSystem(ren::IBOMan::getGCName());
core.addGarbageCollectorSystem(ren::VBOMan::getGCName());
// -- Static Rendering Components --
core.addStaticComponent(ren::StaticShaderMan());
core.addExemptComponent<ren::StaticShaderMan>();
core.addStaticComponent(ren::StaticVBOMan());
core.addExemptComponent<ren::StaticVBOMan>();
core.addStaticComponent(ren::StaticIBOMan());
core.addExemptComponent<ren::StaticIBOMan>();
core.addStaticComponent(ren::StaticFBOMan());
core.addExemptComponent<ren::StaticFBOMan>();
core.addStaticComponent(ren::StaticTextureMan());
core.addExemptComponent<ren::StaticTextureMan>();
core.addStaticComponent(ren::StaticGeomMan());
core.addExemptComponent<ren::StaticGeomMan>();
core.addStaticComponent(ren::StaticFontMan());
core.addExemptComponent<ren::StaticFontMan>();
// --== SCIRun5 Rendering ==--
core.addUserSystem(getSystemName_RenderBasicGeom());
core.addUserSystem(getSystemName_RenderBasicTransGeom());
core.addUserSystem(getSystemName_RenderTransTextGeom());
// --== General ==--
core.addExemptComponent<gen::StaticRandom>();
core.addStaticComponent(gen::StaticRandom());
// -- Static General Components --
// Misc components that were added by the os specific layer that need
// to be exempt.
core.addExemptComponent<gen::StaticMouseInput>();
core.addExemptComponent<gen::StaticKeyboardInput>();
core.addExemptComponent<gen::StaticScreenDims>();
core.addExemptComponent<gen::StaticGlobalTime>();
core.addExemptComponent<ren::StaticGLState>();
core.addExemptComponent<spire::StaticFS>();
// Setup default camera projection.
gen::StaticCamera cam;
float aspect = static_cast<float>(800) / static_cast<float>(600);
float perspFOVY = 0.59f;
float perspZNear = 1.0f;
float perspZFar = 2000.0f;
glm::mat4 proj = glm::perspective(perspFOVY, aspect, perspZNear, perspZFar);
cam.data.setProjection(proj, perspFOVY, aspect, perspZNear, perspZFar);
cam.data.setView(glm::mat4());
// float desZ = std::get<0>(cam.data.getPPDesWidth(6.0f));
// std::cout << "Desired Z: " << desZ << std::endl;
float desZ = -7.40457f;
cam.data.setZPlaneOfPlay(desZ);
core.addStaticComponent(cam);
core.addExemptComponent<gen::StaticCamera>();
// Add static world light.
StaticWorldLight worldLight;
//worldLight.lightDir = glm::vec3(1.0f, 0.0f, 0.0f);
core.addStaticComponent(worldLight);
core.addExemptComponent<StaticWorldLight>();
// Add static clipping planes.
StaticClippingPlanes clippingPlanes;
for (int i = 0; i < 6; ++i)
{
clippingPlanes.clippingPlanes.push_back(glm::vec4());
clippingPlanes.clippingPlaneCtrls.push_back(glm::vec4());
}
core.addStaticComponent(clippingPlanes);
core.addExemptComponent<StaticClippingPlanes>();
// Setup default ortho camera projection
gen::StaticOrthoCamera orthoCam;
float orthoZNear = -1000.0f;
float orthoZFar = 1000.0f;
glm::mat4 orthoProj =
glm::ortho(/*left*/ -1.0f, /*right*/ 1.0f,
/*bottom*/ -1.0f, /*top*/ 1.0f,
/*znear*/ orthoZNear, /*zfar*/ orthoZFar);
orthoCam.data.setOrthoProjection(orthoProj, aspect, 2.0f, 2.0f, orthoZNear, orthoZFar);
orthoCam.data.setView(glm::mat4());
core.addStaticComponent(orthoCam);
core.addExemptComponent<gen::StaticOrthoCamera>();
// Add asset bootstrap.
core.addUserSystem(getSystemName_AssetBootstrap());
// Now remove ourselves. We should only execute for one frame.
core.removeUserSystem(getName());
}
};
void registerSystem_CoreBootstrap(spire::Acorn& core)
{
core.registerSystem<CoreBootstrap>();
}
const char* getSystemName_CoreBootstrap() {return CoreBootstrap::getName();}
} // namespace Render
} // namespace SCIRun
|
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2008 Greenplum, Inc.
//
// @filename:
// CAutoRgTest.cpp
//
// @doc:
// Tests for CAutoRg
//---------------------------------------------------------------------------
#include "unittest/gpos/common/CAutoRgTest.h"
#include "gpos/base.h"
#include "gpos/common/CAutoRg.h"
#include "gpos/memory/CAutoMemoryPool.h"
#include "gpos/test/CUnittest.h"
using namespace gpos;
//---------------------------------------------------------------------------
// @function:
// CAutoRg::EresUnittest
//
// @doc:
// Unittest for bit vectors
//
//---------------------------------------------------------------------------
GPOS_RESULT
CAutoRgTest::EresUnittest()
{
CUnittest rgut[] = {GPOS_UNITTEST_FUNC(CAutoRgTest::EresUnittest_Basics)};
return CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut));
}
//---------------------------------------------------------------------------
// @function:
// CAutoRgTest::EresUnittest_Basics
//
// @doc:
// Various basic operations
//
//---------------------------------------------------------------------------
GPOS_RESULT
CAutoRgTest::EresUnittest_Basics()
{
// create memory pool
CAutoMemoryPool amp;
CMemoryPool *mp = amp.Pmp();
CAutoRg<CHAR> asz;
CHAR *sz = GPOS_NEW_ARRAY(mp, CHAR, 1234);
asz = sz;
CAutoRg<CHAR> asz2;
CAutoRg<CHAR> asz3;
CHAR *sz2 = GPOS_NEW_ARRAY(mp, CHAR, 1234);
asz2 = sz2;
asz3 = asz2;
#ifdef GPOS_DEBUG
CHAR ch = asz3[0];
GPOS_ASSERT(ch == sz2[0]);
#endif // GPOS_DEBUG
asz2 = NULL;
GPOS_DELETE_ARRAY(asz3.RgtReset());
// ctor
CAutoRg<CHAR> asz4(GPOS_NEW_ARRAY(mp, CHAR, 1234));
return GPOS_OK;
}
// EOF
|
#include <iostream>
using namespace std;
class StackException {
string message_;
public:
StackException(string message)
: message_(message)
{}
string get_message() const {
return message_;
}
};
class Stack {
const static int INITIAL_SIZE = 2;
int *data_;
int top_;
int size_;
public:
Stack() {
size_ = INITIAL_SIZE;
data_ = new int[INITIAL_SIZE];
top_ = -1;
}
Stack(const Stack& other) {
size_ = other.size_;
top_ = other.top_;
data_ = new int[size_];
for (int i = 0; i < size_; i++) {
data_[i] = other.data_[i];
}
}
void push(int value) {
if (top_ >= size_ - 1) {
resize();
}
data_[++top_] = value;
}
int pop() {
if (top_ < 0) {
throw StackException("Cannot pop from an empty stack!");
}
return data_[top_--];
}
~Stack() {
delete[] data_;
}
Stack& operator=(const Stack& other) {
if (this != &other) {
size_ = other.size_;
top_ = other.top_;
delete[] data_;
data_ = new int[size_];
for (int i = 0; i < size_; i++) {
data_[i] = other.data_[i];
}
}
return *this;
}
private:
void resize() {
int *temp_data = data_;
int new_size = size_ + INITIAL_SIZE;
data_ = new int[new_size];
for (int i = 0; i < size_; i++) {
data_[i] = temp_data[i];
}
delete[] temp_data;
size_ = new_size;
}
};
int main() {
Stack s1;
s1.push(42);
s1.push(666);
s1.push(1337);
Stack s2 = s1;
Stack s3;
s3 = s2;
try {
for (int i = 0; i <= 3; i++) {
cout << s3.pop() << endl;
}
} catch (const StackException &ex) {
cout << ex.get_message() << endl;
}
return 0;
}
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkAAClip.h"
#include "SkAtomics.h"
#include "SkBlitter.h"
#include "SkColorPriv.h"
#include "SkPath.h"
#include "SkScan.h"
#include "SkUtils.h"
class AutoAAClipValidate {
public:
AutoAAClipValidate(const SkAAClip& clip) : fClip(clip) {
fClip.validate();
}
~AutoAAClipValidate() {
fClip.validate();
}
private:
const SkAAClip& fClip;
};
#ifdef SK_DEBUG
#define AUTO_AACLIP_VALIDATE(clip) AutoAAClipValidate acv(clip)
#else
#define AUTO_AACLIP_VALIDATE(clip)
#endif
///////////////////////////////////////////////////////////////////////////////
#define kMaxInt32 0x7FFFFFFF
#ifdef SK_DEBUG
static inline bool x_in_rect(int x, const SkIRect& rect) {
return (unsigned)(x - rect.fLeft) < (unsigned)rect.width();
}
#endif
static inline bool y_in_rect(int y, const SkIRect& rect) {
return (unsigned)(y - rect.fTop) < (unsigned)rect.height();
}
/*
* Data runs are packed [count, alpha]
*/
struct SkAAClip::YOffset {
int32_t fY;
uint32_t fOffset;
};
struct SkAAClip::RunHead {
int32_t fRefCnt;
int32_t fRowCount;
size_t fDataSize;
YOffset* yoffsets() {
return (YOffset*)((char*)this + sizeof(RunHead));
}
const YOffset* yoffsets() const {
return (const YOffset*)((const char*)this + sizeof(RunHead));
}
uint8_t* data() {
return (uint8_t*)(this->yoffsets() + fRowCount);
}
const uint8_t* data() const {
return (const uint8_t*)(this->yoffsets() + fRowCount);
}
static RunHead* Alloc(int rowCount, size_t dataSize) {
size_t size = sizeof(RunHead) + rowCount * sizeof(YOffset) + dataSize;
RunHead* head = (RunHead*)sk_malloc_throw(size);
head->fRefCnt = 1;
head->fRowCount = rowCount;
head->fDataSize = dataSize;
return head;
}
static int ComputeRowSizeForWidth(int width) {
// 2 bytes per segment, where each segment can store up to 255 for count
int segments = 0;
while (width > 0) {
segments += 1;
int n = SkMin32(width, 255);
width -= n;
}
return segments * 2; // each segment is row[0] + row[1] (n + alpha)
}
static RunHead* AllocRect(const SkIRect& bounds) {
SkASSERT(!bounds.isEmpty());
int width = bounds.width();
size_t rowSize = ComputeRowSizeForWidth(width);
RunHead* head = RunHead::Alloc(1, rowSize);
YOffset* yoff = head->yoffsets();
yoff->fY = bounds.height() - 1;
yoff->fOffset = 0;
uint8_t* row = head->data();
while (width > 0) {
int n = SkMin32(width, 255);
row[0] = n;
row[1] = 0xFF;
width -= n;
row += 2;
}
return head;
}
};
class SkAAClip::Iter {
public:
Iter(const SkAAClip&);
bool done() const { return fDone; }
int top() const { return fTop; }
int bottom() const { return fBottom; }
const uint8_t* data() const { return fData; }
void next();
private:
const YOffset* fCurrYOff;
const YOffset* fStopYOff;
const uint8_t* fData;
int fTop, fBottom;
bool fDone;
};
SkAAClip::Iter::Iter(const SkAAClip& clip) {
if (clip.isEmpty()) {
fDone = true;
fTop = fBottom = clip.fBounds.fBottom;
fData = nullptr;
fCurrYOff = nullptr;
fStopYOff = nullptr;
return;
}
const RunHead* head = clip.fRunHead;
fCurrYOff = head->yoffsets();
fStopYOff = fCurrYOff + head->fRowCount;
fData = head->data() + fCurrYOff->fOffset;
// setup first value
fTop = clip.fBounds.fTop;
fBottom = clip.fBounds.fTop + fCurrYOff->fY + 1;
fDone = false;
}
void SkAAClip::Iter::next() {
if (!fDone) {
const YOffset* prev = fCurrYOff;
const YOffset* curr = prev + 1;
SkASSERT(curr <= fStopYOff);
fTop = fBottom;
if (curr >= fStopYOff) {
fDone = true;
fBottom = kMaxInt32;
fData = nullptr;
} else {
fBottom += curr->fY - prev->fY;
fData += curr->fOffset - prev->fOffset;
fCurrYOff = curr;
}
}
}
#ifdef SK_DEBUG
// assert we're exactly width-wide, and then return the number of bytes used
static size_t compute_row_length(const uint8_t row[], int width) {
const uint8_t* origRow = row;
while (width > 0) {
int n = row[0];
SkASSERT(n > 0);
SkASSERT(n <= width);
row += 2;
width -= n;
}
SkASSERT(0 == width);
return row - origRow;
}
void SkAAClip::validate() const {
if (nullptr == fRunHead) {
SkASSERT(fBounds.isEmpty());
return;
}
const RunHead* head = fRunHead;
SkASSERT(head->fRefCnt > 0);
SkASSERT(head->fRowCount > 0);
const YOffset* yoff = head->yoffsets();
const YOffset* ystop = yoff + head->fRowCount;
const int lastY = fBounds.height() - 1;
// Y and offset must be monotonic
int prevY = -1;
int32_t prevOffset = -1;
while (yoff < ystop) {
SkASSERT(prevY < yoff->fY);
SkASSERT(yoff->fY <= lastY);
prevY = yoff->fY;
SkASSERT(prevOffset < (int32_t)yoff->fOffset);
prevOffset = yoff->fOffset;
const uint8_t* row = head->data() + yoff->fOffset;
size_t rowLength = compute_row_length(row, fBounds.width());
SkASSERT(yoff->fOffset + rowLength <= head->fDataSize);
yoff += 1;
}
// check the last entry;
--yoff;
SkASSERT(yoff->fY == lastY);
}
static void dump_one_row(const uint8_t* SK_RESTRICT row,
int width, int leading_num) {
if (leading_num) {
SkDebugf( "%03d ", leading_num );
}
while (width > 0) {
int n = row[0];
int val = row[1];
char out = '.';
if (val == 0xff) {
out = '*';
} else if (val > 0) {
out = '+';
}
for (int i = 0 ; i < n ; i++) {
SkDebugf( "%c", out );
}
row += 2;
width -= n;
}
SkDebugf( "\n" );
}
void SkAAClip::debug(bool compress_y) const {
Iter iter(*this);
const int width = fBounds.width();
int y = fBounds.fTop;
while (!iter.done()) {
if (compress_y) {
dump_one_row(iter.data(), width, iter.bottom() - iter.top() + 1);
} else {
do {
dump_one_row(iter.data(), width, 0);
} while (++y < iter.bottom());
}
iter.next();
}
}
#endif
///////////////////////////////////////////////////////////////////////////////
// Count the number of zeros on the left and right edges of the passed in
// RLE row. If 'row' is all zeros return 'width' in both variables.
static void count_left_right_zeros(const uint8_t* row, int width,
int* leftZ, int* riteZ) {
int zeros = 0;
do {
if (row[1]) {
break;
}
int n = row[0];
SkASSERT(n > 0);
SkASSERT(n <= width);
zeros += n;
row += 2;
width -= n;
} while (width > 0);
*leftZ = zeros;
if (0 == width) {
// this line is completely empty return 'width' in both variables
*riteZ = *leftZ;
return;
}
zeros = 0;
while (width > 0) {
int n = row[0];
SkASSERT(n > 0);
if (0 == row[1]) {
zeros += n;
} else {
zeros = 0;
}
row += 2;
width -= n;
}
*riteZ = zeros;
}
#ifdef SK_DEBUG
static void test_count_left_right_zeros() {
static bool gOnce;
if (gOnce) {
return;
}
gOnce = true;
const uint8_t data0[] = { 0, 0, 10, 0xFF };
const uint8_t data1[] = { 0, 0, 5, 0xFF, 2, 0, 3, 0xFF };
const uint8_t data2[] = { 7, 0, 5, 0, 2, 0, 3, 0xFF };
const uint8_t data3[] = { 0, 5, 5, 0xFF, 2, 0, 3, 0 };
const uint8_t data4[] = { 2, 3, 2, 0, 5, 0xFF, 3, 0 };
const uint8_t data5[] = { 10, 10, 10, 0 };
const uint8_t data6[] = { 2, 2, 2, 0, 2, 0xFF, 2, 0, 2, 0xFF, 2, 0 };
const uint8_t* array[] = {
data0, data1, data2, data3, data4, data5, data6
};
for (size_t i = 0; i < SK_ARRAY_COUNT(array); ++i) {
const uint8_t* data = array[i];
const int expectedL = *data++;
const int expectedR = *data++;
int L = 12345, R = 12345;
count_left_right_zeros(data, 10, &L, &R);
SkASSERT(expectedL == L);
SkASSERT(expectedR == R);
}
}
#endif
// modify row in place, trimming off (zeros) from the left and right sides.
// return the number of bytes that were completely eliminated from the left
static int trim_row_left_right(uint8_t* row, int width, int leftZ, int riteZ) {
int trim = 0;
while (leftZ > 0) {
SkASSERT(0 == row[1]);
int n = row[0];
SkASSERT(n > 0);
SkASSERT(n <= width);
width -= n;
row += 2;
if (n > leftZ) {
row[-2] = n - leftZ;
break;
}
trim += 2;
leftZ -= n;
SkASSERT(leftZ >= 0);
}
if (riteZ) {
// walk row to the end, and then we'll back up to trim riteZ
while (width > 0) {
int n = row[0];
SkASSERT(n <= width);
width -= n;
row += 2;
}
// now skip whole runs of zeros
do {
row -= 2;
SkASSERT(0 == row[1]);
int n = row[0];
SkASSERT(n > 0);
if (n > riteZ) {
row[0] = n - riteZ;
break;
}
riteZ -= n;
SkASSERT(riteZ >= 0);
} while (riteZ > 0);
}
return trim;
}
#ifdef SK_DEBUG
// assert that this row is exactly this width
static void assert_row_width(const uint8_t* row, int width) {
while (width > 0) {
int n = row[0];
SkASSERT(n > 0);
SkASSERT(n <= width);
width -= n;
row += 2;
}
SkASSERT(0 == width);
}
static void test_trim_row_left_right() {
static bool gOnce;
if (gOnce) {
return;
}
gOnce = true;
uint8_t data0[] = { 0, 0, 0, 10, 10, 0xFF };
uint8_t data1[] = { 2, 0, 0, 10, 5, 0, 2, 0, 3, 0xFF };
uint8_t data2[] = { 5, 0, 2, 10, 5, 0, 2, 0, 3, 0xFF };
uint8_t data3[] = { 6, 0, 2, 10, 5, 0, 2, 0, 3, 0xFF };
uint8_t data4[] = { 0, 0, 0, 10, 2, 0, 2, 0xFF, 2, 0, 2, 0xFF, 2, 0 };
uint8_t data5[] = { 1, 0, 0, 10, 2, 0, 2, 0xFF, 2, 0, 2, 0xFF, 2, 0 };
uint8_t data6[] = { 0, 1, 0, 10, 2, 0, 2, 0xFF, 2, 0, 2, 0xFF, 2, 0 };
uint8_t data7[] = { 1, 1, 0, 10, 2, 0, 2, 0xFF, 2, 0, 2, 0xFF, 2, 0 };
uint8_t data8[] = { 2, 2, 2, 10, 2, 0, 2, 0xFF, 2, 0, 2, 0xFF, 2, 0 };
uint8_t data9[] = { 5, 2, 4, 10, 2, 0, 2, 0, 2, 0, 2, 0xFF, 2, 0 };
uint8_t data10[] ={ 74, 0, 4, 150, 9, 0, 65, 0, 76, 0xFF };
uint8_t* array[] = {
data0, data1, data2, data3, data4,
data5, data6, data7, data8, data9,
data10
};
for (size_t i = 0; i < SK_ARRAY_COUNT(array); ++i) {
uint8_t* data = array[i];
const int trimL = *data++;
const int trimR = *data++;
const int expectedSkip = *data++;
const int origWidth = *data++;
assert_row_width(data, origWidth);
int skip = trim_row_left_right(data, origWidth, trimL, trimR);
SkASSERT(expectedSkip == skip);
int expectedWidth = origWidth - trimL - trimR;
assert_row_width(data + skip, expectedWidth);
}
}
#endif
bool SkAAClip::trimLeftRight() {
SkDEBUGCODE(test_trim_row_left_right();)
if (this->isEmpty()) {
return false;
}
AUTO_AACLIP_VALIDATE(*this);
const int width = fBounds.width();
RunHead* head = fRunHead;
YOffset* yoff = head->yoffsets();
YOffset* stop = yoff + head->fRowCount;
uint8_t* base = head->data();
// After this loop, 'leftZeros' & 'rightZeros' will contain the minimum
// number of zeros on the left and right of the clip. This information
// can be used to shrink the bounding box.
int leftZeros = width;
int riteZeros = width;
while (yoff < stop) {
int L, R;
count_left_right_zeros(base + yoff->fOffset, width, &L, &R);
SkASSERT(L + R < width || (L == width && R == width));
if (L < leftZeros) {
leftZeros = L;
}
if (R < riteZeros) {
riteZeros = R;
}
if (0 == (leftZeros | riteZeros)) {
// no trimming to do
return true;
}
yoff += 1;
}
SkASSERT(leftZeros || riteZeros);
if (width == leftZeros) {
SkASSERT(width == riteZeros);
return this->setEmpty();
}
this->validate();
fBounds.fLeft += leftZeros;
fBounds.fRight -= riteZeros;
SkASSERT(!fBounds.isEmpty());
// For now we don't realloc the storage (for time), we just shrink in place
// This means we don't have to do any memmoves either, since we can just
// play tricks with the yoff->fOffset for each row
yoff = head->yoffsets();
while (yoff < stop) {
uint8_t* row = base + yoff->fOffset;
SkDEBUGCODE((void)compute_row_length(row, width);)
yoff->fOffset += trim_row_left_right(row, width, leftZeros, riteZeros);
SkDEBUGCODE((void)compute_row_length(base + yoff->fOffset, width - leftZeros - riteZeros);)
yoff += 1;
}
return true;
}
static bool row_is_all_zeros(const uint8_t* row, int width) {
SkASSERT(width > 0);
do {
if (row[1]) {
return false;
}
int n = row[0];
SkASSERT(n <= width);
width -= n;
row += 2;
} while (width > 0);
SkASSERT(0 == width);
return true;
}
bool SkAAClip::trimTopBottom() {
if (this->isEmpty()) {
return false;
}
this->validate();
const int width = fBounds.width();
RunHead* head = fRunHead;
YOffset* yoff = head->yoffsets();
YOffset* stop = yoff + head->fRowCount;
const uint8_t* base = head->data();
// Look to trim away empty rows from the top.
//
int skip = 0;
while (yoff < stop) {
const uint8_t* data = base + yoff->fOffset;
if (!row_is_all_zeros(data, width)) {
break;
}
skip += 1;
yoff += 1;
}
SkASSERT(skip <= head->fRowCount);
if (skip == head->fRowCount) {
return this->setEmpty();
}
if (skip > 0) {
// adjust fRowCount and fBounds.fTop, and slide all the data up
// as we remove [skip] number of YOffset entries
yoff = head->yoffsets();
int dy = yoff[skip - 1].fY + 1;
for (int i = skip; i < head->fRowCount; ++i) {
SkASSERT(yoff[i].fY >= dy);
yoff[i].fY -= dy;
}
YOffset* dst = head->yoffsets();
size_t size = head->fRowCount * sizeof(YOffset) + head->fDataSize;
memmove(dst, dst + skip, size - skip * sizeof(YOffset));
fBounds.fTop += dy;
SkASSERT(!fBounds.isEmpty());
head->fRowCount -= skip;
SkASSERT(head->fRowCount > 0);
this->validate();
// need to reset this after the memmove
base = head->data();
}
// Look to trim away empty rows from the bottom.
// We know that we have at least one non-zero row, so we can just walk
// backwards without checking for running past the start.
//
stop = yoff = head->yoffsets() + head->fRowCount;
do {
yoff -= 1;
} while (row_is_all_zeros(base + yoff->fOffset, width));
skip = SkToInt(stop - yoff - 1);
SkASSERT(skip >= 0 && skip < head->fRowCount);
if (skip > 0) {
// removing from the bottom is easier than from the top, as we don't
// have to adjust any of the Y values, we just have to trim the array
memmove(stop - skip, stop, head->fDataSize);
fBounds.fBottom = fBounds.fTop + yoff->fY + 1;
SkASSERT(!fBounds.isEmpty());
head->fRowCount -= skip;
SkASSERT(head->fRowCount > 0);
}
this->validate();
return true;
}
// can't validate before we're done, since trimming is part of the process of
// making us valid after the Builder. Since we build from top to bottom, its
// possible our fBounds.fBottom is bigger than our last scanline of data, so
// we trim fBounds.fBottom back up.
//
// TODO: check for duplicates in X and Y to further compress our data
//
bool SkAAClip::trimBounds() {
if (this->isEmpty()) {
return false;
}
const RunHead* head = fRunHead;
const YOffset* yoff = head->yoffsets();
SkASSERT(head->fRowCount > 0);
const YOffset& lastY = yoff[head->fRowCount - 1];
SkASSERT(lastY.fY + 1 <= fBounds.height());
fBounds.fBottom = fBounds.fTop + lastY.fY + 1;
SkASSERT(lastY.fY + 1 == fBounds.height());
SkASSERT(!fBounds.isEmpty());
return this->trimTopBottom() && this->trimLeftRight();
}
///////////////////////////////////////////////////////////////////////////////
void SkAAClip::freeRuns() {
if (fRunHead) {
SkASSERT(fRunHead->fRefCnt >= 1);
if (1 == sk_atomic_dec(&fRunHead->fRefCnt)) {
sk_free(fRunHead);
}
}
}
SkAAClip::SkAAClip() {
fBounds.setEmpty();
fRunHead = nullptr;
}
SkAAClip::SkAAClip(const SkAAClip& src) {
SkDEBUGCODE(fBounds.setEmpty();) // need this for validate
fRunHead = nullptr;
*this = src;
}
SkAAClip::~SkAAClip() {
this->freeRuns();
}
SkAAClip& SkAAClip::operator=(const SkAAClip& src) {
AUTO_AACLIP_VALIDATE(*this);
src.validate();
if (this != &src) {
this->freeRuns();
fBounds = src.fBounds;
fRunHead = src.fRunHead;
if (fRunHead) {
sk_atomic_inc(&fRunHead->fRefCnt);
}
}
return *this;
}
bool operator==(const SkAAClip& a, const SkAAClip& b) {
a.validate();
b.validate();
if (&a == &b) {
return true;
}
if (a.fBounds != b.fBounds) {
return false;
}
const SkAAClip::RunHead* ah = a.fRunHead;
const SkAAClip::RunHead* bh = b.fRunHead;
// this catches empties and rects being equal
if (ah == bh) {
return true;
}
// now we insist that both are complex (but different ptrs)
if (!a.fRunHead || !b.fRunHead) {
return false;
}
return ah->fRowCount == bh->fRowCount &&
ah->fDataSize == bh->fDataSize &&
!memcmp(ah->data(), bh->data(), ah->fDataSize);
}
void SkAAClip::swap(SkAAClip& other) {
AUTO_AACLIP_VALIDATE(*this);
other.validate();
SkTSwap(fBounds, other.fBounds);
SkTSwap(fRunHead, other.fRunHead);
}
bool SkAAClip::set(const SkAAClip& src) {
*this = src;
return !this->isEmpty();
}
bool SkAAClip::setEmpty() {
this->freeRuns();
fBounds.setEmpty();
fRunHead = nullptr;
return false;
}
bool SkAAClip::setRect(const SkIRect& bounds) {
if (bounds.isEmpty()) {
return this->setEmpty();
}
AUTO_AACLIP_VALIDATE(*this);
#if 0
SkRect r;
r.set(bounds);
SkPath path;
path.addRect(r);
return this->setPath(path);
#else
this->freeRuns();
fBounds = bounds;
fRunHead = RunHead::AllocRect(bounds);
SkASSERT(!this->isEmpty());
return true;
#endif
}
bool SkAAClip::isRect() const {
if (this->isEmpty()) {
return false;
}
const RunHead* head = fRunHead;
if (head->fRowCount != 1) {
return false;
}
const YOffset* yoff = head->yoffsets();
if (yoff->fY != fBounds.fBottom - 1) {
return false;
}
const uint8_t* row = head->data() + yoff->fOffset;
int width = fBounds.width();
do {
if (row[1] != 0xFF) {
return false;
}
int n = row[0];
SkASSERT(n <= width);
width -= n;
row += 2;
} while (width > 0);
return true;
}
bool SkAAClip::setRect(const SkRect& r, bool doAA) {
if (r.isEmpty()) {
return this->setEmpty();
}
AUTO_AACLIP_VALIDATE(*this);
// TODO: special case this
SkPath path;
path.addRect(r);
return this->setPath(path, nullptr, doAA);
}
static void append_run(SkTDArray<uint8_t>& array, uint8_t value, int count) {
SkASSERT(count >= 0);
while (count > 0) {
int n = count;
if (n > 255) {
n = 255;
}
uint8_t* data = array.append(2);
data[0] = n;
data[1] = value;
count -= n;
}
}
bool SkAAClip::setRegion(const SkRegion& rgn) {
if (rgn.isEmpty()) {
return this->setEmpty();
}
if (rgn.isRect()) {
return this->setRect(rgn.getBounds());
}
#if 0
SkAAClip clip;
SkRegion::Iterator iter(rgn);
for (; !iter.done(); iter.next()) {
clip.op(iter.rect(), SkRegion::kUnion_Op);
}
this->swap(clip);
return !this->isEmpty();
#else
const SkIRect& bounds = rgn.getBounds();
const int offsetX = bounds.fLeft;
const int offsetY = bounds.fTop;
SkTDArray<YOffset> yArray;
SkTDArray<uint8_t> xArray;
yArray.setReserve(SkMin32(bounds.height(), 1024));
xArray.setReserve(SkMin32(bounds.width() * 128, 64 * 1024));
SkRegion::Iterator iter(rgn);
int prevRight = 0;
int prevBot = 0;
YOffset* currY = nullptr;
for (; !iter.done(); iter.next()) {
const SkIRect& r = iter.rect();
SkASSERT(bounds.contains(r));
int bot = r.fBottom - offsetY;
SkASSERT(bot >= prevBot);
if (bot > prevBot) {
if (currY) {
// flush current row
append_run(xArray, 0, bounds.width() - prevRight);
}
// did we introduce an empty-gap from the prev row?
int top = r.fTop - offsetY;
if (top > prevBot) {
currY = yArray.append();
currY->fY = top - 1;
currY->fOffset = xArray.count();
append_run(xArray, 0, bounds.width());
}
// create a new record for this Y value
currY = yArray.append();
currY->fY = bot - 1;
currY->fOffset = xArray.count();
prevRight = 0;
prevBot = bot;
}
int x = r.fLeft - offsetX;
append_run(xArray, 0, x - prevRight);
int w = r.fRight - r.fLeft;
append_run(xArray, 0xFF, w);
prevRight = x + w;
SkASSERT(prevRight <= bounds.width());
}
// flush last row
append_run(xArray, 0, bounds.width() - prevRight);
// now pack everything into a RunHead
RunHead* head = RunHead::Alloc(yArray.count(), xArray.bytes());
memcpy(head->yoffsets(), yArray.begin(), yArray.bytes());
memcpy(head->data(), xArray.begin(), xArray.bytes());
this->setEmpty();
fBounds = bounds;
fRunHead = head;
this->validate();
return true;
#endif
}
///////////////////////////////////////////////////////////////////////////////
const uint8_t* SkAAClip::findRow(int y, int* lastYForRow) const {
SkASSERT(fRunHead);
if (!y_in_rect(y, fBounds)) {
return nullptr;
}
y -= fBounds.y(); // our yoffs values are relative to the top
const YOffset* yoff = fRunHead->yoffsets();
while (yoff->fY < y) {
yoff += 1;
SkASSERT(yoff - fRunHead->yoffsets() < fRunHead->fRowCount);
}
if (lastYForRow) {
*lastYForRow = fBounds.y() + yoff->fY;
}
return fRunHead->data() + yoff->fOffset;
}
const uint8_t* SkAAClip::findX(const uint8_t data[], int x, int* initialCount) const {
SkASSERT(x_in_rect(x, fBounds));
x -= fBounds.x();
// first skip up to X
for (;;) {
int n = data[0];
if (x < n) {
if (initialCount) {
*initialCount = n - x;
}
break;
}
data += 2;
x -= n;
}
return data;
}
bool SkAAClip::quickContains(int left, int top, int right, int bottom) const {
if (this->isEmpty()) {
return false;
}
if (!fBounds.contains(left, top, right, bottom)) {
return false;
}
#if 0
if (this->isRect()) {
return true;
}
#endif
int lastY SK_INIT_TO_AVOID_WARNING;
const uint8_t* row = this->findRow(top, &lastY);
if (lastY < bottom) {
return false;
}
// now just need to check in X
int count;
row = this->findX(row, left, &count);
#if 0
return count >= (right - left) && 0xFF == row[1];
#else
int rectWidth = right - left;
while (0xFF == row[1]) {
if (count >= rectWidth) {
return true;
}
rectWidth -= count;
row += 2;
count = row[0];
}
return false;
#endif
}
///////////////////////////////////////////////////////////////////////////////
class SkAAClip::Builder {
SkIRect fBounds;
struct Row {
int fY;
int fWidth;
SkTDArray<uint8_t>* fData;
};
SkTDArray<Row> fRows;
Row* fCurrRow;
int fPrevY;
int fWidth;
int fMinY;
public:
Builder(const SkIRect& bounds) : fBounds(bounds) {
fPrevY = -1;
fWidth = bounds.width();
fCurrRow = nullptr;
fMinY = bounds.fTop;
}
~Builder() {
Row* row = fRows.begin();
Row* stop = fRows.end();
while (row < stop) {
delete row->fData;
row += 1;
}
}
const SkIRect& getBounds() const { return fBounds; }
void addRun(int x, int y, U8CPU alpha, int count) {
SkASSERT(count > 0);
SkASSERT(fBounds.contains(x, y));
SkASSERT(fBounds.contains(x + count - 1, y));
x -= fBounds.left();
y -= fBounds.top();
Row* row = fCurrRow;
if (y != fPrevY) {
SkASSERT(y > fPrevY);
fPrevY = y;
row = this->flushRow(true);
row->fY = y;
row->fWidth = 0;
SkASSERT(row->fData);
SkASSERT(0 == row->fData->count());
fCurrRow = row;
}
SkASSERT(row->fWidth <= x);
SkASSERT(row->fWidth < fBounds.width());
SkTDArray<uint8_t>& data = *row->fData;
int gap = x - row->fWidth;
if (gap) {
AppendRun(data, 0, gap);
row->fWidth += gap;
SkASSERT(row->fWidth < fBounds.width());
}
AppendRun(data, alpha, count);
row->fWidth += count;
SkASSERT(row->fWidth <= fBounds.width());
}
void addColumn(int x, int y, U8CPU alpha, int height) {
SkASSERT(fBounds.contains(x, y + height - 1));
this->addRun(x, y, alpha, 1);
this->flushRowH(fCurrRow);
y -= fBounds.fTop;
SkASSERT(y == fCurrRow->fY);
fCurrRow->fY = y + height - 1;
}
void addRectRun(int x, int y, int width, int height) {
SkASSERT(fBounds.contains(x + width - 1, y + height - 1));
this->addRun(x, y, 0xFF, width);
// we assum the rect must be all we'll see for these scanlines
// so we ensure our row goes all the way to our right
this->flushRowH(fCurrRow);
y -= fBounds.fTop;
SkASSERT(y == fCurrRow->fY);
fCurrRow->fY = y + height - 1;
}
void addAntiRectRun(int x, int y, int width, int height,
SkAlpha leftAlpha, SkAlpha rightAlpha) {
SkASSERT(fBounds.contains(x + width - 1 +
(leftAlpha > 0 ? 1 : 0) + (rightAlpha > 0 ? 1 : 0),
y + height - 1));
SkASSERT(width >= 0);
// Conceptually we're always adding 3 runs, but we should
// merge or omit them if possible.
if (leftAlpha == 0xFF) {
width++;
} else if (leftAlpha > 0) {
this->addRun(x++, y, leftAlpha, 1);
}
if (rightAlpha == 0xFF) {
width++;
}
if (width > 0) {
this->addRun(x, y, 0xFF, width);
}
if (rightAlpha > 0 && rightAlpha < 255) {
this->addRun(x + width, y, rightAlpha, 1);
}
// we assume the rect must be all we'll see for these scanlines
// so we ensure our row goes all the way to our right
this->flushRowH(fCurrRow);
y -= fBounds.fTop;
SkASSERT(y == fCurrRow->fY);
fCurrRow->fY = y + height - 1;
}
bool finish(SkAAClip* target) {
this->flushRow(false);
const Row* row = fRows.begin();
const Row* stop = fRows.end();
size_t dataSize = 0;
while (row < stop) {
dataSize += row->fData->count();
row += 1;
}
if (0 == dataSize) {
return target->setEmpty();
}
SkASSERT(fMinY >= fBounds.fTop);
SkASSERT(fMinY < fBounds.fBottom);
int adjustY = fMinY - fBounds.fTop;
fBounds.fTop = fMinY;
RunHead* head = RunHead::Alloc(fRows.count(), dataSize);
YOffset* yoffset = head->yoffsets();
uint8_t* data = head->data();
uint8_t* baseData = data;
row = fRows.begin();
SkDEBUGCODE(int prevY = row->fY - 1;)
while (row < stop) {
SkASSERT(prevY < row->fY); // must be monotonic
SkDEBUGCODE(prevY = row->fY);
yoffset->fY = row->fY - adjustY;
yoffset->fOffset = SkToU32(data - baseData);
yoffset += 1;
size_t n = row->fData->count();
memcpy(data, row->fData->begin(), n);
#ifdef SK_DEBUG
size_t bytesNeeded = compute_row_length(data, fBounds.width());
SkASSERT(bytesNeeded == n);
#endif
data += n;
row += 1;
}
target->freeRuns();
target->fBounds = fBounds;
target->fRunHead = head;
return target->trimBounds();
}
void dump() {
this->validate();
int y;
for (y = 0; y < fRows.count(); ++y) {
const Row& row = fRows[y];
SkDebugf("Y:%3d W:%3d", row.fY, row.fWidth);
const SkTDArray<uint8_t>& data = *row.fData;
int count = data.count();
SkASSERT(!(count & 1));
const uint8_t* ptr = data.begin();
for (int x = 0; x < count; x += 2) {
SkDebugf(" [%3d:%02X]", ptr[0], ptr[1]);
ptr += 2;
}
SkDebugf("\n");
}
}
void validate() {
#ifdef SK_DEBUG
if (false) { // avoid bit rot, suppress warning
test_count_left_right_zeros();
}
int prevY = -1;
for (int i = 0; i < fRows.count(); ++i) {
const Row& row = fRows[i];
SkASSERT(prevY < row.fY);
SkASSERT(fWidth == row.fWidth);
int count = row.fData->count();
const uint8_t* ptr = row.fData->begin();
SkASSERT(!(count & 1));
int w = 0;
for (int x = 0; x < count; x += 2) {
int n = ptr[0];
SkASSERT(n > 0);
w += n;
SkASSERT(w <= fWidth);
ptr += 2;
}
SkASSERT(w == fWidth);
prevY = row.fY;
}
#endif
}
// only called by BuilderBlitter
void setMinY(int y) {
fMinY = y;
}
private:
void flushRowH(Row* row) {
// flush current row if needed
if (row->fWidth < fWidth) {
AppendRun(*row->fData, 0, fWidth - row->fWidth);
row->fWidth = fWidth;
}
}
Row* flushRow(bool readyForAnother) {
Row* next = nullptr;
int count = fRows.count();
if (count > 0) {
this->flushRowH(&fRows[count - 1]);
}
if (count > 1) {
// are our last two runs the same?
Row* prev = &fRows[count - 2];
Row* curr = &fRows[count - 1];
SkASSERT(prev->fWidth == fWidth);
SkASSERT(curr->fWidth == fWidth);
if (*prev->fData == *curr->fData) {
prev->fY = curr->fY;
if (readyForAnother) {
curr->fData->rewind();
next = curr;
} else {
delete curr->fData;
fRows.removeShuffle(count - 1);
}
} else {
if (readyForAnother) {
next = fRows.append();
next->fData = new SkTDArray<uint8_t>;
}
}
} else {
if (readyForAnother) {
next = fRows.append();
next->fData = new SkTDArray<uint8_t>;
}
}
return next;
}
static void AppendRun(SkTDArray<uint8_t>& data, U8CPU alpha, int count) {
do {
int n = count;
if (n > 255) {
n = 255;
}
uint8_t* ptr = data.append(2);
ptr[0] = n;
ptr[1] = alpha;
count -= n;
} while (count > 0);
}
};
class SkAAClip::BuilderBlitter : public SkBlitter {
int fLastY;
/*
If we see a gap of 1 or more empty scanlines while building in Y-order,
we inject an explicit empty scanline (alpha==0)
See AAClipTest.cpp : test_path_with_hole()
*/
void checkForYGap(int y) {
SkASSERT(y >= fLastY);
if (fLastY > -SK_MaxS32) {
int gap = y - fLastY;
if (gap > 1) {
fBuilder->addRun(fLeft, y - 1, 0, fRight - fLeft);
}
}
fLastY = y;
}
public:
BuilderBlitter(Builder* builder) {
fBuilder = builder;
fLeft = builder->getBounds().fLeft;
fRight = builder->getBounds().fRight;
fMinY = SK_MaxS32;
fLastY = -SK_MaxS32; // sentinel
}
void finish() {
if (fMinY < SK_MaxS32) {
fBuilder->setMinY(fMinY);
}
}
/**
Must evaluate clips in scan-line order, so don't want to allow blitV(),
but an AAClip can be clipped down to a single pixel wide, so we
must support it (given AntiRect semantics: minimum width is 2).
Instead we'll rely on the runtime asserts to guarantee Y monotonicity;
any failure cases that misses may have minor artifacts.
*/
void blitV(int x, int y, int height, SkAlpha alpha) override {
this->recordMinY(y);
fBuilder->addColumn(x, y, alpha, height);
fLastY = y + height - 1;
}
void blitRect(int x, int y, int width, int height) override {
this->recordMinY(y);
this->checkForYGap(y);
fBuilder->addRectRun(x, y, width, height);
fLastY = y + height - 1;
}
virtual void blitAntiRect(int x, int y, int width, int height,
SkAlpha leftAlpha, SkAlpha rightAlpha) override {
this->recordMinY(y);
this->checkForYGap(y);
fBuilder->addAntiRectRun(x, y, width, height, leftAlpha, rightAlpha);
fLastY = y + height - 1;
}
void blitMask(const SkMask&, const SkIRect& clip) override
{ unexpected(); }
const SkPixmap* justAnOpaqueColor(uint32_t*) override {
return nullptr;
}
void blitH(int x, int y, int width) override {
this->recordMinY(y);
this->checkForYGap(y);
fBuilder->addRun(x, y, 0xFF, width);
}
virtual void blitAntiH(int x, int y, const SkAlpha alpha[],
const int16_t runs[]) override {
this->recordMinY(y);
this->checkForYGap(y);
for (;;) {
int count = *runs;
if (count <= 0) {
return;
}
// The supersampler's buffer can be the width of the device, so
// we may have to trim the run to our bounds. If so, we assert that
// the extra spans are always alpha==0
int localX = x;
int localCount = count;
if (x < fLeft) {
SkASSERT(0 == *alpha);
int gap = fLeft - x;
SkASSERT(gap <= count);
localX += gap;
localCount -= gap;
}
int right = x + count;
if (right > fRight) {
SkASSERT(0 == *alpha);
localCount -= right - fRight;
SkASSERT(localCount >= 0);
}
if (localCount) {
fBuilder->addRun(localX, y, *alpha, localCount);
}
// Next run
runs += count;
alpha += count;
x += count;
}
}
private:
Builder* fBuilder;
int fLeft; // cache of builder's bounds' left edge
int fRight;
int fMinY;
/*
* We track this, in case the scan converter skipped some number of
* scanlines at the (relative to the bounds it was given). This allows
* the builder, during its finish, to trip its bounds down to the "real"
* top.
*/
void recordMinY(int y) {
if (y < fMinY) {
fMinY = y;
}
}
void unexpected() {
SkDebugf("---- did not expect to get called here");
sk_throw();
}
};
bool SkAAClip::setPath(const SkPath& path, const SkRegion* clip, bool doAA) {
AUTO_AACLIP_VALIDATE(*this);
if (clip && clip->isEmpty()) {
return this->setEmpty();
}
SkIRect ibounds;
path.getBounds().roundOut(&ibounds);
SkRegion tmpClip;
if (nullptr == clip) {
tmpClip.setRect(ibounds);
clip = &tmpClip;
}
if (path.isInverseFillType()) {
ibounds = clip->getBounds();
} else {
if (ibounds.isEmpty() || !ibounds.intersect(clip->getBounds())) {
return this->setEmpty();
}
}
Builder builder(ibounds);
BuilderBlitter blitter(&builder);
if (doAA) {
SkScan::AntiFillPath(path, *clip, &blitter, true);
} else {
SkScan::FillPath(path, *clip, &blitter);
}
blitter.finish();
return builder.finish(this);
}
///////////////////////////////////////////////////////////////////////////////
typedef void (*RowProc)(SkAAClip::Builder&, int bottom,
const uint8_t* rowA, const SkIRect& rectA,
const uint8_t* rowB, const SkIRect& rectB);
typedef U8CPU (*AlphaProc)(U8CPU alphaA, U8CPU alphaB);
static U8CPU sectAlphaProc(U8CPU alphaA, U8CPU alphaB) {
// Multiply
return SkMulDiv255Round(alphaA, alphaB);
}
static U8CPU unionAlphaProc(U8CPU alphaA, U8CPU alphaB) {
// SrcOver
return alphaA + alphaB - SkMulDiv255Round(alphaA, alphaB);
}
static U8CPU diffAlphaProc(U8CPU alphaA, U8CPU alphaB) {
// SrcOut
return SkMulDiv255Round(alphaA, 0xFF - alphaB);
}
static U8CPU xorAlphaProc(U8CPU alphaA, U8CPU alphaB) {
// XOR
return alphaA + alphaB - 2 * SkMulDiv255Round(alphaA, alphaB);
}
static AlphaProc find_alpha_proc(SkRegion::Op op) {
switch (op) {
case SkRegion::kIntersect_Op:
return sectAlphaProc;
case SkRegion::kDifference_Op:
return diffAlphaProc;
case SkRegion::kUnion_Op:
return unionAlphaProc;
case SkRegion::kXOR_Op:
return xorAlphaProc;
default:
SkDEBUGFAIL("unexpected region op");
return sectAlphaProc;
}
}
class RowIter {
public:
RowIter(const uint8_t* row, const SkIRect& bounds) {
fRow = row;
fLeft = bounds.fLeft;
fBoundsRight = bounds.fRight;
if (row) {
fRight = bounds.fLeft + row[0];
SkASSERT(fRight <= fBoundsRight);
fAlpha = row[1];
fDone = false;
} else {
fDone = true;
fRight = kMaxInt32;
fAlpha = 0;
}
}
bool done() const { return fDone; }
int left() const { return fLeft; }
int right() const { return fRight; }
U8CPU alpha() const { return fAlpha; }
void next() {
if (!fDone) {
fLeft = fRight;
if (fRight == fBoundsRight) {
fDone = true;
fRight = kMaxInt32;
fAlpha = 0;
} else {
fRow += 2;
fRight += fRow[0];
fAlpha = fRow[1];
SkASSERT(fRight <= fBoundsRight);
}
}
}
private:
const uint8_t* fRow;
int fLeft;
int fRight;
int fBoundsRight;
bool fDone;
uint8_t fAlpha;
};
static void adjust_row(RowIter& iter, int& leftA, int& riteA, int rite) {
if (rite == riteA) {
iter.next();
leftA = iter.left();
riteA = iter.right();
}
}
#if 0 // UNUSED
static bool intersect(int& min, int& max, int boundsMin, int boundsMax) {
SkASSERT(min < max);
SkASSERT(boundsMin < boundsMax);
if (min >= boundsMax || max <= boundsMin) {
return false;
}
if (min < boundsMin) {
min = boundsMin;
}
if (max > boundsMax) {
max = boundsMax;
}
return true;
}
#endif
static void operatorX(SkAAClip::Builder& builder, int lastY,
RowIter& iterA, RowIter& iterB,
AlphaProc proc, const SkIRect& bounds) {
int leftA = iterA.left();
int riteA = iterA.right();
int leftB = iterB.left();
int riteB = iterB.right();
int prevRite = bounds.fLeft;
do {
U8CPU alphaA = 0;
U8CPU alphaB = 0;
int left, rite;
if (leftA < leftB) {
left = leftA;
alphaA = iterA.alpha();
if (riteA <= leftB) {
rite = riteA;
} else {
rite = leftA = leftB;
}
} else if (leftB < leftA) {
left = leftB;
alphaB = iterB.alpha();
if (riteB <= leftA) {
rite = riteB;
} else {
rite = leftB = leftA;
}
} else {
left = leftA; // or leftB, since leftA == leftB
rite = leftA = leftB = SkMin32(riteA, riteB);
alphaA = iterA.alpha();
alphaB = iterB.alpha();
}
if (left >= bounds.fRight) {
break;
}
if (rite > bounds.fRight) {
rite = bounds.fRight;
}
if (left >= bounds.fLeft) {
SkASSERT(rite > left);
builder.addRun(left, lastY, proc(alphaA, alphaB), rite - left);
prevRite = rite;
}
adjust_row(iterA, leftA, riteA, rite);
adjust_row(iterB, leftB, riteB, rite);
} while (!iterA.done() || !iterB.done());
if (prevRite < bounds.fRight) {
builder.addRun(prevRite, lastY, 0, bounds.fRight - prevRite);
}
}
static void adjust_iter(SkAAClip::Iter& iter, int& topA, int& botA, int bot) {
if (bot == botA) {
iter.next();
topA = botA;
SkASSERT(botA == iter.top());
botA = iter.bottom();
}
}
static void operateY(SkAAClip::Builder& builder, const SkAAClip& A,
const SkAAClip& B, SkRegion::Op op) {
AlphaProc proc = find_alpha_proc(op);
const SkIRect& bounds = builder.getBounds();
SkAAClip::Iter iterA(A);
SkAAClip::Iter iterB(B);
SkASSERT(!iterA.done());
int topA = iterA.top();
int botA = iterA.bottom();
SkASSERT(!iterB.done());
int topB = iterB.top();
int botB = iterB.bottom();
do {
const uint8_t* rowA = nullptr;
const uint8_t* rowB = nullptr;
int top, bot;
if (topA < topB) {
top = topA;
rowA = iterA.data();
if (botA <= topB) {
bot = botA;
} else {
bot = topA = topB;
}
} else if (topB < topA) {
top = topB;
rowB = iterB.data();
if (botB <= topA) {
bot = botB;
} else {
bot = topB = topA;
}
} else {
top = topA; // or topB, since topA == topB
bot = topA = topB = SkMin32(botA, botB);
rowA = iterA.data();
rowB = iterB.data();
}
if (top >= bounds.fBottom) {
break;
}
if (bot > bounds.fBottom) {
bot = bounds.fBottom;
}
SkASSERT(top < bot);
if (!rowA && !rowB) {
builder.addRun(bounds.fLeft, bot - 1, 0, bounds.width());
} else if (top >= bounds.fTop) {
SkASSERT(bot <= bounds.fBottom);
RowIter rowIterA(rowA, rowA ? A.getBounds() : bounds);
RowIter rowIterB(rowB, rowB ? B.getBounds() : bounds);
operatorX(builder, bot - 1, rowIterA, rowIterB, proc, bounds);
}
adjust_iter(iterA, topA, botA, bot);
adjust_iter(iterB, topB, botB, bot);
} while (!iterA.done() || !iterB.done());
}
bool SkAAClip::op(const SkAAClip& clipAOrig, const SkAAClip& clipBOrig,
SkRegion::Op op) {
AUTO_AACLIP_VALIDATE(*this);
if (SkRegion::kReplace_Op == op) {
return this->set(clipBOrig);
}
const SkAAClip* clipA = &clipAOrig;
const SkAAClip* clipB = &clipBOrig;
if (SkRegion::kReverseDifference_Op == op) {
SkTSwap(clipA, clipB);
op = SkRegion::kDifference_Op;
}
bool a_empty = clipA->isEmpty();
bool b_empty = clipB->isEmpty();
SkIRect bounds;
switch (op) {
case SkRegion::kDifference_Op:
if (a_empty) {
return this->setEmpty();
}
if (b_empty || !SkIRect::Intersects(clipA->fBounds, clipB->fBounds)) {
return this->set(*clipA);
}
bounds = clipA->fBounds;
break;
case SkRegion::kIntersect_Op:
if ((a_empty | b_empty) || !bounds.intersect(clipA->fBounds,
clipB->fBounds)) {
return this->setEmpty();
}
break;
case SkRegion::kUnion_Op:
case SkRegion::kXOR_Op:
if (a_empty) {
return this->set(*clipB);
}
if (b_empty) {
return this->set(*clipA);
}
bounds = clipA->fBounds;
bounds.join(clipB->fBounds);
break;
default:
SkDEBUGFAIL("unknown region op");
return !this->isEmpty();
}
SkASSERT(SkIRect::Intersects(bounds, clipB->fBounds));
SkASSERT(SkIRect::Intersects(bounds, clipB->fBounds));
Builder builder(bounds);
operateY(builder, *clipA, *clipB, op);
return builder.finish(this);
}
/*
* It can be expensive to build a local aaclip before applying the op, so
* we first see if we can restrict the bounds of new rect to our current
* bounds, or note that the new rect subsumes our current clip.
*/
bool SkAAClip::op(const SkIRect& rOrig, SkRegion::Op op) {
SkIRect rStorage;
const SkIRect* r = &rOrig;
switch (op) {
case SkRegion::kIntersect_Op:
if (!rStorage.intersect(rOrig, fBounds)) {
// no overlap, so we're empty
return this->setEmpty();
}
if (rStorage == fBounds) {
// we were wholly inside the rect, no change
return !this->isEmpty();
}
if (this->quickContains(rStorage)) {
// the intersection is wholly inside us, we're a rect
return this->setRect(rStorage);
}
r = &rStorage; // use the intersected bounds
break;
case SkRegion::kDifference_Op:
break;
case SkRegion::kUnion_Op:
if (rOrig.contains(fBounds)) {
return this->setRect(rOrig);
}
break;
default:
break;
}
SkAAClip clip;
clip.setRect(*r);
return this->op(*this, clip, op);
}
bool SkAAClip::op(const SkRect& rOrig, SkRegion::Op op, bool doAA) {
SkRect rStorage, boundsStorage;
const SkRect* r = &rOrig;
boundsStorage.set(fBounds);
switch (op) {
case SkRegion::kIntersect_Op:
case SkRegion::kDifference_Op:
if (!rStorage.intersect(rOrig, boundsStorage)) {
if (SkRegion::kIntersect_Op == op) {
return this->setEmpty();
} else { // kDifference
return !this->isEmpty();
}
}
r = &rStorage; // use the intersected bounds
break;
case SkRegion::kUnion_Op:
if (rOrig.contains(boundsStorage)) {
return this->setRect(rOrig);
}
break;
default:
break;
}
SkAAClip clip;
clip.setRect(*r, doAA);
return this->op(*this, clip, op);
}
bool SkAAClip::op(const SkAAClip& clip, SkRegion::Op op) {
return this->op(*this, clip, op);
}
///////////////////////////////////////////////////////////////////////////////
bool SkAAClip::translate(int dx, int dy, SkAAClip* dst) const {
if (nullptr == dst) {
return !this->isEmpty();
}
if (this->isEmpty()) {
return dst->setEmpty();
}
if (this != dst) {
sk_atomic_inc(&fRunHead->fRefCnt);
dst->freeRuns();
dst->fRunHead = fRunHead;
dst->fBounds = fBounds;
}
dst->fBounds.offset(dx, dy);
return true;
}
static void expand_row_to_mask(uint8_t* SK_RESTRICT mask,
const uint8_t* SK_RESTRICT row,
int width) {
while (width > 0) {
int n = row[0];
SkASSERT(width >= n);
memset(mask, row[1], n);
mask += n;
row += 2;
width -= n;
}
SkASSERT(0 == width);
}
void SkAAClip::copyToMask(SkMask* mask) const {
mask->fFormat = SkMask::kA8_Format;
if (this->isEmpty()) {
mask->fBounds.setEmpty();
mask->fImage = nullptr;
mask->fRowBytes = 0;
return;
}
mask->fBounds = fBounds;
mask->fRowBytes = fBounds.width();
size_t size = mask->computeImageSize();
mask->fImage = SkMask::AllocImage(size);
Iter iter(*this);
uint8_t* dst = mask->fImage;
const int width = fBounds.width();
int y = fBounds.fTop;
while (!iter.done()) {
do {
expand_row_to_mask(dst, iter.data(), width);
dst += mask->fRowBytes;
} while (++y < iter.bottom());
iter.next();
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
static void expandToRuns(const uint8_t* SK_RESTRICT data, int initialCount, int width,
int16_t* SK_RESTRICT runs, SkAlpha* SK_RESTRICT aa) {
// we don't read our initial n from data, since the caller may have had to
// clip it, hence the initialCount parameter.
int n = initialCount;
for (;;) {
if (n > width) {
n = width;
}
SkASSERT(n > 0);
runs[0] = n;
runs += n;
aa[0] = data[1];
aa += n;
data += 2;
width -= n;
if (0 == width) {
break;
}
// load the next count
n = data[0];
}
runs[0] = 0; // sentinel
}
SkAAClipBlitter::~SkAAClipBlitter() {
sk_free(fScanlineScratch);
}
void SkAAClipBlitter::ensureRunsAndAA() {
if (nullptr == fScanlineScratch) {
// add 1 so we can store the terminating run count of 0
int count = fAAClipBounds.width() + 1;
// we use this either for fRuns + fAA, or a scaline of a mask
// which may be as deep as 32bits
fScanlineScratch = sk_malloc_throw(count * sizeof(SkPMColor));
fRuns = (int16_t*)fScanlineScratch;
fAA = (SkAlpha*)(fRuns + count);
}
}
void SkAAClipBlitter::blitH(int x, int y, int width) {
SkASSERT(width > 0);
SkASSERT(fAAClipBounds.contains(x, y));
SkASSERT(fAAClipBounds.contains(x + width - 1, y));
const uint8_t* row = fAAClip->findRow(y);
int initialCount;
row = fAAClip->findX(row, x, &initialCount);
if (initialCount >= width) {
SkAlpha alpha = row[1];
if (0 == alpha) {
return;
}
if (0xFF == alpha) {
fBlitter->blitH(x, y, width);
return;
}
}
this->ensureRunsAndAA();
expandToRuns(row, initialCount, width, fRuns, fAA);
fBlitter->blitAntiH(x, y, fAA, fRuns);
}
static void merge(const uint8_t* SK_RESTRICT row, int rowN,
const SkAlpha* SK_RESTRICT srcAA,
const int16_t* SK_RESTRICT srcRuns,
SkAlpha* SK_RESTRICT dstAA,
int16_t* SK_RESTRICT dstRuns,
int width) {
SkDEBUGCODE(int accumulated = 0;)
int srcN = srcRuns[0];
// do we need this check?
if (0 == srcN) {
return;
}
for (;;) {
SkASSERT(rowN > 0);
SkASSERT(srcN > 0);
unsigned newAlpha = SkMulDiv255Round(srcAA[0], row[1]);
int minN = SkMin32(srcN, rowN);
dstRuns[0] = minN;
dstRuns += minN;
dstAA[0] = newAlpha;
dstAA += minN;
if (0 == (srcN -= minN)) {
srcN = srcRuns[0]; // refresh
srcRuns += srcN;
srcAA += srcN;
srcN = srcRuns[0]; // reload
if (0 == srcN) {
break;
}
}
if (0 == (rowN -= minN)) {
row += 2;
rowN = row[0]; // reload
}
SkDEBUGCODE(accumulated += minN;)
SkASSERT(accumulated <= width);
}
dstRuns[0] = 0;
}
void SkAAClipBlitter::blitAntiH(int x, int y, const SkAlpha aa[],
const int16_t runs[]) {
const uint8_t* row = fAAClip->findRow(y);
int initialCount;
row = fAAClip->findX(row, x, &initialCount);
this->ensureRunsAndAA();
merge(row, initialCount, aa, runs, fAA, fRuns, fAAClipBounds.width());
fBlitter->blitAntiH(x, y, fAA, fRuns);
}
void SkAAClipBlitter::blitV(int x, int y, int height, SkAlpha alpha) {
if (fAAClip->quickContains(x, y, x + 1, y + height)) {
fBlitter->blitV(x, y, height, alpha);
return;
}
for (;;) {
int lastY SK_INIT_TO_AVOID_WARNING;
const uint8_t* row = fAAClip->findRow(y, &lastY);
int dy = lastY - y + 1;
if (dy > height) {
dy = height;
}
height -= dy;
row = fAAClip->findX(row, x);
SkAlpha newAlpha = SkMulDiv255Round(alpha, row[1]);
if (newAlpha) {
fBlitter->blitV(x, y, dy, newAlpha);
}
SkASSERT(height >= 0);
if (height <= 0) {
break;
}
y = lastY + 1;
}
}
void SkAAClipBlitter::blitRect(int x, int y, int width, int height) {
if (fAAClip->quickContains(x, y, x + width, y + height)) {
fBlitter->blitRect(x, y, width, height);
return;
}
while (--height >= 0) {
this->blitH(x, y, width);
y += 1;
}
}
typedef void (*MergeAAProc)(const void* src, int width, const uint8_t* row,
int initialRowCount, void* dst);
static void small_memcpy(void* dst, const void* src, size_t n) {
memcpy(dst, src, n);
}
static void small_bzero(void* dst, size_t n) {
sk_bzero(dst, n);
}
static inline uint8_t mergeOne(uint8_t value, unsigned alpha) {
return SkMulDiv255Round(value, alpha);
}
static inline uint16_t mergeOne(uint16_t value, unsigned alpha) {
unsigned r = SkGetPackedR16(value);
unsigned g = SkGetPackedG16(value);
unsigned b = SkGetPackedB16(value);
return SkPackRGB16(SkMulDiv255Round(r, alpha),
SkMulDiv255Round(g, alpha),
SkMulDiv255Round(b, alpha));
}
template <typename T>
void mergeT(const void* inSrc, int srcN, const uint8_t* SK_RESTRICT row, int rowN, void* inDst) {
const T* SK_RESTRICT src = static_cast<const T*>(inSrc);
T* SK_RESTRICT dst = static_cast<T*>(inDst);
for (;;) {
SkASSERT(rowN > 0);
SkASSERT(srcN > 0);
int n = SkMin32(rowN, srcN);
unsigned rowA = row[1];
if (0xFF == rowA) {
small_memcpy(dst, src, n * sizeof(T));
} else if (0 == rowA) {
small_bzero(dst, n * sizeof(T));
} else {
for (int i = 0; i < n; ++i) {
dst[i] = mergeOne(src[i], rowA);
}
}
if (0 == (srcN -= n)) {
break;
}
src += n;
dst += n;
SkASSERT(rowN == n);
row += 2;
rowN = row[0];
}
}
static MergeAAProc find_merge_aa_proc(SkMask::Format format) {
switch (format) {
case SkMask::kBW_Format:
SkDEBUGFAIL("unsupported");
return nullptr;
case SkMask::kA8_Format:
case SkMask::k3D_Format:
return mergeT<uint8_t> ;
case SkMask::kLCD16_Format:
return mergeT<uint16_t>;
default:
SkDEBUGFAIL("unsupported");
return nullptr;
}
}
static U8CPU bit2byte(int bitInAByte) {
SkASSERT(bitInAByte <= 0xFF);
// negation turns any non-zero into 0xFFFFFF??, so we just shift down
// some value >= 8 to get a full FF value
return -bitInAByte >> 8;
}
static void upscaleBW2A8(SkMask* dstMask, const SkMask& srcMask) {
SkASSERT(SkMask::kBW_Format == srcMask.fFormat);
SkASSERT(SkMask::kA8_Format == dstMask->fFormat);
const int width = srcMask.fBounds.width();
const int height = srcMask.fBounds.height();
const uint8_t* SK_RESTRICT src = (const uint8_t*)srcMask.fImage;
const size_t srcRB = srcMask.fRowBytes;
uint8_t* SK_RESTRICT dst = (uint8_t*)dstMask->fImage;
const size_t dstRB = dstMask->fRowBytes;
const int wholeBytes = width >> 3;
const int leftOverBits = width & 7;
for (int y = 0; y < height; ++y) {
uint8_t* SK_RESTRICT d = dst;
for (int i = 0; i < wholeBytes; ++i) {
int srcByte = src[i];
d[0] = bit2byte(srcByte & (1 << 7));
d[1] = bit2byte(srcByte & (1 << 6));
d[2] = bit2byte(srcByte & (1 << 5));
d[3] = bit2byte(srcByte & (1 << 4));
d[4] = bit2byte(srcByte & (1 << 3));
d[5] = bit2byte(srcByte & (1 << 2));
d[6] = bit2byte(srcByte & (1 << 1));
d[7] = bit2byte(srcByte & (1 << 0));
d += 8;
}
if (leftOverBits) {
int srcByte = src[wholeBytes];
for (int x = 0; x < leftOverBits; ++x) {
*d++ = bit2byte(srcByte & 0x80);
srcByte <<= 1;
}
}
src += srcRB;
dst += dstRB;
}
}
void SkAAClipBlitter::blitMask(const SkMask& origMask, const SkIRect& clip) {
SkASSERT(fAAClip->getBounds().contains(clip));
if (fAAClip->quickContains(clip)) {
fBlitter->blitMask(origMask, clip);
return;
}
const SkMask* mask = &origMask;
// if we're BW, we need to upscale to A8 (ugh)
SkMask grayMask;
if (SkMask::kBW_Format == origMask.fFormat) {
grayMask.fFormat = SkMask::kA8_Format;
grayMask.fBounds = origMask.fBounds;
grayMask.fRowBytes = origMask.fBounds.width();
size_t size = grayMask.computeImageSize();
grayMask.fImage = (uint8_t*)fGrayMaskScratch.reset(size,
SkAutoMalloc::kReuse_OnShrink);
upscaleBW2A8(&grayMask, origMask);
mask = &grayMask;
}
this->ensureRunsAndAA();
// HACK -- we are devolving 3D into A8, need to copy the rest of the 3D
// data into a temp block to support it better (ugh)
const void* src = mask->getAddr(clip.fLeft, clip.fTop);
const size_t srcRB = mask->fRowBytes;
const int width = clip.width();
MergeAAProc mergeProc = find_merge_aa_proc(mask->fFormat);
SkMask rowMask;
rowMask.fFormat = SkMask::k3D_Format == mask->fFormat ? SkMask::kA8_Format : mask->fFormat;
rowMask.fBounds.fLeft = clip.fLeft;
rowMask.fBounds.fRight = clip.fRight;
rowMask.fRowBytes = mask->fRowBytes; // doesn't matter, since our height==1
rowMask.fImage = (uint8_t*)fScanlineScratch;
int y = clip.fTop;
const int stopY = y + clip.height();
do {
int localStopY SK_INIT_TO_AVOID_WARNING;
const uint8_t* row = fAAClip->findRow(y, &localStopY);
// findRow returns last Y, not stop, so we add 1
localStopY = SkMin32(localStopY + 1, stopY);
int initialCount;
row = fAAClip->findX(row, clip.fLeft, &initialCount);
do {
mergeProc(src, width, row, initialCount, rowMask.fImage);
rowMask.fBounds.fTop = y;
rowMask.fBounds.fBottom = y + 1;
fBlitter->blitMask(rowMask, rowMask.fBounds);
src = (const void*)((const char*)src + srcRB);
} while (++y < localStopY);
} while (y < stopY);
}
const SkPixmap* SkAAClipBlitter::justAnOpaqueColor(uint32_t* value) {
return nullptr;
}
|
//
// Copyright (c) 2019 Erwin Rol <erwin@erwinrol.com>
//
// SPDX-License-Identifier: Apache-2.0
//
#ifndef ZPP_INCLUDE_ZPP_POLL_EVENT_SET_HPP
#define ZPP_INCLUDE_ZPP_POLL_EVENT_SET_HPP
#ifdef CONFIG_POLL
#include <kernel.h>
#include <sys/__assert.h>
#include <chrono>
#include <limits>
#include <optional>
#include <array>
#include <utility>
#include <zpp/clock.hpp>
#include <zpp/sem.hpp>
#include <zpp/fifo.hpp>
#include <zpp/poll_event.hpp>
#include <zpp/poll_signal.hpp>
namespace zpp {
///
/// @brief A set of poll events
///
/// @param Size the size of the set
///
template<int T_Size>
class poll_event_set
{
public:
auto begin() noexcept { return m_events.begin(); }
auto end() noexcept { return m_events.end(); }
public:
///
/// @brief default constructor
///
poll_event_set() noexcept
{
}
///
/// @brief constructor that takes arguments for initialization
///
/// @param t the arguments to use for initialization
///
template <class... T_Args>
poll_event_set(T_Args&&... t) noexcept
{
assign(0, std::forward<T_Args>(t)...);
}
///
/// @brief access an element of the set
///
/// @param idx the index of the event to get
///
/// @return a poll_event that has a reference to the indexed event
///
auto operator[](size_t idx) noexcept
{
__ASSERT_NO_MSG(idx < T_Size);
return poll_event(&m_events[idx]);
}
///
/// @brief poll events waiting for ever
///
/// @return false on error
///
auto poll() noexcept
{
return poll(K_FOREVER);
}
///
/// @brief try poll events without waiting
///
/// @return false on error
///
auto try_poll() noexcept
{
return poll(K_NO_WAIT);
}
///
/// @brief try poll events waiting for e certain time
///
/// @param timeout the time to wait
///
/// @return false on error
///
template<class T_Rep, class T_Period>
auto try_poll_for(const std::chrono::duration<T_Rep, T_Period>&
timeout) noexcept
{
using namespace std::chrono;
return poll(to_timeout(timeout));
}
private:
///
/// @brief try poll events waiting for e certain time
///
/// @param timeout the time to wait
///
/// @return false on error
///
void assign(int index) noexcept
{
__ASSERT_NO_MSG(index == T_Size);
}
///
/// @brief try poll events waiting for e certain time
///
/// @param timeout the time to wait
///
/// @return false on error
///
template<class T_FirstArg, class... T_Args>
void assign(int index, T_FirstArg&& f, T_Args&&... t) noexcept
{
poll_event(&m_events[index]).assign(std::forward<T_FirstArg>(f));
assign(index+1, std::forward<T_Args>(t)...);
}
///
/// @brief try poll events waiting for e certain time
///
/// @param timeout the time to wait
///
/// @return false on error
///
auto poll(k_timeout_t timeout) noexcept
{
for (auto& e: m_events) {
e.state = K_POLL_STATE_NOT_READY;
if (e.tag == (int)poll_event::type_tag::type_signal) {
__ASSERT_NO_MSG(e.signal != nullptr);
e.signal->signaled = 0;
}
}
auto rc = k_poll(m_events.data(), m_events.size(), timeout);
if (rc == 0) {
return true;
} else {
return false;
}
}
private:
std::array<struct k_poll_event, T_Size> m_events;
};
///
/// @brief try poll events waiting for e certain time
///
/// @param timeout the time to wait
///
/// @return false on error
///
template <class... T_Args>
poll_event_set(T_Args&&... t) noexcept -> poll_event_set<sizeof...(T_Args)>;
} // namespace zpp
#endif // CONFIG_POLL
#endif // ZPP_INCLUDE_ZPP_POLL_EVENT_SET_HPP
|
#include <iostream>
using namespace std;
/*
* https://algo-logic.info/combination/
*/
const int MOD = 1000000007;
long long r_seq(long long x, long long p) {
if(p==0)
return 1;
if(p % 2 == 0) {
long long partial = r_seq(x, p/2);
return ((partial % MOD) * (partial % MOD)) % MOD;
}
long long a = r_seq(x, p-1) % MOD;
return ((x % MOD) * a) % MOD;
}
long long fact(long long start, long long end) {
long long temp = 1;
for (long long i= start;i<=end;i++) {
temp *= i;
temp %= MOD;
}
return temp % MOD;
}
long long qpow(long long a, long long b, long long res){ //a^b
while(b){
if(b & 1) res = res * a % MOD;
a = a * a % MOD;
b >>= 1;
}
return res;
};
long long getC(long long n, long long x) {
if (x > n) return 0;
long long res1 = 1, res2 = 1;
for (long long i = n; i >= n - x + 1; i--) res1 = res1 * i % MOD;
for (long long i = x; i >= 1; i--) res2 = res2 * i % MOD;
return res1 * qpow(res2, MOD - 2, 1) % MOD;
};
long long bouquet(long long n, int a, int b) {
long long all = (r_seq(2, n) - 1) % MOD;
long long nac = fact(n-a+1, n);
long long ac = fact(1, a);
long long comb_a = (nac * r_seq(ac, MOD-2)) % MOD;
long long nbc = fact(n-b+1, n);
long long bc = fact(1, b);
long long comb_b = (nbc * r_seq(bc, MOD-2)) % MOD;
long long sum = (comb_a + comb_b) % MOD;
return ((all - sum) % MOD + MOD) % MOD;
}
/*
int main() {
long long n;
int a, b;
cin >> n;
cin >> a;
cin >> b;
cout << bouquet(n, a, b);
}
*/
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/mediastore-data/model/ListItemsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/http/URI.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::MediaStoreData::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws::Http;
ListItemsRequest::ListItemsRequest() :
m_pathHasBeenSet(false),
m_maxResults(0),
m_maxResultsHasBeenSet(false),
m_nextTokenHasBeenSet(false)
{
}
Aws::String ListItemsRequest::SerializePayload() const
{
return {};
}
void ListItemsRequest::AddQueryStringParameters(URI& uri) const
{
Aws::StringStream ss;
if(m_pathHasBeenSet)
{
ss << m_path;
uri.AddQueryStringParameter("Path", ss.str());
ss.str("");
}
if(m_maxResultsHasBeenSet)
{
ss << m_maxResults;
uri.AddQueryStringParameter("MaxResults", ss.str());
ss.str("");
}
if(m_nextTokenHasBeenSet)
{
ss << m_nextToken;
uri.AddQueryStringParameter("NextToken", ss.str());
ss.str("");
}
}
|
#include "image/ImageHeader.h"
#include "image/ImageUtility.h"
#include "common/Exception.hpp"
#include "common/MathFuncs.h"
#include <glm/glm.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/string_cast.hpp>
#include <spdlog/spdlog.h>
ImageHeader::ImageHeader( const ImageIoInfo& ioInfoOnDisk, const ImageIoInfo& ioInfoInMemory )
:
m_existsOnDisk( true ),
m_fileName( ioInfoOnDisk.m_fileInfo.m_fileName ),
m_numComponentsPerPixel( ioInfoOnDisk.m_pixelInfo.m_numComponents ),
m_numPixels( ioInfoOnDisk.m_sizeInfo.m_imageSizeInPixels ),
m_fileImageSizeInBytes( ioInfoOnDisk.m_sizeInfo.m_imageSizeInBytes ),
m_memoryImageSizeInBytes( ioInfoInMemory.m_sizeInfo.m_imageSizeInBytes ),
m_pixelType( fromItkPixelType( ioInfoOnDisk.m_pixelInfo.m_pixelType ) ),
m_pixelTypeAsString( ioInfoOnDisk.m_pixelInfo.m_pixelTypeString ),
m_fileComponentType( fromItkComponentType( ioInfoOnDisk.m_componentInfo.m_componentType ) ),
m_fileComponentTypeAsString( ioInfoOnDisk.m_componentInfo.m_componentTypeString ),
m_fileComponentSizeInBytes( ioInfoOnDisk.m_componentInfo.m_componentSizeInBytes ),
m_memoryComponentType( fromItkComponentType( ioInfoInMemory.m_componentInfo.m_componentType ) ),
m_memoryComponentTypeAsString( ioInfoInMemory.m_componentInfo.m_componentTypeString ),
m_memoryComponentSizeInBytes( ioInfoInMemory.m_componentInfo.m_componentSizeInBytes )
{
if ( ComponentType::Undefined == m_memoryComponentType )
{
spdlog::error( "Cannot set header for image {} with undefined component type",
ioInfoInMemory.m_fileInfo.m_fileName );
throw_debug( "Undefined component type" )
}
else if ( PixelType::Undefined == m_pixelType )
{
spdlog::error( "Cannot set header for image {} with undefined pixel type",
ioInfoInMemory.m_fileInfo.m_fileName );
throw_debug( "undefined pixel type" )
}
setSpace( ioInfoInMemory );
std::tie( m_spiralCode, m_isOblique ) = math::computeSpiralCodeFromDirectionMatrix( m_directions );
}
void ImageHeader::setSpace( const ImageIoInfo& ioInfo )
{
const uint32_t numDim = ioInfo.m_spaceInfo.m_numDimensions;
std::vector<size_t> dims = ioInfo.m_spaceInfo.m_dimensions;
std::vector<double> orig = ioInfo.m_spaceInfo.m_origin;
std::vector<double> space = ioInfo.m_spaceInfo.m_spacing;
std::vector< std::vector<double> > dirs = ioInfo.m_spaceInfo.m_directions;
// Expect a 3D image
if ( numDim != 3 || orig.size() != 3 || space.size() != 3 || dims.size() != 3 || dirs.size() != 3 )
{
spdlog::debug( "Vector sizes: numDims = {}, origin = {}, spacing = {}, dims = {}, directions = {}",
numDim, orig.size(), space.size(), dims.size(), dirs.size() );
if ( numDim == 2 && orig.size() == 2 && space.size() == 2 && dims.size() == 2 && dirs.size() == 4 )
{
// The image is 2D: augment to 3D
orig.push_back( 0.0 );
space.push_back( 1.0 );
dims.push_back( 1 );
std::vector< std::vector<double> > d3x3( 3 );
d3x3[0].resize( 3 );
d3x3[1].resize( 3 );
d3x3[2].resize( 3 );
d3x3[0][0] = dirs[0][0]; d3x3[0][1] = dirs[0][1]; d3x3[0][2] = 0.0;
d3x3[1][0] = dirs[1][0]; d3x3[1][1] = dirs[1][1]; d3x3[1][2] = 0.0;
d3x3[2][0] = 0.0; d3x3[2][1] = 0.0; d3x3[2][2] = 1.0;
dirs = std::move( d3x3 );
}
else
{
throw_debug( "Image must have dimension of 2 or 3" )
}
}
m_pixelDimensions = glm::uvec3{ dims[0], dims[1], dims[2] };
m_spacing = glm::vec3{ space[0], space[1], space[2] };
m_origin = glm::vec3{ orig[0], orig[1], orig[2] };
// Set matrix of direction vectors in column-major order
m_directions = glm::mat3{ dirs[0][0], dirs[0][1], dirs[0][2],
dirs[1][0], dirs[1][1], dirs[1][2],
dirs[2][0], dirs[2][1], dirs[2][2] };
setBoundingBox();
}
void ImageHeader::setBoundingBox()
{
m_pixelBBoxCorners = math::computeImagePixelAABBoxCorners( m_pixelDimensions );
m_subjectBBoxCorners = math::computeImageSubjectBoundingBoxCorners(
m_pixelDimensions, m_directions, m_spacing, m_origin );
m_subjectMinMaxAABBoxCorners = math::computeMinMaxCornersOfAABBox( m_subjectBBoxCorners );
m_subjectBBoxSize = glm::vec3{
m_spacing.x * m_pixelDimensions.x,
m_spacing.y * m_pixelDimensions.y,
m_spacing.z * m_pixelDimensions.z };
m_subjectBBoxCenter = glm::vec3{ 0.0f, 0.0f, 0.0f };
for ( const auto& p : m_subjectBBoxCorners )
{
m_subjectBBoxCenter += p;
}
m_subjectBBoxCenter /= m_subjectBBoxCorners.size();
}
void ImageHeader::adjustToScalarUCharFormat()
{
m_numComponentsPerPixel = 1;
m_pixelType = PixelType::Scalar;
m_pixelTypeAsString = "scalar";
m_fileComponentType = ComponentType::UInt8;
m_fileComponentTypeAsString = "uchar";
m_fileComponentSizeInBytes = 1;
m_memoryComponentType = ComponentType::UInt8;
m_memoryComponentTypeAsString = "uchar";
m_memoryComponentSizeInBytes = 1;
m_fileImageSizeInBytes = m_fileComponentSizeInBytes * m_numComponentsPerPixel * m_numPixels;
m_memoryImageSizeInBytes = m_memoryComponentSizeInBytes * m_numComponentsPerPixel * m_numPixels;
}
bool ImageHeader::existsOnDisk() const { return m_existsOnDisk; }
void ImageHeader::setExistsOnDisk( bool onDisk ) { m_existsOnDisk = onDisk; }
const std::string& ImageHeader::fileName() const { return m_fileName; }
void ImageHeader::setFileName( std::string fileName ) { m_fileName = std::move( fileName ); }
uint32_t ImageHeader::numComponentsPerPixel() const { return m_numComponentsPerPixel; }
uint64_t ImageHeader::numPixels() const { return m_numPixels; }
uint64_t ImageHeader::fileImageSizeInBytes() const { return m_fileImageSizeInBytes; }
uint64_t ImageHeader::memoryImageSizeInBytes() const { return m_memoryImageSizeInBytes; }
PixelType ImageHeader::pixelType() const { return m_pixelType; }
std::string ImageHeader::pixelTypeAsString() const { return m_pixelTypeAsString; }
ComponentType ImageHeader::fileComponentType() const { return m_fileComponentType; }
std::string ImageHeader::fileComponentTypeAsString() const { return m_fileComponentTypeAsString; }
uint32_t ImageHeader::fileComponentSizeInBytes() const { return m_fileComponentSizeInBytes; }
ComponentType ImageHeader::memoryComponentType() const { return m_memoryComponentType; }
std::string ImageHeader::memoryComponentTypeAsString() const { return m_memoryComponentTypeAsString; }
uint32_t ImageHeader::memoryComponentSizeInBytes() const { return m_memoryComponentSizeInBytes; }
const glm::uvec3& ImageHeader::pixelDimensions() const { return m_pixelDimensions; }
const glm::vec3& ImageHeader::origin() const { return m_origin; }
const glm::vec3& ImageHeader::spacing() const { return m_spacing; }
const glm::mat3& ImageHeader::directions() const { return m_directions; }
const std::array< glm::vec3, 8 >& ImageHeader::pixelBBoxCorners() const { return m_pixelBBoxCorners; }
const std::array< glm::vec3, 8 >& ImageHeader::subjectBBoxCorners() const { return m_subjectBBoxCorners; }
const std::pair< glm::vec3, glm::vec3 >& ImageHeader::subjectAABboxMinMaxCorners() const { return m_subjectMinMaxAABBoxCorners; }
const glm::vec3& ImageHeader::subjectBBoxCenter() const { return m_subjectBBoxCenter; }
const glm::vec3& ImageHeader::subjectBBoxSize() const { return m_subjectBBoxSize; }
const std::string& ImageHeader::spiralCode() const { return m_spiralCode; }
bool ImageHeader::isOblique() const { return m_isOblique; }
std::ostream& operator<< ( std::ostream& os, const ImageHeader& header )
{
os << "Exists on disk: " << std::boolalpha << header.m_existsOnDisk
<< "\nFile name: " << header.m_fileName
<< "\nPixel type: " << header.m_pixelTypeAsString
<< "\nNum. components per pixel: " << header.m_numComponentsPerPixel
<< "\n\nComponent type (disk): " << header.m_fileComponentTypeAsString
<< "\nComponent size (bytes, disk): " << header.m_fileComponentSizeInBytes
<< "\nComponent type (memory): " << header.m_memoryComponentTypeAsString
<< "\nComponent size (bytes, memory): " << header.m_memoryComponentSizeInBytes
<< "\n\nImage size (pixels): " << header.m_numPixels
<< "\nImage size (bytes, disk): " << header.m_fileImageSizeInBytes
<< "\nImage size (bytes, memory): " << header.m_memoryImageSizeInBytes
<< "\n\nDimensions (pixels): " << glm::to_string( header.m_pixelDimensions )
<< "\nOrigin (mm): " << glm::to_string( header.m_origin )
<< "\nSpacing (mm): " << glm::to_string( header.m_spacing )
<< "\nDirections: " << glm::to_string( header.m_directions )
<< "\n\nBounding box (in Subject space):"
<< "\n\tMin/max corners (mm): " << glm::to_string( header.m_subjectMinMaxAABBoxCorners.first ) << ", "
<< glm::to_string( header.m_subjectMinMaxAABBoxCorners.second )
<< "\n\tBox center (mm): " << glm::to_string( header.m_subjectBBoxCenter )
<< "\n\tBox size (mm): " << glm::to_string( header.m_subjectBBoxSize )
<< "\n\nSPIRAL code: " << header.m_spiralCode
<< "\nIs oblique: " << std::boolalpha << header.m_isOblique;
return os;
}
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/allocator/partition_allocator/partition_alloc.h"
#include <string.h>
#include <memory>
#include "base/allocator/partition_allocator/address_pool_manager.h"
#include "base/allocator/partition_allocator/checked_ptr_support.h"
#include "base/allocator/partition_allocator/memory_reclaimer.h"
#include "base/allocator/partition_allocator/page_allocator_internal.h"
#include "base/allocator/partition_allocator/partition_address_space.h"
#include "base/allocator/partition_allocator/partition_alloc_features.h"
#include "base/allocator/partition_allocator/partition_alloc_hooks.h"
#include "base/allocator/partition_allocator/partition_direct_map_extent.h"
#include "base/allocator/partition_allocator/partition_oom.h"
#include "base/allocator/partition_allocator/partition_page.h"
#include "base/allocator/partition_allocator/partition_root.h"
#include "base/allocator/partition_allocator/partition_stats.h"
#include "base/allocator/partition_allocator/pcscan.h"
namespace base {
void PartitionAllocGlobalInit(OomFunction on_out_of_memory) {
// This is from page_allocator_constants.h and doesn't really fit here, but
// there isn't a centralized initialization function in page_allocator.cc, so
// there's no good place in that file to do a STATIC_ASSERT_OR_PA_CHECK.
STATIC_ASSERT_OR_PA_CHECK((SystemPageSize() & (SystemPageSize() - 1)) == 0,
"SystemPageSize() must be power of 2");
// Two partition pages are used as guard / metadata page so make sure the
// super page size is bigger.
STATIC_ASSERT_OR_PA_CHECK(PartitionPageSize() * 4 <= kSuperPageSize,
"ok super page size");
STATIC_ASSERT_OR_PA_CHECK(!(kSuperPageSize % PartitionPageSize()),
"ok super page multiple");
// Four system pages gives us room to hack out a still-guard-paged piece
// of metadata in the middle of a guard partition page.
STATIC_ASSERT_OR_PA_CHECK(SystemPageSize() * 4 <= PartitionPageSize(),
"ok partition page size");
STATIC_ASSERT_OR_PA_CHECK(!(PartitionPageSize() % SystemPageSize()),
"ok partition page multiple");
static_assert(sizeof(internal::PartitionPage<internal::ThreadSafe>) <=
kPageMetadataSize,
"PartitionPage should not be too big");
STATIC_ASSERT_OR_PA_CHECK(
kPageMetadataSize * NumPartitionPagesPerSuperPage() <= SystemPageSize(),
"page metadata fits in hole");
// Limit to prevent callers accidentally overflowing an int size.
STATIC_ASSERT_OR_PA_CHECK(
MaxDirectMapped() <= (1UL << 31) + PageAllocationGranularity(),
"maximum direct mapped allocation");
// Check that some of our zanier calculations worked out as expected.
static_assert(kSmallestBucket == kAlignment, "generic smallest bucket");
static_assert(kMaxBucketed == 983040, "generic max bucketed");
STATIC_ASSERT_OR_PA_CHECK(
MaxSystemPagesPerSlotSpan() < (1 << 8),
"System pages per slot span must be less than 128.");
PA_DCHECK(on_out_of_memory);
internal::g_oom_handling_function = on_out_of_memory;
}
void PartitionAllocGlobalUninitForTesting() {
#if !BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
if (features::IsPartitionAllocGigaCageEnabled()) {
#if defined(PA_HAS_64_BITS_POINTERS)
internal::PartitionAddressSpace::UninitForTesting();
#else
internal::AddressPoolManager::GetInstance()->ResetForTesting();
#endif // defined(PA_HAS_64_BITS_POINTERS)
}
#endif // !BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
internal::PCScan<internal::ThreadSafe>::Instance()
.ClearRootsForTesting(); // IN-TEST
internal::g_oom_handling_function = nullptr;
}
namespace internal {
template <bool thread_safe>
PartitionAllocator<thread_safe>::~PartitionAllocator() {
PartitionAllocMemoryReclaimer::Instance()->UnregisterPartition(
&partition_root_);
}
template <bool thread_safe>
void PartitionAllocator<thread_safe>::init(PartitionOptions opts) {
#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
PA_CHECK(opts.thread_cache == PartitionOptions::ThreadCache::kDisabled)
<< "Cannot use a thread cache when PartitionAlloc is malloc().";
#endif
partition_root_.Init(opts);
PartitionAllocMemoryReclaimer::Instance()->RegisterPartition(
&partition_root_);
}
template PartitionAllocator<internal::ThreadSafe>::~PartitionAllocator();
template void PartitionAllocator<internal::ThreadSafe>::init(PartitionOptions);
template PartitionAllocator<internal::NotThreadSafe>::~PartitionAllocator();
template void PartitionAllocator<internal::NotThreadSafe>::init(
PartitionOptions);
#if DCHECK_IS_ON()
void DCheckGetSlotOffsetIsZero(void* ptr) {
PA_DCHECK(PartitionAllocGetSlotOffset(ptr) == 0);
}
#endif
} // namespace internal
} // namespace base
|
#include <Engine_pch.h>
// The contents can only be accessed on a Win32 platform.
// If it is not present than just compile it out.
#if defined (IE_PLATFORM_BUILD_WIN32)
#include "Console_Window.h"
namespace Insight {
ConsoleWindow::ConsoleWindow()
{
Init();
}
ConsoleWindow::~ConsoleWindow()
{
Shutdown();
}
bool ConsoleWindow::Init(int bufferLines, int bufferColumns, int windowLines, int windowColumns)
{
// Our temp console info struct
CONSOLE_SCREEN_BUFFER_INFO coninfo;
// Get the console info and set the number of lines
AllocConsole();
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
coninfo.dwSize.Y = bufferLines;
coninfo.dwSize.X = bufferColumns;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
SMALL_RECT rect;
rect.Left = 0;
rect.Top = 0;
rect.Right = windowColumns;
rect.Bottom = windowLines;
SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &rect);
FILE *stream;
freopen_s(&stream, "CONIN$", "r", stdin);
freopen_s(&stream, "CONOUT$", "w", stdout);
freopen_s(&stream, "CONOUT$", "w", stderr);
// Prevent accidental console window close
m_WindowHandle = GetConsoleWindow();
m_WindowHMenu = GetSystemMenu(m_WindowHandle, FALSE);
EnableMenuItem(m_WindowHMenu, SC_CLOSE, MF_GRAYED);
return true;
}
void ConsoleWindow::Shutdown()
{
DestroyWindow(m_WindowHandle);
DestroyMenu(m_WindowHMenu);
}
}
#endif // IE_PLATFORM_BUILD_WIN32
|
#include "EditorModelDebug.h"
#include "../Container/Ptr.h"
#include "../Core/Context.h"
#include "../Graphics/Batch.h"
#include "../Graphics/Camera.h"
#include "../Graphics/DebugRenderer.h"
#include "../Graphics/Drawable.h"
#include "../Graphics/Geometry.h"
#include "../Graphics/Graphics.h"
#include "../Graphics/IndexBuffer.h"
#include "../Graphics/Model.h"
#include "../Graphics/OcclusionBuffer.h"
#include "../Graphics/OctreeQuery.h"
#include "../Graphics/StaticModel.h"
#include "../Graphics/Texture2D.h"
#include "../Graphics/VertexBuffer.h"
#include "../IO/File.h"
#include "../IO/FileSystem.h"
#include "../IO/Log.h"
#include "../Resource/Image.h"
#include "../Resource/ResourceCache.h"
#include "../Resource/ResourceEvents.h"
#include "../Scene/Scene.h"
namespace Urho3D
{
enum ClipMask : unsigned
{
CLIPMASK_X_POS = 0x1,
CLIPMASK_X_NEG = 0x2,
CLIPMASK_Y_POS = 0x4,
CLIPMASK_Y_NEG = 0x8,
CLIPMASK_Z_POS = 0x10,
CLIPMASK_Z_NEG = 0x20,
};
URHO3D_FLAGSET(ClipMask, ClipMaskFlags);
extern const char* GEOMETRY_CATEGORY;
static float cubeVertices[] = {
// front
-1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
// back
-1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0};
static short cubeIndex[] = {
// front
0, 1, 2, 2, 3, 0,
// right
1, 5, 6, 6, 2, 1,
// back
7, 6, 5, 5, 4, 7,
// left
4, 0, 3, 3, 7, 4,
// bottom
4, 5, 1, 1, 0, 4,
// top
3, 2, 6, 6, 7, 3};
static const VertexCollisionMask DEFAULT_VERTEX_COLLISION_MASK_TYPE = TRACK_ROAD;
static const char* VertexCollisionMaskNames[] = {"None", "Track Road", "Track Border",
"Offtrack Weak", "Offtrack Heavy", nullptr};
EditorModelDebug::EditorModelDebug(Context* context)
: Drawable(context, DRAWABLE_GEOMETRY)
, geometry_(new Geometry(context))
, geometryFaces_(new Geometry(context))
, vertexBuffer_(new VertexBuffer(context))
, indexBuffer_(new IndexBuffer(context))
, vertexBufferFaces_(new VertexBuffer(context))
, indexBufferFaces_(new IndexBuffer(context))
, vertexMaskType_(TRACK_ROAD)
, vertexScale_(0.01f)
, currentFace_(0)
, currentIndex_(IntVector3::ZERO)
, texture_(nullptr)
, img_(nullptr)
, imgData_(nullptr)
, brushColor_(1.0f, 0.0f, 0.0f, 1.0f)
, brushSize_(100)
, lastUVPoint_(-1, -1)
{
geometry_->SetVertexBuffer(0, vertexBuffer_);
geometry_->SetIndexBuffer(indexBuffer_);
geometryFaces_->SetVertexBuffer(0, vertexBufferFaces_);
geometryFaces_->SetIndexBuffer(indexBufferFaces_);
batches_.Resize(2);
// original model vertices
// batches_[0].geometry_ = geometry_;
// batches_[0].geometryType_ = GEOM_INSTANCED;
// debug triangle info and world's transform for each vertices
// batches_[1].geometry_ = geometryFaces_;
// batches_[1].geometryType_ = GEOM_INSTANCED;
}
EditorModelDebug::~EditorModelDebug()
{
free(imgData_);
if (batches_.Size() && batches_[0].instancingData_)
delete batches_[0].instancingData_;
if (batches_.Size() > 1 && batches_[1].instancingData_)
delete batches_[1].instancingData_;
}
void EditorModelDebug::RegisterObject(Context* context)
{
context->RegisterFactory<EditorModelDebug>(GEOMETRY_CATEGORY);
URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
URHO3D_ENUM_ATTRIBUTE("Vertex Mask Type", vertexMaskType_, VertexCollisionMaskNames,
DEFAULT_VERTEX_COLLISION_MASK_TYPE, AM_DEFAULT);
URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef,
ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
}
void EditorModelDebug::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
{
// If no bones or no bone-level testing, use the Drawable test
RayQueryLevel level = query.level_;
if (level < RAY_AABB)
{
Drawable::ProcessRayQuery(query, results);
return;
}
// Check ray hit distance to AABB before proceeding with more accurate tests
// GetWorldBoundingBox() updates the world transforms
if (query.ray_.HitDistance(GetWorldBoundingBox()) >= query.maxDistance_)
return;
for (unsigned i = 0; i < numWorldTransforms_; ++i)
{
// Initial test using AABB
const Matrix3x4& transform = worldTransforms_[i];
BoundingBox transformedBoundingBox = boundingBox_.Transformed(transform);
float distance = query.ray_.HitDistance(transformedBoundingBox);
Vector3 normal = -query.ray_.direction_;
unsigned subObjectElementIndex = M_MAX_UNSIGNED;
// Then proceed to OBB and triangle-level tests if necessary
if (level >= RAY_OBB && distance < query.maxDistance_)
{
float distance2 = query.ray_.HitDistance(boundingBox_.Transformed(transform));
Matrix3x4 inverse = worldTransforms_[i].Inverse();
Ray localRay = query.ray_.Transformed(inverse);
distance = localRay.HitDistance(boundingBox_);
if (level == RAY_TRIANGLE && distance < query.maxDistance_)
{
distance = M_INFINITY;
for (unsigned j = 0; j < batches_.Size(); ++j)
{
Geometry* geometry = batches_[j].geometry_;
if (geometry)
{
Vector3 geometryNormal;
float geometryDistance =
geometry->GetHitDistance(localRay, subObjectElementIndex, &geometryNormal);
if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
{
distance = geometryDistance;
normal = (worldTransforms_[i] * Vector4(geometryNormal, 0.0f)).Normalized();
}
}
}
}
}
if (distance < query.maxDistance_)
{
RayQueryResult result;
result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
result.normal_ = normal;
result.distance_ = distance;
result.drawable_ = this;
result.node_ = node_;
result.subObject_ = i;
result.subObjectElementIndex_ = subObjectElementIndex;
results.Push(result);
}
}
}
void EditorModelDebug::UpdateBatches(const FrameInfo& frame)
{
unsigned offset = 0;
unsigned char* instanceData = static_cast<unsigned char*>(batches_[0].instancingData_);
Color color(Color::GREEN);
const Matrix3x4* worldTransform = node_ ? &node_->GetWorldTransform() : nullptr;
for (unsigned i = 0; i < numWorldTransforms_; i++)
{
// transform
Matrix3x4 transform(Matrix3x4::IDENTITY);
transform.SetTranslation(*worldTransform * vertexOffset_[i]);
worldTransforms_[i] = transform;
// color
memcpy(instanceData + offset, color.ToVector4().Data(), sizeof(Vector4));
offset += sizeof(Vector4);
}
color = Color::RED;
for (unsigned i = 0; i < selectedIndex_.Size(); i++)
{
int s = selectedIndex_[i];
memcpy(instanceData + s * sizeof(Vector4), color.ToVector4().Data(), sizeof(Vector4));
}
// CalcMatrixFaces();
UpdateFacesColor();
// offset = 0;
// unsigned char* instanceDataFaces = static_cast<unsigned char*>(batches_[1].instancingData_);
// for(unsigned i = 0; i < numWorldTransformsFaces_; i++)
// {
// Matrix3x4 transform(Matrix3x4::IDENTITY);
// transform.SetTranslation(Vector3(0.0f, 0.5f, 0.0f));
// // Matrix4 tt = worldTransform->ToMatrix4().Transpose() *
// worldTransformsFaces_[i].ToMatrix4().Transpose();
// // transform = Matrix3x4(tt);
// // worldTransformsFaces_[i] = worldTransformsFaces_[i] * *worldTransform;
// // worldTransformsFaces_[i].SetTranslation(Vector3(0.0f, 1.0f, 0.0f));
// }
}
void EditorModelDebug::UpdateGeometry(const FrameInfo& frame)
{
URHO3D_LOGERRORF("editordebug applyattr: <%u>", vertexMaskType_);
}
void EditorModelDebug::ApplyAttributes() { URHO3D_LOGERRORF("editordebug applyattr: <%u>", vertexMaskType_); }
void EditorModelDebug::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
{
Serializable::OnSetAttribute(attr, src);
if (attr.name_ == "Vertex Mask Type")
{
// switch (src.GetInt()) {
// case 0: vertexMaskType_ = NONE; break;
// case 1: vertexMaskType_ = TRACK_ROAD; break;
// case 2: vertexMaskType_ = TRACK_BORDER; break;
// case 3: vertexMaskType_ = OFFTRACK_WEAK; break;
// case 4: vertexMaskType_ = OFFTRACK_HEAVY; break;
// }
// if(src.GetInt())
// vertexMaskType_ = (VertexCollisionMask) (1 << (src.GetInt() - 1));
// else
// vertexMaskType_ = NONE;
}
// char b[16];
// sprintf(b, "%#010x", vertexMaskType_);
// URHO3D_LOGERRORF("editordebug attrset: <%s>", b);
// URHO3D_LOGERRORF("editordebug attrset: name <%s> value <%i>", attr.name_.CString(), src.GetInt());
selectedFaces_.Clear();
selectedIndex_.Clear();
selectedFacesIndex_.Clear();
}
void EditorModelDebug::SetModelAttr(const ResourceRef& value)
{
auto* cache = GetSubsystem<ResourceCache>();
SetModel(cache->GetResource<Model>(value.name_));
}
ResourceRef EditorModelDebug::GetModelAttr() const { return GetResourceRef(model_, Model::GetTypeStatic()); }
unsigned EditorModelDebug::GetFacesCount() const
{
const Vector<SharedPtr<IndexBuffer>>& ib = model_->GetIndexBuffers();
IndexBuffer* indexBuffer = ib.At(0);
unsigned count = indexBuffer->GetIndexCount();
return count / 3;
}
void EditorModelDebug::SetModel(Model* model)
{
if (model == model_)
return;
if (!node_)
{
URHO3D_LOGERROR("Can not set model while model component is not attached to a scene node");
return;
}
ResourceCache* cache = GetSubsystem<ResourceCache>();
if (model_)
UnsubscribeFromEvent(model_, E_RELOADFINISHED);
model_ = model;
StaticModel* staticModel = node_->GetComponent<StaticModel>();
if (staticModel)
{
Material* mat = staticModel->GetMaterial();
if (mat)
{
texture_ = (Texture2D*)mat->GetTexture(TU_DIFFUSE);
if (texture_)
{
// SharedPtr<Image> testImg = texture_->GetImage();
// testImg->SavePNG(GetSubsystem<FileSystem>()->GetProgramDir() + "Data/Screenshot_" +
// Time::GetTimeStamp().Replaced(':', '_').Replaced('.', '_').Replaced(' ', '_') + ".png");
img_ = cache->GetResource<Image>(texture_->GetName());
imgAux_ = cache->GetResource<Image>(texture_->GetName());
unsigned imgSize = img_->GetWidth() * img_->GetHeight() * sizeof(unsigned);
imgData_ = (unsigned*)malloc(imgSize);
memset(imgData_, 0, imgSize);
memcpy(imgData_, img_->GetData(), imgSize);
// URHO3D_LOGERRORF("EditorModelDebug::SetModel: model <%s> pointer_img <%p> size <%u>",
// model_->GetName().CString(), imgData_, imgSize);
}
}
}
if (model)
{
SubscribeToEvent(model, E_RELOADFINISHED, URHO3D_HANDLER(EditorModelDebug, HandleModelReloadFinished));
CreateVertexInstances();
CreateFaceInstances();
SetMaterial(cache->GetResource<Material>("Materials/plane-collision.xml"));
}
}
void EditorModelDebug::SetMaterial(Material* material)
{
batches_[0].material_ = material;
batches_[1].material_ = material;
}
void EditorModelDebug::SetBoundingBox(const BoundingBox& box)
{
boundingBox_ = box;
OnMarkedDirty(node_);
}
void EditorModelDebug::SelectVertex(const Frustum& frustum)
{
// selectedIndex_.Clear();
for (unsigned i = 0; i < numWorldTransforms_; ++i)
{
// Initial test using AABB
const Matrix3x4& transform = worldTransforms_[i];
BoundingBox transformedBoundingBox = boundingBox_.Transformed(transform);
if (frustum.IsInside(transformedBoundingBox) > INTERSECTS)
{
if (!selectedIndex_.Contains(i))
{
selectedIndex_.Push(i);
}
}
}
}
void EditorModelDebug::SelectFaces(const PODVector<IntVector2>& faces) { selectedFaces_ = faces; }
void EditorModelDebug::AddSelectedFaces(const PODVector<IntVector2>& faces, const PODVector<Vector2>& texUV, bool end)
{
selectedFaces_.Clear();
for (unsigned i = 0; i < faces.Size(); i++)
{
if (!selectedFaces_.Contains(faces[i]))
{
selectedFaces_.Push(faces[i]);
}
}
UpdateFacesIndexes();
// ApplyVertexCollisionMask();
ApplyVertexUV(texUV);
if (end)
{
unsigned imgSize = img_->GetWidth() * img_->GetHeight() * sizeof(unsigned);
memset(imgData_, 0, imgSize);
memcpy(imgData_, imgAux_->GetData(), imgSize);
}
// DebugList(selectedFaces_);
}
void EditorModelDebug::AddPointUV(const IntVector2& screenPosition, const Vector2& texUV, Image* image, bool end)
{
int texWidth = texture_->GetLevelWidth(0);
int texHeight = texture_->GetLevelHeight(0);
int x = static_cast<int>(texUV.x_ * texWidth);
int y = static_cast<int>(texUV.y_ * texHeight);
// first
if (lastUVPoint_.x_ == -1 && lastUVPoint_.y_ == -1)
{
lastUVPoint_ = IntVector2(x, y);
lastScreenPoint_ = screenPosition;
return;
}
else
{
// draw over texture
// int scale = 2;
// unsigned color = Color::YELLOW.ToUInt();
// DrawLine2(lastScreenPoint_ / scale, screenPosition / scale, image, color);
// Vector2 dif = Vector2(screenPosition) - Vector2(lastScreenPoint_);
Vector2 dif = Vector2(x, y) - Vector2(lastUVPoint_);
Vector2 lastScreenPoint;
// URHO3D_LOGERRORF("EditorModelDebug::AddPointUV: last <%s> curr <%s> ver <%i>", lastUVPoint_.ToString().CString(), Vector2(x, y).ToString().CString(), vertices_.Size());
DrawLine(lastUVPoint_, IntVector2(x, y));
int iter = 5;
float step = 1.0f / iter;
for (unsigned i = 0; i < (unsigned)iter; i++)
{
float p = step * i;
Vector2 pos = dif * p + Vector2(lastUVPoint_);
// URHO3D_LOGERRORF("EditorModelDebug::AddPointUV: step <%f> pos <%f, %f>", p, pos.x_, pos.y_);
// DrawLine(IntVector2(lastScreenPoint.x_, lastScreenPoint_.y_), IntVector2(pos.x_, pos.y_));
// si el punto esta en algun triangulo marcar
// ese triangulo para dibujar
// unsigned index = FindTriangleIndex(pos);
// if (index > -1)
// {
// Vector2 v0 = uvs_.At(k + u);
// // Vector2 v1 = uvs_.At(k + 1);
// // Vector2 v2 = uvs_.At(k + 2);
// int xx = texWidth * v0.x_;
// int yy = texHeight * v0.y_;
// URHO3D_LOGERRORF("EditorModelDebug::AddPointUV: uv <%f, %f> pos <%i, %i>", v0.x_, v0.y_, xx, yy);
// DrawPoint(xx, yy, img_, Color::CYAN.ToUInt());
// }
// DrawPoint((pos.x_ / scale), (pos.y_ / scale), image, color);
lastScreenPoint = pos;
}
lastUVPoint_ = end ? IntVector2(-1, -1) : IntVector2(x, y);
// texture_->SetData(0, 0, 0, texWidth, texHeight, img_->GetData());
// for (unsigned i = 0; i < 9; i++)
// {
// int x = (i % 3) - 1;
// int y = (i / 3) - 1;
// image->SetPixel((screenPosition.x_ / scale) + x, (screenPosition.y_ / scale) + y, Color::GREEN);
// }
lastScreenPoint_ = end ? IntVector2(-1, -1) : screenPosition;
}
}
unsigned EditorModelDebug::FindTriangleIndex(const Vector2& pos)
{
bool inside = false;
for (unsigned k = 0; k < vertices_.Size(); k += 3)
{
Vector3 v0 = vertices_.At(k);
Vector3 v1 = vertices_.At(k + 1);
Vector3 v2 = vertices_.At(k + 2);
inside = IsInsideTriangle(v0, v1, v2, pos);
// URHO3D_LOGERRORF("EditorModelDebug::AddPointUV: pos <%i> inside <%i>", k, inside);
if (inside)
{
return k;
// for (unsigned u = 0; u < 3; u++)
// {
// Vector2 v0 = uvs_.At(k + u);
// // Vector2 v1 = uvs_.At(k + 1);
// // Vector2 v2 = uvs_.At(k + 2);
// int xx = texWidth * v0.x_;
// int yy = texHeight * v0.y_;
// URHO3D_LOGERRORF("EditorModelDebug::AddPointUV: uv <%f, %f> pos <%i, %i>", v0.x_, v0.y_, xx, yy);
// DrawPoint(xx, yy, img_, Color::CYAN.ToUInt());
// }
// URHO3D_LOGERRORF("EditorModelDebug::AddPointUV: diff <%f> pos <%f, %f> inside <%i>", dif.Length(), pos.x_, pos.y_, inside);
}
}
return -1;
}
bool EditorModelDebug::IsInsideTriangle(const Vector3& v0, const Vector3& v1, const Vector3& v2, const Vector2& pos)
{
float area = 0.5f * (-v1.y_ * v2.x_ + v0.y_ * (-v1.x_ + v2.x_) + v0.x_ * (v1.y_ - v2.y_) + v1.x_ * v2.y_);
float s = 1 / (2 * area) * (v0.y_ * v2.x_ - v0.x_ * v2.y_ + (v2.y_ - v0.y_) * pos.x_ + (v0.x_ - v2.x_) * pos.y_);
float t = 1 / (2 * area) * (v0.x_ * v1.y_ - v0.y_ * v1.x_ + (v0.y_ - v1.y_) * pos.x_ + (v1.x_ - v0.x_) * pos.y_);
return s > 0.0f && t > 0.0f && (1.0f - s - t) > 0.0f;
}
void EditorModelDebug::DrawLine(const IntVector2& p1, const IntVector2& p2)
{
if (!model_ || !imgData_)
return;
unsigned level = 0;
int texWidth = texture_->GetLevelWidth(0);
int texHeight = texture_->GetLevelHeight(0);
unsigned color = brushColor_.ToUInt();
int x1 = p1.x_;
int y1 = p1.y_;
int x2 = p2.x_;
int y2 = p2.y_;
// Iterators, counters required by algorithm
int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i;
// Calculate line deltas
dx = x2 - x1;
dy = y2 - y1;
// Create a positive copy of deltas (makes iterating easier)
dx1 = Urho3D::Abs(dx);
dy1 = Urho3D::Abs(dy);
// Calculate error intervals for both axis
px = 2 * dy1 - dx1;
py = 2 * dx1 - dy1;
// The line is X-axis dominant
if (dy1 <= dx1)
{
// Line is drawn left to right
if (dx >= 0)
{
x = x1;
y = y1;
xe = x2;
}
else
{ // Line is drawn right to left (swap ends)
x = x2;
y = y2;
xe = x1;
}
// Color c(img_->GetPixel(x, y));
// if (c.a_ == 1.0f)
img_->SetPixelInt(x, y, color); // Draw first pixel
// Rasterize the line
for (i = 0; x < xe; i++)
{
x = x + 1;
// Deal with octants...
if (px < 0)
{
px = px + 2 * dy1;
}
else
{
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0))
{
y = y + 1;
}
else
{
y = y - 1;
}
px = px + 2 * (dy1 - dx1);
}
// Draw pixel from line span at
// currently rasterized position
// Color c(img_->GetPixel(x, y));
// if (c.a_ == 1.0f)
img_->SetPixelInt(x, y, color);
}
}
else
{ // The line is Y-axis dominant
// Line is drawn bottom to top
if (dy >= 0)
{
x = x1;
y = y1;
ye = y2;
}
else
{ // Line is drawn top to bottom
x = x2;
y = y2;
ye = y1;
}
// Color c(img_->GetPixel(x, y));
// if (c.a_ == 1.0f)
img_->SetPixelInt(x, y, color);
// Rasterize the line
for (i = 0; y < ye; i++)
{
y = y + 1;
// Deal with octants...
if (py <= 0)
{
py = py + 2 * dx1;
}
else
{
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0))
{
x = x + 1;
}
else
{
x = x - 1;
}
py = py + 2 * (dx1 - dy1);
}
// Draw pixel from line span at
// currently rasterized position
// Color c(img_->GetPixel(x, y));
// if (c.a_ == 1.0f)
img_->SetPixelInt(x, y, color);
}
}
texture_->SetData(level, 0, 0, texWidth, texHeight, img_->GetData());
}
void EditorModelDebug::DrawLine2(const IntVector2& p1, const IntVector2& p2, Image* img, unsigned color)
{
if (!model_ || !imgData_)
return;
// URHO3D_LOGERRORF("EditorModelDebug::DrawLine2: p1 <%i, %i> p2 <%i, %i>", p1.x_, p1.y_, p2.x_, p2.y_);
unsigned level = 0;
// int texWidth = width;
// int texHeight = height;
int texWidth = img->GetWidth();
int texHeight = img->GetHeight();
// unsigned color = Color::RED.ToUInt();
int x1 = p1.x_;
int y1 = p1.y_;
int x2 = p2.x_;
int y2 = p2.y_;
// Iterators, counters required by algorithm
int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i;
// Calculate line deltas
dx = x2 - x1;
dy = y2 - y1;
// Create a positive copy of deltas (makes iterating easier)
dx1 = Urho3D::Abs(dx);
dy1 = Urho3D::Abs(dy);
// Calculate error intervals for both axis
px = 2 * dy1 - dx1;
py = 2 * dx1 - dy1;
// The line is X-axis dominant
if (dy1 <= dx1)
{
// Line is drawn left to right
if (dx >= 0)
{
x = x1;
y = y1;
xe = x2;
}
else
{ // Line is drawn right to left (swap ends)
x = x2;
y = y2;
xe = x1;
}
// Color c(img_->GetPixel(x, y));
// if (c.a_ == 1.0f)
img->SetPixelInt(x, y, color); // Draw first pixel
// Rasterize the line
for (i = 0; x < xe; i++)
{
x = x + 1;
// Deal with octants...
if (px < 0)
{
px = px + 2 * dy1;
}
else
{
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0))
{
y = y + 1;
}
else
{
y = y - 1;
}
px = px + 2 * (dy1 - dx1);
}
// Draw pixel from line span at
// currently rasterized position
// Color c(img_->GetPixel(x, y));
// if (c.a_ == 1.0f)
img->SetPixelInt(x, y, color);
}
}
else
{ // The line is Y-axis dominant
// Line is drawn bottom to top
if (dy >= 0)
{
x = x1;
y = y1;
ye = y2;
}
else
{ // Line is drawn top to bottom
x = x2;
y = y2;
ye = y1;
}
// Color c(img_->GetPixel(x, y));
// if (c.a_ == 1.0f)
img->SetPixelInt(x, y, color);
// Rasterize the line
for (i = 0; y < ye; i++)
{
y = y + 1;
// Deal with octants...
if (py <= 0)
{
py = py + 2 * dx1;
}
else
{
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0))
{
x = x + 1;
}
else
{
x = x - 1;
}
py = py + 2 * (dx1 - dy1);
}
// Draw pixel from line span at
// currently rasterized position
// Color c(img_->GetPixel(x, y));
// if (c.a_ == 1.0f)
img->SetPixelInt(x, y, color);
}
}
// texture_->SetData(level, 0, 0, texWidth, texHeight, img_->GetData());
}
void EditorModelDebug::DrawFaces(const PODVector<IntVector2>& faces)
{
const Vector<SharedPtr<VertexBuffer>>& vb = model_->GetVertexBuffers();
const Vector<SharedPtr<IndexBuffer>>& ib = model_->GetIndexBuffers();
VertexBuffer* vertexBuffer = vb.At(0);
unsigned vertexSize = vertexBuffer->GetVertexSize();
const Vector<Vector<SharedPtr<Geometry>>>& geoms = model_->GetGeometries();
// URHO3D_LOGERRORF("buffer vertex <%u> index <%u> geom <%u>", vb.Size(), ib.Size(), geoms.Size());
// for(unsigned i = 0; i < geoms.Size(); i++)
// {
// const Vector<SharedPtr<Geometry>>& gs = geoms[i];
// SharedPtr<Geometry> g = geoms[i][0];
// // VertexBuffer* vb = g->GetVertexBuffer(0);
// // URHO3D_LOGERRORF("geom <%u> vb <%u> ib <%u>", i, vb->GetVertexCount(),
// g->GetIndexBuffer()->GetIndexCount()); URHO3D_LOGERRORF("geom <%u> vb start <%u> vb count <%u> ib start
// <%u> ib count <%u> ", i,
// g->GetVertexStart(), g->GetVertexCount(), g->GetIndexStart(), g->GetIndexCount());
// }
IndexBuffer* indexBuffer = ib.At(0);
// unsigned indexSize = indexBuffer->GetIndexSize();
unsigned char* indexData = indexBuffer->GetShadowData();
// FIXME here isn't required to lock, its only for reading
// unsigned char* dstData = static_cast<unsigned char*>(vertexBuffer->Lock(0, vertexBuffer->GetVertexCount(),
// true));
unsigned char* dstData = vertexBuffer->GetShadowDataShared();
if (!dstData)
return;
Color color = GetFaceColor();
DebugRenderer* debugRenderer = node_->GetScene()->GetComponent<DebugRenderer>();
for (unsigned i = 0; i < faces.Size(); i++)
{
const IntVector2& face = faces.At(i);
if (face.y_ != M_MAX_UNSIGNED)
{
SharedPtr<Geometry> g = geoms[face.x_][0];
unsigned short* index = ((unsigned short*)&indexData[0]) + g->GetIndexStart() + face.y_;
currentFace_ = face.y_ / 3;
currentIndex_.x_ = index[0];
currentIndex_.y_ = index[1];
currentIndex_.z_ = index[2];
const Vector3& v0 = *((const Vector3*)(&dstData[index[0] * vertexSize]));
const Vector3& v1 = *((const Vector3*)(&dstData[index[1] * vertexSize]));
const Vector3& v2 = *((const Vector3*)(&dstData[index[2] * vertexSize]));
const Matrix3x4& transform = node_->GetWorldTransform();
debugRenderer->AddTriangle(transform * v0, transform * v1, transform * v2, color);
// float d0 = (transform * v0).DistanceToPoint(hitPosition_);
// float d1 = (transform * v1).DistanceToPoint(hitPosition_);
// float d2 = (transform * v2).DistanceToPoint(hitPosition_);
Sphere sphere;
sphere.radius_ = 0.02f;
Color sphereColor;
sphereColor.FromHSL(39.0f, 100.0f, 50.0f);
// if(d0 < d1 && d0 < d2)
{
sphere.center_ = (transform * v0);
debugRenderer->AddSphere(sphere, sphereColor);
}
// else if(d1 < d0 && d1 < d2)
{
sphere.center_ = (transform * v1);
debugRenderer->AddSphere(sphere, sphereColor);
}
// else
{
sphere.center_ = (transform * v2);
debugRenderer->AddSphere(sphere, sphereColor);
}
}
}
// vertexBuffer->Unlock();
// debugRenderer->AddTriangleMesh(&vertexData[0], vertexSize, &indexData[0], indexSize, geom->GetIndexStart(),
// geom->GetIndexCount(), transform, color);
}
void EditorModelDebug::UpdateFacesIndexes()
{
if (!model_)
return;
const Vector<SharedPtr<VertexBuffer>>& vb = model_->GetVertexBuffers();
const Vector<SharedPtr<IndexBuffer>>& ib = model_->GetIndexBuffers();
VertexBuffer* vertexBuffer = vb.At(0);
// unsigned vertexSize = vertexBuffer->GetVertexSize();
IndexBuffer* indexBuffer = ib.At(0);
// unsigned indexSize = indexBuffer->GetIndexSize();
unsigned char* indexData = indexBuffer->GetShadowData();
const Vector<Vector<SharedPtr<Geometry>>>& geoms = model_->GetGeometries();
// unsigned char* dstData = static_cast<unsigned char*>(vertexBuffer->Lock(0, vertexBuffer->GetVertexCount(),
// true)); if(!dstData)
// return;
for (unsigned i = 0; i < selectedFaces_.Size(); i++)
{
IntVector2 face = selectedFaces_.At(i);
if (face.y_ != M_MAX_UNSIGNED)
{
SharedPtr<Geometry> g = geoms[face.x_][0];
unsigned short* index = ((unsigned short*)&indexData[0]) + g->GetIndexStart() + face.y_;
for (unsigned j = 0; j < 3; j++)
{
if (!selectedIndex_.Contains(index[j]))
{
selectedIndex_.Push(index[j]);
}
}
IntVector3 faceIndex(index[0], index[1], index[2]);
selectedFacesIndex_.Push(faceIndex);
}
}
// vertexBuffer->Unlock();
}
void EditorModelDebug::ApplyVertexCollisionMask()
{
if (!model_)
return;
const Vector<SharedPtr<VertexBuffer>>& vb = model_->GetVertexBuffers();
VertexBuffer* vertexBuffer = vb.At(0);
const PODVector<VertexElement>& ve = vertexBuffer->GetElements();
const VertexElement* vertexObjectIndex = VertexBuffer::GetElement(ve, TYPE_INT, SEM_OBJECTINDEX);
const VertexElement* vertexUV = VertexBuffer::GetElement(ve, TYPE_VECTOR2, SEM_TEXCOORD);
if (!vertexObjectIndex || !vertexUV)
{
URHO3D_LOGERRORF("vertex element not found!");
return;
}
unsigned char* dstData = static_cast<unsigned char*>(vertexBuffer->Lock(0, vertexBuffer->GetVertexCount(), true));
if (dstData)
{
unsigned vertexSize = vertexBuffer->GetVertexSize();
unsigned size = ELEMENT_TYPESIZES[vertexObjectIndex->type_];
// for(unsigned i = 0; i < vertexBuffer->GetVertexCount(); i++)
for (unsigned i = 0; i < selectedIndex_.Size(); i++)
{
int s = selectedIndex_[i];
// unsigned int val = *((unsigned int*)&dstData[s * vertexSize + vertexElement->offset_]);
// val = val | GetCollisionMask(vertexMaskType_);
unsigned val = GetCollisionMask(vertexMaskType_);
memcpy(&dstData[(unsigned)s * vertexSize + vertexObjectIndex->offset_], &val, size);
}
vertexBuffer->Unlock();
}
}
void EditorModelDebug::ApplyVertexUV(const PODVector<Vector2>& texUV)
{
if (!model_ || texUV.Size() == 0 || !imgData_)
return;
int texWidth = texture_->GetLevelWidth(0);
int texHeight = texture_->GetLevelHeight(0);
unsigned* data = (unsigned*)malloc(brushSize_ * brushSize_ * sizeof(unsigned));
memset(data, 0, brushSize_ * brushSize_ * sizeof(unsigned));
Vector2 uv = texUV.At(0);
unsigned xx = static_cast<int>(uv.x_ * texWidth);
unsigned yy = static_cast<int>(uv.y_ * texHeight);
// ARGB
// unsigned c = (0xAA << 24) | (0x00 << 16) | (0xFF << 8) | 0x00;
unsigned c = brushColor_.ToUInt();
unsigned t = (0xfF << 24) | (0x00 << 16) | (0x00 << 8) | 0xFF;
for (unsigned ii = 0; ii < brushSize_; ii++)
{
for (unsigned jj = 0; jj < brushSize_; jj++)
{
int x = jj - brushSize_ / 2;
int y = brushSize_ / 2 - ii;
int sumsq = x * x + y * y;
int r = brushSize_ / 2;
int offsetx = xx - (brushSize_ / 2) + jj;
int offsety = yy - (brushSize_ / 2) + ii;
if ((sumsq < r * r))
{
unsigned p = 0;
if ((offsetx >= 0) && (offsety >= 0) && (offsety * texWidth + offsetx < texWidth * texHeight))
p = imgData_[offsety * texWidth + offsetx];
Color c2(p);
Color c1(brushColor_);
c = c1.Blend(c2).ToUInt();
data[ii * brushSize_ + jj] = (unsigned)c;
// if ((offsetx >= 0) && (offsety >=0))
// imgData_[offsety * texWidth + offsetx] = (unsigned)c;
}
else
{
unsigned p = 0;
// if ((offsetx >= 0) && (offsety >=0) && (offsetx * texWidth + offsety < texWidth * texHeight))
// p = imgData_[offsety * texWidth + offsetx];
if ((offsetx >= 0) && (offsety >= 0) && (offsetx * texWidth + offsety < texWidth * texHeight))
p = img_->GetPixel(offsetx, offsety).ToUInt();
data[ii * brushSize_ + jj] = (unsigned)p;
}
}
}
int halfBrushSize = brushSize_ / 2;
int centerx = xx - halfBrushSize;
int centery = yy - halfBrushSize;
// check border size
if (centerx < 0)
centerx = 0;
if (centery < 0)
centery = 0;
if (centerx + brushSize_ > texWidth)
centerx = texWidth - brushSize_;
if (centery + brushSize_ > texHeight)
centery = texHeight - brushSize_;
if (centerx < 0 || centerx + brushSize_ > texWidth || centery < 0 || centery + brushSize_ > texHeight ||
brushSize_ <= 0 || brushSize_ <= 0)
{
URHO3D_LOGERRORF("EditorModelDebug::ApplyVertexUV: center <%i, %i>", centerx, centery);
}
texture_->SetData(0, centerx, centery, brushSize_, brushSize_, data);
Image imgData(context_);
imgData.SetSize(brushSize_, brushSize_, 4);
imgData.SetData((const unsigned char*)data);
bool subImage =
imgAux_->SetSubimage(&imgData, IntRect(centerx, centery, centerx + brushSize_, centery + brushSize_));
free(data);
}
void EditorModelDebug::AddVertexElement(unsigned vertexIndex, unsigned vertexElementIndex)
{
// Resize VertexElement anterior
// URHO3D_LOGERRORF("addindex <%i> vertexindex <%i>", vertexElementIndex, vertexIndex);
const Vector<SharedPtr<VertexBuffer>>& vb = model_->GetVertexBuffers();
VertexBuffer* vertexBuffer = vb.At(vertexIndex);
PODVector<VertexElement> veOriginal = vertexBuffer->GetElements();
PODVector<VertexElement> ves = veOriginal;
VertexElementType type = TYPE_INT;
VertexElementSemantic semantic = SEM_OBJECTINDEX;
ves.Insert(vertexElementIndex + 1, VertexElement(type, semantic));
// Save data before resizing
SharedArrayPtr<unsigned char> vertexData;
vertexData = vertexBuffer->GetShadowDataShared();
unsigned vertexSizeOld = vertexBuffer->GetVertexSize();
// URHO3D_LOGERRORF("before size <%i> count <%i> size <%i> ve <%i>", sizeof(vertexData.Get()),
// vertexBuffer->GetVertexCount(), vertexBuffer->GetVertexSize(), veOriginal.Size());
vertexBuffer->SetSize(vertexBuffer->GetVertexCount(), ves);
ves = vertexBuffer->GetElements();
unsigned vertexSize = vertexBuffer->GetVertexSize();
// URHO3D_LOGERRORF("after size <%i> count <%i> size <%i> ve <%i>", sizeof(vertexBuffer->GetShadowData()),
// vertexBuffer->GetVertexCount(), vertexBuffer->GetVertexSize(), ves.Size());
URHO3D_LOGERRORF("vertex element sizes: old <%i> new <%i>", veOriginal.Size(), ves.Size());
unsigned char* srcData = reinterpret_cast<unsigned char*>(&vertexData[0]);
unsigned char* dstData = static_cast<unsigned char*>(vertexBuffer->Lock(0, vertexBuffer->GetVertexCount(), true));
if (dstData)
{
// const PODVector<VertexElement>& ve = vertexBuffer->GetElements();
for (unsigned i = 0; i < vertexBuffer->GetVertexCount(); i++)
{
for (unsigned j = 0; j < veOriginal.Size(); j++)
{
const VertexElement& el = veOriginal.At(j);
unsigned size = ELEMENT_TYPESIZES[el.type_];
const VertexElement* elNew = VertexBuffer::GetElement(ves, el.type_, el.semantic_);
if (elNew)
{
// URHO3D_LOGERRORF("coping type <%i> semantic <%i> size <%i> offset <%u, %u>", el.type_,
// el.semantic_, size, el.offset_, elNew->offset_);
memcpy(&dstData[i * vertexSize + elNew->offset_], &srcData[i * vertexSizeOld + el.offset_], size);
}
else
{
URHO3D_LOGERRORF("vertex element not found, type <%i> semantic <%i>", el.type_, el.semantic_);
}
}
// init new vertex element
const VertexElement* elNew = VertexBuffer::GetElement(ves, TYPE_INT, SEM_OBJECTINDEX);
unsigned size = ELEMENT_TYPESIZES[TYPE_INT];
if (elNew)
{
(void)size;
// memcpy(&dstData[i * vertexSize + elNew->offset_], NONE, size);
memset(&dstData[i * vertexSize + elNew->offset_], NONE, size);
}
}
vertexBuffer->Unlock();
}
}
void EditorModelDebug::SaveModel()
{
ApplyVertexCollisionMask();
// String fileName = GetSubsystem<FileSystem>()->GetProgramDir() + "MeshTest.mdl";
URHO3D_LOGERRORF("file name <%s>", model_->GetName().CString());
String fileName = GetSubsystem<FileSystem>()->GetProgramDir() + "Data/" + model_->GetName() + "-collision";
File file(context_, fileName, FILE_WRITE);
if (model_->Save(file))
URHO3D_LOGERRORF("file saved name <%s>", fileName.CString());
else
URHO3D_LOGERRORF("error saving name <%s>", fileName.CString());
}
void EditorModelDebug::SelectAll()
{
const Vector<SharedPtr<VertexBuffer>>& vb = model_->GetVertexBuffers();
const Vector<SharedPtr<IndexBuffer>>& ib = model_->GetIndexBuffers();
// VertexBuffer* vertexBuffer = vb.At(0);
// unsigned vertexSize = vertexBuffer->GetVertexSize();
IndexBuffer* indexBuffer = ib.At(0);
unsigned indexCount = indexBuffer->GetIndexCount();
// unsigned indexSize = indexBuffer->GetIndexSize();
unsigned char* indexData = indexBuffer->GetShadowData();
if (!indexData)
return;
// const Vector<Vector<SharedPtr<Geometry> > >& geoms = model_->GetGeometries();
selectedIndex_.Clear();
selectedFacesIndex_.Clear();
for (unsigned i = 0; i < indexCount; i++)
{
unsigned short* index = ((unsigned short*)&indexData[0]) + i;
// for(unsigned j = 0; j < 3; j++)
{
// if(!selectedIndex_.Contains(index[0]))
{
selectedIndex_.Push(index[0]);
}
}
}
ApplyVertexCollisionMask();
}
void EditorModelDebug::OnWorldBoundingBoxUpdate()
{
if (model_)
{
worldBoundingBox_ = model_->GetBoundingBox();
const Matrix3x4& transform = node_->GetWorldTransform();
worldBoundingBox_.Transform(transform);
}
}
void EditorModelDebug::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
{
Model* currentModel = model_;
model_.Reset(); // Set null to allow to be re-set
SetModel(currentModel);
}
Color EditorModelDebug::GetFaceColor()
{
VertexCollisionMask type = GetCollisionMask(vertexMaskType_);
return GetFaceColor(type);
}
Color EditorModelDebug::GetFaceColor(VertexCollisionMaskFlags mask)
{
Color color(Color::BLUE);
// if((mask & TRACK_ROAD) == TRACK_ROAD)
// color = Color::GREEN;
// else if((mask & TRACK_BORDER) == TRACK_BORDER)
// color = Color::YELLOW;
// else if((mask & OFFTRACK_WEAK) == OFFTRACK_WEAK)
// color = Color::RED;
// else if((mask & OFFTRACK_HEAVY) == OFFTRACK_HEAVY)
// color = Color::BLACK;
if ((mask & TRACK_ROAD))
color = Color::GREEN;
else if ((mask & TRACK_BORDER))
color = Color::YELLOW;
else if ((mask & OFFTRACK_WEAK))
color = Color::RED;
else if ((mask & OFFTRACK_HEAVY))
color = Color::BLACK;
color.a_ = 0.7f;
return color;
}
VertexCollisionMask EditorModelDebug::GetCollisionMask(unsigned int mask)
{
VertexCollisionMask maskType = NONE;
switch (mask)
{
case 0:
maskType = NONE;
break;
case 1:
maskType = TRACK_ROAD;
break;
case 2:
maskType = TRACK_BORDER;
break;
case 3:
maskType = OFFTRACK_WEAK;
break;
case 4:
maskType = OFFTRACK_HEAVY;
break;
}
return maskType;
}
void EditorModelDebug::CreateVertexInstances()
{
/// set up
primitiveType_ = TRIANGLE_LIST;
transform_ = Matrix3x4::IDENTITY;
if (model_->GetVertexBuffers().Size())
{
VertexBuffer* vb = model_->GetVertexBuffers().At(0);
unsigned vertexSize = vb->GetVertexSize();
unsigned totalVerticesReal = vb->GetVertexCount();
URHO3D_LOGERRORF("editormodeldebug: vertices <%u>", totalVerticesReal);
unsigned totalVertices = 1;
const SharedArrayPtr<unsigned char>& vertexData = vb->GetShadowDataShared();
const auto* srcData = (const unsigned char*)&vertexData[0];
unsigned positionOffset = VertexBuffer::GetElementOffset(vb->GetElements(), TYPE_VECTOR3, SEM_POSITION);
vertexElements_.Clear();
vertexElements_.Push(VertexElement(TYPE_VECTOR3, SEM_POSITION, 0, false));
vertexElements_.Push(VertexElement(TYPE_UBYTE4_NORM, SEM_COLOR, 0, false));
VertexBuffer::UpdateOffsets(vertexElements_);
unsigned indexLength = sizeof(cubeIndex) / sizeof(cubeIndex[0]);
unsigned indexCount = totalVertices * indexLength;
unsigned size = 8;
indexBuffer_->SetShadowed(true);
// indexCount > 0xFFFF
indexBuffer_->SetSize(indexCount, true);
unsigned* indexDest = (unsigned*)indexBuffer_->Lock(0, indexCount);
vertexBuffer_->SetShadowed(true);
vertexBuffer_->SetSize(totalVertices * size, vertexElements_, true);
auto* dest = (unsigned char*)vertexBuffer_->Lock(0, totalVertices * size, true);
if (dest && indexDest)
{
unsigned color = Color::GREEN.ToUInt();
unsigned indexOffset = 0;
for (unsigned i = 0; i < totalVertices; i++)
{
// Vector3 position = *((const Vector3*)(&srcData[i * vertexSize + positionOffset]));
Vector3 position = Vector3::ZERO;
for (unsigned j = 0; j < size; j++)
{
*((Vector3*)dest) = position + Vector3(cubeVertices + j * 3) * vertexScale_;
dest += sizeof(Vector3);
*((unsigned*)dest) = color;
dest += sizeof(unsigned);
}
for (unsigned j = 0; j < indexLength; j++)
{
unsigned index = indexOffset + cubeIndex[j];
indexDest[indexOffset + j] = index;
}
indexOffset += indexLength;
}
worldTransforms_.Resize(totalVerticesReal);
numWorldTransforms_ = totalVerticesReal;
batches_[0].worldTransform_ = &worldTransforms_[0];
batches_[0].numWorldTransforms_ = totalVerticesReal;
batches_[0].instancingData_ = new float[4 * totalVerticesReal];
unsigned offset = 0;
unsigned char* instanceData = static_cast<unsigned char*>(batches_[0].instancingData_);
for (unsigned i = 0; i < totalVerticesReal; i++)
{
memcpy(instanceData + offset, Vector4(1.0f, 0.2f, 0.3f, 0.4f).Data(), sizeof(Vector4));
offset += sizeof(Vector4);
}
for (unsigned i = 0; i < totalVerticesReal; i++)
{
Vector3 position = *((const Vector3*)(&srcData[i * vertexSize + positionOffset]));
vertexOffset_.Push(position);
}
geometry_->SetVertexBuffer(0, vertexBuffer_);
geometry_->SetIndexBuffer(indexBuffer_);
geometry_->SetDrawRange(primitiveType_, 0, indexOffset, 0, totalVertices * size);
vertexBuffer_->Unlock();
indexBuffer_->Unlock();
Vector3 min(cubeVertices + 4 * 3);
Vector3 max(cubeVertices + 2 * 3);
// URHO3D_LOGERRORF("vector min <%f, %f, %f>", min.x_, min.y_, min.z_);
// URHO3D_LOGERRORF("vector max <%f, %f, %f>", max.x_, max.y_, max.z_);
SetBoundingBox(BoundingBox(min * vertexScale_, max * vertexScale_));
}
}
}
void EditorModelDebug::CreateFaceInstances()
{
const Vector<SharedPtr<IndexBuffer>>& ib = model_->GetIndexBuffers();
IndexBuffer* indexBuffer = ib.At(0);
vertexElements_.Clear();
vertexElements_.Push(VertexElement(TYPE_VECTOR3, SEM_POSITION, 0, false));
vertexElements_.Push(VertexElement(TYPE_UBYTE4_NORM, SEM_COLOR, 0, false));
VertexBuffer::UpdateOffsets(vertexElements_);
unsigned totalVertices = 1;
unsigned totalVerticesReal = 1;
unsigned indexLength = 3;
unsigned indexCount = totalVertices * indexLength;
unsigned size = 3;
indexBufferFaces_->SetShadowed(true);
indexBufferFaces_->SetSize(indexCount, true);
unsigned* indexDest = (unsigned*)indexBufferFaces_->Lock(0, indexCount);
vertexBufferFaces_->SetShadowed(true);
vertexBufferFaces_->SetSize(totalVertices * size, vertexElements_, true);
unsigned char* dest = (unsigned char*)vertexBufferFaces_->Lock(0, totalVertices * size, true);
if (dest && indexDest)
{
float scale = 1.00f;
unsigned color = Color::YELLOW.ToUInt();
unsigned indexOffset = 0;
for (unsigned i = 0; i < totalVertices; i++)
{
Vector3 position = Vector3::ZERO;
for (unsigned j = 0; j < size; j++)
{
*((Vector3*)dest) = position + Vector3(cubeVertices + j * 3) * scale;
dest += sizeof(Vector3);
*((unsigned*)dest) = color;
dest += sizeof(unsigned);
}
for (unsigned j = 0; j < indexLength; j++)
{
unsigned index = indexOffset + cubeIndex[j];
indexDest[indexOffset + j] = index;
}
indexOffset += indexLength;
}
geometryFaces_->SetVertexBuffer(0, vertexBufferFaces_);
geometryFaces_->SetIndexBuffer(indexBufferFaces_);
geometryFaces_->SetDrawRange(primitiveType_, 0, indexOffset, 0, totalVertices * size);
vertexBufferFaces_->Unlock();
indexBufferFaces_->Unlock();
unsigned count = indexBuffer->GetIndexCount();
CalcMatrixFaces();
numWorldTransformsFaces_ = count / 3;
batches_[1].worldTransform_ = &worldTransformsFaces_[0];
batches_[1].numWorldTransforms_ = count / 3;
batches_[1].instancingData_ = new float[4 * count / 3];
UpdateFacesColor();
}
}
void EditorModelDebug::UpdateFacesColor()
{
if (!model_)
return;
const Vector<SharedPtr<IndexBuffer>>& ib = model_->GetIndexBuffers();
IndexBuffer* indexBuffer = ib.At(0);
unsigned count = indexBuffer->GetIndexCount();
unsigned offset = 0;
unsigned char* instanceData = static_cast<unsigned char*>(batches_[1].instancingData_);
// count = 6;
for (unsigned i = 0; i < count; i += 3)
{
VertexCollisionMask collisionMask = GetFaceCollisionMask(i);
memcpy(instanceData + offset, GetFaceColor(collisionMask).Data(), sizeof(Vector4));
// memcpy(instanceData + offset, Color::GREEN.Data(), sizeof(Vector4));
offset += sizeof(Vector4);
}
}
void EditorModelDebug::CalcMatrixFaces()
{
if (!model_)
return;
const Vector<SharedPtr<IndexBuffer>>& ib = model_->GetIndexBuffers();
IndexBuffer* indexBuffer = ib.At(0);
float scale = 1.0f;
// create matrix transform for each face
Vector3 p1, p2, p3;
p1 = Vector3(cubeVertices + 0 * 3) * scale;
p2 = Vector3(cubeVertices + 1 * 3) * scale;
p3 = Vector3(cubeVertices + 2 * 3) * scale;
// URHO3D_LOGERRORF("p1 <%f, %f, %f>", p1.x_, p1.y_, p1.z_);
// URHO3D_LOGERRORF("p2 <%f, %f, %f>", p2.x_, p2.y_, p2.z_);
// URHO3D_LOGERRORF("p3 <%f, %f, %f>", p3.x_, p3.y_, p3.z_);
unsigned count = indexBuffer->GetIndexCount();
// count = 3;
worldTransformsFaces_.Resize(count / 3);
worldTransformsFaces_.Clear();
for (unsigned i = 0; i < count; i += 3)
{
Vector3 q1, q2, q3;
// float vertexScale = node_->GetScale().x_;
Matrix3x4 transform = node_->GetTransform();
Vector3 nodeTrans = transform.Translation();
nodeTrans += Vector3(0.0f, 0.01f, 0.0f);
transform.SetTranslation(nodeTrans);
Vector<Vector3> r = GetFacePoints(i);
q1 = transform * r[0];
q2 = transform * r[1];
q3 = transform * r[2];
// URHO3D_LOGERRORF("q1 <%f, %f, %f>", q1.x_, q1.y_, q1.z_);
// URHO3D_LOGERRORF("q2 <%f, %f, %f>", q2.x_, q2.y_, q2.z_);
// URHO3D_LOGERRORF("q3 <%f, %f, %f>", q3.x_, q3.y_, q3.z_);
Matrix4 matQ(q1.x_, q1.y_, q1.z_, 1.0f, q2.x_, q2.y_, q2.z_, 1.0f, q3.x_, q3.y_, q3.z_, 1.0f, 0.0f, 0.0f, 0.0f,
1.0f);
Matrix4 matP(p1.x_, p1.y_, p1.z_, 1.0f, p2.x_, p2.y_, p2.z_, 1.0f, p3.x_, p3.y_, p3.z_, 1.0f, 0.0f, 0.0f, 0.0f,
1.0f);
Matrix4 t = matQ.Transpose() * matP.Transpose().Inverse();
// Vector4 q11 = t * Vector4(p1, 1.0f);
// Vector4 q22 = t * Vector4(p2, 1.0f);
// Vector4 q33 = t * Vector4(p3, 1.0f);
// URHO3D_LOGERRORF("q11 <%f, %f, %f, %f>", q11.x_, q11.y_, q11.z_, q11.w_);
// URHO3D_LOGERRORF("q22 <%f, %f, %f, %f>", q22.x_, q22.y_, q22.z_, q22.w_);
// URHO3D_LOGERRORF("q33 <%f, %f, %f, %f>", q33.x_, q33.y_, q33.z_, q33.w_);
worldTransformsFaces_.Push(Matrix3x4(t));
}
}
Vector<Vector3> EditorModelDebug::GetFacePoints(unsigned face)
{
Vector<Vector3> result;
const Vector<SharedPtr<VertexBuffer>>& vb = model_->GetVertexBuffers();
const Vector<SharedPtr<IndexBuffer>>& ib = model_->GetIndexBuffers();
VertexBuffer* vertexBuffer = vb.At(0);
unsigned vertexSize = vertexBuffer->GetVertexSize();
IndexBuffer* indexBuffer = ib.At(0);
// unsigned indexSize = indexBuffer->GetIndexSize();
unsigned char* indexData = indexBuffer->GetShadowData();
// unsigned indexStart = indexBuffer->GetS
// FIXME here isn't required to lock, its only for reading
unsigned char* vertexData = vertexBuffer->GetShadowData();
if (!vertexData)
return result;
if (face != M_MAX_UNSIGNED)
{
unsigned short* index = ((unsigned short*)&indexData[0]) + face;
result.Push(*((const Vector3*)(&vertexData[index[0] * vertexSize])));
result.Push(*((const Vector3*)(&vertexData[index[1] * vertexSize])));
result.Push(*((const Vector3*)(&vertexData[index[2] * vertexSize])));
}
return result;
}
VertexCollisionMask EditorModelDebug::GetFaceCollisionMask(unsigned face)
{
const Vector<SharedPtr<VertexBuffer>>& vb = model_->GetVertexBuffers();
const Vector<SharedPtr<IndexBuffer>>& ib = model_->GetIndexBuffers();
VertexBuffer* vertexBuffer = vb.At(0);
unsigned vertexSize = vertexBuffer->GetVertexSize();
IndexBuffer* indexBuffer = ib.At(0);
// unsigned indexSize = indexBuffer->GetIndexSize();
unsigned char* indexData = indexBuffer->GetShadowData();
// unsigned indexStart = indexBuffer->GetS
const Vector<Vector<SharedPtr<Geometry>>>& geoms = model_->GetGeometries();
// FIXME here isn't required to lock, its only for reading
unsigned char* vertexData = vertexBuffer->GetShadowData();
if (!vertexData)
return NONE;
const PODVector<VertexElement>& ve = vertexBuffer->GetElements();
const VertexElement* vertexElement = VertexBuffer::GetElement(ve, TYPE_INT, SEM_OBJECTINDEX);
if (!vertexElement)
{
// URHO3D_LOGERRORF("vertex element for collision not found!");
return NONE;
}
if (face != M_MAX_UNSIGNED)
{
SharedPtr<Geometry> g = geoms[0][0];
// FIXME verificar el tipo de los indices
unsigned short* index = ((unsigned short*)&indexData[0]) + g->GetIndexStart() + face;
unsigned short i = index[0];
unsigned short j = index[1];
unsigned short k = index[2];
// const unsigned& c0 = *((const unsigned*)(&vertexData[index[0] * vertexSize +
// vertexElement->offset_])); const unsigned& c1 = *((const unsigned*)(&vertexData[index[1] * vertexSize
// + vertexElement->offset_])); const unsigned& c2 = *((const unsigned*)(&vertexData[index[2] *
// vertexSize + vertexElement->offset_]));
const VertexCollisionMaskFlags& c0 =
*((const VertexCollisionMaskFlags*)(&vertexData[i * vertexSize + vertexElement->offset_]));
const VertexCollisionMaskFlags& c1 =
*((const VertexCollisionMaskFlags*)(&vertexData[j * vertexSize + vertexElement->offset_]));
const VertexCollisionMaskFlags& c2 =
*((const VertexCollisionMaskFlags*)(&vertexData[k * vertexSize + vertexElement->offset_]));
// color = GetFaceColor(c0);
if ((c0 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY)) &&
(c1 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY)) &&
(c2 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY)) && c0 == c1 && c0 == c2 && c1 == c2)
{
return (VertexCollisionMask)c0;
}
}
return NONE;
}
void EditorModelDebug::DebugList(const PODVector<IntVector2>& list)
{
// char b[1024 * 8];
// memset(b, 0, sizeof(b));
// unsigned offset = 0;
// for (unsigned i = 0; i < list.Size(); i++)
// {
// offset += sprintf(b + offset, "[%u,%u] ", list[i].x_, list[i].y_);
// }
// URHO3D_LOGERRORF("debug list <%s> size <%u>", b, list.Size());
}
void EditorModelDebug::SaveImage(const String& name) { img_->SavePNG(name); }
bool EditorModelDebug::SetSize(int width, int height, bool threaded)
{
if (width <= 0 || height <= 0)
return false;
width_ = width;
height_ = height;
CalculateViewport();
return true;
}
void EditorModelDebug::CalculateViewport()
{
// Add half pixel offset due to 3D frustum culling
scaleX_ = 0.5f * width_;
scaleY_ = -0.5f * height_;
offsetX_ = 0.5f * width_ + 0.5f;
offsetY_ = 0.5f * height_ + 0.5f;
projOffsetScaleX_ = projection_.m00_ * scaleX_;
projOffsetScaleY_ = projection_.m11_ * scaleY_;
}
void EditorModelDebug::CheckVertexVisibility(Camera* camera, Image* image)
{
if (!model_)
return;
// Geometries
const Vector<Vector<SharedPtr<Geometry>>>& geoms = model_->GetGeometries();
SharedPtr<Geometry> geometry = geoms[0][0];
// Vertex Buffer
const Vector<SharedPtr<VertexBuffer>>& vb = model_->GetVertexBuffers();
VertexBuffer* vertexBuffer = vb.At(0);
const PODVector<VertexElement>& ve = vertexBuffer->GetElements();
const VertexElement* vPos = VertexBuffer::GetElement(ve, TYPE_VECTOR3, SEM_POSITION);
const VertexElement* vUV = VertexBuffer::GetElement(ve, TYPE_VECTOR2, SEM_TEXCOORD);
if (!vPos || !vUV)
{
URHO3D_LOGERRORF("vertex element not found!");
return;
}
// URHO3D_LOGERRORF("EditorModelDebug::CheckVertexVisibility: vertex count <%u> size <%u>",
// vertexBuffer->GetVertexCount(), sizeof(unsigned short));
// Index Buffer
const Vector<SharedPtr<IndexBuffer>>& ib = model_->GetIndexBuffers();
IndexBuffer* indexBuffer = ib.At(0);
unsigned indexSize = indexBuffer->GetIndexSize();
unsigned char* indexData = indexBuffer->GetShadowData();
Matrix3x4 modelMatrix = node_->GetWorldTransform();
Matrix3x4 view = camera->GetView();
projection_ = camera->GetProjection();
Matrix4 viewProj = projection_ * view;
float nearClip = camera->GetNearClip();
float farClip = camera->GetFarClip();
// reverseCulling_ = camera->GetReverseCulling();
Matrix4 modelViewProj = viewProj * modelMatrix;
Graphics* graphics = GetSubsystem<Graphics>();
SetSize(graphics->GetWidth(), graphics->GetHeight(), false);
numTriangles_ = 0;
Vector4 vertices[64 * 3];
Vector2 uvs[3];
vertices_.Clear();
uvs_.Clear();
unsigned char* vertexData =
static_cast<unsigned char*>(vertexBuffer->Lock(0, vertexBuffer->GetVertexCount(), true));
if (vertexData)
{
unsigned positionOffset = VertexBuffer::GetElementOffset(ve, TYPE_VECTOR3, SEM_POSITION);
unsigned uvOffset = VertexBuffer::GetElementOffset(ve, TYPE_VECTOR2, SEM_TEXCOORD);
unsigned vertexSize = vertexBuffer->GetVertexSize();
// ver de donde sacar indexStart
unsigned indexStart = geometry->GetIndexStart();
unsigned indexCount = indexBuffer->GetIndexCount();
// // 16-bit indices
if (indexSize == sizeof(unsigned short))
{
const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
const unsigned short* indicesEnd = indices + indexCount;
while (indices < indicesEnd)
{
const Vector3& v0 = *((const Vector3*)(&vertexData[indices[0] * vertexSize]));
const Vector3& v1 = *((const Vector3*)(&vertexData[indices[1] * vertexSize]));
const Vector3& v2 = *((const Vector3*)(&vertexData[indices[2] * vertexSize]));
const Vector2& uv0 = *((const Vector2*)(&vertexData[indices[0] * vertexSize + uvOffset]));
const Vector2& uv1 = *((const Vector2*)(&vertexData[indices[1] * vertexSize + uvOffset]));
const Vector2& uv2 = *((const Vector2*)(&vertexData[indices[2] * vertexSize + uvOffset]));
uvs[0] = uv0;
uvs[1] = uv1;
uvs[2] = uv2;
vertices[0] = ModelTransform(modelViewProj, v0);
vertices[1] = ModelTransform(modelViewProj, v1);
vertices[2] = ModelTransform(modelViewProj, v2);
DrawTriangle(vertices, 0, image, uvs);
indices += 3;
}
}
vertexBuffer->Unlock();
}
URHO3D_LOGERRORF("EditorModelDebug::CheckVertexVisibility: num triangles <%u>", numTriangles_);
}
inline Vector4 EditorModelDebug::ModelTransform(const Matrix4& transform, const Vector3& vertex) const
{
return Vector4(
transform.m00_ * vertex.x_ + transform.m01_ * vertex.y_ + transform.m02_ * vertex.z_ + transform.m03_,
transform.m10_ * vertex.x_ + transform.m11_ * vertex.y_ + transform.m12_ * vertex.z_ + transform.m13_,
transform.m20_ * vertex.x_ + transform.m21_ * vertex.y_ + transform.m22_ * vertex.z_ + transform.m23_,
transform.m30_ * vertex.x_ + transform.m31_ * vertex.y_ + transform.m32_ * vertex.z_ + transform.m33_);
}
inline Vector3 EditorModelDebug::ViewportTransform(const Vector4& vertex) const
{
float invW = 1.0f / vertex.w_;
return Vector3(invW * vertex.x_ * scaleX_ + offsetX_, invW * vertex.y_ * scaleY_ + offsetY_,
invW * vertex.z_ * OCCLUSION_Z_SCALE);
}
void EditorModelDebug::DrawTriangle(Vector4* vertices, unsigned threadIndex, Image* image, Vector2* uvs)
{
ClipMaskFlags clipMask{};
ClipMaskFlags andClipMask{};
bool drawOk = false;
Vector3 projected[3];
// Build the clip plane mask for the triangle
for (unsigned i = 0; i < 3; ++i)
{
ClipMaskFlags vertexClipMask{};
if (vertices[i].x_ > vertices[i].w_)
vertexClipMask |= CLIPMASK_X_POS;
if (vertices[i].x_ < -vertices[i].w_)
vertexClipMask |= CLIPMASK_X_NEG;
if (vertices[i].y_ > vertices[i].w_)
vertexClipMask |= CLIPMASK_Y_POS;
if (vertices[i].y_ < -vertices[i].w_)
vertexClipMask |= CLIPMASK_Y_NEG;
if (vertices[i].z_ > vertices[i].w_)
vertexClipMask |= CLIPMASK_Z_POS;
if (vertices[i].z_ < 0.0f)
vertexClipMask |= CLIPMASK_Z_NEG;
clipMask |= vertexClipMask;
if (!i)
andClipMask = vertexClipMask;
else
andClipMask &= vertexClipMask;
}
// If triangle is fully behind any clip plane, can reject quickly
if (andClipMask)
return;
// Check if triangle is fully inside
if (!clipMask)
{
projected[0] = ViewportTransform(vertices[0]);
projected[1] = ViewportTransform(vertices[1]);
projected[2] = ViewportTransform(vertices[2]);
bool clockwise = SignedArea(projected[0], projected[1], projected[2]) < 0.0f;
if (cullMode_ == CULL_NONE || (cullMode_ == CULL_CCW && clockwise) || (cullMode_ == CULL_CW && !clockwise))
{
DrawTriangle2D(projected, clockwise, threadIndex, image, uvs);
drawOk = true;
}
}
else
{
bool triangles[64];
// Initial triangle
triangles[0] = true;
unsigned numTriangles = 1;
if (clipMask & CLIPMASK_X_POS)
ClipVertices(Vector4(-1.0f, 0.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
if (clipMask & CLIPMASK_X_NEG)
ClipVertices(Vector4(1.0f, 0.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
if (clipMask & CLIPMASK_Y_POS)
ClipVertices(Vector4(0.0f, -1.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
if (clipMask & CLIPMASK_Y_NEG)
ClipVertices(Vector4(0.0f, 1.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
if (clipMask & CLIPMASK_Z_POS)
ClipVertices(Vector4(0.0f, 0.0f, -1.0f, 1.0f), vertices, triangles, numTriangles);
if (clipMask & CLIPMASK_Z_NEG)
ClipVertices(Vector4(0.0f, 0.0f, 1.0f, 0.0f), vertices, triangles, numTriangles);
// Draw each accepted triangle
for (unsigned i = 0; i < numTriangles; ++i)
{
if (triangles[i])
{
unsigned index = i * 3;
projected[0] = ViewportTransform(vertices[index]);
projected[1] = ViewportTransform(vertices[index + 1]);
projected[2] = ViewportTransform(vertices[index + 2]);
bool clockwise = SignedArea(projected[0], projected[1], projected[2]) < 0.0f;
if (cullMode_ == CULL_NONE || (cullMode_ == CULL_CCW && clockwise) ||
(cullMode_ == CULL_CW && !clockwise))
{
// DrawTriangle2D(projected, clockwise, threadIndex);
DrawTriangle2D(projected, clockwise, threadIndex, image, uvs);
drawOk = true;
}
}
}
}
if (drawOk)
++numTriangles_;
}
inline float EditorModelDebug::SignedArea(const Vector3& v0, const Vector3& v1, const Vector3& v2) const
{
float aX = v0.x_ - v1.x_;
float aY = v0.y_ - v1.y_;
float bX = v2.x_ - v1.x_;
float bY = v2.y_ - v1.y_;
return aX * bY - aY * bX;
}
void EditorModelDebug::ClipVertices(const Vector4& plane, Vector4* vertices, bool* triangles, unsigned& numTriangles)
{
unsigned num = numTriangles;
for (unsigned i = 0; i < num; ++i)
{
if (triangles[i])
{
unsigned index = i * 3;
float d0 = plane.DotProduct(vertices[index]);
float d1 = plane.DotProduct(vertices[index + 1]);
float d2 = plane.DotProduct(vertices[index + 2]);
// If all vertices behind the plane, reject triangle
if (d0 < 0.0f && d1 < 0.0f && d2 < 0.0f)
{
triangles[i] = false;
continue;
}
// If 2 vertices behind the plane, create a new triangle in-place
else if (d0 < 0.0f && d1 < 0.0f)
{
vertices[index] = ClipEdge(vertices[index], vertices[index + 2], d0, d2);
vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index + 2], d1, d2);
}
else if (d0 < 0.0f && d2 < 0.0f)
{
vertices[index] = ClipEdge(vertices[index], vertices[index + 1], d0, d1);
vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index + 1], d2, d1);
}
else if (d1 < 0.0f && d2 < 0.0f)
{
vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index], d1, d0);
vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index], d2, d0);
}
// 1 vertex behind the plane: create one new triangle, and modify one in-place
else if (d0 < 0.0f)
{
unsigned newIdx = numTriangles * 3;
triangles[numTriangles] = true;
++numTriangles;
vertices[newIdx] = ClipEdge(vertices[index], vertices[index + 2], d0, d2);
vertices[newIdx + 1] = vertices[index] = ClipEdge(vertices[index], vertices[index + 1], d0, d1);
vertices[newIdx + 2] = vertices[index + 2];
}
else if (d1 < 0.0f)
{
unsigned newIdx = numTriangles * 3;
triangles[numTriangles] = true;
++numTriangles;
vertices[newIdx + 1] = ClipEdge(vertices[index + 1], vertices[index], d1, d0);
vertices[newIdx + 2] = vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index + 2], d1, d2);
vertices[newIdx] = vertices[index];
}
else if (d2 < 0.0f)
{
unsigned newIdx = numTriangles * 3;
triangles[numTriangles] = true;
++numTriangles;
vertices[newIdx + 2] = ClipEdge(vertices[index + 2], vertices[index + 1], d2, d1);
vertices[newIdx] = vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index], d2, d0);
vertices[newIdx + 1] = vertices[index + 1];
}
}
}
}
inline Vector4 EditorModelDebug::ClipEdge(const Vector4& v0, const Vector4& v1, float d0, float d1) const
{
float t = d0 / (d0 - d1);
return v0 + t * (v1 - v0);
}
void EditorModelDebug::DrawTriangle2D(const Vector3* vertices, bool clockwise, unsigned threadIndex, Image* texImage, Vector2* uvs)
{
Vector3 v0 = vertices[0];
Vector3 v1 = vertices[1];
Vector3 v2 = vertices[2];
vertices_.Push(v0);
vertices_.Push(v1);
vertices_.Push(v2);
uvs_.Push(uvs[0]);
uvs_.Push(uvs[1]);
uvs_.Push(uvs[2]);
float scale = 1.0f / 2.0f;
// URHO3D_LOGERRORF("EditorModelDebug::DrawTriangle2D: size <%i, %i> v0 <%s> v1 <%s>", width, height, (v0 *
// scale).ToString().CString(), (v1 * scale).ToString().CString());
unsigned color = Color::RED.ToUInt();
DrawLine2(IntVector2(v0.x_ * scale, v0.y_ * scale), IntVector2(v1.x_ * scale, v1.y_ * scale), texImage, color);
DrawLine2(IntVector2(v1.x_ * scale, v1.y_ * scale), IntVector2(v2.x_ * scale, v2.y_ * scale), texImage, color);
DrawLine2(IntVector2(v2.x_ * scale, v2.y_ * scale), IntVector2(v0.x_ * scale, v0.y_ * scale), texImage, color);
}
void EditorModelDebug::DrawPoint(int x, int y, Image* image, unsigned color)
{
// draw point
for (unsigned j = 0; j < 9; j++)
{
int xx = (j % 3) - 1;
int yy = (j / 3) - 1;
image->SetPixelInt(x + xx, y + yy, color);
}
}
} // namespace Urho3D
|
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/selu_op.h"
#include <memory>
#include <string>
#include <unordered_map>
namespace paddle {
namespace operators {
class SeluOp : public framework::OperatorWithKernel {
public:
SeluOp(const std::string &type, const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorWithKernel(type, inputs, outputs, attrs) {}
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"),
"Input(X) of SeluOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Out"),
"Output(Out) of SeluOp should not be null.");
ctx->ShareDim("X", /*->*/ "Out");
ctx->ShareLoD("X", /*->*/ "Out");
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
return framework::OpKernelType(
OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
}
};
class SeluOpInferVarType : public framework::PassInDtypeAndVarTypeToOutput {
protected:
std::unordered_map<std::string, std::string> GetInputOutputWithSameType()
const override {
return std::unordered_map<std::string, std::string>{{"X", /*->*/ "Out"}};
}
};
class SeluOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X", "The input tensor of selu operator.");
AddOutput("Out", "The output tensor of selu operator.");
AddAttr<float>("scale",
"(float) the default value is 1.0507~. For more "
"information about this value, please refer to:"
"https://arxiv.org/abs/1706.02515.")
.SetDefault(1.0507009873554804934193349852946);
AddAttr<float>("alpha",
"(float) the default value is 1.6732~. For more "
"information about this value, please refer to:"
"https://arxiv.org/abs/1706.02515.")
.SetDefault(1.6732632423543772848170429916717);
AddComment(R"DOC(
Selu Operator.
The equation is:
$$
f(x) =\lambda*
\begin{cases}
\quad \quad x, \quad \quad \quad \text{if} \ x > 0 \\
\alpha * e^x - \alpha, \qquad \text{if} \ x <= 0
\end{cases}
$$
The input `X` can carry the LoD (Level of Details) information,
or not. And the output shares the LoD information with input `X`.
)DOC");
}
};
class SeluGradMaker : public framework::SingleGradOpDescMaker {
public:
using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;
std::unique_ptr<framework::OpDesc> Apply() const override {
auto *grad_op = new framework::OpDesc();
grad_op->SetType("selu_grad");
grad_op->SetInput("Out", Output("Out"));
grad_op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
grad_op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
grad_op->SetAttrMap(this->Attrs());
return std::unique_ptr<framework::OpDesc>(grad_op);
}
};
class SeluGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null");
PADDLE_ENFORCE(ctx->HasInput("Out"), "Input(Out) should not be null");
auto x_grad_name = framework::GradVarName("X");
ctx->SetOutputDim(x_grad_name, ctx->GetInputDim("Out"));
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
return framework::OpKernelType(
OperatorWithKernel::IndicateVarDataType(ctx, "Out"), ctx.GetPlace());
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(selu, ops::SeluOp, ops::SeluOpMaker, ops::SeluOpInferVarType,
ops::SeluGradMaker);
REGISTER_OPERATOR(selu_grad, ops::SeluGradOp);
REGISTER_OP_CPU_KERNEL(
selu, ops::SeluKernel<paddle::platform::CPUDeviceContext, float>,
ops::SeluKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
selu_grad, ops::SeluGradKernel<paddle::platform::CPUDeviceContext, float>,
ops::SeluGradKernel<paddle::platform::CPUDeviceContext, double>);
|
#include <CQSound.h>
#include <QSound>
#include <QAudioDeviceInfo>
#include <CSDLSound.h>
CQSoundMgr *
CQSoundMgr::
getInstance()
{
static CQSoundMgr *instance;
if (! instance)
instance = new CQSoundMgr;
return instance;
}
void
CQSoundMgr::
setActive(bool active)
{
active_ = active;
}
CQSoundMgr::
CQSoundMgr() :
active_(true), qsound_(false), sdl_sound_(0)
{
//qsound_ = QSound::isAvailable();
qsound_ = ! QAudioDeviceInfo::availableDevices(QAudio::AudioOutput).isEmpty();
}
CQSound *
CQSoundMgr::
addSound(const char *filename)
{
CQSound *sound = new CQSound(filename, qsound_);
sounds_.push_back(sound);
return sound;
}
void
CQSoundMgr::
playSound(CQSound *sound)
{
if (! active_) return;
SoundList::const_iterator p1, p2;
if (qsound_) {
for (p1 = sounds_.begin(), p2 = sounds_.end(); p1 != p2; ++p1)
(*p1)->stop();
}
sound->play();
}
//--------------
CQSound::
CQSound(const char *filename, bool qsound) :
filename_(filename), qsound_(0)
{
if (qsound)
qsound_ = new QSound(filename);
else
sound_ = CSDLSoundMgrInst->createSound(filename);
}
CQSound::
~CQSound()
{
delete qsound_;
delete sound_;
}
void
CQSound::
play()
{
if (qsound_)
qsound_->play();
else
sound_->play();
}
void
CQSound::
stop()
{
if (qsound_)
qsound_->stop();
else
sound_->stop();
}
|
// Copyright (c) 2017-2018 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "zciphcontroldialog.h"
#include "ui_zciphcontroldialog.h"
#include "accumulators.h"
#include "main.h"
#include "walletmodel.h"
using namespace std;
using namespace libzerocoin;
std::set<std::string> ZPivControlDialog::setSelectedMints;
std::set<CMintMeta> ZPivControlDialog::setMints;
ZPivControlDialog::ZPivControlDialog(QWidget *parent) :
QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::ZPivControlDialog),
model(0)
{
ui->setupUi(this);
setMints.clear();
privacyDialog = (PrivacyDialog*)parent;
// click on checkbox
connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(updateSelection(QTreeWidgetItem*, int)));
// push select/deselect all button
connect(ui->pushButtonAll, SIGNAL(clicked()), this, SLOT(ButtonAllClicked()));
}
ZPivControlDialog::~ZPivControlDialog()
{
delete ui;
}
void ZPivControlDialog::setModel(WalletModel *model)
{
this->model = model;
updateList();
}
//Update the tree widget
void ZPivControlDialog::updateList()
{
// need to prevent the slot from being called each time something is changed
ui->treeWidget->blockSignals(true);
ui->treeWidget->clear();
// add a top level item for each denomination
QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
map<libzerocoin::CoinDenomination, int> mapDenomPosition;
for (auto denom : libzerocoin::zerocoinDenomList) {
QTreeWidgetItem* itemDenom(new QTreeWidgetItem);
ui->treeWidget->addTopLevelItem(itemDenom);
//keep track of where this is positioned in tree widget
mapDenomPosition[denom] = ui->treeWidget->indexOfTopLevelItem(itemDenom);
itemDenom->setFlags(flgTristate);
itemDenom->setText(COLUMN_DENOMINATION, QString::number(denom));
}
// select all unused coins - including not mature. Update status of coins too.
std::set<CMintMeta> set;
model->listZerocoinMints(set, true, false, true);
this->setMints = set;
//populate rows with mint info
int nBestHeight = chainActive.Height();
map<CoinDenomination, int> mapMaturityHeight = GetMintMaturityHeight();
for (const CMintMeta& mint : setMints) {
// assign this mint to the correct denomination in the tree view
libzerocoin::CoinDenomination denom = mint.denom;
QTreeWidgetItem *itemMint = new QTreeWidgetItem(ui->treeWidget->topLevelItem(mapDenomPosition.at(denom)));
// if the mint is already selected, then it needs to have the checkbox checked
std::string strPubCoinHash = mint.hashPubcoin.GetHex();
if (setSelectedMints.count(strPubCoinHash))
itemMint->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
else
itemMint->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
itemMint->setText(COLUMN_DENOMINATION, QString::number(mint.denom));
itemMint->setText(COLUMN_PUBCOIN, QString::fromStdString(strPubCoinHash));
itemMint->setText(COLUMN_VERSION, QString::number(mint.nVersion));
int nConfirmations = (mint.nHeight ? nBestHeight - mint.nHeight : 0);
if (nConfirmations < 0) {
// Sanity check
nConfirmations = 0;
}
itemMint->setText(COLUMN_CONFIRMATIONS, QString::number(nConfirmations));
// check for maturity
bool isMature = false;
if (mapMaturityHeight.count(mint.denom))
isMature = mint.nHeight < mapMaturityHeight.at(denom);
// disable selecting this mint if it is not spendable - also display a reason why
bool fSpendable = isMature && nConfirmations >= Params().Zerocoin_MintRequiredConfirmations();
if(!fSpendable) {
itemMint->setDisabled(true);
itemMint->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
//if this mint is in the selection list, then remove it
if (setSelectedMints.count(strPubCoinHash))
setSelectedMints.erase(strPubCoinHash);
string strReason = "";
if(nConfirmations < Params().Zerocoin_MintRequiredConfirmations())
strReason = strprintf("Needs %d more confirmations", Params().Zerocoin_MintRequiredConfirmations() - nConfirmations);
else
strReason = strprintf("Needs %d more mints added to network", Params().Zerocoin_RequiredAccumulation());
itemMint->setText(COLUMN_ISSPENDABLE, QString::fromStdString(strReason));
} else {
itemMint->setText(COLUMN_ISSPENDABLE, QString("Yes"));
}
}
ui->treeWidget->blockSignals(false);
updateLabels();
}
// Update the list when a checkbox is clicked
void ZPivControlDialog::updateSelection(QTreeWidgetItem* item, int column)
{
// only want updates from non top level items that are available to spend
if (item->parent() && column == COLUMN_CHECKBOX && !item->isDisabled()){
// see if this mint is already selected in the selection list
std::string strPubcoin = item->text(COLUMN_PUBCOIN).toStdString();
bool fSelected = setSelectedMints.count(strPubcoin);
// set the checkbox to the proper state and add or remove the mint from the selection list
if (item->checkState(COLUMN_CHECKBOX) == Qt::Checked) {
if (fSelected) return;
setSelectedMints.insert(strPubcoin);
} else {
if (!fSelected) return;
setSelectedMints.erase(strPubcoin);
}
updateLabels();
}
}
// Update the Quantity and Amount display
void ZPivControlDialog::updateLabels()
{
int64_t nAmount = 0;
for (const CMintMeta& mint : setMints) {
if (setSelectedMints.count(mint.hashPubcoin.GetHex()))
nAmount += mint.denom;
}
//update this dialog's labels
ui->labelZPiv_int->setText(QString::number(nAmount));
ui->labelQuantity_int->setText(QString::number(setSelectedMints.size()));
//update PrivacyDialog labels
privacyDialog->setZPivControlLabels(nAmount, setSelectedMints.size());
}
std::vector<CMintMeta> ZPivControlDialog::GetSelectedMints()
{
std::vector<CMintMeta> listReturn;
for (const CMintMeta& mint : setMints) {
if (setSelectedMints.count(mint.hashPubcoin.GetHex()))
listReturn.emplace_back(mint);
}
return listReturn;
}
// select or deselect all of the mints
void ZPivControlDialog::ButtonAllClicked()
{
ui->treeWidget->blockSignals(true);
Qt::CheckState state = Qt::Checked;
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) {
if(ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) {
state = Qt::Unchecked;
break;
}
}
//much quicker to start from scratch than to have QT go through all the objects and update
ui->treeWidget->clear();
if (state == Qt::Checked) {
for(const CMintMeta& mint : setMints)
setSelectedMints.insert(mint.hashPubcoin.GetHex());
} else {
setSelectedMints.clear();
}
updateList();
}
|
#ifndef PT_HIT_RECORD_HPP
#define PT_HIT_RECORD_HPP
#pragma once
#include "ray.hpp"
#include "sphere.hpp"
#include "vec.hpp"
namespace pt {
struct hit_record
{
ray original_ray{};
vec3 hit_point{ 0, 0, 0 };
vec3 outward_normal{ 0, 0, 0 };
vec3 normal{ 0, 0, 0 };
bool front_facing{ false };
};
[[nodiscard]] auto get_hit_record_at(sphere const& sphere, ray const& r, double t) noexcept -> hit_record;
} // namespace pt
#endif // !PT_HIT_RECORD_HPP
|
#include <bits/stdc++.h>
using namespace std;
// Complete the maxMin function below.
int maxMin(int k, vector<int> arr) {
int ret = 999999999;
sort(arr.begin(), arr.end());
for (int i = 0, j = k - 1; j < arr.size(); ++j, ++i) {
if ((arr[j] - arr[i]) < ret) {
ret = arr[j] - arr[i];
}
}
return ret;
}
|
// -------------------------------------------------------------------------------------------------
// Copyright 2016 - NumScale SAS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
// -------------------------------------------------------------------------------------------------
#include <simd_bench.hpp>
#include <boost/simd/function/simd/is_negative.hpp>
#include <boost/simd/pack.hpp>
namespace nsb = ns::bench;
namespace bs = boost::simd;
DEFINE_SIMD_BENCH(simd_is_negative, bs::is_negative);
DEFINE_BENCH_MAIN()
{
nsb::for_each<simd_is_negative, NS_BENCH_IEEE_TYPES>(-10, 10);
}
|
#include "stdafx.h"
#include "Professor.h"
// Initializes professor data
Professor::Professor(int id, const string& name) : _id(id),
_name(name) { }
// Bind professor to course
void Professor::AddCourseClass(CourseClass* courseClass)
{
_courseClasses.push_back( courseClass );
}
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_TEXTURE_CONST_PART_UNIQUE_PTR_HPP_INCLUDED
#define SGE_TEXTURE_CONST_PART_UNIQUE_PTR_HPP_INCLUDED
#include <sge/texture/part_fwd.hpp>
#include <fcppt/unique_ptr_impl.hpp>
namespace sge::texture
{
using const_part_unique_ptr = fcppt::unique_ptr<sge::texture::part const>;
}
#endif
|
//=================================================================================================
/*!
// \file src/mathtest/dmatsmatmult/SDaUCb.cpp
// \brief Source file for the SDaUCb dense matrix/sparse matrix multiplication math test
//
// Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/SymmetricMatrix.h>
#include <blaze/math/UpperMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatsmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'SDaUCb'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using SDa = blaze::SymmetricMatrix< blaze::DynamicMatrix<TypeA> >;
using UCb = blaze::UpperMatrix< blaze::CompressedMatrix<TypeB> >;
// Creator type definitions
using CSDa = blazetest::Creator<SDa>;
using CUCb = blazetest::Creator<UCb>;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=UCb::maxNonZeros( i ); ++j ) {
RUN_DMATSMATMULT_OPERATION_TEST( CSDa( i ), CUCb( i, j ) );
}
}
// Running tests with large matrices
RUN_DMATSMATMULT_OPERATION_TEST( CSDa( 31UL ), CUCb( 31UL, 7UL ) );
RUN_DMATSMATMULT_OPERATION_TEST( CSDa( 67UL ), CUCb( 67UL, 7UL ) );
RUN_DMATSMATMULT_OPERATION_TEST( CSDa( 127UL ), CUCb( 127UL, 13UL ) );
RUN_DMATSMATMULT_OPERATION_TEST( CSDa( 32UL ), CUCb( 32UL, 8UL ) );
RUN_DMATSMATMULT_OPERATION_TEST( CSDa( 64UL ), CUCb( 64UL, 8UL ) );
RUN_DMATSMATMULT_OPERATION_TEST( CSDa( 128UL ), CUCb( 128UL, 16UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
// Copyright (c) 2011 Thomas Heller
// Copyright (c) 2013 Hartmut Kaiser
// Copyright (c) 2014 Agustin Berge
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <hpx/functional/detail/empty_function.hpp>
#include <hpx/errors.hpp>
namespace hpx { namespace util { namespace detail {
HPX_NORETURN void throw_bad_function_call()
{
hpx::throw_exception(bad_function_call,
"empty function object should not be used",
"empty_function::operator()");
}
}}} // namespace hpx::util::detail
|
// Copyright (c) 2011-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/util/setup_common.h>
#include <addrman.h>
#include <banman.h>
#include <chainparams.h>
#include <consensus/consensus.h>
#include <consensus/params.h>
#include <consensus/validation.h>
#include <crypto/sha256.h>
#include <init.h>
#include <interfaces/chain.h>
#include <miner.h>
#include <net.h>
#include <net_processing.h>
#include <noui.h>
#include <policy/fees.h>
#include <pow.h>
#include <rpc/blockchain.h>
#include <rpc/register.h>
#include <rpc/server.h>
#include <scheduler.h>
#include <script/sigcache.h>
#include <streams.h>
#include <txdb.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/thread.h>
#include <util/threadnames.h>
#include <util/time.h>
#include <util/translation.h>
#include <util/url.h>
#include <util/vector.h>
#include <validation.h>
#include <validationinterface.h>
#include <walletinitinterface.h>
#include <functional>
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
UrlDecodeFn* const URL_DECODE = nullptr;
FastRandomContext g_insecure_rand_ctx;
/** Random context to get unique temp data dirs. Separate from g_insecure_rand_ctx, which can be seeded from a const env var */
static FastRandomContext g_insecure_rand_ctx_temp_path;
/** Return the unsigned from the environment var if available, otherwise 0 */
static uint256 GetUintFromEnv(const std::string& env_name)
{
const char* num = std::getenv(env_name.c_str());
if (!num) return {};
return uint256S(num);
}
void Seed(FastRandomContext& ctx)
{
// Should be enough to get the seed once for the process
static uint256 seed{};
static const std::string RANDOM_CTX_SEED{"RANDOM_CTX_SEED"};
if (seed.IsNull()) seed = GetUintFromEnv(RANDOM_CTX_SEED);
if (seed.IsNull()) seed = GetRandHash();
LogPrintf("%s: Setting random seed for current tests to %s=%s\n", __func__, RANDOM_CTX_SEED, seed.GetHex());
ctx = FastRandomContext(seed);
}
std::ostream& operator<<(std::ostream& os, const uint256& num)
{
os << num.ToString();
return os;
}
BasicTestingSetup::BasicTestingSetup(const std::string& chainName, const std::vector<const char*>& extra_args)
: m_path_root{fs::temp_directory_path() / "test_common_" PACKAGE_NAME / g_insecure_rand_ctx_temp_path.rand256().ToString()},
m_args{}
{
m_node.args = &gArgs;
const std::vector<const char*> arguments = Cat(
{
"dummy",
"-printtoconsole=0",
"-logsourcelocations",
"-logtimemicros",
"-logthreadnames",
"-debug",
"-debugexclude=libevent",
"-debugexclude=leveldb",
},
extra_args);
util::ThreadRename("test");
fs::create_directories(m_path_root);
m_args.ForceSetArg("-datadir", m_path_root.string());
gArgs.ForceSetArg("-datadir", m_path_root.string());
gArgs.ClearPathCache();
{
SetupServerArgs(*m_node.args);
std::string error;
const bool success{m_node.args->ParseParameters(arguments.size(), arguments.data(), error)};
assert(success);
assert(error.empty());
}
SelectParams(chainName);
SeedInsecureRand();
if (G_TEST_LOG_FUN) LogInstance().PushBackCallback(G_TEST_LOG_FUN);
InitLogging(*m_node.args);
AppInitParameterInteraction(*m_node.args);
LogInstance().StartLogging();
SHA256AutoDetect();
ECC_Start();
SetupEnvironment();
SetupNetworking();
InitSignatureCache();
InitScriptExecutionCache();
m_node.chain = interfaces::MakeChain(m_node);
g_wallet_init_interface.Construct(m_node);
fCheckBlockIndex = true;
static bool noui_connected = false;
if (!noui_connected) {
noui_connect();
noui_connected = true;
}
}
BasicTestingSetup::~BasicTestingSetup()
{
SetMockTime(0s); // Reset mocktime for following tests
LogInstance().DisconnectTestLogger();
fs::remove_all(m_path_root);
gArgs.ClearArgs();
ECC_Stop();
}
ChainTestingSetup::ChainTestingSetup(const std::string& chainName, const std::vector<const char*>& extra_args)
: BasicTestingSetup(chainName, extra_args)
{
// We have to run a scheduler thread to prevent ActivateBestChain
// from blocking due to queue overrun.
m_node.scheduler = std::make_unique<CScheduler>();
m_node.scheduler->m_service_thread = std::thread(util::TraceThread, "scheduler", [&] { m_node.scheduler->serviceQueue(); });
GetMainSignals().RegisterBackgroundSignalScheduler(*m_node.scheduler);
pblocktree.reset(new CBlockTreeDB(1 << 20, true));
m_node.fee_estimator = std::make_unique<CBlockPolicyEstimator>();
m_node.mempool = std::make_unique<CTxMemPool>(m_node.fee_estimator.get(), 1);
m_node.chainman = std::make_unique<ChainstateManager>();
// Start script-checking threads. Set g_parallel_script_checks to true so they are used.
constexpr int script_check_threads = 2;
StartScriptCheckWorkerThreads(script_check_threads);
g_parallel_script_checks = true;
}
ChainTestingSetup::~ChainTestingSetup()
{
if (m_node.scheduler) m_node.scheduler->stop();
StopScriptCheckWorkerThreads();
GetMainSignals().FlushBackgroundCallbacks();
GetMainSignals().UnregisterBackgroundSignalScheduler();
m_node.connman.reset();
m_node.banman.reset();
m_node.addrman.reset();
m_node.args = nullptr;
UnloadBlockIndex(m_node.mempool.get(), *m_node.chainman);
m_node.mempool.reset();
m_node.scheduler.reset();
m_node.chainman->Reset();
m_node.chainman.reset();
pblocktree.reset();
}
TestingSetup::TestingSetup(const std::string& chainName, const std::vector<const char*>& extra_args)
: ChainTestingSetup(chainName, extra_args)
{
const CChainParams& chainparams = Params();
// Ideally we'd move all the RPC tests to the functional testing framework
// instead of unit tests, but for now we need these here.
RegisterAllCoreRPCCommands(tableRPC);
m_node.chainman->InitializeChainstate(*m_node.mempool);
m_node.chainman->ActiveChainstate().InitCoinsDB(
/* cache_size_bytes */ 1 << 23, /* in_memory */ true, /* should_wipe */ false);
assert(!m_node.chainman->ActiveChainstate().CanFlushToDisk());
m_node.chainman->ActiveChainstate().InitCoinsCache(1 << 23);
assert(m_node.chainman->ActiveChainstate().CanFlushToDisk());
if (!m_node.chainman->ActiveChainstate().LoadGenesisBlock(chainparams)) {
throw std::runtime_error("LoadGenesisBlock failed.");
}
BlockValidationState state;
if (!m_node.chainman->ActiveChainstate().ActivateBestChain(state, chainparams)) {
throw std::runtime_error(strprintf("ActivateBestChain failed. (%s)", state.ToString()));
}
m_node.addrman = std::make_unique<CAddrMan>();
m_node.banman = std::make_unique<BanMan>(m_args.GetDataDirBase() / "banlist", nullptr, DEFAULT_MISBEHAVING_BANTIME);
m_node.connman = std::make_unique<CConnman>(0x1337, 0x1337, *m_node.addrman); // Deterministic randomness for tests.
m_node.peerman = PeerManager::make(chainparams, *m_node.connman, *m_node.addrman,
m_node.banman.get(), *m_node.scheduler, *m_node.chainman,
*m_node.mempool, false);
{
CConnman::Options options;
options.m_msgproc = m_node.peerman.get();
m_node.connman->Init(options);
}
}
TestChain100Setup::TestChain100Setup()
{
SetMockTime(1598887952);
constexpr std::array<unsigned char, 32> vchKey = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}};
coinbaseKey.Set(vchKey.begin(), vchKey.end(), true);
// Generate a 100-block chain:
this->mineBlocks(COINBASE_MATURITY);
{
LOCK(::cs_main);
assert(
m_node.chainman->ActiveChain().Tip()->GetBlockHash().ToString() ==
"571d80a9967ae599cec0448b0b0ba1cfb606f584d8069bd7166b86854ba7a191");
}
}
void TestChain100Setup::mineBlocks(int num_blocks)
{
CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
for (int i = 0; i < num_blocks; i++) {
std::vector<CMutableTransaction> noTxns;
CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey);
SetMockTime(GetTime() + 1);
m_coinbase_txns.push_back(b.vtx[0]);
}
}
CBlock TestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey)
{
const CChainParams& chainparams = Params();
CTxMemPool empty_pool;
CBlock block = BlockAssembler(m_node.chainman->ActiveChainstate(), empty_pool, chainparams).CreateNewBlock(scriptPubKey)->block;
Assert(block.vtx.size() == 1);
for (const CMutableTransaction& tx : txns) {
block.vtx.push_back(MakeTransactionRef(tx));
}
RegenerateCommitments(block, *Assert(m_node.chainman));
while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce;
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
Assert(m_node.chainman)->ProcessNewBlock(chainparams, shared_pblock, true, nullptr);
return block;
}
CMutableTransaction TestChain100Setup::CreateValidMempoolTransaction(CTransactionRef input_transaction,
int input_vout,
int input_height,
CKey input_signing_key,
CScript output_destination,
CAmount output_amount,
bool submit)
{
// Transaction we will submit to the mempool
CMutableTransaction mempool_txn;
// Create an input
COutPoint outpoint_to_spend(input_transaction->GetHash(), input_vout);
CTxIn input(outpoint_to_spend);
mempool_txn.vin.push_back(input);
// Create an output
CTxOut output(output_amount, output_destination);
mempool_txn.vout.push_back(output);
// Sign the transaction
// - Add the signing key to a keystore
FillableSigningProvider keystore;
keystore.AddKey(input_signing_key);
// - Populate a CoinsViewCache with the unspent output
CCoinsView coins_view;
CCoinsViewCache coins_cache(&coins_view);
AddCoins(coins_cache, *input_transaction.get(), input_height);
// - Use GetCoin to properly populate utxo_to_spend,
Coin utxo_to_spend;
assert(coins_cache.GetCoin(outpoint_to_spend, utxo_to_spend));
// - Then add it to a map to pass in to SignTransaction
std::map<COutPoint, Coin> input_coins;
input_coins.insert({outpoint_to_spend, utxo_to_spend});
// - Default signature hashing type
int nHashType = SIGHASH_ALL;
std::map<int, std::string> input_errors;
assert(SignTransaction(mempool_txn, &keystore, input_coins, nHashType, input_errors));
// If submit=true, add transaction to the mempool.
if (submit) {
LOCK(cs_main);
const MempoolAcceptResult result = AcceptToMemoryPool(m_node.chainman->ActiveChainstate(), *m_node.mempool.get(), MakeTransactionRef(mempool_txn), /* bypass_limits */ false);
assert(result.m_result_type == MempoolAcceptResult::ResultType::VALID);
}
return mempool_txn;
}
TestChain100Setup::~TestChain100Setup()
{
gArgs.ForceSetArg("-segwitheight", "0");
}
CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction& tx) const
{
return FromTx(MakeTransactionRef(tx));
}
CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransactionRef& tx) const
{
return CTxMemPoolEntry(tx, nFee, nTime, nHeight,
spendsCoinbase, sigOpCost, lp);
}
/**
* @returns a real block (0000000000013b8ab2cd513b0261a14096412195a72a0c4827d229dcc7e0f7af)
* with 9 txs.
*/
CBlock getBlock13b8a()
{
CBlock block;
CDataStream stream(ParseHex("0100000090f0a9f110702f808219ebea1173056042a714bad51b916cb6800000000000005275289558f51c9966699404ae2294730c3c9f9bda53523ce50e9b95e558da2fdb261b4d4c86041b1ab1bf930901000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0146ffffffff0100f2052a01000000434104e18f7afbe4721580e81e8414fc8c24d7cfacf254bb5c7b949450c3e997c2dc1242487a8169507b631eb3771f2b425483fb13102c4eb5d858eef260fe70fbfae0ac00000000010000000196608ccbafa16abada902780da4dc35dafd7af05fa0da08cf833575f8cf9e836000000004a493046022100dab24889213caf43ae6adc41cf1c9396c08240c199f5225acf45416330fd7dbd022100fe37900e0644bf574493a07fc5edba06dbc07c311b947520c2d514bc5725dcb401ffffffff0100f2052a010000001976a914f15d1921f52e4007b146dfa60f369ed2fc393ce288ac000000000100000001fb766c1288458c2bafcfec81e48b24d98ec706de6b8af7c4e3c29419bfacb56d000000008c493046022100f268ba165ce0ad2e6d93f089cfcd3785de5c963bb5ea6b8c1b23f1ce3e517b9f022100da7c0f21adc6c401887f2bfd1922f11d76159cbc597fbd756a23dcbb00f4d7290141042b4e8625a96127826915a5b109852636ad0da753c9e1d5606a50480cd0c40f1f8b8d898235e571fe9357d9ec842bc4bba1827daaf4de06d71844d0057707966affffffff0280969800000000001976a9146963907531db72d0ed1a0cfb471ccb63923446f388ac80d6e34c000000001976a914f0688ba1c0d1ce182c7af6741e02658c7d4dfcd388ac000000000100000002c40297f730dd7b5a99567eb8d27b78758f607507c52292d02d4031895b52f2ff010000008b483045022100f7edfd4b0aac404e5bab4fd3889e0c6c41aa8d0e6fa122316f68eddd0a65013902205b09cc8b2d56e1cd1f7f2fafd60a129ed94504c4ac7bdc67b56fe67512658b3e014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffffca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefb000000008a473044022068010362a13c7f9919fa832b2dee4e788f61f6f5d344a7c2a0da6ae740605658022006d1af525b9a14a35c003b78b72bd59738cd676f845d1ff3fc25049e01003614014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffff01001ec4110200000043410469ab4181eceb28985b9b4e895c13fa5e68d85761b7eee311db5addef76fa8621865134a221bd01f28ec9999ee3e021e60766e9d1f3458c115fb28650605f11c9ac000000000100000001cdaf2f758e91c514655e2dc50633d1e4c84989f8aa90a0dbc883f0d23ed5c2fa010000008b48304502207ab51be6f12a1962ba0aaaf24a20e0b69b27a94fac5adf45aa7d2d18ffd9236102210086ae728b370e5329eead9accd880d0cb070aea0c96255fae6c4f1ddcce1fd56e014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff02404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac002d3101000000001976a9141befba0cdc1ad56529371864d9f6cb042faa06b588ac000000000100000001b4a47603e71b61bc3326efd90111bf02d2f549b067f4c4a8fa183b57a0f800cb010000008a4730440220177c37f9a505c3f1a1f0ce2da777c339bd8339ffa02c7cb41f0a5804f473c9230220585b25a2ee80eb59292e52b987dad92acb0c64eced92ed9ee105ad153cdb12d001410443bd44f683467e549dae7d20d1d79cbdb6df985c6e9c029c8d0c6cb46cc1a4d3cf7923c5021b27f7a0b562ada113bc85d5fda5a1b41e87fe6e8802817cf69996ffffffff0280651406000000001976a9145505614859643ab7b547cd7f1f5e7e2a12322d3788ac00aa0271000000001976a914ea4720a7a52fc166c55ff2298e07baf70ae67e1b88ac00000000010000000586c62cd602d219bb60edb14a3e204de0705176f9022fe49a538054fb14abb49e010000008c493046022100f2bc2aba2534becbdf062eb993853a42bbbc282083d0daf9b4b585bd401aa8c9022100b1d7fd7ee0b95600db8535bbf331b19eed8d961f7a8e54159c53675d5f69df8c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff03ad0e58ccdac3df9dc28a218bcf6f1997b0a93306faaa4b3a28ae83447b2179010000008b483045022100be12b2937179da88599e27bb31c3525097a07cdb52422d165b3ca2f2020ffcf702200971b51f853a53d644ebae9ec8f3512e442b1bcb6c315a5b491d119d10624c83014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff2acfcab629bbc8685792603762c921580030ba144af553d271716a95089e107b010000008b483045022100fa579a840ac258871365dd48cd7552f96c8eea69bd00d84f05b283a0dab311e102207e3c0ee9234814cfbb1b659b83671618f45abc1326b9edcc77d552a4f2a805c0014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffdcdc6023bbc9944a658ddc588e61eacb737ddf0a3cd24f113b5a8634c517fcd2000000008b4830450221008d6df731df5d32267954bd7d2dda2302b74c6c2a6aa5c0ca64ecbabc1af03c75022010e55c571d65da7701ae2da1956c442df81bbf076cdbac25133f99d98a9ed34c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffe15557cd5ce258f479dfd6dc6514edf6d7ed5b21fcfa4a038fd69f06b83ac76e010000008b483045022023b3e0ab071eb11de2eb1cc3a67261b866f86bf6867d4558165f7c8c8aca2d86022100dc6e1f53a91de3efe8f63512850811f26284b62f850c70ca73ed5de8771fb451014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff01404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000010000000166d7577163c932b4f9690ca6a80b6e4eb001f0a2fa9023df5595602aae96ed8d000000008a4730440220262b42546302dfb654a229cefc86432b89628ff259dc87edd1154535b16a67e102207b4634c020a97c3e7bbd0d4d19da6aa2269ad9dded4026e896b213d73ca4b63f014104979b82d02226b3a4597523845754d44f13639e3bf2df5e82c6aab2bdc79687368b01b1ab8b19875ae3c90d661a3d0a33161dab29934edeb36aa01976be3baf8affffffff02404b4c00000000001976a9144854e695a02af0aeacb823ccbc272134561e0a1688ac40420f00000000001976a914abee93376d6b37b5c2940655a6fcaf1c8e74237988ac0000000001000000014e3f8ef2e91349a9059cb4f01e54ab2597c1387161d3da89919f7ea6acdbb371010000008c49304602210081f3183471a5ca22307c0800226f3ef9c353069e0773ac76bb580654d56aa523022100d4c56465bdc069060846f4fbf2f6b20520b2a80b08b168b31e66ddb9c694e240014104976c79848e18251612f8940875b2b08d06e6dc73b9840e8860c066b7e87432c477e9a59a453e71e6d76d5fe34058b800a098fc1740ce3012e8fc8a00c96af966ffffffff02c0e1e400000000001976a9144134e75a6fcb6042034aab5e18570cf1f844f54788ac404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
return block;
}
|
#ifndef FEEDING_FOODITEM_HPP_
#define FEEDING_FOODITEM_HPP_
#include <aikido/common/pointers.hpp>
#include <aikido/perception/DetectedObject.hpp>
#include <dart/dart.hpp>
#include <yaml-cpp/exceptions.h>
#include "feeding/AcquisitionAction.hpp"
namespace feeding {
AIKIDO_DECLARE_POINTERS(FoodItem)
class FoodItem {
public:
FoodItem(std::string name, std::string uid,
dart::dynamics::MetaSkeletonPtr metaSkeleton,
AcquisitionAction action, double score);
FoodItem(std::string name, std::string uid,
dart::dynamics::MetaSkeletonPtr metaSkeleton,
AcquisitionAction action, double score, const YAML::Node info);
Eigen::Isometry3d getPose() const;
std::string getName() const;
std::string getUid() const;
dart::dynamics::MetaSkeletonPtr getMetaSkeleton() const;
AcquisitionAction const *getAction() const;
void setAction(int actionNum);
double getScore() const;
YAML::Node getExtraInfo() const;
private:
const std::string mName;
const std::string mUid; // unique id necessary for tracking
const dart::dynamics::MetaSkeletonPtr mMetaSkeleton;
AcquisitionAction mAction;
double mScore;
const YAML::Node mExtraInfo;
};
} // namespace feeding
#endif
|
// Copyright 2014 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 "config.h"
#include "modules/battery/BatteryDispatcher.h"
#include "modules/battery/BatteryStatus.h"
#include "platform/NotImplemented.h"
#include "public/platform/Platform.h"
namespace blink {
BatteryDispatcher& BatteryDispatcher::instance()
{
DEFINE_STATIC_LOCAL(BatteryDispatcher, batteryDispatcher, ());
return batteryDispatcher;
}
BatteryDispatcher::BatteryDispatcher()
{
}
BatteryDispatcher::~BatteryDispatcher()
{
}
void BatteryDispatcher::updateBatteryStatus(const WebBatteryStatus& batteryStatus)
{
m_batteryStatus = BatteryStatus::create(batteryStatus.charging, batteryStatus.chargingTime, batteryStatus.dischargingTime, batteryStatus.level);
notifyControllers();
}
BatteryStatus* BatteryDispatcher::latestData()
{
return m_batteryStatus.get();
}
void BatteryDispatcher::startListening()
{
Platform::current()->startListening(WebPlatformEventBattery, this);
}
void BatteryDispatcher::stopListening()
{
Platform::current()->stopListening(WebPlatformEventBattery);
m_batteryStatus.clear();
}
} // namespace blink
|
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#include "accessors.h"
#include "api.h"
#include "bootstrapper.h"
#include "codegen.h"
#include "compilation-cache.h"
#include "debug.h"
#include "deoptimizer.h"
#include "global-handles.h"
#include "heap-profiler.h"
#include "incremental-marking.h"
#include "mark-compact.h"
#include "natives.h"
#include "objects-visiting.h"
#include "objects-visiting-inl.h"
#include "once.h"
#include "runtime-profiler.h"
#include "scopeinfo.h"
#include "snapshot.h"
#include "store-buffer.h"
#include "v8threads.h"
#include "v8utils.h"
#include "vm-state-inl.h"
#if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
#include "regexp-macro-assembler.h"
#include "arm/regexp-macro-assembler-arm.h"
#endif
#if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
#include "regexp-macro-assembler.h"
#include "mips/regexp-macro-assembler-mips.h"
#endif
namespace v8 {
namespace internal {
Heap::Heap()
: isolate_(NULL),
// semispace_size_ should be a power of 2 and old_generation_size_ should be
// a multiple of Page::kPageSize.
#if defined(V8_TARGET_ARCH_X64)
#define LUMP_OF_MEMORY (2 * MB)
code_range_size_(512*MB),
#else
#define LUMP_OF_MEMORY MB
code_range_size_(0),
#endif
#if defined(ANDROID)
reserved_semispace_size_(4 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
max_semispace_size_(4 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
initial_semispace_size_(Page::kPageSize),
max_old_generation_size_(192*MB),
max_executable_size_(max_old_generation_size_),
#else
reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
initial_semispace_size_(Page::kPageSize),
max_old_generation_size_(700ul * LUMP_OF_MEMORY),
max_executable_size_(256l * LUMP_OF_MEMORY),
#endif
// Variables set based on semispace_size_ and old_generation_size_ in
// ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
// Will be 4 * reserved_semispace_size_ to ensure that young
// generation can be aligned to its size.
survived_since_last_expansion_(0),
sweep_generation_(0),
always_allocate_scope_depth_(0),
linear_allocation_scope_depth_(0),
contexts_disposed_(0),
global_ic_age_(0),
flush_monomorphic_ics_(false),
scan_on_scavenge_pages_(0),
new_space_(this),
old_pointer_space_(NULL),
old_data_space_(NULL),
code_space_(NULL),
map_space_(NULL),
cell_space_(NULL),
lo_space_(NULL),
gc_state_(NOT_IN_GC),
gc_post_processing_depth_(0),
ms_count_(0),
gc_count_(0),
remembered_unmapped_pages_index_(0),
unflattened_strings_length_(0),
#ifdef DEBUG
allocation_allowed_(true),
allocation_timeout_(0),
disallow_allocation_failure_(false),
#endif // DEBUG
new_space_high_promotion_mode_active_(false),
old_gen_promotion_limit_(kMinimumPromotionLimit),
old_gen_allocation_limit_(kMinimumAllocationLimit),
old_gen_limit_factor_(1),
size_of_old_gen_at_last_old_space_gc_(0),
external_allocation_limit_(0),
amount_of_external_allocated_memory_(0),
amount_of_external_allocated_memory_at_last_global_gc_(0),
old_gen_exhausted_(false),
store_buffer_rebuilder_(store_buffer()),
hidden_string_(NULL),
global_gc_prologue_callback_(NULL),
global_gc_epilogue_callback_(NULL),
gc_safe_size_of_old_object_(NULL),
total_regexp_code_generated_(0),
tracer_(NULL),
young_survivors_after_last_gc_(0),
high_survival_rate_period_length_(0),
low_survival_rate_period_length_(0),
survival_rate_(0),
previous_survival_rate_trend_(Heap::STABLE),
survival_rate_trend_(Heap::STABLE),
max_gc_pause_(0.0),
total_gc_time_ms_(0.0),
max_alive_after_gc_(0),
min_in_mutator_(kMaxInt),
alive_after_last_gc_(0),
last_gc_end_timestamp_(0.0),
marking_time_(0.0),
sweeping_time_(0.0),
store_buffer_(this),
marking_(this),
incremental_marking_(this),
number_idle_notifications_(0),
last_idle_notification_gc_count_(0),
last_idle_notification_gc_count_init_(false),
mark_sweeps_since_idle_round_started_(0),
ms_count_at_last_idle_notification_(0),
gc_count_at_last_idle_gc_(0),
scavenges_since_last_idle_round_(kIdleScavengeThreshold),
#ifdef VERIFY_HEAP
no_weak_embedded_maps_verification_scope_depth_(0),
#endif
promotion_queue_(this),
configured_(false),
chunks_queued_for_free_(NULL),
relocation_mutex_(NULL) {
// Allow build-time customization of the max semispace size. Building
// V8 with snapshots and a non-default max semispace size is much
// easier if you can define it as part of the build environment.
#if defined(V8_MAX_SEMISPACE_SIZE)
max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
#endif
intptr_t max_virtual = OS::MaxVirtualMemory();
if (max_virtual > 0) {
if (code_range_size_ > 0) {
// Reserve no more than 1/8 of the memory for the code range.
code_range_size_ = Min(code_range_size_, max_virtual >> 3);
}
}
memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
native_contexts_list_ = NULL;
mark_compact_collector_.heap_ = this;
external_string_table_.heap_ = this;
// Put a dummy entry in the remembered pages so we can find the list the
// minidump even if there are no real unmapped pages.
RememberUnmappedPage(NULL, false);
ClearObjectStats(true);
}
intptr_t Heap::Capacity() {
if (!HasBeenSetUp()) return 0;
return new_space_.Capacity() +
old_pointer_space_->Capacity() +
old_data_space_->Capacity() +
code_space_->Capacity() +
map_space_->Capacity() +
cell_space_->Capacity();
}
intptr_t Heap::CommittedMemory() {
if (!HasBeenSetUp()) return 0;
return new_space_.CommittedMemory() +
old_pointer_space_->CommittedMemory() +
old_data_space_->CommittedMemory() +
code_space_->CommittedMemory() +
map_space_->CommittedMemory() +
cell_space_->CommittedMemory() +
lo_space_->Size();
}
size_t Heap::CommittedPhysicalMemory() {
if (!HasBeenSetUp()) return 0;
return new_space_.CommittedPhysicalMemory() +
old_pointer_space_->CommittedPhysicalMemory() +
old_data_space_->CommittedPhysicalMemory() +
code_space_->CommittedPhysicalMemory() +
map_space_->CommittedPhysicalMemory() +
cell_space_->CommittedPhysicalMemory() +
lo_space_->CommittedPhysicalMemory();
}
intptr_t Heap::CommittedMemoryExecutable() {
if (!HasBeenSetUp()) return 0;
return isolate()->memory_allocator()->SizeExecutable();
}
intptr_t Heap::Available() {
if (!HasBeenSetUp()) return 0;
return new_space_.Available() +
old_pointer_space_->Available() +
old_data_space_->Available() +
code_space_->Available() +
map_space_->Available() +
cell_space_->Available();
}
bool Heap::HasBeenSetUp() {
return old_pointer_space_ != NULL &&
old_data_space_ != NULL &&
code_space_ != NULL &&
map_space_ != NULL &&
cell_space_ != NULL &&
lo_space_ != NULL;
}
int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
if (IntrusiveMarking::IsMarked(object)) {
return IntrusiveMarking::SizeOfMarkedObject(object);
}
return object->SizeFromMap(object->map());
}
GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
const char** reason) {
// Is global GC requested?
if (space != NEW_SPACE) {
isolate_->counters()->gc_compactor_caused_by_request()->Increment();
*reason = "GC in old space requested";
return MARK_COMPACTOR;
}
if (FLAG_gc_global || (FLAG_stress_compaction && (gc_count_ & 1) != 0)) {
*reason = "GC in old space forced by flags";
return MARK_COMPACTOR;
}
// Is enough data promoted to justify a global GC?
if (OldGenerationPromotionLimitReached()) {
isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
*reason = "promotion limit reached";
return MARK_COMPACTOR;
}
// Have allocation in OLD and LO failed?
if (old_gen_exhausted_) {
isolate_->counters()->
gc_compactor_caused_by_oldspace_exhaustion()->Increment();
*reason = "old generations exhausted";
return MARK_COMPACTOR;
}
// Is there enough space left in OLD to guarantee that a scavenge can
// succeed?
//
// Note that MemoryAllocator->MaxAvailable() undercounts the memory available
// for object promotion. It counts only the bytes that the memory
// allocator has not yet allocated from the OS and assigned to any space,
// and does not count available bytes already in the old space or code
// space. Undercounting is safe---we may get an unrequested full GC when
// a scavenge would have succeeded.
if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
isolate_->counters()->
gc_compactor_caused_by_oldspace_exhaustion()->Increment();
*reason = "scavenge might not succeed";
return MARK_COMPACTOR;
}
// Default
*reason = NULL;
return SCAVENGER;
}
// TODO(1238405): Combine the infrastructure for --heap-stats and
// --log-gc to avoid the complicated preprocessor and flag testing.
void Heap::ReportStatisticsBeforeGC() {
// Heap::ReportHeapStatistics will also log NewSpace statistics when
// compiled --log-gc is set. The following logic is used to avoid
// double logging.
#ifdef DEBUG
if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
if (FLAG_heap_stats) {
ReportHeapStatistics("Before GC");
} else if (FLAG_log_gc) {
new_space_.ReportStatistics();
}
if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
#else
if (FLAG_log_gc) {
new_space_.CollectStatistics();
new_space_.ReportStatistics();
new_space_.ClearHistograms();
}
#endif // DEBUG
}
void Heap::PrintShortHeapStatistics() {
if (!FLAG_trace_gc_verbose) return;
PrintPID("Memory allocator, used: %6" V8_PTR_PREFIX "d KB"
", available: %6" V8_PTR_PREFIX "d KB\n",
isolate_->memory_allocator()->Size() / KB,
isolate_->memory_allocator()->Available() / KB);
PrintPID("New space, used: %6" V8_PTR_PREFIX "d KB"
", available: %6" V8_PTR_PREFIX "d KB"
", committed: %6" V8_PTR_PREFIX "d KB\n",
new_space_.Size() / KB,
new_space_.Available() / KB,
new_space_.CommittedMemory() / KB);
PrintPID("Old pointers, used: %6" V8_PTR_PREFIX "d KB"
", available: %6" V8_PTR_PREFIX "d KB"
", committed: %6" V8_PTR_PREFIX "d KB\n",
old_pointer_space_->SizeOfObjects() / KB,
old_pointer_space_->Available() / KB,
old_pointer_space_->CommittedMemory() / KB);
PrintPID("Old data space, used: %6" V8_PTR_PREFIX "d KB"
", available: %6" V8_PTR_PREFIX "d KB"
", committed: %6" V8_PTR_PREFIX "d KB\n",
old_data_space_->SizeOfObjects() / KB,
old_data_space_->Available() / KB,
old_data_space_->CommittedMemory() / KB);
PrintPID("Code space, used: %6" V8_PTR_PREFIX "d KB"
", available: %6" V8_PTR_PREFIX "d KB"
", committed: %6" V8_PTR_PREFIX "d KB\n",
code_space_->SizeOfObjects() / KB,
code_space_->Available() / KB,
code_space_->CommittedMemory() / KB);
PrintPID("Map space, used: %6" V8_PTR_PREFIX "d KB"
", available: %6" V8_PTR_PREFIX "d KB"
", committed: %6" V8_PTR_PREFIX "d KB\n",
map_space_->SizeOfObjects() / KB,
map_space_->Available() / KB,
map_space_->CommittedMemory() / KB);
PrintPID("Cell space, used: %6" V8_PTR_PREFIX "d KB"
", available: %6" V8_PTR_PREFIX "d KB"
", committed: %6" V8_PTR_PREFIX "d KB\n",
cell_space_->SizeOfObjects() / KB,
cell_space_->Available() / KB,
cell_space_->CommittedMemory() / KB);
PrintPID("Large object space, used: %6" V8_PTR_PREFIX "d KB"
", available: %6" V8_PTR_PREFIX "d KB"
", committed: %6" V8_PTR_PREFIX "d KB\n",
lo_space_->SizeOfObjects() / KB,
lo_space_->Available() / KB,
lo_space_->CommittedMemory() / KB);
PrintPID("All spaces, used: %6" V8_PTR_PREFIX "d KB"
", available: %6" V8_PTR_PREFIX "d KB"
", committed: %6" V8_PTR_PREFIX "d KB\n",
this->SizeOfObjects() / KB,
this->Available() / KB,
this->CommittedMemory() / KB);
PrintPID("Total time spent in GC : %.1f ms\n", total_gc_time_ms_);
}
// TODO(1238405): Combine the infrastructure for --heap-stats and
// --log-gc to avoid the complicated preprocessor and flag testing.
void Heap::ReportStatisticsAfterGC() {
// Similar to the before GC, we use some complicated logic to ensure that
// NewSpace statistics are logged exactly once when --log-gc is turned on.
#if defined(DEBUG)
if (FLAG_heap_stats) {
new_space_.CollectStatistics();
ReportHeapStatistics("After GC");
} else if (FLAG_log_gc) {
new_space_.ReportStatistics();
}
#else
if (FLAG_log_gc) new_space_.ReportStatistics();
#endif // DEBUG
}
void Heap::GarbageCollectionPrologue() {
isolate_->transcendental_cache()->Clear();
ClearJSFunctionResultCaches();
gc_count_++;
unflattened_strings_length_ = 0;
if (FLAG_flush_code && FLAG_flush_code_incrementally) {
mark_compact_collector()->EnableCodeFlushing(true);
}
#ifdef VERIFY_HEAP
if (FLAG_verify_heap) {
Verify();
}
#endif
#ifdef DEBUG
ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
allow_allocation(false);
if (FLAG_gc_verbose) Print();
ReportStatisticsBeforeGC();
#endif // DEBUG
store_buffer()->GCPrologue();
}
intptr_t Heap::SizeOfObjects() {
intptr_t total = 0;
AllSpaces spaces(this);
for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
total += space->SizeOfObjects();
}
return total;
}
void Heap::RepairFreeListsAfterBoot() {
PagedSpaces spaces(this);
for (PagedSpace* space = spaces.next();
space != NULL;
space = spaces.next()) {
space->RepairFreeListsAfterBoot();
}
}
void Heap::GarbageCollectionEpilogue() {
store_buffer()->GCEpilogue();
// In release mode, we only zap the from space under heap verification.
if (Heap::ShouldZapGarbage()) {
ZapFromSpace();
}
#ifdef VERIFY_HEAP
if (FLAG_verify_heap) {
Verify();
}
#endif
#ifdef DEBUG
allow_allocation(true);
if (FLAG_print_global_handles) isolate_->global_handles()->Print();
if (FLAG_print_handles) PrintHandles();
if (FLAG_gc_verbose) Print();
if (FLAG_code_stats) ReportCodeStatistics("After GC");
#endif
isolate_->counters()->alive_after_last_gc()->Set(
static_cast<int>(SizeOfObjects()));
isolate_->counters()->string_table_capacity()->Set(
string_table()->Capacity());
isolate_->counters()->number_of_symbols()->Set(
string_table()->NumberOfElements());
if (CommittedMemory() > 0) {
isolate_->counters()->external_fragmentation_total()->AddSample(
static_cast<int>(100 - (SizeOfObjects() * 100.0) / CommittedMemory()));
isolate_->counters()->heap_fraction_map_space()->AddSample(
static_cast<int>(
(map_space()->CommittedMemory() * 100.0) / CommittedMemory()));
isolate_->counters()->heap_fraction_cell_space()->AddSample(
static_cast<int>(
(cell_space()->CommittedMemory() * 100.0) / CommittedMemory()));
isolate_->counters()->heap_sample_total_committed()->AddSample(
static_cast<int>(CommittedMemory() / KB));
isolate_->counters()->heap_sample_total_used()->AddSample(
static_cast<int>(SizeOfObjects() / KB));
isolate_->counters()->heap_sample_map_space_committed()->AddSample(
static_cast<int>(map_space()->CommittedMemory() / KB));
isolate_->counters()->heap_sample_cell_space_committed()->AddSample(
static_cast<int>(cell_space()->CommittedMemory() / KB));
}
#define UPDATE_COUNTERS_FOR_SPACE(space) \
isolate_->counters()->space##_bytes_available()->Set( \
static_cast<int>(space()->Available())); \
isolate_->counters()->space##_bytes_committed()->Set( \
static_cast<int>(space()->CommittedMemory())); \
isolate_->counters()->space##_bytes_used()->Set( \
static_cast<int>(space()->SizeOfObjects()));
#define UPDATE_FRAGMENTATION_FOR_SPACE(space) \
if (space()->CommittedMemory() > 0) { \
isolate_->counters()->external_fragmentation_##space()->AddSample( \
static_cast<int>(100 - \
(space()->SizeOfObjects() * 100.0) / space()->CommittedMemory())); \
}
#define UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(space) \
UPDATE_COUNTERS_FOR_SPACE(space) \
UPDATE_FRAGMENTATION_FOR_SPACE(space)
UPDATE_COUNTERS_FOR_SPACE(new_space)
UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(old_pointer_space)
UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(old_data_space)
UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(code_space)
UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(map_space)
UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(cell_space)
UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(lo_space)
#undef UPDATE_COUNTERS_FOR_SPACE
#undef UPDATE_FRAGMENTATION_FOR_SPACE
#undef UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE
#if defined(DEBUG)
ReportStatisticsAfterGC();
#endif // DEBUG
#ifdef ENABLE_DEBUGGER_SUPPORT
isolate_->debug()->AfterGarbageCollection();
#endif // ENABLE_DEBUGGER_SUPPORT
error_object_list_.DeferredFormatStackTrace(isolate());
}
void Heap::CollectAllGarbage(int flags, const char* gc_reason) {
// Since we are ignoring the return value, the exact choice of space does
// not matter, so long as we do not specify NEW_SPACE, which would not
// cause a full GC.
mark_compact_collector_.SetFlags(flags);
CollectGarbage(OLD_POINTER_SPACE, gc_reason);
mark_compact_collector_.SetFlags(kNoGCFlags);
}
void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
// Since we are ignoring the return value, the exact choice of space does
// not matter, so long as we do not specify NEW_SPACE, which would not
// cause a full GC.
// Major GC would invoke weak handle callbacks on weakly reachable
// handles, but won't collect weakly reachable objects until next
// major GC. Therefore if we collect aggressively and weak handle callback
// has been invoked, we rerun major GC to release objects which become
// garbage.
// Note: as weak callbacks can execute arbitrary code, we cannot
// hope that eventually there will be no weak callbacks invocations.
// Therefore stop recollecting after several attempts.
mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
kReduceMemoryFootprintMask);
isolate_->compilation_cache()->Clear();
const int kMaxNumberOfAttempts = 7;
for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR, gc_reason, NULL)) {
break;
}
}
mark_compact_collector()->SetFlags(kNoGCFlags);
new_space_.Shrink();
UncommitFromSpace();
incremental_marking()->UncommitMarkingDeque();
}
bool Heap::CollectGarbage(AllocationSpace space,
GarbageCollector collector,
const char* gc_reason,
const char* collector_reason) {
// The VM is in the GC state until exiting this function.
VMState state(isolate_, GC);
#ifdef DEBUG
// Reset the allocation timeout to the GC interval, but make sure to
// allow at least a few allocations after a collection. The reason
// for this is that we have a lot of allocation sequences and we
// assume that a garbage collection will allow the subsequent
// allocation attempts to go through.
allocation_timeout_ = Max(6, FLAG_gc_interval);
#endif
if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
if (FLAG_trace_incremental_marking) {
PrintF("[IncrementalMarking] Scavenge during marking.\n");
}
}
if (collector == MARK_COMPACTOR &&
!mark_compact_collector()->abort_incremental_marking() &&
!incremental_marking()->IsStopped() &&
!incremental_marking()->should_hurry() &&
FLAG_incremental_marking_steps) {
// Make progress in incremental marking.
const intptr_t kStepSizeWhenDelayedByScavenge = 1 * MB;
incremental_marking()->Step(kStepSizeWhenDelayedByScavenge,
IncrementalMarking::NO_GC_VIA_STACK_GUARD);
if (!incremental_marking()->IsComplete()) {
if (FLAG_trace_incremental_marking) {
PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
}
collector = SCAVENGER;
collector_reason = "incremental marking delaying mark-sweep";
}
}
bool next_gc_likely_to_collect_more = false;
{ GCTracer tracer(this, gc_reason, collector_reason);
GarbageCollectionPrologue();
// The GC count was incremented in the prologue. Tell the tracer about
// it.
tracer.set_gc_count(gc_count_);
// Tell the tracer which collector we've selected.
tracer.set_collector(collector);
{
HistogramTimerScope histogram_timer_scope(
(collector == SCAVENGER) ? isolate_->counters()->gc_scavenger()
: isolate_->counters()->gc_compactor());
next_gc_likely_to_collect_more =
PerformGarbageCollection(collector, &tracer);
}
GarbageCollectionEpilogue();
}
// Start incremental marking for the next cycle. The heap snapshot
// generator needs incremental marking to stay off after it aborted.
if (!mark_compact_collector()->abort_incremental_marking() &&
incremental_marking()->IsStopped() &&
incremental_marking()->WorthActivating() &&
NextGCIsLikelyToBeFull()) {
incremental_marking()->Start();
}
return next_gc_likely_to_collect_more;
}
void Heap::PerformScavenge() {
GCTracer tracer(this, NULL, NULL);
if (incremental_marking()->IsStopped()) {
PerformGarbageCollection(SCAVENGER, &tracer);
} else {
PerformGarbageCollection(MARK_COMPACTOR, &tracer);
}
}
void Heap::MoveElements(FixedArray* array,
int dst_index,
int src_index,
int len) {
if (len == 0) return;
ASSERT(array->map() != HEAP->fixed_cow_array_map());
Object** dst_objects = array->data_start() + dst_index;
memmove(dst_objects,
array->data_start() + src_index,
len * kPointerSize);
if (!InNewSpace(array)) {
for (int i = 0; i < len; i++) {
// TODO(hpayer): check store buffer for entries
if (InNewSpace(dst_objects[i])) {
RecordWrite(array->address(), array->OffsetOfElementAt(dst_index + i));
}
}
}
incremental_marking()->RecordWrites(array);
}
#ifdef VERIFY_HEAP
// Helper class for verifying the string table.
class StringTableVerifier : public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
// Visit all HeapObject pointers in [start, end).
for (Object** p = start; p < end; p++) {
if ((*p)->IsHeapObject()) {
// Check that the string is actually internalized.
CHECK((*p)->IsTheHole() || (*p)->IsUndefined() ||
(*p)->IsInternalizedString());
}
}
}
};
static void VerifyStringTable() {
StringTableVerifier verifier;
HEAP->string_table()->IterateElements(&verifier);
}
#endif // VERIFY_HEAP
static bool AbortIncrementalMarkingAndCollectGarbage(
Heap* heap,
AllocationSpace space,
const char* gc_reason = NULL) {
heap->mark_compact_collector()->SetFlags(Heap::kAbortIncrementalMarkingMask);
bool result = heap->CollectGarbage(space, gc_reason);
heap->mark_compact_collector()->SetFlags(Heap::kNoGCFlags);
return result;
}
void Heap::ReserveSpace(
int *sizes,
Address *locations_out) {
bool gc_performed = true;
int counter = 0;
static const int kThreshold = 20;
while (gc_performed && counter++ < kThreshold) {
gc_performed = false;
ASSERT(NEW_SPACE == FIRST_PAGED_SPACE - 1);
for (int space = NEW_SPACE; space <= LAST_PAGED_SPACE; space++) {
if (sizes[space] != 0) {
MaybeObject* allocation;
if (space == NEW_SPACE) {
allocation = new_space()->AllocateRaw(sizes[space]);
} else {
allocation = paged_space(space)->AllocateRaw(sizes[space]);
}
FreeListNode* node;
if (!allocation->To<FreeListNode>(&node)) {
if (space == NEW_SPACE) {
Heap::CollectGarbage(NEW_SPACE,
"failed to reserve space in the new space");
} else {
AbortIncrementalMarkingAndCollectGarbage(
this,
static_cast<AllocationSpace>(space),
"failed to reserve space in paged space");
}
gc_performed = true;
break;
} else {
// Mark with a free list node, in case we have a GC before
// deserializing.
node->set_size(this, sizes[space]);
locations_out[space] = node->address();
}
}
}
}
if (gc_performed) {
// Failed to reserve the space after several attempts.
V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
}
}
void Heap::EnsureFromSpaceIsCommitted() {
if (new_space_.CommitFromSpaceIfNeeded()) return;
// Committing memory to from space failed.
// Memory is exhausted and we will die.
V8::FatalProcessOutOfMemory("Committing semi space failed.");
}
void Heap::ClearJSFunctionResultCaches() {
if (isolate_->bootstrapper()->IsActive()) return;
Object* context = native_contexts_list_;
while (!context->IsUndefined()) {
// Get the caches for this context. GC can happen when the context
// is not fully initialized, so the caches can be undefined.
Object* caches_or_undefined =
Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
if (!caches_or_undefined->IsUndefined()) {
FixedArray* caches = FixedArray::cast(caches_or_undefined);
// Clear the caches:
int length = caches->length();
for (int i = 0; i < length; i++) {
JSFunctionResultCache::cast(caches->get(i))->Clear();
}
}
// Get the next context:
context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
}
}
void Heap::ClearNormalizedMapCaches() {
if (isolate_->bootstrapper()->IsActive() &&
!incremental_marking()->IsMarking()) {
return;
}
Object* context = native_contexts_list_;
while (!context->IsUndefined()) {
// GC can happen when the context is not fully initialized,
// so the cache can be undefined.
Object* cache =
Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
if (!cache->IsUndefined()) {
NormalizedMapCache::cast(cache)->Clear();
}
context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
}
}
void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
double survival_rate =
(static_cast<double>(young_survivors_after_last_gc_) * 100) /
start_new_space_size;
if (survival_rate > kYoungSurvivalRateHighThreshold) {
high_survival_rate_period_length_++;
} else {
high_survival_rate_period_length_ = 0;
}
if (survival_rate < kYoungSurvivalRateLowThreshold) {
low_survival_rate_period_length_++;
} else {
low_survival_rate_period_length_ = 0;
}
double survival_rate_diff = survival_rate_ - survival_rate;
if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
set_survival_rate_trend(DECREASING);
} else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
set_survival_rate_trend(INCREASING);
} else {
set_survival_rate_trend(STABLE);
}
survival_rate_ = survival_rate;
}
bool Heap::PerformGarbageCollection(GarbageCollector collector,
GCTracer* tracer) {
bool next_gc_likely_to_collect_more = false;
if (collector != SCAVENGER) {
PROFILE(isolate_, CodeMovingGCEvent());
}
#ifdef VERIFY_HEAP
if (FLAG_verify_heap) {
VerifyStringTable();
}
#endif
GCType gc_type =
collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
{
GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
VMState state(isolate_, EXTERNAL);
CallGCPrologueCallbacks(gc_type);
}
EnsureFromSpaceIsCommitted();
int start_new_space_size = Heap::new_space()->SizeAsInt();
if (IsHighSurvivalRate()) {
// We speed up the incremental marker if it is running so that it
// does not fall behind the rate of promotion, which would cause a
// constantly growing old space.
incremental_marking()->NotifyOfHighPromotionRate();
}
if (collector == MARK_COMPACTOR) {
// Perform mark-sweep with optional compaction.
MarkCompact(tracer);
sweep_generation_++;
bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
IsStableOrIncreasingSurvivalTrend();
UpdateSurvivalRateTrend(start_new_space_size);
size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSizeOfObjects();
if (high_survival_rate_during_scavenges &&
IsStableOrIncreasingSurvivalTrend()) {
// Stable high survival rates of young objects both during partial and
// full collection indicate that mutator is either building or modifying
// a structure with a long lifetime.
// In this case we aggressively raise old generation memory limits to
// postpone subsequent mark-sweep collection and thus trade memory
// space for the mutation speed.
old_gen_limit_factor_ = 2;
} else {
old_gen_limit_factor_ = 1;
}
old_gen_promotion_limit_ =
OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
old_gen_allocation_limit_ =
OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
old_gen_exhausted_ = false;
} else {
tracer_ = tracer;
Scavenge();
tracer_ = NULL;
UpdateSurvivalRateTrend(start_new_space_size);
}
if (!new_space_high_promotion_mode_active_ &&
new_space_.Capacity() == new_space_.MaximumCapacity() &&
IsStableOrIncreasingSurvivalTrend() &&
IsHighSurvivalRate()) {
// Stable high survival rates even though young generation is at
// maximum capacity indicates that most objects will be promoted.
// To decrease scavenger pauses and final mark-sweep pauses, we
// have to limit maximal capacity of the young generation.
new_space_high_promotion_mode_active_ = true;
if (FLAG_trace_gc) {
PrintPID("Limited new space size due to high promotion rate: %d MB\n",
new_space_.InitialCapacity() / MB);
}
} else if (new_space_high_promotion_mode_active_ &&
IsStableOrDecreasingSurvivalTrend() &&
IsLowSurvivalRate()) {
// Decreasing low survival rates might indicate that the above high
// promotion mode is over and we should allow the young generation
// to grow again.
new_space_high_promotion_mode_active_ = false;
if (FLAG_trace_gc) {
PrintPID("Unlimited new space size due to low promotion rate: %d MB\n",
new_space_.MaximumCapacity() / MB);
}
}
if (new_space_high_promotion_mode_active_ &&
new_space_.Capacity() > new_space_.InitialCapacity()) {
new_space_.Shrink();
}
isolate_->counters()->objs_since_last_young()->Set(0);
// Callbacks that fire after this point might trigger nested GCs and
// restart incremental marking, the assertion can't be moved down.
ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
gc_post_processing_depth_++;
{ DisableAssertNoAllocation allow_allocation;
GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
next_gc_likely_to_collect_more =
isolate_->global_handles()->PostGarbageCollectionProcessing(
collector, tracer);
}
gc_post_processing_depth_--;
// Update relocatables.
Relocatable::PostGarbageCollectionProcessing();
if (collector == MARK_COMPACTOR) {
// Register the amount of external allocated memory.
amount_of_external_allocated_memory_at_last_global_gc_ =
amount_of_external_allocated_memory_;
}
{
GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
VMState state(isolate_, EXTERNAL);
CallGCEpilogueCallbacks(gc_type);
}
#ifdef VERIFY_HEAP
if (FLAG_verify_heap) {
VerifyStringTable();
}
#endif
return next_gc_likely_to_collect_more;
}
void Heap::CallGCPrologueCallbacks(GCType gc_type) {
if (gc_type == kGCTypeMarkSweepCompact && global_gc_prologue_callback_) {
global_gc_prologue_callback_();
}
for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
if (gc_type & gc_prologue_callbacks_[i].gc_type) {
gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
}
}
}
void Heap::CallGCEpilogueCallbacks(GCType gc_type) {
for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
gc_epilogue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
}
}
if (gc_type == kGCTypeMarkSweepCompact && global_gc_epilogue_callback_) {
global_gc_epilogue_callback_();
}
}
void Heap::MarkCompact(GCTracer* tracer) {
gc_state_ = MARK_COMPACT;
LOG(isolate_, ResourceEvent("markcompact", "begin"));
mark_compact_collector_.Prepare(tracer);
ms_count_++;
tracer->set_full_gc_count(ms_count_);
MarkCompactPrologue();
mark_compact_collector_.CollectGarbage();
LOG(isolate_, ResourceEvent("markcompact", "end"));
gc_state_ = NOT_IN_GC;
isolate_->counters()->objs_since_last_full()->Set(0);
contexts_disposed_ = 0;
flush_monomorphic_ics_ = false;
}
void Heap::MarkCompactPrologue() {
// At any old GC clear the keyed lookup cache to enable collection of unused
// maps.
isolate_->keyed_lookup_cache()->Clear();
isolate_->context_slot_cache()->Clear();
isolate_->descriptor_lookup_cache()->Clear();
RegExpResultsCache::Clear(string_split_cache());
RegExpResultsCache::Clear(regexp_multiple_cache());
isolate_->compilation_cache()->MarkCompactPrologue();
CompletelyClearInstanceofCache();
FlushNumberStringCache();
if (FLAG_cleanup_code_caches_at_gc) {
polymorphic_code_cache()->set_cache(undefined_value());
}
ClearNormalizedMapCaches();
}
Object* Heap::FindCodeObject(Address a) {
return isolate()->inner_pointer_to_code_cache()->
GcSafeFindCodeForInnerPointer(a);
}
// Helper class for copying HeapObjects
class ScavengeVisitor: public ObjectVisitor {
public:
explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
void VisitPointer(Object** p) { ScavengePointer(p); }
void VisitPointers(Object** start, Object** end) {
// Copy all HeapObject pointers in [start, end)
for (Object** p = start; p < end; p++) ScavengePointer(p);
}
private:
void ScavengePointer(Object** p) {
Object* object = *p;
if (!heap_->InNewSpace(object)) return;
Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
reinterpret_cast<HeapObject*>(object));
}
Heap* heap_;
};
#ifdef VERIFY_HEAP
// Visitor class to verify pointers in code or data space do not point into
// new space.
class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
public:
void VisitPointers(Object** start, Object**end) {
for (Object** current = start; current < end; current++) {
if ((*current)->IsHeapObject()) {
CHECK(!HEAP->InNewSpace(HeapObject::cast(*current)));
}
}
}
};
static void VerifyNonPointerSpacePointers() {
// Verify that there are no pointers to new space in spaces where we
// do not expect them.
VerifyNonPointerSpacePointersVisitor v;
HeapObjectIterator code_it(HEAP->code_space());
for (HeapObject* object = code_it.Next();
object != NULL; object = code_it.Next())
object->Iterate(&v);
// The old data space was normally swept conservatively so that the iterator
// doesn't work, so we normally skip the next bit.
if (!HEAP->old_data_space()->was_swept_conservatively()) {
HeapObjectIterator data_it(HEAP->old_data_space());
for (HeapObject* object = data_it.Next();
object != NULL; object = data_it.Next())
object->Iterate(&v);
}
}
#endif // VERIFY_HEAP
void Heap::CheckNewSpaceExpansionCriteria() {
if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
survived_since_last_expansion_ > new_space_.Capacity() &&
!new_space_high_promotion_mode_active_) {
// Grow the size of new space if there is room to grow, enough data
// has survived scavenge since the last expansion and we are not in
// high promotion mode.
new_space_.Grow();
survived_since_last_expansion_ = 0;
}
}
static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
return heap->InNewSpace(*p) &&
!HeapObject::cast(*p)->map_word().IsForwardingAddress();
}
void Heap::ScavengeStoreBufferCallback(
Heap* heap,
MemoryChunk* page,
StoreBufferEvent event) {
heap->store_buffer_rebuilder_.Callback(page, event);
}
void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
if (event == kStoreBufferStartScanningPagesEvent) {
start_of_current_page_ = NULL;
current_page_ = NULL;
} else if (event == kStoreBufferScanningPageEvent) {
if (current_page_ != NULL) {
// If this page already overflowed the store buffer during this iteration.
if (current_page_->scan_on_scavenge()) {
// Then we should wipe out the entries that have been added for it.
store_buffer_->SetTop(start_of_current_page_);
} else if (store_buffer_->Top() - start_of_current_page_ >=
(store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
// Did we find too many pointers in the previous page? The heuristic is
// that no page can take more then 1/5 the remaining slots in the store
// buffer.
current_page_->set_scan_on_scavenge(true);
store_buffer_->SetTop(start_of_current_page_);
} else {
// In this case the page we scanned took a reasonable number of slots in
// the store buffer. It has now been rehabilitated and is no longer
// marked scan_on_scavenge.
ASSERT(!current_page_->scan_on_scavenge());
}
}
start_of_current_page_ = store_buffer_->Top();
current_page_ = page;
} else if (event == kStoreBufferFullEvent) {
// The current page overflowed the store buffer again. Wipe out its entries
// in the store buffer and mark it scan-on-scavenge again. This may happen
// several times while scanning.
if (current_page_ == NULL) {
// Store Buffer overflowed while scanning promoted objects. These are not
// in any particular page, though they are likely to be clustered by the
// allocation routines.
store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize);
} else {
// Store Buffer overflowed while scanning a particular old space page for
// pointers to new space.
ASSERT(current_page_ == page);
ASSERT(page != NULL);
current_page_->set_scan_on_scavenge(true);
ASSERT(start_of_current_page_ != store_buffer_->Top());
store_buffer_->SetTop(start_of_current_page_);
}
} else {
UNREACHABLE();
}
}
void PromotionQueue::Initialize() {
// Assumes that a NewSpacePage exactly fits a number of promotion queue
// entries (where each is a pair of intptr_t). This allows us to simplify
// the test fpr when to switch pages.
ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
== 0);
limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
front_ = rear_ =
reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
emergency_stack_ = NULL;
guard_ = false;
}
void PromotionQueue::RelocateQueueHead() {
ASSERT(emergency_stack_ == NULL);
Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
intptr_t* head_start = rear_;
intptr_t* head_end =
Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
int entries_count =
static_cast<int>(head_end - head_start) / kEntrySizeInWords;
emergency_stack_ = new List<Entry>(2 * entries_count);
while (head_start != head_end) {
int size = static_cast<int>(*(head_start++));
HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
emergency_stack_->Add(Entry(obj, size));
}
rear_ = head_end;
}
class ScavengeWeakObjectRetainer : public WeakObjectRetainer {
public:
explicit ScavengeWeakObjectRetainer(Heap* heap) : heap_(heap) { }
virtual Object* RetainAs(Object* object) {
if (!heap_->InFromSpace(object)) {
return object;
}
MapWord map_word = HeapObject::cast(object)->map_word();
if (map_word.IsForwardingAddress()) {
return map_word.ToForwardingAddress();
}
return NULL;
}
private:
Heap* heap_;
};
void Heap::Scavenge() {
RelocationLock relocation_lock(this);
#ifdef VERIFY_HEAP
if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
#endif
gc_state_ = SCAVENGE;
// Implements Cheney's copying algorithm
LOG(isolate_, ResourceEvent("scavenge", "begin"));
// Clear descriptor cache.
isolate_->descriptor_lookup_cache()->Clear();
// Used for updating survived_since_last_expansion_ at function end.
intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
CheckNewSpaceExpansionCriteria();
SelectScavengingVisitorsTable();
incremental_marking()->PrepareForScavenge();
paged_space(OLD_DATA_SPACE)->EnsureSweeperProgress(new_space_.Size());
paged_space(OLD_POINTER_SPACE)->EnsureSweeperProgress(new_space_.Size());
// Flip the semispaces. After flipping, to space is empty, from space has
// live objects.
new_space_.Flip();
new_space_.ResetAllocationInfo();
// We need to sweep newly copied objects which can be either in the
// to space or promoted to the old generation. For to-space
// objects, we treat the bottom of the to space as a queue. Newly
// copied and unswept objects lie between a 'front' mark and the
// allocation pointer.
//
// Promoted objects can go into various old-generation spaces, and
// can be allocated internally in the spaces (from the free list).
// We treat the top of the to space as a queue of addresses of
// promoted objects. The addresses of newly promoted and unswept
// objects lie between a 'front' mark and a 'rear' mark that is
// updated as a side effect of promoting an object.
//
// There is guaranteed to be enough room at the top of the to space
// for the addresses of promoted objects: every object promoted
// frees up its size in bytes from the top of the new space, and
// objects are at least one pointer in size.
Address new_space_front = new_space_.ToSpaceStart();
promotion_queue_.Initialize();
#ifdef DEBUG
store_buffer()->Clean();
#endif
ScavengeVisitor scavenge_visitor(this);
// Copy roots.
IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
// Copy objects reachable from the old generation.
{
StoreBufferRebuildScope scope(this,
store_buffer(),
&ScavengeStoreBufferCallback);
store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
}
// Copy objects reachable from cells by scavenging cell values directly.
HeapObjectIterator cell_iterator(cell_space_);
for (HeapObject* heap_object = cell_iterator.Next();
heap_object != NULL;
heap_object = cell_iterator.Next()) {
if (heap_object->IsJSGlobalPropertyCell()) {
JSGlobalPropertyCell* cell = JSGlobalPropertyCell::cast(heap_object);
Address value_address = cell->ValueAddress();
scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
}
}
// Copy objects reachable from the code flushing candidates list.
MarkCompactCollector* collector = mark_compact_collector();
if (collector->is_code_flushing_enabled()) {
collector->code_flusher()->IteratePointersToFromSpace(&scavenge_visitor);
}
// Scavenge object reachable from the native contexts list directly.
scavenge_visitor.VisitPointer(BitCast<Object**>(&native_contexts_list_));
new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
while (isolate()->global_handles()->IterateObjectGroups(
&scavenge_visitor, &IsUnscavengedHeapObject)) {
new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
}
isolate()->global_handles()->RemoveObjectGroups();
isolate()->global_handles()->RemoveImplicitRefGroups();
isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
&IsUnscavengedHeapObject);
isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
&scavenge_visitor);
new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
UpdateNewSpaceReferencesInExternalStringTable(
&UpdateNewSpaceReferenceInExternalStringTableEntry);
error_object_list_.UpdateReferencesInNewSpace(this);
promotion_queue_.Destroy();
if (!FLAG_watch_ic_patching) {
isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
}
incremental_marking()->UpdateMarkingDequeAfterScavenge();
ScavengeWeakObjectRetainer weak_object_retainer(this);
ProcessWeakReferences(&weak_object_retainer);
ASSERT(new_space_front == new_space_.top());
// Set age mark.
new_space_.set_age_mark(new_space_.top());
new_space_.LowerInlineAllocationLimit(
new_space_.inline_allocation_limit_step());
// Update how much has survived scavenge.
IncrementYoungSurvivorsCounter(static_cast<int>(
(PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
LOG(isolate_, ResourceEvent("scavenge", "end"));
gc_state_ = NOT_IN_GC;
scavenges_since_last_idle_round_++;
}
String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
Object** p) {
MapWord first_word = HeapObject::cast(*p)->map_word();
if (!first_word.IsForwardingAddress()) {
// Unreachable external string can be finalized.
heap->FinalizeExternalString(String::cast(*p));
return NULL;
}
// String is still reachable.
return String::cast(first_word.ToForwardingAddress());
}
void Heap::UpdateNewSpaceReferencesInExternalStringTable(
ExternalStringTableUpdaterCallback updater_func) {
#ifdef VERIFY_HEAP
if (FLAG_verify_heap) {
external_string_table_.Verify();
}
#endif
if (external_string_table_.new_space_strings_.is_empty()) return;
Object** start = &external_string_table_.new_space_strings_[0];
Object** end = start + external_string_table_.new_space_strings_.length();
Object** last = start;
for (Object** p = start; p < end; ++p) {
ASSERT(InFromSpace(*p));
String* target = updater_func(this, p);
if (target == NULL) continue;
ASSERT(target->IsExternalString());
if (InNewSpace(target)) {
// String is still in new space. Update the table entry.
*last = target;
++last;
} else {
// String got promoted. Move it to the old string list.
external_string_table_.AddOldString(target);
}
}
ASSERT(last <= end);
external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
}
void Heap::UpdateReferencesInExternalStringTable(
ExternalStringTableUpdaterCallback updater_func) {
// Update old space string references.
if (external_string_table_.old_space_strings_.length() > 0) {
Object** start = &external_string_table_.old_space_strings_[0];
Object** end = start + external_string_table_.old_space_strings_.length();
for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
}
UpdateNewSpaceReferencesInExternalStringTable(updater_func);
}
static Object* ProcessFunctionWeakReferences(Heap* heap,
Object* function,
WeakObjectRetainer* retainer,
bool record_slots) {
Object* undefined = heap->undefined_value();
Object* head = undefined;
JSFunction* tail = NULL;
Object* candidate = function;
while (candidate != undefined) {
// Check whether to keep the candidate in the list.
JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
Object* retain = retainer->RetainAs(candidate);
if (retain != NULL) {
if (head == undefined) {
// First element in the list.
head = retain;
} else {
// Subsequent elements in the list.
ASSERT(tail != NULL);
tail->set_next_function_link(retain);
if (record_slots) {
Object** next_function =
HeapObject::RawField(tail, JSFunction::kNextFunctionLinkOffset);
heap->mark_compact_collector()->RecordSlot(
next_function, next_function, retain);
}
}
// Retained function is new tail.
candidate_function = reinterpret_cast<JSFunction*>(retain);
tail = candidate_function;
ASSERT(retain->IsUndefined() || retain->IsJSFunction());
if (retain == undefined) break;
}
// Move to next element in the list.
candidate = candidate_function->next_function_link();
}
// Terminate the list if there is one or more elements.
if (tail != NULL) {
tail->set_next_function_link(undefined);
}
return head;
}
void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
Object* undefined = undefined_value();
Object* head = undefined;
Context* tail = NULL;
Object* candidate = native_contexts_list_;
// We don't record weak slots during marking or scavenges.
// Instead we do it once when we complete mark-compact cycle.
// Note that write barrier has no effect if we are already in the middle of
// compacting mark-sweep cycle and we have to record slots manually.
bool record_slots =
gc_state() == MARK_COMPACT &&
mark_compact_collector()->is_compacting();
while (candidate != undefined) {
// Check whether to keep the candidate in the list.
Context* candidate_context = reinterpret_cast<Context*>(candidate);
Object* retain = retainer->RetainAs(candidate);
if (retain != NULL) {
if (head == undefined) {
// First element in the list.
head = retain;
} else {
// Subsequent elements in the list.
ASSERT(tail != NULL);
tail->set_unchecked(this,
Context::NEXT_CONTEXT_LINK,
retain,
UPDATE_WRITE_BARRIER);
if (record_slots) {
Object** next_context =
HeapObject::RawField(
tail, FixedArray::SizeFor(Context::NEXT_CONTEXT_LINK));
mark_compact_collector()->RecordSlot(
next_context, next_context, retain);
}
}
// Retained context is new tail.
candidate_context = reinterpret_cast<Context*>(retain);
tail = candidate_context;
if (retain == undefined) break;
// Process the weak list of optimized functions for the context.
Object* function_list_head =
ProcessFunctionWeakReferences(
this,
candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
retainer,
record_slots);
candidate_context->set_unchecked(this,
Context::OPTIMIZED_FUNCTIONS_LIST,
function_list_head,
UPDATE_WRITE_BARRIER);
if (record_slots) {
Object** optimized_functions =
HeapObject::RawField(
tail, FixedArray::SizeFor(Context::OPTIMIZED_FUNCTIONS_LIST));
mark_compact_collector()->RecordSlot(
optimized_functions, optimized_functions, function_list_head);
}
}
// Move to next element in the list.
candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
}
// Terminate the list if there is one or more elements.
if (tail != NULL) {
tail->set_unchecked(this,
Context::NEXT_CONTEXT_LINK,
Heap::undefined_value(),
UPDATE_WRITE_BARRIER);
}
// Update the head of the list of contexts.
native_contexts_list_ = head;
}
void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
AssertNoAllocation no_allocation;
// Both the external string table and the string table may contain
// external strings, but neither lists them exhaustively, nor is the
// intersection set empty. Therefore we iterate over the external string
// table first, ignoring internalized strings, and then over the
// internalized string table.
class ExternalStringTableVisitorAdapter : public ObjectVisitor {
public:
explicit ExternalStringTableVisitorAdapter(
v8::ExternalResourceVisitor* visitor) : visitor_(visitor) {}
virtual void VisitPointers(Object** start, Object** end) {
for (Object** p = start; p < end; p++) {
// Visit non-internalized external strings,
// since internalized strings are listed in the string table.
if (!(*p)->IsInternalizedString()) {
ASSERT((*p)->IsExternalString());
visitor_->VisitExternalString(Utils::ToLocal(
Handle<String>(String::cast(*p))));
}
}
}
private:
v8::ExternalResourceVisitor* visitor_;
} external_string_table_visitor(visitor);
external_string_table_.Iterate(&external_string_table_visitor);
class StringTableVisitorAdapter : public ObjectVisitor {
public:
explicit StringTableVisitorAdapter(
v8::ExternalResourceVisitor* visitor) : visitor_(visitor) {}
virtual void VisitPointers(Object** start, Object** end) {
for (Object** p = start; p < end; p++) {
if ((*p)->IsExternalString()) {
ASSERT((*p)->IsInternalizedString());
visitor_->VisitExternalString(Utils::ToLocal(
Handle<String>(String::cast(*p))));
}
}
}
private:
v8::ExternalResourceVisitor* visitor_;
} string_table_visitor(visitor);
string_table()->IterateElements(&string_table_visitor);
}
class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
public:
static inline void VisitPointer(Heap* heap, Object** p) {
Object* object = *p;
if (!heap->InNewSpace(object)) return;
Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
reinterpret_cast<HeapObject*>(object));
}
};
Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
Address new_space_front) {
do {
SemiSpace::AssertValidRange(new_space_front, new_space_.top());
// The addresses new_space_front and new_space_.top() define a
// queue of unprocessed copied objects. Process them until the
// queue is empty.
while (new_space_front != new_space_.top()) {
if (!NewSpacePage::IsAtEnd(new_space_front)) {
HeapObject* object = HeapObject::FromAddress(new_space_front);
new_space_front +=
NewSpaceScavenger::IterateBody(object->map(), object);
} else {
new_space_front =
NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
}
}
// Promote and process all the to-be-promoted objects.
{
StoreBufferRebuildScope scope(this,
store_buffer(),
&ScavengeStoreBufferCallback);
while (!promotion_queue()->is_empty()) {
HeapObject* target;
int size;
promotion_queue()->remove(&target, &size);
// Promoted object might be already partially visited
// during old space pointer iteration. Thus we search specificly
// for pointers to from semispace instead of looking for pointers
// to new space.
ASSERT(!target->IsMap());
IterateAndMarkPointersToFromSpace(target->address(),
target->address() + size,
&ScavengeObject);
}
}
// Take another spin if there are now unswept objects in new space
// (there are currently no more unswept promoted objects).
} while (new_space_front != new_space_.top());
return new_space_front;
}
STATIC_ASSERT((FixedDoubleArray::kHeaderSize & kDoubleAlignmentMask) == 0);
INLINE(static HeapObject* EnsureDoubleAligned(Heap* heap,
HeapObject* object,
int size));
static HeapObject* EnsureDoubleAligned(Heap* heap,
HeapObject* object,
int size) {
if ((OffsetFrom(object->address()) & kDoubleAlignmentMask) != 0) {
heap->CreateFillerObjectAt(object->address(), kPointerSize);
return HeapObject::FromAddress(object->address() + kPointerSize);
} else {
heap->CreateFillerObjectAt(object->address() + size - kPointerSize,
kPointerSize);
return object;
}
}
enum LoggingAndProfiling {
LOGGING_AND_PROFILING_ENABLED,
LOGGING_AND_PROFILING_DISABLED
};
enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
template<MarksHandling marks_handling,
LoggingAndProfiling logging_and_profiling_mode>
class ScavengingVisitor : public StaticVisitorBase {
public:
static void Initialize() {
table_.Register(kVisitSeqOneByteString, &EvacuateSeqOneByteString);
table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
table_.Register(kVisitByteArray, &EvacuateByteArray);
table_.Register(kVisitFixedArray, &EvacuateFixedArray);
table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
table_.Register(kVisitNativeContext,
&ObjectEvacuationStrategy<POINTER_OBJECT>::
template VisitSpecialized<Context::kSize>);
table_.Register(kVisitConsString,
&ObjectEvacuationStrategy<POINTER_OBJECT>::
template VisitSpecialized<ConsString::kSize>);
table_.Register(kVisitSlicedString,
&ObjectEvacuationStrategy<POINTER_OBJECT>::
template VisitSpecialized<SlicedString::kSize>);
table_.Register(kVisitSymbol,
&ObjectEvacuationStrategy<POINTER_OBJECT>::
template VisitSpecialized<Symbol::kSize>);
table_.Register(kVisitSharedFunctionInfo,
&ObjectEvacuationStrategy<POINTER_OBJECT>::
template VisitSpecialized<SharedFunctionInfo::kSize>);
table_.Register(kVisitJSWeakMap,
&ObjectEvacuationStrategy<POINTER_OBJECT>::
Visit);
table_.Register(kVisitJSRegExp,
&ObjectEvacuationStrategy<POINTER_OBJECT>::
Visit);
if (marks_handling == IGNORE_MARKS) {
table_.Register(kVisitJSFunction,
&ObjectEvacuationStrategy<POINTER_OBJECT>::
template VisitSpecialized<JSFunction::kSize>);
} else {
table_.Register(kVisitJSFunction, &EvacuateJSFunction);
}
table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
kVisitDataObject,
kVisitDataObjectGeneric>();
table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
kVisitJSObject,
kVisitJSObjectGeneric>();
table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
kVisitStruct,
kVisitStructGeneric>();
}
static VisitorDispatchTable<ScavengingCallback>* GetTable() {
return &table_;
}
private:
enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
enum SizeRestriction { SMALL, UNKNOWN_SIZE };
static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
bool should_record = false;
#ifdef DEBUG
should_record = FLAG_heap_stats;
#endif
should_record = should_record || FLAG_log_gc;
if (should_record) {
if (heap->new_space()->Contains(obj)) {
heap->new_space()->RecordAllocation(obj);
} else {
heap->new_space()->RecordPromotion(obj);
}
}
}
// Helper function used by CopyObject to copy a source object to an
// allocated target object and update the forwarding pointer in the source
// object. Returns the target object.
INLINE(static void MigrateObject(Heap* heap,
HeapObject* source,
HeapObject* target,
int size)) {
// Copy the content of source to target.
heap->CopyBlock(target->address(), source->address(), size);
// Set the forwarding address.
source->set_map_word(MapWord::FromForwardingAddress(target));
if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
// Update NewSpace stats if necessary.
RecordCopiedObject(heap, target);
HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
Isolate* isolate = heap->isolate();
if (isolate->logger()->is_logging_code_events() ||
isolate->cpu_profiler()->is_profiling()) {
if (target->IsSharedFunctionInfo()) {
PROFILE(isolate, SharedFunctionInfoMoveEvent(
source->address(), target->address()));
}
}
}
if (marks_handling == TRANSFER_MARKS) {
if (Marking::TransferColor(source, target)) {
MemoryChunk::IncrementLiveBytesFromGC(target->address(), size);
}
}
}
template<ObjectContents object_contents,
SizeRestriction size_restriction,
int alignment>
static inline void EvacuateObject(Map* map,
HeapObject** slot,
HeapObject* object,
int object_size) {
SLOW_ASSERT((size_restriction != SMALL) ||
(object_size <= Page::kMaxNonCodeHeapObjectSize));
SLOW_ASSERT(object->Size() == object_size);
int allocation_size = object_size;
if (alignment != kObjectAlignment) {
ASSERT(alignment == kDoubleAlignment);
allocation_size += kPointerSize;
}
Heap* heap = map->GetHeap();
if (heap->ShouldBePromoted(object->address(), object_size)) {
MaybeObject* maybe_result;
if ((size_restriction != SMALL) &&
(allocation_size > Page::kMaxNonCodeHeapObjectSize)) {
maybe_result = heap->lo_space()->AllocateRaw(allocation_size,
NOT_EXECUTABLE);
} else {
if (object_contents == DATA_OBJECT) {
maybe_result = heap->old_data_space()->AllocateRaw(allocation_size);
} else {
maybe_result =
heap->old_pointer_space()->AllocateRaw(allocation_size);
}
}
Object* result = NULL; // Initialization to please compiler.
if (maybe_result->ToObject(&result)) {
HeapObject* target = HeapObject::cast(result);
if (alignment != kObjectAlignment) {
target = EnsureDoubleAligned(heap, target, allocation_size);
}
// Order is important: slot might be inside of the target if target
// was allocated over a dead object and slot comes from the store
// buffer.
*slot = target;
MigrateObject(heap, object, target, object_size);
if (object_contents == POINTER_OBJECT) {
if (map->instance_type() == JS_FUNCTION_TYPE) {
heap->promotion_queue()->insert(
target, JSFunction::kNonWeakFieldsEndOffset);
} else {
heap->promotion_queue()->insert(target, object_size);
}
}
heap->tracer()->increment_promoted_objects_size(object_size);
return;
}
}
MaybeObject* allocation = heap->new_space()->AllocateRaw(allocation_size);
heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
Object* result = allocation->ToObjectUnchecked();
HeapObject* target = HeapObject::cast(result);
if (alignment != kObjectAlignment) {
target = EnsureDoubleAligned(heap, target, allocation_size);
}
// Order is important: slot might be inside of the target if target
// was allocated over a dead object and slot comes from the store
// buffer.
*slot = target;
MigrateObject(heap, object, target, object_size);
return;
}
static inline void EvacuateJSFunction(Map* map,
HeapObject** slot,
HeapObject* object) {
ObjectEvacuationStrategy<POINTER_OBJECT>::
template VisitSpecialized<JSFunction::kSize>(map, slot, object);
HeapObject* target = *slot;
MarkBit mark_bit = Marking::MarkBitFrom(target);
if (Marking::IsBlack(mark_bit)) {
// This object is black and it might not be rescanned by marker.
// We should explicitly record code entry slot for compaction because
// promotion queue processing (IterateAndMarkPointersToFromSpace) will
// miss it as it is not HeapObject-tagged.
Address code_entry_slot =
target->address() + JSFunction::kCodeEntryOffset;
Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
map->GetHeap()->mark_compact_collector()->
RecordCodeEntrySlot(code_entry_slot, code);
}
}
static inline void EvacuateFixedArray(Map* map,
HeapObject** slot,
HeapObject* object) {
int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(map,
slot,
object,
object_size);
}
static inline void EvacuateFixedDoubleArray(Map* map,
HeapObject** slot,
HeapObject* object) {
int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
int object_size = FixedDoubleArray::SizeFor(length);
EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kDoubleAlignment>(
map,
slot,
object,
object_size);
}
static inline void EvacuateByteArray(Map* map,
HeapObject** slot,
HeapObject* object) {
int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
map, slot, object, object_size);
}
static inline void EvacuateSeqOneByteString(Map* map,
HeapObject** slot,
HeapObject* object) {
int object_size = SeqOneByteString::cast(object)->
SeqOneByteStringSize(map->instance_type());
EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
map, slot, object, object_size);
}
static inline void EvacuateSeqTwoByteString(Map* map,
HeapObject** slot,
HeapObject* object) {
int object_size = SeqTwoByteString::cast(object)->
SeqTwoByteStringSize(map->instance_type());
EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
map, slot, object, object_size);
}
static inline bool IsShortcutCandidate(int type) {
return ((type & kShortcutTypeMask) == kShortcutTypeTag);
}
static inline void EvacuateShortcutCandidate(Map* map,
HeapObject** slot,
HeapObject* object) {
ASSERT(IsShortcutCandidate(map->instance_type()));
Heap* heap = map->GetHeap();
if (marks_handling == IGNORE_MARKS &&
ConsString::cast(object)->unchecked_second() ==
heap->empty_string()) {
HeapObject* first =
HeapObject::cast(ConsString::cast(object)->unchecked_first());
*slot = first;
if (!heap->InNewSpace(first)) {
object->set_map_word(MapWord::FromForwardingAddress(first));
return;
}
MapWord first_word = first->map_word();
if (first_word.IsForwardingAddress()) {
HeapObject* target = first_word.ToForwardingAddress();
*slot = target;
object->set_map_word(MapWord::FromForwardingAddress(target));
return;
}
heap->DoScavengeObject(first->map(), slot, first);
object->set_map_word(MapWord::FromForwardingAddress(*slot));
return;
}
int object_size = ConsString::kSize;
EvacuateObject<POINTER_OBJECT, SMALL, kObjectAlignment>(
map, slot, object, object_size);
}
template<ObjectContents object_contents>
class ObjectEvacuationStrategy {
public:
template<int object_size>
static inline void VisitSpecialized(Map* map,
HeapObject** slot,
HeapObject* object) {
EvacuateObject<object_contents, SMALL, kObjectAlignment>(
map, slot, object, object_size);
}
static inline void Visit(Map* map,
HeapObject** slot,
HeapObject* object) {
int object_size = map->instance_size();
EvacuateObject<object_contents, SMALL, kObjectAlignment>(
map, slot, object, object_size);
}
};
static VisitorDispatchTable<ScavengingCallback> table_;
};
template<MarksHandling marks_handling,
LoggingAndProfiling logging_and_profiling_mode>
VisitorDispatchTable<ScavengingCallback>
ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
static void InitializeScavengingVisitorsTables() {
ScavengingVisitor<TRANSFER_MARKS,
LOGGING_AND_PROFILING_DISABLED>::Initialize();
ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
ScavengingVisitor<TRANSFER_MARKS,
LOGGING_AND_PROFILING_ENABLED>::Initialize();
ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
}
void Heap::SelectScavengingVisitorsTable() {
bool logging_and_profiling =
isolate()->logger()->is_logging() ||
isolate()->cpu_profiler()->is_profiling() ||
(isolate()->heap_profiler() != NULL &&
isolate()->heap_profiler()->is_profiling());
if (!incremental_marking()->IsMarking()) {
if (!logging_and_profiling) {
scavenging_visitors_table_.CopyFrom(
ScavengingVisitor<IGNORE_MARKS,
LOGGING_AND_PROFILING_DISABLED>::GetTable());
} else {
scavenging_visitors_table_.CopyFrom(
ScavengingVisitor<IGNORE_MARKS,
LOGGING_AND_PROFILING_ENABLED>::GetTable());
}
} else {
if (!logging_and_profiling) {
scavenging_visitors_table_.CopyFrom(
ScavengingVisitor<TRANSFER_MARKS,
LOGGING_AND_PROFILING_DISABLED>::GetTable());
} else {
scavenging_visitors_table_.CopyFrom(
ScavengingVisitor<TRANSFER_MARKS,
LOGGING_AND_PROFILING_ENABLED>::GetTable());
}
if (incremental_marking()->IsCompacting()) {
// When compacting forbid short-circuiting of cons-strings.
// Scavenging code relies on the fact that new space object
// can't be evacuated into evacuation candidate but
// short-circuiting violates this assumption.
scavenging_visitors_table_.Register(
StaticVisitorBase::kVisitShortcutCandidate,
scavenging_visitors_table_.GetVisitorById(
StaticVisitorBase::kVisitConsString));
}
}
}
void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
SLOW_ASSERT(HEAP->InFromSpace(object));
MapWord first_word = object->map_word();
SLOW_ASSERT(!first_word.IsForwardingAddress());
Map* map = first_word.ToMap();
map->GetHeap()->DoScavengeObject(map, p, object);
}
MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
int instance_size) {
Object* result;
MaybeObject* maybe_result = AllocateRawMap();
if (!maybe_result->ToObject(&result)) return maybe_result;
// Map::cast cannot be used due to uninitialized map field.
reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
reinterpret_cast<Map*>(result)->set_visitor_id(
StaticVisitorBase::GetVisitorId(instance_type, instance_size));
reinterpret_cast<Map*>(result)->set_inobject_properties(0);
reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
reinterpret_cast<Map*>(result)->set_bit_field(0);
reinterpret_cast<Map*>(result)->set_bit_field2(0);
int bit_field3 = Map::EnumLengthBits::encode(Map::kInvalidEnumCache) |
Map::OwnsDescriptors::encode(true);
reinterpret_cast<Map*>(result)->set_bit_field3(bit_field3);
return result;
}
MaybeObject* Heap::AllocateMap(InstanceType instance_type,
int instance_size,
ElementsKind elements_kind) {
Object* result;
MaybeObject* maybe_result = AllocateRawMap();
if (!maybe_result->To(&result)) return maybe_result;
Map* map = reinterpret_cast<Map*>(result);
map->set_map_no_write_barrier(meta_map());
map->set_instance_type(instance_type);
map->set_visitor_id(
StaticVisitorBase::GetVisitorId(instance_type, instance_size));
map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
map->set_instance_size(instance_size);
map->set_inobject_properties(0);
map->set_pre_allocated_property_fields(0);
map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
map->set_dependent_code(DependentCode::cast(empty_fixed_array()),
SKIP_WRITE_BARRIER);
map->init_back_pointer(undefined_value());
map->set_unused_property_fields(0);
map->set_instance_descriptors(empty_descriptor_array());
map->set_bit_field(0);
map->set_bit_field2(1 << Map::kIsExtensible);
int bit_field3 = Map::EnumLengthBits::encode(Map::kInvalidEnumCache) |
Map::OwnsDescriptors::encode(true);
map->set_bit_field3(bit_field3);
map->set_elements_kind(elements_kind);
return map;
}
MaybeObject* Heap::AllocateCodeCache() {
CodeCache* code_cache;
{ MaybeObject* maybe_code_cache = AllocateStruct(CODE_CACHE_TYPE);
if (!maybe_code_cache->To(&code_cache)) return maybe_code_cache;
}
code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
return code_cache;
}
MaybeObject* Heap::AllocatePolymorphicCodeCache() {
return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
}
MaybeObject* Heap::AllocateAccessorPair() {
AccessorPair* accessors;
{ MaybeObject* maybe_accessors = AllocateStruct(ACCESSOR_PAIR_TYPE);
if (!maybe_accessors->To(&accessors)) return maybe_accessors;
}
accessors->set_getter(the_hole_value(), SKIP_WRITE_BARRIER);
accessors->set_setter(the_hole_value(), SKIP_WRITE_BARRIER);
return accessors;
}
MaybeObject* Heap::AllocateTypeFeedbackInfo() {
TypeFeedbackInfo* info;
{ MaybeObject* maybe_info = AllocateStruct(TYPE_FEEDBACK_INFO_TYPE);
if (!maybe_info->To(&info)) return maybe_info;
}
info->initialize_storage();
info->set_type_feedback_cells(TypeFeedbackCells::cast(empty_fixed_array()),
SKIP_WRITE_BARRIER);
return info;
}
MaybeObject* Heap::AllocateAliasedArgumentsEntry(int aliased_context_slot) {
AliasedArgumentsEntry* entry;
{ MaybeObject* maybe_entry = AllocateStruct(ALIASED_ARGUMENTS_ENTRY_TYPE);
if (!maybe_entry->To(&entry)) return maybe_entry;
}
entry->set_aliased_context_slot(aliased_context_slot);
return entry;
}
const Heap::StringTypeTable Heap::string_type_table[] = {
#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
{type, size, k##camel_name##MapRootIndex},
STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
#undef STRING_TYPE_ELEMENT
};
const Heap::ConstantStringTable Heap::constant_string_table[] = {
#define CONSTANT_STRING_ELEMENT(name, contents) \
{contents, k##name##RootIndex},
INTERNALIZED_STRING_LIST(CONSTANT_STRING_ELEMENT)
#undef CONSTANT_STRING_ELEMENT
};
const Heap::StructTable Heap::struct_table[] = {
#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
{ NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
STRUCT_LIST(STRUCT_TABLE_ELEMENT)
#undef STRUCT_TABLE_ELEMENT
};
bool Heap::CreateInitialMaps() {
Object* obj;
{ MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
// Map::cast cannot be used due to uninitialized map field.
Map* new_meta_map = reinterpret_cast<Map*>(obj);
set_meta_map(new_meta_map);
new_meta_map->set_map(new_meta_map);
{ MaybeObject* maybe_obj =
AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_fixed_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_oddball_map(Map::cast(obj));
// Allocate the empty array.
{ MaybeObject* maybe_obj = AllocateEmptyFixedArray();
if (!maybe_obj->ToObject(&obj)) return false;
}
set_empty_fixed_array(FixedArray::cast(obj));
{ MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_null_value(Oddball::cast(obj));
Oddball::cast(obj)->set_kind(Oddball::kNull);
{ MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_undefined_value(Oddball::cast(obj));
Oddball::cast(obj)->set_kind(Oddball::kUndefined);
ASSERT(!InNewSpace(undefined_value()));
// Allocate the empty descriptor array.
{ MaybeObject* maybe_obj = AllocateEmptyFixedArray();
if (!maybe_obj->ToObject(&obj)) return false;
}
set_empty_descriptor_array(DescriptorArray::cast(obj));
// Fix the instance_descriptors for the existing maps.
meta_map()->set_code_cache(empty_fixed_array());
meta_map()->set_dependent_code(DependentCode::cast(empty_fixed_array()));
meta_map()->init_back_pointer(undefined_value());
meta_map()->set_instance_descriptors(empty_descriptor_array());
fixed_array_map()->set_code_cache(empty_fixed_array());
fixed_array_map()->set_dependent_code(
DependentCode::cast(empty_fixed_array()));
fixed_array_map()->init_back_pointer(undefined_value());
fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
oddball_map()->set_code_cache(empty_fixed_array());
oddball_map()->set_dependent_code(DependentCode::cast(empty_fixed_array()));
oddball_map()->init_back_pointer(undefined_value());
oddball_map()->set_instance_descriptors(empty_descriptor_array());
// Fix prototype object for existing maps.
meta_map()->set_prototype(null_value());
meta_map()->set_constructor(null_value());
fixed_array_map()->set_prototype(null_value());
fixed_array_map()->set_constructor(null_value());
oddball_map()->set_prototype(null_value());
oddball_map()->set_constructor(null_value());
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_fixed_cow_array_map(Map::cast(obj));
ASSERT(fixed_array_map() != fixed_cow_array_map());
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_scope_info_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_heap_number_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(SYMBOL_TYPE, Symbol::kSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_symbol_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_foreign_map(Map::cast(obj));
for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
const StringTypeTable& entry = string_type_table[i];
{ MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
if (!maybe_obj->ToObject(&obj)) return false;
}
roots_[entry.index] = Map::cast(obj);
}
{ MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_undetectable_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
{ MaybeObject* maybe_obj =
AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_undetectable_ascii_string_map(Map::cast(obj));
Map::cast(obj)->set_is_undetectable();
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_fixed_double_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_byte_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_free_space_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_empty_byte_array(ByteArray::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_external_pixel_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
ExternalArray::kAlignedSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_external_byte_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
ExternalArray::kAlignedSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_external_unsigned_byte_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
ExternalArray::kAlignedSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_external_short_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
ExternalArray::kAlignedSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_external_unsigned_short_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
ExternalArray::kAlignedSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_external_int_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
ExternalArray::kAlignedSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_external_unsigned_int_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
ExternalArray::kAlignedSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_external_float_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_non_strict_arguments_elements_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
ExternalArray::kAlignedSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_external_double_array_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_code_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
JSGlobalPropertyCell::kSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_global_property_cell_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_one_pointer_filler_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_two_pointer_filler_map(Map::cast(obj));
for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
const StructTable& entry = struct_table[i];
{ MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
if (!maybe_obj->ToObject(&obj)) return false;
}
roots_[entry.index] = Map::cast(obj);
}
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_hash_table_map(Map::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_function_context_map(Map::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_catch_context_map(Map::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_with_context_map(Map::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_block_context_map(Map::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_module_context_map(Map::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_global_context_map(Map::cast(obj));
{ MaybeObject* maybe_obj =
AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
if (!maybe_obj->ToObject(&obj)) return false;
}
Map* native_context_map = Map::cast(obj);
native_context_map->set_dictionary_map(true);
native_context_map->set_visitor_id(StaticVisitorBase::kVisitNativeContext);
set_native_context_map(native_context_map);
{ MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
SharedFunctionInfo::kAlignedSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_shared_function_info_map(Map::cast(obj));
{ MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
JSMessageObject::kSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_message_object_map(Map::cast(obj));
Map* external_map;
{ MaybeObject* maybe_obj =
AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize + kPointerSize);
if (!maybe_obj->To(&external_map)) return false;
}
external_map->set_is_extensible(false);
set_external_map(external_map);
ASSERT(!InNewSpace(empty_fixed_array()));
return true;
}
MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
// Statically ensure that it is safe to allocate heap numbers in paged
// spaces.
STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Object* result;
{ MaybeObject* maybe_result =
AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
HeapNumber::cast(result)->set_value(value);
return result;
}
MaybeObject* Heap::AllocateHeapNumber(double value) {
// Use general version, if we're forced to always allocate.
if (always_allocate()) return AllocateHeapNumber(value, TENURED);
// This version of AllocateHeapNumber is optimized for
// allocation in new space.
STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
Object* result;
{ MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
HeapNumber::cast(result)->set_value(value);
return result;
}
MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
Object* result;
{ MaybeObject* maybe_result = AllocateRawCell();
if (!maybe_result->ToObject(&result)) return maybe_result;
}
HeapObject::cast(result)->set_map_no_write_barrier(
global_property_cell_map());
JSGlobalPropertyCell::cast(result)->set_value(value);
return result;
}
MaybeObject* Heap::CreateOddball(const char* to_string,
Object* to_number,
byte kind) {
Object* result;
{ MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
return Oddball::cast(result)->Initialize(to_string, to_number, kind);
}
bool Heap::CreateApiObjects() {
Object* obj;
{ MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
// Don't use Smi-only elements optimizations for objects with the neander
// map. There are too many cases where element values are set directly with a
// bottleneck to trap the Smi-only -> fast elements transition, and there
// appears to be no benefit for optimize this case.
Map* new_neander_map = Map::cast(obj);
new_neander_map->set_elements_kind(TERMINAL_FAST_ELEMENTS_KIND);
set_neander_map(new_neander_map);
{ MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
if (!maybe_obj->ToObject(&obj)) return false;
}
Object* elements;
{ MaybeObject* maybe_elements = AllocateFixedArray(2);
if (!maybe_elements->ToObject(&elements)) return false;
}
FixedArray::cast(elements)->set(0, Smi::FromInt(0));
JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
set_message_listeners(JSObject::cast(obj));
return true;
}
void Heap::CreateJSEntryStub() {
JSEntryStub stub;
set_js_entry_code(*stub.GetCode(isolate()));
}
void Heap::CreateJSConstructEntryStub() {
JSConstructEntryStub stub;
set_js_construct_entry_code(*stub.GetCode(isolate()));
}
void Heap::CreateFixedStubs() {
// Here we create roots for fixed stubs. They are needed at GC
// for cooking and uncooking (check out frames.cc).
// The eliminates the need for doing dictionary lookup in the
// stub cache for these stubs.
HandleScope scope(isolate());
// gcc-4.4 has problem generating correct code of following snippet:
// { JSEntryStub stub;
// js_entry_code_ = *stub.GetCode();
// }
// { JSConstructEntryStub stub;
// js_construct_entry_code_ = *stub.GetCode();
// }
// To workaround the problem, make separate functions without inlining.
Heap::CreateJSEntryStub();
Heap::CreateJSConstructEntryStub();
// Create stubs that should be there, so we don't unexpectedly have to
// create them if we need them during the creation of another stub.
// Stub creation mixes raw pointers and handles in an unsafe manner so
// we cannot create stubs while we are creating stubs.
CodeStub::GenerateStubsAheadOfTime(isolate());
}
bool Heap::CreateInitialObjects() {
Object* obj;
// The -0 value must be set before NumberFromDouble works.
{ MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_minus_zero_value(HeapNumber::cast(obj));
ASSERT(signbit(minus_zero_value()->Number()) != 0);
{ MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_nan_value(HeapNumber::cast(obj));
{ MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_infinity_value(HeapNumber::cast(obj));
// The hole has not been created yet, but we want to put something
// predictable in the gaps in the string table, so lets make that Smi zero.
set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
// Allocate initial string table.
{ MaybeObject* maybe_obj =
StringTable::Allocate(this, kInitialStringTableSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
// Don't use set_string_table() due to asserts.
roots_[kStringTableRootIndex] = obj;
// Finish initializing oddballs after creating the string table.
{ MaybeObject* maybe_obj =
undefined_value()->Initialize("undefined",
nan_value(),
Oddball::kUndefined);
if (!maybe_obj->ToObject(&obj)) return false;
}
// Initialize the null_value.
{ MaybeObject* maybe_obj =
null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
if (!maybe_obj->ToObject(&obj)) return false;
}
{ MaybeObject* maybe_obj = CreateOddball("true",
Smi::FromInt(1),
Oddball::kTrue);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_true_value(Oddball::cast(obj));
{ MaybeObject* maybe_obj = CreateOddball("false",
Smi::FromInt(0),
Oddball::kFalse);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_false_value(Oddball::cast(obj));
{ MaybeObject* maybe_obj = CreateOddball("hole",
Smi::FromInt(-1),
Oddball::kTheHole);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_the_hole_value(Oddball::cast(obj));
{ MaybeObject* maybe_obj = CreateOddball("arguments_marker",
Smi::FromInt(-4),
Oddball::kArgumentMarker);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_arguments_marker(Oddball::cast(obj));
{ MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
Smi::FromInt(-2),
Oddball::kOther);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_no_interceptor_result_sentinel(obj);
{ MaybeObject* maybe_obj = CreateOddball("termination_exception",
Smi::FromInt(-3),
Oddball::kOther);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_termination_exception(obj);
for (unsigned i = 0; i < ARRAY_SIZE(constant_string_table); i++) {
{ MaybeObject* maybe_obj =
InternalizeUtf8String(constant_string_table[i].contents);
if (!maybe_obj->ToObject(&obj)) return false;
}
roots_[constant_string_table[i].index] = String::cast(obj);
}
// Allocate the hidden string which is used to identify the hidden properties
// in JSObjects. The hash code has a special value so that it will not match
// the empty string when searching for the property. It cannot be part of the
// loop above because it needs to be allocated manually with the special
// hash code in place. The hash code for the hidden_string is zero to ensure
// that it will always be at the first entry in property descriptors.
{ MaybeObject* maybe_obj = AllocateOneByteInternalizedString(
OneByteVector("", 0), String::kEmptyStringHash);
if (!maybe_obj->ToObject(&obj)) return false;
}
hidden_string_ = String::cast(obj);
// Allocate the code_stubs dictionary. The initial size is set to avoid
// expanding the dictionary during bootstrapping.
{ MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(this, 128);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_code_stubs(UnseededNumberDictionary::cast(obj));
// Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
// is set to avoid expanding the dictionary during bootstrapping.
{ MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(this, 64);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
{ MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
if (!maybe_obj->ToObject(&obj)) return false;
}
set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
set_instanceof_cache_function(Smi::FromInt(0));
set_instanceof_cache_map(Smi::FromInt(0));
set_instanceof_cache_answer(Smi::FromInt(0));
CreateFixedStubs();
// Allocate the dictionary of intrinsic function names.
{ MaybeObject* maybe_obj =
NameDictionary::Allocate(this, Runtime::kNumFunctions);
if (!maybe_obj->ToObject(&obj)) return false;
}
{ MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
obj);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_intrinsic_function_names(NameDictionary::cast(obj));
{ MaybeObject* maybe_obj = AllocateInitialNumberStringCache();
if (!maybe_obj->ToObject(&obj)) return false;
}
set_number_string_cache(FixedArray::cast(obj));
// Allocate cache for single character one byte strings.
{ MaybeObject* maybe_obj =
AllocateFixedArray(String::kMaxOneByteCharCode + 1, TENURED);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_single_character_string_cache(FixedArray::cast(obj));
// Allocate cache for string split.
{ MaybeObject* maybe_obj = AllocateFixedArray(
RegExpResultsCache::kRegExpResultsCacheSize, TENURED);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_string_split_cache(FixedArray::cast(obj));
{ MaybeObject* maybe_obj = AllocateFixedArray(
RegExpResultsCache::kRegExpResultsCacheSize, TENURED);
if (!maybe_obj->ToObject(&obj)) return false;
}
set_regexp_multiple_cache(FixedArray::cast(obj));
// Allocate cache for external strings pointing to native source code.
{ MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
if (!maybe_obj->ToObject(&obj)) return false;
}
set_natives_source_cache(FixedArray::cast(obj));
// Allocate object to hold object observation state.
{ MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
if (!maybe_obj->ToObject(&obj)) return false;
}
{ MaybeObject* maybe_obj = AllocateJSObjectFromMap(Map::cast(obj));
if (!maybe_obj->ToObject(&obj)) return false;
}
set_observation_state(JSObject::cast(obj));
// Handling of script id generation is in FACTORY->NewScript.
set_last_script_id(undefined_value());
// Initialize keyed lookup cache.
isolate_->keyed_lookup_cache()->Clear();
// Initialize context slot cache.
isolate_->context_slot_cache()->Clear();
// Initialize descriptor cache.
isolate_->descriptor_lookup_cache()->Clear();
// Initialize compilation cache.
isolate_->compilation_cache()->Clear();
return true;
}
bool Heap::RootCanBeWrittenAfterInitialization(Heap::RootListIndex root_index) {
RootListIndex writable_roots[] = {
kStoreBufferTopRootIndex,
kStackLimitRootIndex,
kNumberStringCacheRootIndex,
kInstanceofCacheFunctionRootIndex,
kInstanceofCacheMapRootIndex,
kInstanceofCacheAnswerRootIndex,
kCodeStubsRootIndex,
kNonMonomorphicCacheRootIndex,
kPolymorphicCodeCacheRootIndex,
kLastScriptIdRootIndex,
kEmptyScriptRootIndex,
kRealStackLimitRootIndex,
kArgumentsAdaptorDeoptPCOffsetRootIndex,
kConstructStubDeoptPCOffsetRootIndex,
kGetterStubDeoptPCOffsetRootIndex,
kSetterStubDeoptPCOffsetRootIndex,
kStringTableRootIndex,
};
for (unsigned int i = 0; i < ARRAY_SIZE(writable_roots); i++) {
if (root_index == writable_roots[i])
return true;
}
return false;
}
Object* RegExpResultsCache::Lookup(Heap* heap,
String* key_string,
Object* key_pattern,
ResultsCacheType type) {
FixedArray* cache;
if (!key_string->IsInternalizedString()) return Smi::FromInt(0);
if (type == STRING_SPLIT_SUBSTRINGS) {
ASSERT(key_pattern->IsString());
if (!key_pattern->IsInternalizedString()) return Smi::FromInt(0);
cache = heap->string_split_cache();
} else {
ASSERT(type == REGEXP_MULTIPLE_INDICES);
ASSERT(key_pattern->IsFixedArray());
cache = heap->regexp_multiple_cache();
}
uint32_t hash = key_string->Hash();
uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) &
~(kArrayEntriesPerCacheEntry - 1));
if (cache->get(index + kStringOffset) == key_string &&
cache->get(index + kPatternOffset) == key_pattern) {
return cache->get(index + kArrayOffset);
}
index =
((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1));
if (cache->get(index + kStringOffset) == key_string &&
cache->get(index + kPatternOffset) == key_pattern) {
return cache->get(index + kArrayOffset);
}
return Smi::FromInt(0);
}
void RegExpResultsCache::Enter(Heap* heap,
String* key_string,
Object* key_pattern,
FixedArray* value_array,
ResultsCacheType type) {
FixedArray* cache;
if (!key_string->IsInternalizedString()) return;
if (type == STRING_SPLIT_SUBSTRINGS) {
ASSERT(key_pattern->IsString());
if (!key_pattern->IsInternalizedString()) return;
cache = heap->string_split_cache();
} else {
ASSERT(type == REGEXP_MULTIPLE_INDICES);
ASSERT(key_pattern->IsFixedArray());
cache = heap->regexp_multiple_cache();
}
uint32_t hash = key_string->Hash();
uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) &
~(kArrayEntriesPerCacheEntry - 1));
if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
cache->set(index + kStringOffset, key_string);
cache->set(index + kPatternOffset, key_pattern);
cache->set(index + kArrayOffset, value_array);
} else {
uint32_t index2 =
((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1));
if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
cache->set(index2 + kStringOffset, key_string);
cache->set(index2 + kPatternOffset, key_pattern);
cache->set(index2 + kArrayOffset, value_array);
} else {
cache->set(index2 + kStringOffset, Smi::FromInt(0));
cache->set(index2 + kPatternOffset, Smi::FromInt(0));
cache->set(index2 + kArrayOffset, Smi::FromInt(0));
cache->set(index + kStringOffset, key_string);
cache->set(index + kPatternOffset, key_pattern);
cache->set(index + kArrayOffset, value_array);
}
}
// If the array is a reasonably short list of substrings, convert it into a
// list of internalized strings.
if (type == STRING_SPLIT_SUBSTRINGS && value_array->length() < 100) {
for (int i = 0; i < value_array->length(); i++) {
String* str = String::cast(value_array->get(i));
Object* internalized_str;
MaybeObject* maybe_string = heap->InternalizeString(str);
if (maybe_string->ToObject(&internalized_str)) {
value_array->set(i, internalized_str);
}
}
}
// Convert backing store to a copy-on-write array.
value_array->set_map_no_write_barrier(heap->fixed_cow_array_map());
}
void RegExpResultsCache::Clear(FixedArray* cache) {
for (int i = 0; i < kRegExpResultsCacheSize; i++) {
cache->set(i, Smi::FromInt(0));
}
}
MaybeObject* Heap::AllocateInitialNumberStringCache() {
MaybeObject* maybe_obj =
AllocateFixedArray(kInitialNumberStringCacheSize * 2, TENURED);
return maybe_obj;
}
int Heap::FullSizeNumberStringCacheLength() {
// Compute the size of the number string cache based on the max newspace size.
// The number string cache has a minimum size based on twice the initial cache
// size to ensure that it is bigger after being made 'full size'.
int number_string_cache_size = max_semispace_size_ / 512;
number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
Min(0x4000, number_string_cache_size));
// There is a string and a number per entry so the length is twice the number
// of entries.
return number_string_cache_size * 2;
}
void Heap::AllocateFullSizeNumberStringCache() {
// The idea is to have a small number string cache in the snapshot to keep
// boot-time memory usage down. If we expand the number string cache already
// while creating the snapshot then that didn't work out.
ASSERT(!Serializer::enabled() || FLAG_extra_code != NULL);
MaybeObject* maybe_obj =
AllocateFixedArray(FullSizeNumberStringCacheLength(), TENURED);
Object* new_cache;
if (maybe_obj->ToObject(&new_cache)) {
// We don't bother to repopulate the cache with entries from the old cache.
// It will be repopulated soon enough with new strings.
set_number_string_cache(FixedArray::cast(new_cache));
}
// If allocation fails then we just return without doing anything. It is only
// a cache, so best effort is OK here.
}
void Heap::FlushNumberStringCache() {
// Flush the number to string cache.
int len = number_string_cache()->length();
for (int i = 0; i < len; i++) {
number_string_cache()->set_undefined(this, i);
}
}
static inline int double_get_hash(double d) {
DoubleRepresentation rep(d);
return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
}
static inline int smi_get_hash(Smi* smi) {
return smi->value();
}
Object* Heap::GetNumberStringCache(Object* number) {
int hash;
int mask = (number_string_cache()->length() >> 1) - 1;
if (number->IsSmi()) {
hash = smi_get_hash(Smi::cast(number)) & mask;
} else {
hash = double_get_hash(number->Number()) & mask;
}
Object* key = number_string_cache()->get(hash * 2);
if (key == number) {
return String::cast(number_string_cache()->get(hash * 2 + 1));
} else if (key->IsHeapNumber() &&
number->IsHeapNumber() &&
key->Number() == number->Number()) {
return String::cast(number_string_cache()->get(hash * 2 + 1));
}
return undefined_value();
}
void Heap::SetNumberStringCache(Object* number, String* string) {
int hash;
int mask = (number_string_cache()->length() >> 1) - 1;
if (number->IsSmi()) {
hash = smi_get_hash(Smi::cast(number)) & mask;
} else {
hash = double_get_hash(number->Number()) & mask;
}
if (number_string_cache()->get(hash * 2) != undefined_value() &&
number_string_cache()->length() != FullSizeNumberStringCacheLength()) {
// The first time we have a hash collision, we move to the full sized
// number string cache.
AllocateFullSizeNumberStringCache();
return;
}
number_string_cache()->set(hash * 2, number);
number_string_cache()->set(hash * 2 + 1, string);
}
MaybeObject* Heap::NumberToString(Object* number,
bool check_number_string_cache) {
isolate_->counters()->number_to_string_runtime()->Increment();
if (check_number_string_cache) {
Object* cached = GetNumberStringCache(number);
if (cached != undefined_value()) {
return cached;
}
}
char arr[100];
Vector<char> buffer(arr, ARRAY_SIZE(arr));
const char* str;
if (number->IsSmi()) {
int num = Smi::cast(number)->value();
str = IntToCString(num, buffer);
} else {
double num = HeapNumber::cast(number)->value();
str = DoubleToCString(num, buffer);
}
Object* js_string;
MaybeObject* maybe_js_string = AllocateStringFromOneByte(CStrVector(str));
if (maybe_js_string->ToObject(&js_string)) {
SetNumberStringCache(number, String::cast(js_string));
}
return maybe_js_string;
}
MaybeObject* Heap::Uint32ToString(uint32_t value,
bool check_number_string_cache) {
Object* number;
MaybeObject* maybe = NumberFromUint32(value);
if (!maybe->To<Object>(&number)) return maybe;
return NumberToString(number, check_number_string_cache);
}
Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
}
Heap::RootListIndex Heap::RootIndexForExternalArrayType(
ExternalArrayType array_type) {
switch (array_type) {
case kExternalByteArray:
return kExternalByteArrayMapRootIndex;
case kExternalUnsignedByteArray:
return kExternalUnsignedByteArrayMapRootIndex;
case kExternalShortArray:
return kExternalShortArrayMapRootIndex;
case kExternalUnsignedShortArray:
return kExternalUnsignedShortArrayMapRootIndex;
case kExternalIntArray:
return kExternalIntArrayMapRootIndex;
case kExternalUnsignedIntArray:
return kExternalUnsignedIntArrayMapRootIndex;
case kExternalFloatArray:
return kExternalFloatArrayMapRootIndex;
case kExternalDoubleArray:
return kExternalDoubleArrayMapRootIndex;
case kExternalPixelArray:
return kExternalPixelArrayMapRootIndex;
default:
UNREACHABLE();
return kUndefinedValueRootIndex;
}
}
MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
// We need to distinguish the minus zero value and this cannot be
// done after conversion to int. Doing this by comparing bit
// patterns is faster than using fpclassify() et al.
static const DoubleRepresentation minus_zero(-0.0);
DoubleRepresentation rep(value);
if (rep.bits == minus_zero.bits) {
return AllocateHeapNumber(-0.0, pretenure);
}
int int_value = FastD2I(value);
if (value == int_value && Smi::IsValid(int_value)) {
return Smi::FromInt(int_value);
}
// Materialize the value in the heap.
return AllocateHeapNumber(value, pretenure);
}
MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
// Statically ensure that it is safe to allocate foreigns in paged spaces.
STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Foreign* result;
MaybeObject* maybe_result = Allocate(foreign_map(), space);
if (!maybe_result->To(&result)) return maybe_result;
result->set_foreign_address(address);
return result;
}
MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
SharedFunctionInfo* share;
MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
// Set pointer fields.
share->set_name(name);
Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
share->set_code(illegal);
share->ClearOptimizedCodeMap();
share->set_scope_info(ScopeInfo::Empty(isolate_));
Code* construct_stub =
isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
share->set_construct_stub(construct_stub);
share->set_instance_class_name(Object_string());
share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
share->set_ast_node_count(0);
share->set_stress_deopt_counter(FLAG_deopt_every_n_times);
share->set_counters(0);
// Set integer fields (smi or int, depending on the architecture).
share->set_length(0);
share->set_formal_parameter_count(0);
share->set_expected_nof_properties(0);
share->set_num_literals(0);
share->set_start_position_and_type(0);
share->set_end_position(0);
share->set_function_token_position(0);
// All compiler hints default to false or 0.
share->set_compiler_hints(0);
share->set_this_property_assignments_count(0);
share->set_opt_count(0);
return share;
}
MaybeObject* Heap::AllocateJSMessageObject(String* type,
JSArray* arguments,
int start_position,
int end_position,
Object* script,
Object* stack_trace,
Object* stack_frames) {
Object* result;
{ MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
JSMessageObject* message = JSMessageObject::cast(result);
message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
message->initialize_elements();
message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
message->set_type(type);
message->set_arguments(arguments);
message->set_start_position(start_position);
message->set_end_position(end_position);
message->set_script(script);
message->set_stack_trace(stack_trace);
message->set_stack_frames(stack_frames);
return result;
}
// Returns true for a character in a range. Both limits are inclusive.
static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
// This makes uses of the the unsigned wraparound.
return character - from <= to - from;
}
MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
Heap* heap,
uint16_t c1,
uint16_t c2) {
String* result;
// Numeric strings have a different hash algorithm not known by
// LookupTwoCharsStringIfExists, so we skip this step for such strings.
if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
heap->string_table()->LookupTwoCharsStringIfExists(c1, c2, &result)) {
return result;
// Now we know the length is 2, we might as well make use of that fact
// when building the new string.
} else if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
// We can do this.
ASSERT(IsPowerOf2(String::kMaxOneByteCharCodeU + 1)); // because of this.
Object* result;
{ MaybeObject* maybe_result = heap->AllocateRawOneByteString(2);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
uint8_t* dest = SeqOneByteString::cast(result)->GetChars();
dest[0] = static_cast<uint8_t>(c1);
dest[1] = static_cast<uint8_t>(c2);
return result;
} else {
Object* result;
{ MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
uc16* dest = SeqTwoByteString::cast(result)->GetChars();
dest[0] = c1;
dest[1] = c2;
return result;
}
}
MaybeObject* Heap::AllocateConsString(String* first, String* second) {
int first_length = first->length();
if (first_length == 0) {
return second;
}
int second_length = second->length();
if (second_length == 0) {
return first;
}
int length = first_length + second_length;
// Optimization for 2-byte strings often used as keys in a decompression
// dictionary. Check whether we already have the string in the string
// table to prevent creation of many unneccesary strings.
if (length == 2) {
uint16_t c1 = first->Get(0);
uint16_t c2 = second->Get(0);
return MakeOrFindTwoCharacterString(this, c1, c2);
}
bool first_is_one_byte = first->IsOneByteRepresentation();
bool second_is_one_byte = second->IsOneByteRepresentation();
bool is_one_byte = first_is_one_byte && second_is_one_byte;
// Make sure that an out of memory exception is thrown if the length
// of the new cons string is too large.
if (length > String::kMaxLength || length < 0) {
isolate()->context()->mark_out_of_memory();
return Failure::OutOfMemoryException(0x4);
}
bool is_ascii_data_in_two_byte_string = false;
if (!is_one_byte) {
// At least one of the strings uses two-byte representation so we
// can't use the fast case code for short ASCII strings below, but
// we can try to save memory if all chars actually fit in ASCII.
is_ascii_data_in_two_byte_string =
first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
if (is_ascii_data_in_two_byte_string) {
isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
}
}
// If the resulting string is small make a flat string.
if (length < ConsString::kMinLength) {
// Note that neither of the two inputs can be a slice because:
STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
ASSERT(first->IsFlat());
ASSERT(second->IsFlat());
if (is_one_byte) {
Object* result;
{ MaybeObject* maybe_result = AllocateRawOneByteString(length);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Copy the characters into the new object.
uint8_t* dest = SeqOneByteString::cast(result)->GetChars();
// Copy first part.
const uint8_t* src;
if (first->IsExternalString()) {
src = ExternalAsciiString::cast(first)->GetChars();
} else {
src = SeqOneByteString::cast(first)->GetChars();
}
for (int i = 0; i < first_length; i++) *dest++ = src[i];
// Copy second part.
if (second->IsExternalString()) {
src = ExternalAsciiString::cast(second)->GetChars();
} else {
src = SeqOneByteString::cast(second)->GetChars();
}
for (int i = 0; i < second_length; i++) *dest++ = src[i];
return result;
} else {
if (is_ascii_data_in_two_byte_string) {
Object* result;
{ MaybeObject* maybe_result = AllocateRawOneByteString(length);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Copy the characters into the new object.
uint8_t* dest = SeqOneByteString::cast(result)->GetChars();
String::WriteToFlat(first, dest, 0, first_length);
String::WriteToFlat(second, dest + first_length, 0, second_length);
isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
return result;
}
Object* result;
{ MaybeObject* maybe_result = AllocateRawTwoByteString(length);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Copy the characters into the new object.
uc16* dest = SeqTwoByteString::cast(result)->GetChars();
String::WriteToFlat(first, dest, 0, first_length);
String::WriteToFlat(second, dest + first_length, 0, second_length);
return result;
}
}
Map* map = (is_one_byte || is_ascii_data_in_two_byte_string) ?
cons_ascii_string_map() : cons_string_map();
Object* result;
{ MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
AssertNoAllocation no_gc;
ConsString* cons_string = ConsString::cast(result);
WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
cons_string->set_length(length);
cons_string->set_hash_field(String::kEmptyHashField);
cons_string->set_first(first, mode);
cons_string->set_second(second, mode);
return result;
}
MaybeObject* Heap::AllocateSubString(String* buffer,
int start,
int end,
PretenureFlag pretenure) {
int length = end - start;
if (length <= 0) {
return empty_string();
} else if (length == 1) {
return LookupSingleCharacterStringFromCode(buffer->Get(start));
} else if (length == 2) {
// Optimization for 2-byte strings often used as keys in a decompression
// dictionary. Check whether we already have the string in the string
// table to prevent creation of many unnecessary strings.
uint16_t c1 = buffer->Get(start);
uint16_t c2 = buffer->Get(start + 1);
return MakeOrFindTwoCharacterString(this, c1, c2);
}
// Make an attempt to flatten the buffer to reduce access time.
buffer = buffer->TryFlattenGetString();
if (!FLAG_string_slices ||
!buffer->IsFlat() ||
length < SlicedString::kMinLength ||
pretenure == TENURED) {
Object* result;
// WriteToFlat takes care of the case when an indirect string has a
// different encoding from its underlying string. These encodings may
// differ because of externalization.
bool is_one_byte = buffer->IsOneByteRepresentation();
{ MaybeObject* maybe_result = is_one_byte
? AllocateRawOneByteString(length, pretenure)
: AllocateRawTwoByteString(length, pretenure);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
String* string_result = String::cast(result);
// Copy the characters into the new object.
if (is_one_byte) {
ASSERT(string_result->IsOneByteRepresentation());
uint8_t* dest = SeqOneByteString::cast(string_result)->GetChars();
String::WriteToFlat(buffer, dest, start, end);
} else {
ASSERT(string_result->IsTwoByteRepresentation());
uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
String::WriteToFlat(buffer, dest, start, end);
}
return result;
}
ASSERT(buffer->IsFlat());
#if VERIFY_HEAP
if (FLAG_verify_heap) {
buffer->StringVerify();
}
#endif
Object* result;
// When slicing an indirect string we use its encoding for a newly created
// slice and don't check the encoding of the underlying string. This is safe
// even if the encodings are different because of externalization. If an
// indirect ASCII string is pointing to a two-byte string, the two-byte char
// codes of the underlying string must still fit into ASCII (because
// externalization must not change char codes).
{ Map* map = buffer->IsOneByteRepresentation()
? sliced_ascii_string_map()
: sliced_string_map();
MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
AssertNoAllocation no_gc;
SlicedString* sliced_string = SlicedString::cast(result);
sliced_string->set_length(length);
sliced_string->set_hash_field(String::kEmptyHashField);
if (buffer->IsConsString()) {
ConsString* cons = ConsString::cast(buffer);
ASSERT(cons->second()->length() == 0);
sliced_string->set_parent(cons->first());
sliced_string->set_offset(start);
} else if (buffer->IsSlicedString()) {
// Prevent nesting sliced strings.
SlicedString* parent_slice = SlicedString::cast(buffer);
sliced_string->set_parent(parent_slice->parent());
sliced_string->set_offset(start + parent_slice->offset());
} else {
sliced_string->set_parent(buffer);
sliced_string->set_offset(start);
}
ASSERT(sliced_string->parent()->IsSeqString() ||
sliced_string->parent()->IsExternalString());
return result;
}
MaybeObject* Heap::AllocateExternalStringFromAscii(
const ExternalAsciiString::Resource* resource) {
size_t length = resource->length();
if (length > static_cast<size_t>(String::kMaxLength)) {
isolate()->context()->mark_out_of_memory();
return Failure::OutOfMemoryException(0x5);
}
Map* map = external_ascii_string_map();
Object* result;
{ MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
external_string->set_length(static_cast<int>(length));
external_string->set_hash_field(String::kEmptyHashField);
external_string->set_resource(resource);
return result;
}
MaybeObject* Heap::AllocateExternalStringFromTwoByte(
const ExternalTwoByteString::Resource* resource) {
size_t length = resource->length();
if (length > static_cast<size_t>(String::kMaxLength)) {
isolate()->context()->mark_out_of_memory();
return Failure::OutOfMemoryException(0x6);
}
// For small strings we check whether the resource contains only
// one byte characters. If yes, we use a different string map.
static const size_t kAsciiCheckLengthLimit = 32;
bool is_one_byte = length <= kAsciiCheckLengthLimit &&
String::IsOneByte(resource->data(), static_cast<int>(length));
Map* map = is_one_byte ?
external_string_with_ascii_data_map() : external_string_map();
Object* result;
{ MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
external_string->set_length(static_cast<int>(length));
external_string->set_hash_field(String::kEmptyHashField);
external_string->set_resource(resource);
return result;
}
MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
if (code <= String::kMaxOneByteCharCode) {
Object* value = single_character_string_cache()->get(code);
if (value != undefined_value()) return value;
uint8_t buffer[1];
buffer[0] = static_cast<uint8_t>(code);
Object* result;
MaybeObject* maybe_result =
InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
if (!maybe_result->ToObject(&result)) return maybe_result;
single_character_string_cache()->set(code, result);
return result;
}
Object* result;
{ MaybeObject* maybe_result = AllocateRawTwoByteString(1);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
String* answer = String::cast(result);
answer->Set(0, code);
return answer;
}
MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
if (length < 0 || length > ByteArray::kMaxLength) {
return Failure::OutOfMemoryException(0x7);
}
if (pretenure == NOT_TENURED) {
return AllocateByteArray(length);
}
int size = ByteArray::SizeFor(length);
Object* result;
{ MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
? old_data_space_->AllocateRaw(size)
: lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
byte_array_map());
reinterpret_cast<ByteArray*>(result)->set_length(length);
return result;
}
MaybeObject* Heap::AllocateByteArray(int length) {
if (length < 0 || length > ByteArray::kMaxLength) {
return Failure::OutOfMemoryException(0x8);
}
int size = ByteArray::SizeFor(length);
AllocationSpace space =
(size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
Object* result;
{ MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
byte_array_map());
reinterpret_cast<ByteArray*>(result)->set_length(length);
return result;
}
void Heap::CreateFillerObjectAt(Address addr, int size) {
if (size == 0) return;
HeapObject* filler = HeapObject::FromAddress(addr);
if (size == kPointerSize) {
filler->set_map_no_write_barrier(one_pointer_filler_map());
} else if (size == 2 * kPointerSize) {
filler->set_map_no_write_barrier(two_pointer_filler_map());
} else {
filler->set_map_no_write_barrier(free_space_map());
FreeSpace::cast(filler)->set_size(size);
}
}
MaybeObject* Heap::AllocateExternalArray(int length,
ExternalArrayType array_type,
void* external_pointer,
PretenureFlag pretenure) {
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Object* result;
{ MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
space,
OLD_DATA_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
reinterpret_cast<ExternalArray*>(result)->set_map_no_write_barrier(
MapForExternalArrayType(array_type));
reinterpret_cast<ExternalArray*>(result)->set_length(length);
reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
external_pointer);
return result;
}
MaybeObject* Heap::CreateCode(const CodeDesc& desc,
Code::Flags flags,
Handle<Object> self_reference,
bool immovable) {
// Allocate ByteArray before the Code object, so that we do not risk
// leaving uninitialized Code object (and breaking the heap).
ByteArray* reloc_info;
MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
// Compute size.
int body_size = RoundUp(desc.instr_size, kObjectAlignment);
int obj_size = Code::SizeFor(body_size);
ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
MaybeObject* maybe_result;
// Large code objects and code objects which should stay at a fixed address
// are allocated in large object space.
HeapObject* result;
bool force_lo_space = obj_size > code_space()->AreaSize();
if (force_lo_space) {
maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
} else {
maybe_result = code_space_->AllocateRaw(obj_size);
}
if (!maybe_result->To<HeapObject>(&result)) return maybe_result;
if (immovable && !force_lo_space &&
// Objects on the first page of each space are never moved.
!code_space_->FirstPage()->Contains(result->address())) {
// Discard the first code allocation, which was on a page where it could be
// moved.
CreateFillerObjectAt(result->address(), obj_size);
maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
if (!maybe_result->To<HeapObject>(&result)) return maybe_result;
}
// Initialize the object
result->set_map_no_write_barrier(code_map());
Code* code = Code::cast(result);
ASSERT(!isolate_->code_range()->exists() ||
isolate_->code_range()->contains(code->address()));
code->set_instruction_size(desc.instr_size);
code->set_relocation_info(reloc_info);
code->set_flags(flags);
if (code->is_call_stub() || code->is_keyed_call_stub()) {
code->set_check_type(RECEIVER_MAP_CHECK);
}
code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
code->InitializeTypeFeedbackInfoNoWriteBarrier(undefined_value());
code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
code->set_gc_metadata(Smi::FromInt(0));
code->set_ic_age(global_ic_age_);
code->set_prologue_offset(kPrologueOffsetNotSet);
if (code->kind() == Code::OPTIMIZED_FUNCTION) {
code->set_marked_for_deoptimization(false);
}
// Allow self references to created code object by patching the handle to
// point to the newly allocated Code object.
if (!self_reference.is_null()) {
*(self_reference.location()) = code;
}
// Migrate generated code.
// The generated code can contain Object** values (typically from handles)
// that are dereferenced during the copy to point directly to the actual heap
// objects. These pointers can include references to the code object itself,
// through the self_reference parameter.
code->CopyFrom(desc);
#ifdef VERIFY_HEAP
if (FLAG_verify_heap) {
code->Verify();
}
#endif
return code;
}
MaybeObject* Heap::CopyCode(Code* code) {
// Allocate an object the same size as the code object.
int obj_size = code->Size();
MaybeObject* maybe_result;
if (obj_size > code_space()->AreaSize()) {
maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
} else {
maybe_result = code_space_->AllocateRaw(obj_size);
}
Object* result;
if (!maybe_result->ToObject(&result)) return maybe_result;
// Copy code object.
Address old_addr = code->address();
Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
CopyBlock(new_addr, old_addr, obj_size);
// Relocate the copy.
Code* new_code = Code::cast(result);
ASSERT(!isolate_->code_range()->exists() ||
isolate_->code_range()->contains(code->address()));
new_code->Relocate(new_addr - old_addr);
return new_code;
}
MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
// Allocate ByteArray before the Code object, so that we do not risk
// leaving uninitialized Code object (and breaking the heap).
Object* reloc_info_array;
{ MaybeObject* maybe_reloc_info_array =
AllocateByteArray(reloc_info.length(), TENURED);
if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
return maybe_reloc_info_array;
}
}
int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
int new_obj_size = Code::SizeFor(new_body_size);
Address old_addr = code->address();
size_t relocation_offset =
static_cast<size_t>(code->instruction_end() - old_addr);
MaybeObject* maybe_result;
if (new_obj_size > code_space()->AreaSize()) {
maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
} else {
maybe_result = code_space_->AllocateRaw(new_obj_size);
}
Object* result;
if (!maybe_result->ToObject(&result)) return maybe_result;
// Copy code object.
Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
// Copy header and instructions.
CopyBytes(new_addr, old_addr, relocation_offset);
Code* new_code = Code::cast(result);
new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
// Copy patched rinfo.
CopyBytes(new_code->relocation_start(),
reloc_info.start(),
static_cast<size_t>(reloc_info.length()));
// Relocate the copy.
ASSERT(!isolate_->code_range()->exists() ||
isolate_->code_range()->contains(code->address()));
new_code->Relocate(new_addr - old_addr);
#ifdef VERIFY_HEAP
if (FLAG_verify_heap) {
code->Verify();
}
#endif
return new_code;
}
MaybeObject* Heap::AllocateWithAllocationSite(Map* map, AllocationSpace space,
Handle<Object> allocation_site_info_payload) {
ASSERT(gc_state_ == NOT_IN_GC);
ASSERT(map->instance_type() != MAP_TYPE);
// If allocation failures are disallowed, we may allocate in a different
// space when new space is full and the object is not a large object.
AllocationSpace retry_space =
(space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
int size = map->instance_size() + AllocationSiteInfo::kSize;
Object* result;
MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
if (!maybe_result->ToObject(&result)) return maybe_result;
// No need for write barrier since object is white and map is in old space.
HeapObject::cast(result)->set_map_no_write_barrier(map);
AllocationSiteInfo* alloc_info = reinterpret_cast<AllocationSiteInfo*>(
reinterpret_cast<Address>(result) + map->instance_size());
alloc_info->set_map_no_write_barrier(allocation_site_info_map());
alloc_info->set_payload(*allocation_site_info_payload, SKIP_WRITE_BARRIER);
return result;
}
MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
ASSERT(gc_state_ == NOT_IN_GC);
ASSERT(map->instance_type() != MAP_TYPE);
// If allocation failures are disallowed, we may allocate in a different
// space when new space is full and the object is not a large object.
AllocationSpace retry_space =
(space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
int size = map->instance_size();
Object* result;
MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
if (!maybe_result->ToObject(&result)) return maybe_result;
// No need for write barrier since object is white and map is in old space.
HeapObject::cast(result)->set_map_no_write_barrier(map);
return result;
}
void Heap::InitializeFunction(JSFunction* function,
SharedFunctionInfo* shared,
Object* prototype) {
ASSERT(!prototype->IsMap());
function->initialize_properties();
function->initialize_elements();
function->set_shared(shared);
function->set_code(shared->code());
function->set_prototype_or_initial_map(prototype);
function->set_context(undefined_value());
function->set_literals_or_bindings(empty_fixed_array());
function->set_next_function_link(undefined_value());
}
MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
// Allocate the prototype. Make sure to use the object function
// from the function's context, since the function can be from a
// different context.
JSFunction* object_function =
function->context()->native_context()->object_function();
// Each function prototype gets a copy of the object function map.
// This avoid unwanted sharing of maps between prototypes of different
// constructors.
Map* new_map;
ASSERT(object_function->has_initial_map());
MaybeObject* maybe_map = object_function->initial_map()->Copy();
if (!maybe_map->To(&new_map)) return maybe_map;
Object* prototype;
MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
// When creating the prototype for the function we must set its
// constructor to the function.
MaybeObject* maybe_failure =
JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
constructor_string(), function, DONT_ENUM);
if (maybe_failure->IsFailure()) return maybe_failure;
return prototype;
}
MaybeObject* Heap::AllocateFunction(Map* function_map,
SharedFunctionInfo* shared,
Object* prototype,
PretenureFlag pretenure) {
AllocationSpace space =
(pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
Object* result;
{ MaybeObject* maybe_result = Allocate(function_map, space);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
InitializeFunction(JSFunction::cast(result), shared, prototype);
return result;
}
MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
// To get fast allocation and map sharing for arguments objects we
// allocate them based on an arguments boilerplate.
JSObject* boilerplate;
int arguments_object_size;
bool strict_mode_callee = callee->IsJSFunction() &&
!JSFunction::cast(callee)->shared()->is_classic_mode();
if (strict_mode_callee) {
boilerplate =
isolate()->context()->native_context()->
strict_mode_arguments_boilerplate();
arguments_object_size = kArgumentsObjectSizeStrict;
} else {
boilerplate =
isolate()->context()->native_context()->arguments_boilerplate();
arguments_object_size = kArgumentsObjectSize;
}
// This calls Copy directly rather than using Heap::AllocateRaw so we
// duplicate the check here.
ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
// Check that the size of the boilerplate matches our
// expectations. The ArgumentsAccessStub::GenerateNewObject relies
// on the size being a known constant.
ASSERT(arguments_object_size == boilerplate->map()->instance_size());
// Do the allocation.
Object* result;
{ MaybeObject* maybe_result =
AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Copy the content. The arguments boilerplate doesn't have any
// fields that point to new space so it's safe to skip the write
// barrier here.
CopyBlock(HeapObject::cast(result)->address(),
boilerplate->address(),
JSObject::kHeaderSize);
// Set the length property.
JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
Smi::FromInt(length),
SKIP_WRITE_BARRIER);
// Set the callee property for non-strict mode arguments object only.
if (!strict_mode_callee) {
JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
callee);
}
// Check the state of the object
ASSERT(JSObject::cast(result)->HasFastProperties());
ASSERT(JSObject::cast(result)->HasFastObjectElements());
return result;
}
static bool HasDuplicates(DescriptorArray* descriptors) {
int count = descriptors->number_of_descriptors();
if (count > 1) {
Name* prev_key = descriptors->GetKey(0);
for (int i = 1; i != count; i++) {
Name* current_key = descriptors->GetKey(i);
if (prev_key == current_key) return true;
prev_key = current_key;
}
}
return false;
}
MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
ASSERT(!fun->has_initial_map());
// First create a new map with the size and number of in-object properties
// suggested by the function.
int instance_size = fun->shared()->CalculateInstanceSize();
int in_object_properties = fun->shared()->CalculateInObjectProperties();
Map* map;
MaybeObject* maybe_map = AllocateMap(JS_OBJECT_TYPE, instance_size);
if (!maybe_map->To(&map)) return maybe_map;
// Fetch or allocate prototype.
Object* prototype;
if (fun->has_instance_prototype()) {
prototype = fun->instance_prototype();
} else {
MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
if (!maybe_prototype->To(&prototype)) return maybe_prototype;
}
map->set_inobject_properties(in_object_properties);
map->set_unused_property_fields(in_object_properties);
map->set_prototype(prototype);
ASSERT(map->has_fast_object_elements());
// If the function has only simple this property assignments add
// field descriptors for these to the initial map as the object
// cannot be constructed without having these properties. Guard by
// the inline_new flag so we only change the map if we generate a
// specialized construct stub.
ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
int count = fun->shared()->this_property_assignments_count();
if (count > in_object_properties) {
// Inline constructor can only handle inobject properties.
fun->shared()->ForbidInlineConstructor();
} else {
DescriptorArray* descriptors;
MaybeObject* maybe_descriptors = DescriptorArray::Allocate(count);
if (!maybe_descriptors->To(&descriptors)) return maybe_descriptors;
DescriptorArray::WhitenessWitness witness(descriptors);
for (int i = 0; i < count; i++) {
String* name = fun->shared()->GetThisPropertyAssignmentName(i);
ASSERT(name->IsInternalizedString());
FieldDescriptor field(name, i, NONE, i + 1);
descriptors->Set(i, &field, witness);
}
descriptors->Sort();
// The descriptors may contain duplicates because the compiler does not
// guarantee the uniqueness of property names (it would have required
// quadratic time). Once the descriptors are sorted we can check for
// duplicates in linear time.
if (HasDuplicates(descriptors)) {
fun->shared()->ForbidInlineConstructor();
} else {
map->InitializeDescriptors(descriptors);
map->set_pre_allocated_property_fields(count);
map->set_unused_property_fields(in_object_properties - count);
}
}
}
fun->shared()->StartInobjectSlackTracking(map);
return map;
}
void Heap::InitializeJSObjectFromMap(JSObject* obj,
FixedArray* properties,
Map* map) {
obj->set_properties(properties);
obj->initialize_elements();
// TODO(1240798): Initialize the object's body using valid initial values
// according to the object's initial map. For example, if the map's
// instance type is JS_ARRAY_TYPE, the length field should be initialized
// to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
// fixed array (e.g. Heap::empty_fixed_array()). Currently, the object
// verification code has to cope with (temporarily) invalid objects. See
// for example, JSArray::JSArrayVerify).
Object* filler;
// We cannot always fill with one_pointer_filler_map because objects
// created from API functions expect their internal fields to be initialized
// with undefined_value.
// Pre-allocated fields need to be initialized with undefined_value as well
// so that object accesses before the constructor completes (e.g. in the
// debugger) will not cause a crash.
if (map->constructor()->IsJSFunction() &&
JSFunction::cast(map->constructor())->shared()->
IsInobjectSlackTrackingInProgress()) {
// We might want to shrink the object later.
ASSERT(obj->GetInternalFieldCount() == 0);
filler = Heap::one_pointer_filler_map();
} else {
filler = Heap::undefined_value();
}
obj->InitializeBody(map, Heap::undefined_value(), filler);
}
MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
// JSFunctions should be allocated using AllocateFunction to be
// properly initialized.
ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
// Both types of global objects should be allocated using
// AllocateGlobalObject to be properly initialized.
ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
// Allocate the backing storage for the properties.
int prop_size =
map->pre_allocated_property_fields() +
map->unused_property_fields() -
map->inobject_properties();
ASSERT(prop_size >= 0);
Object* properties;
{ MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
if (!maybe_properties->ToObject(&properties)) return maybe_properties;
}
// Allocate the JSObject.
AllocationSpace space =
(pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
Object* obj;
MaybeObject* maybe_obj = Allocate(map, space);
if (!maybe_obj->To(&obj)) return maybe_obj;
// Initialize the JSObject.
InitializeJSObjectFromMap(JSObject::cast(obj),
FixedArray::cast(properties),
map);
ASSERT(JSObject::cast(obj)->HasFastElements());
return obj;
}
MaybeObject* Heap::AllocateJSObjectFromMapWithAllocationSite(Map* map,
Handle<Object> allocation_site_info_payload) {
// JSFunctions should be allocated using AllocateFunction to be
// properly initialized.
ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
// Both types of global objects should be allocated using
// AllocateGlobalObject to be properly initialized.
ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
// Allocate the backing storage for the properties.
int prop_size =
map->pre_allocated_property_fields() +
map->unused_property_fields() -
map->inobject_properties();
ASSERT(prop_size >= 0);
Object* properties;
{ MaybeObject* maybe_properties = AllocateFixedArray(prop_size);
if (!maybe_properties->ToObject(&properties)) return maybe_properties;
}
// Allocate the JSObject.
AllocationSpace space = NEW_SPACE;
if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
Object* obj;
MaybeObject* maybe_obj = AllocateWithAllocationSite(map, space,
allocation_site_info_payload);
if (!maybe_obj->To(&obj)) return maybe_obj;
// Initialize the JSObject.
InitializeJSObjectFromMap(JSObject::cast(obj),
FixedArray::cast(properties),
map);
ASSERT(JSObject::cast(obj)->HasFastElements());
return obj;
}
MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
PretenureFlag pretenure) {
// Allocate the initial map if absent.
if (!constructor->has_initial_map()) {
Object* initial_map;
{ MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
}
constructor->set_initial_map(Map::cast(initial_map));
Map::cast(initial_map)->set_constructor(constructor);
}
// Allocate the object based on the constructors initial map.
MaybeObject* result = AllocateJSObjectFromMap(
constructor->initial_map(), pretenure);
#ifdef DEBUG
// Make sure result is NOT a global object if valid.
Object* non_failure;
ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
#endif
return result;
}
MaybeObject* Heap::AllocateJSObjectWithAllocationSite(JSFunction* constructor,
Handle<Object> allocation_site_info_payload) {
// Allocate the initial map if absent.
if (!constructor->has_initial_map()) {
Object* initial_map;
{ MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
}
constructor->set_initial_map(Map::cast(initial_map));
Map::cast(initial_map)->set_constructor(constructor);
}
// Allocate the object based on the constructors initial map, or the payload
// advice
Map* initial_map = constructor->initial_map();
JSGlobalPropertyCell* cell = JSGlobalPropertyCell::cast(
*allocation_site_info_payload);
Smi* smi = Smi::cast(cell->value());
ElementsKind to_kind = static_cast<ElementsKind>(smi->value());
AllocationSiteMode mode = TRACK_ALLOCATION_SITE;
if (to_kind != initial_map->elements_kind()) {
MaybeObject* maybe_new_map = constructor->GetElementsTransitionMap(
isolate(), to_kind);
if (!maybe_new_map->To(&initial_map)) return maybe_new_map;
// Possibly alter the mode, since we found an updated elements kind
// in the type info cell.
mode = AllocationSiteInfo::GetMode(to_kind);
}
MaybeObject* result;
if (mode == TRACK_ALLOCATION_SITE) {
result = AllocateJSObjectFromMapWithAllocationSite(initial_map,
allocation_site_info_payload);
} else {
result = AllocateJSObjectFromMap(initial_map, NOT_TENURED);
}
#ifdef DEBUG
// Make sure result is NOT a global object if valid.
Object* non_failure;
ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
#endif
return result;
}
MaybeObject* Heap::AllocateJSModule(Context* context, ScopeInfo* scope_info) {
// Allocate a fresh map. Modules do not have a prototype.
Map* map;
MaybeObject* maybe_map = AllocateMap(JS_MODULE_TYPE, JSModule::kSize);
if (!maybe_map->To(&map)) return maybe_map;
// Allocate the object based on the map.
JSModule* module;
MaybeObject* maybe_module = AllocateJSObjectFromMap(map, TENURED);
if (!maybe_module->To(&module)) return maybe_module;
module->set_context(context);
module->set_scope_info(scope_info);
return module;
}
MaybeObject* Heap::AllocateJSArrayAndStorage(
ElementsKind elements_kind,
int length,
int capacity,
ArrayStorageAllocationMode mode,
PretenureFlag pretenure) {
MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
JSArray* array;
if (!maybe_array->To(&array)) return maybe_array;
// TODO(mvstanton): this body of code is duplicate with AllocateJSArrayStorage
// for performance reasons.
ASSERT(capacity >= length);
if (capacity == 0) {
array->set_length(Smi::FromInt(0));
array->set_elements(empty_fixed_array());
return array;
}
FixedArrayBase* elms;
MaybeObject* maybe_elms = NULL;
if (IsFastDoubleElementsKind(elements_kind)) {
if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
maybe_elms = AllocateUninitializedFixedDoubleArray(capacity);
} else {
ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
maybe_elms = AllocateFixedDoubleArrayWithHoles(capacity);
}
} else {
ASSERT(IsFastSmiOrObjectElementsKind(elements_kind));
if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
maybe_elms = AllocateUninitializedFixedArray(capacity);
} else {
ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
maybe_elms = AllocateFixedArrayWithHoles(capacity);
}
}
if (!maybe_elms->To(&elms)) return maybe_elms;
array->set_elements(elms);
array->set_length(Smi::FromInt(length));
return array;
}
MaybeObject* Heap::AllocateJSArrayAndStorageWithAllocationSite(
ElementsKind elements_kind,
int length,
int capacity,
Handle<Object> allocation_site_payload,
ArrayStorageAllocationMode mode) {
MaybeObject* maybe_array = AllocateJSArrayWithAllocationSite(elements_kind,
allocation_site_payload);
JSArray* array;
if (!maybe_array->To(&array)) return maybe_array;
return AllocateJSArrayStorage(array, length, capacity, mode);
}
MaybeObject* Heap::AllocateJSArrayStorage(
JSArray* array,
int length,
int capacity,
ArrayStorageAllocationMode mode) {
ASSERT(capacity >= length);
if (capacity == 0) {
array->set_length(Smi::FromInt(0));
array->set_elements(empty_fixed_array());
return array;
}
FixedArrayBase* elms;
MaybeObject* maybe_elms = NULL;
ElementsKind elements_kind = array->GetElementsKind();
if (IsFastDoubleElementsKind(elements_kind)) {
if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
maybe_elms = AllocateUninitializedFixedDoubleArray(capacity);
} else {
ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
maybe_elms = AllocateFixedDoubleArrayWithHoles(capacity);
}
} else {
ASSERT(IsFastSmiOrObjectElementsKind(elements_kind));
if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
maybe_elms = AllocateUninitializedFixedArray(capacity);
} else {
ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
maybe_elms = AllocateFixedArrayWithHoles(capacity);
}
}
if (!maybe_elms->To(&elms)) return maybe_elms;
array->set_elements(elms);
array->set_length(Smi::FromInt(length));
return array;
}
MaybeObject* Heap::AllocateJSArrayWithElements(
FixedArrayBase* elements,
ElementsKind elements_kind,
int length,
PretenureFlag pretenure) {
MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
JSArray* array;
if (!maybe_array->To(&array)) return maybe_array;
array->set_elements(elements);
array->set_length(Smi::FromInt(length));
array->ValidateElements();
return array;
}
MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
// Allocate map.
// TODO(rossberg): Once we optimize proxies, think about a scheme to share
// maps. Will probably depend on the identity of the handler object, too.
Map* map;
MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
map->set_prototype(prototype);
// Allocate the proxy object.
JSProxy* result;
MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
result->InitializeBody(map->instance_size(), Smi::FromInt(0));
result->set_handler(handler);
result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
return result;
}
MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
Object* call_trap,
Object* construct_trap,
Object* prototype) {
// Allocate map.
// TODO(rossberg): Once we optimize proxies, think about a scheme to share
// maps. Will probably depend on the identity of the handler object, too.
Map* map;
MaybeObject* maybe_map_obj =
AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
map->set_prototype(prototype);
// Allocate the proxy object.
JSFunctionProxy* result;
MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
result->InitializeBody(map->instance_size(), Smi::FromInt(0));
result->set_handler(handler);
result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
result->set_call_trap(call_trap);
result->set_construct_trap(construct_trap);
return result;
}
MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
ASSERT(constructor->has_initial_map());
Map* map = constructor->initial_map();
ASSERT(map->is_dictionary_map());
// Make sure no field properties are described in the initial map.
// This guarantees us that normalizing the properties does not
// require us to change property values to JSGlobalPropertyCells.
ASSERT(map->NextFreePropertyIndex() == 0);
// Make sure we don't have a ton of pre-allocated slots in the
// global objects. They will be unused once we normalize the object.
ASSERT(map->unused_property_fields() == 0);
ASSERT(map->inobject_properties() == 0);
// Initial size of the backing store to avoid resize of the storage during
// bootstrapping. The size differs between the JS global object ad the
// builtins object.
int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
// Allocate a dictionary object for backing storage.
NameDictionary* dictionary;
MaybeObject* maybe_dictionary =
NameDictionary::Allocate(
this,
map->NumberOfOwnDescriptors() * 2 + initial_size);
if (!maybe_dictionary->To(&dictionary)) return maybe_dictionary;
// The global object might be created from an object template with accessors.
// Fill these accessors into the dictionary.
DescriptorArray* descs = map->instance_descriptors();
for (int i = 0; i < descs->number_of_descriptors(); i++) {
PropertyDetails details = descs->GetDetails(i);
ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
PropertyDetails d = PropertyDetails(details.attributes(),
CALLBACKS,
details.descriptor_index());
Object* value = descs->GetCallbacksObject(i);
MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
if (!maybe_value->ToObject(&value)) return maybe_value;
MaybeObject* maybe_added = dictionary->Add(descs->GetKey(i), value, d);
if (!maybe_added->To(&dictionary)) return maybe_added;
}
// Allocate the global object and initialize it with the backing store.
JSObject* global;
MaybeObject* maybe_global = Allocate(map, OLD_POINTER_SPACE);
if (!maybe_global->To(&global)) return maybe_global;
InitializeJSObjectFromMap(global, dictionary, map);
// Create a new map for the global object.
Map* new_map;
MaybeObject* maybe_map = map->CopyDropDescriptors();
if (!maybe_map->To(&new_map)) return maybe_map;
new_map->set_dictionary_map(true);
// Set up the global object as a normalized object.
global->set_map(new_map);
global->set_properties(dictionary);
// Make sure result is a global object with properties in dictionary.
ASSERT(global->IsGlobalObject());
ASSERT(!global->HasFastProperties());
return global;
}
MaybeObject* Heap::CopyJSObject(JSObject* source) {
// Never used to copy functions. If functions need to be copied we
// have to be careful to clear the literals array.
SLOW_ASSERT(!source->IsJSFunction());
// Make the clone.
Map* map = source->map();
int object_size = map->instance_size();
Object* clone;
WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
// If we're forced to always allocate, we use the general allocation
// functions which may leave us with an object in old space.
if (always_allocate()) {
{ MaybeObject* maybe_clone =
AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
if (!maybe_clone->ToObject(&clone)) return maybe_clone;
}
Address clone_address = HeapObject::cast(clone)->address();
CopyBlock(clone_address,
source->address(),
object_size);
// Update write barrier for all fields that lie beyond the header.
RecordWrites(clone_address,
JSObject::kHeaderSize,
(object_size - JSObject::kHeaderSize) / kPointerSize);
} else {
wb_mode = SKIP_WRITE_BARRIER;
{ MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
if (!maybe_clone->ToObject(&clone)) return maybe_clone;
}
SLOW_ASSERT(InNewSpace(clone));
// Since we know the clone is allocated in new space, we can copy
// the contents without worrying about updating the write barrier.
CopyBlock(HeapObject::cast(clone)->address(),
source->address(),
object_size);
}
SLOW_ASSERT(
JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
FixedArray* properties = FixedArray::cast(source->properties());
// Update elements if necessary.
if (elements->length() > 0) {
Object* elem;
{ MaybeObject* maybe_elem;
if (elements->map() == fixed_cow_array_map()) {
maybe_elem = FixedArray::cast(elements);
} else if (source->HasFastDoubleElements()) {
maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
} else {
maybe_elem = CopyFixedArray(FixedArray::cast(elements));
}
if (!maybe_elem->ToObject(&elem)) return maybe_elem;
}
JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
}
// Update properties if necessary.
if (properties->length() > 0) {
Object* prop;
{ MaybeObject* maybe_prop = CopyFixedArray(properties);
if (!maybe_prop->ToObject(&prop)) return maybe_prop;
}
JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
}
// Return the new clone.
return clone;
}
MaybeObject* Heap::CopyJSObjectWithAllocationSite(JSObject* source) {
// Never used to copy functions. If functions need to be copied we
// have to be careful to clear the literals array.
SLOW_ASSERT(!source->IsJSFunction());
// Make the clone.
Map* map = source->map();
int object_size = map->instance_size();
Object* clone;
ASSERT(map->CanTrackAllocationSite());
ASSERT(map->instance_type() == JS_ARRAY_TYPE);
WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
// If we're forced to always allocate, we use the general allocation
// functions which may leave us with an object in old space.
int adjusted_object_size = object_size;
if (always_allocate()) {
// We'll only track origin if we are certain to allocate in new space
const int kMinFreeNewSpaceAfterGC = InitialSemiSpaceSize() * 3/4;
if ((object_size + AllocationSiteInfo::kSize) < kMinFreeNewSpaceAfterGC) {
adjusted_object_size += AllocationSiteInfo::kSize;
}
{ MaybeObject* maybe_clone =
AllocateRaw(adjusted_object_size, NEW_SPACE, OLD_POINTER_SPACE);
if (!maybe_clone->ToObject(&clone)) return maybe_clone;
}
Address clone_address = HeapObject::cast(clone)->address();
CopyBlock(clone_address,
source->address(),
object_size);
// Update write barrier for all fields that lie beyond the header.
int write_barrier_offset = adjusted_object_size > object_size
? JSArray::kSize + AllocationSiteInfo::kSize
: JSObject::kHeaderSize;
if (((object_size - write_barrier_offset) / kPointerSize) > 0) {
RecordWrites(clone_address,
write_barrier_offset,
(object_size - write_barrier_offset) / kPointerSize);
}
// Track allocation site information, if we failed to allocate it inline.
if (InNewSpace(clone) &&
adjusted_object_size == object_size) {
MaybeObject* maybe_alloc_info =
AllocateStruct(ALLOCATION_SITE_INFO_TYPE);
AllocationSiteInfo* alloc_info;
if (maybe_alloc_info->To(&alloc_info)) {
alloc_info->set_map_no_write_barrier(allocation_site_info_map());
alloc_info->set_payload(source, SKIP_WRITE_BARRIER);
}
}
} else {
wb_mode = SKIP_WRITE_BARRIER;
adjusted_object_size += AllocationSiteInfo::kSize;
{ MaybeObject* maybe_clone = new_space_.AllocateRaw(adjusted_object_size);
if (!maybe_clone->ToObject(&clone)) return maybe_clone;
}
SLOW_ASSERT(InNewSpace(clone));
// Since we know the clone is allocated in new space, we can copy
// the contents without worrying about updating the write barrier.
CopyBlock(HeapObject::cast(clone)->address(),
source->address(),
object_size);
}
if (adjusted_object_size > object_size) {
AllocationSiteInfo* alloc_info = reinterpret_cast<AllocationSiteInfo*>(
reinterpret_cast<Address>(clone) + object_size);
alloc_info->set_map_no_write_barrier(allocation_site_info_map());
alloc_info->set_payload(source, SKIP_WRITE_BARRIER);
}
SLOW_ASSERT(
JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
FixedArray* properties = FixedArray::cast(source->properties());
// Update elements if necessary.
if (elements->length() > 0) {
Object* elem;
{ MaybeObject* maybe_elem;
if (elements->map() == fixed_cow_array_map()) {
maybe_elem = FixedArray::cast(elements);
} else if (source->HasFastDoubleElements()) {
maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
} else {
maybe_elem = CopyFixedArray(FixedArray::cast(elements));
}
if (!maybe_elem->ToObject(&elem)) return maybe_elem;
}
JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
}
// Update properties if necessary.
if (properties->length() > 0) {
Object* prop;
{ MaybeObject* maybe_prop = CopyFixedArray(properties);
if (!maybe_prop->ToObject(&prop)) return maybe_prop;
}
JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
}
// Return the new clone.
return clone;
}
MaybeObject* Heap::ReinitializeJSReceiver(
JSReceiver* object, InstanceType type, int size) {
ASSERT(type >= FIRST_JS_OBJECT_TYPE);
// Allocate fresh map.
// TODO(rossberg): Once we optimize proxies, cache these maps.
Map* map;
MaybeObject* maybe = AllocateMap(type, size);
if (!maybe->To<Map>(&map)) return maybe;
// Check that the receiver has at least the size of the fresh object.
int size_difference = object->map()->instance_size() - map->instance_size();
ASSERT(size_difference >= 0);
map->set_prototype(object->map()->prototype());
// Allocate the backing storage for the properties.
int prop_size = map->unused_property_fields() - map->inobject_properties();
Object* properties;
maybe = AllocateFixedArray(prop_size, TENURED);
if (!maybe->ToObject(&properties)) return maybe;
// Functions require some allocation, which might fail here.
SharedFunctionInfo* shared = NULL;
if (type == JS_FUNCTION_TYPE) {
String* name;
maybe =
InternalizeOneByteString(STATIC_ASCII_VECTOR("<freezing call trap>"));
if (!maybe->To<String>(&name)) return maybe;
maybe = AllocateSharedFunctionInfo(name);
if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
}
// Because of possible retries of this function after failure,
// we must NOT fail after this point, where we have changed the type!
// Reset the map for the object.
object->set_map(map);
JSObject* jsobj = JSObject::cast(object);
// Reinitialize the object from the constructor map.
InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
// Functions require some minimal initialization.
if (type == JS_FUNCTION_TYPE) {
map->set_function_with_prototype(true);
InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
JSFunction::cast(object)->set_context(
isolate()->context()->native_context());
}
// Put in filler if the new object is smaller than the old.
if (size_difference > 0) {
CreateFillerObjectAt(
object->address() + map->instance_size(), size_difference);
}
return object;
}
MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
JSGlobalProxy* object) {
ASSERT(constructor->has_initial_map());
Map* map = constructor->initial_map();
// Check that the already allocated object has the same size and type as
// objects allocated using the constructor.
ASSERT(map->instance_size() == object->map()->instance_size());
ASSERT(map->instance_type() == object->map()->instance_type());
// Allocate the backing storage for the properties.
int prop_size = map->unused_property_fields() - map->inobject_properties();
Object* properties;
{ MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
if (!maybe_properties->ToObject(&properties)) return maybe_properties;
}
// Reset the map for the object.
object->set_map(constructor->initial_map());
// Reinitialize the object from the constructor map.
InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
return object;
}
MaybeObject* Heap::AllocateStringFromOneByte(Vector<const uint8_t> string,
PretenureFlag pretenure) {
int length = string.length();
if (length == 1) {
return Heap::LookupSingleCharacterStringFromCode(string[0]);
}
Object* result;
{ MaybeObject* maybe_result =
AllocateRawOneByteString(string.length(), pretenure);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Copy the characters into the new object.
CopyChars(SeqOneByteString::cast(result)->GetChars(),
string.start(),
length);
return result;
}
MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
int non_ascii_start,
PretenureFlag pretenure) {
// Continue counting the number of characters in the UTF-8 string, starting
// from the first non-ascii character or word.
Access<UnicodeCache::Utf8Decoder>
decoder(isolate_->unicode_cache()->utf8_decoder());
decoder->Reset(string.start() + non_ascii_start,
string.length() - non_ascii_start);
int utf16_length = decoder->Utf16Length();
ASSERT(utf16_length > 0);
// Allocate string.
Object* result;
{
int chars = non_ascii_start + utf16_length;
MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Convert and copy the characters into the new object.
SeqTwoByteString* twobyte = SeqTwoByteString::cast(result);
// Copy ascii portion.
uint16_t* data = twobyte->GetChars();
if (non_ascii_start != 0) {
const char* ascii_data = string.start();
for (int i = 0; i < non_ascii_start; i++) {
*data++ = *ascii_data++;
}
}
// Now write the remainder.
decoder->WriteUtf16(data, utf16_length);
return result;
}
MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
PretenureFlag pretenure) {
// Check if the string is an ASCII string.
Object* result;
int length = string.length();
const uc16* start = string.start();
if (String::IsOneByte(start, length)) {
MaybeObject* maybe_result = AllocateRawOneByteString(length, pretenure);
if (!maybe_result->ToObject(&result)) return maybe_result;
CopyChars(SeqOneByteString::cast(result)->GetChars(), start, length);
} else { // It's not a one byte string.
MaybeObject* maybe_result = AllocateRawTwoByteString(length, pretenure);
if (!maybe_result->ToObject(&result)) return maybe_result;
CopyChars(SeqTwoByteString::cast(result)->GetChars(), start, length);
}
return result;
}
Map* Heap::InternalizedStringMapForString(String* string) {
// If the string is in new space it cannot be used as internalized.
if (InNewSpace(string)) return NULL;
// Find the corresponding internalized string map for strings.
switch (string->map()->instance_type()) {
case STRING_TYPE: return internalized_string_map();
case ASCII_STRING_TYPE: return ascii_internalized_string_map();
case CONS_STRING_TYPE: return cons_internalized_string_map();
case CONS_ASCII_STRING_TYPE: return cons_ascii_internalized_string_map();
case EXTERNAL_STRING_TYPE: return external_internalized_string_map();
case EXTERNAL_ASCII_STRING_TYPE:
return external_ascii_internalized_string_map();
case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
return external_internalized_string_with_ascii_data_map();
case SHORT_EXTERNAL_STRING_TYPE:
return short_external_internalized_string_map();
case SHORT_EXTERNAL_ASCII_STRING_TYPE:
return short_external_ascii_internalized_string_map();
case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
return short_external_internalized_string_with_ascii_data_map();
default: return NULL; // No match found.
}
}
static inline void WriteOneByteData(Vector<const char> vector,
uint8_t* chars,
int len) {
// Only works for ascii.
ASSERT(vector.length() == len);
memcpy(chars, vector.start(), len);
}
static inline void WriteTwoByteData(Vector<const char> vector,
uint16_t* chars,
int len) {
const uint8_t* stream = reinterpret_cast<const uint8_t*>(vector.start());
unsigned stream_length = vector.length();
while (stream_length != 0) {
unsigned consumed = 0;
uint32_t c = unibrow::Utf8::ValueOf(stream, stream_length, &consumed);
ASSERT(c != unibrow::Utf8::kBadChar);
ASSERT(consumed <= stream_length);
stream_length -= consumed;
stream += consumed;
if (c > unibrow::Utf16::kMaxNonSurrogateCharCode) {
len -= 2;
if (len < 0) break;
*chars++ = unibrow::Utf16::LeadSurrogate(c);
*chars++ = unibrow::Utf16::TrailSurrogate(c);
} else {
len -= 1;
if (len < 0) break;
*chars++ = c;
}
}
ASSERT(stream_length == 0);
ASSERT(len == 0);
}
static inline void WriteOneByteData(String* s, uint8_t* chars, int len) {
ASSERT(s->length() == len);
String::WriteToFlat(s, chars, 0, len);
}
static inline void WriteTwoByteData(String* s, uint16_t* chars, int len) {
ASSERT(s->length() == len);
String::WriteToFlat(s, chars, 0, len);
}
template<bool is_one_byte, typename T>
MaybeObject* Heap::AllocateInternalizedStringImpl(
T t, int chars, uint32_t hash_field) {
ASSERT(chars >= 0);
// Compute map and object size.
int size;
Map* map;
if (is_one_byte) {
if (chars > SeqOneByteString::kMaxLength) {
return Failure::OutOfMemoryException(0x9);
}
map = ascii_internalized_string_map();
size = SeqOneByteString::SizeFor(chars);
} else {
if (chars > SeqTwoByteString::kMaxLength) {
return Failure::OutOfMemoryException(0xa);
}
map = internalized_string_map();
size = SeqTwoByteString::SizeFor(chars);
}
// Allocate string.
Object* result;
{ MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
: old_data_space_->AllocateRaw(size);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
// Set length and hash fields of the allocated string.
String* answer = String::cast(result);
answer->set_length(chars);
answer->set_hash_field(hash_field);
ASSERT_EQ(size, answer->Size());
if (is_one_byte) {
WriteOneByteData(t, SeqOneByteString::cast(answer)->GetChars(), chars);
} else {
WriteTwoByteData(t, SeqTwoByteString::cast(answer)->GetChars(), chars);
}
return answer;
}
// Need explicit instantiations.
template
MaybeObject* Heap::AllocateInternalizedStringImpl<true>(String*, int, uint32_t);
template
MaybeObject* Heap::AllocateInternalizedStringImpl<false>(
String*, int, uint32_t);
template
MaybeObject* Heap::AllocateInternalizedStringImpl<false>(
Vector<const char>, int, uint32_t);
MaybeObject* Heap::AllocateRawOneByteString(int length,
PretenureFlag pretenure) {
if (length < 0 || length > SeqOneByteString::kMaxLength) {
return Failure::OutOfMemoryException(0xb);
}
int size = SeqOneByteString::SizeFor(length);
ASSERT(size <= SeqOneByteString::kMaxSize);
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
AllocationSpace retry_space = OLD_DATA_SPACE;
if (space == NEW_SPACE) {
if (size > kMaxObjectSizeInNewSpace) {
// Allocate in large object space, retry space will be ignored.
space = LO_SPACE;
} else if (size > Page::kMaxNonCodeHeapObjectSize) {
// Allocate in new space, retry in large object space.
retry_space = LO_SPACE;
}
} else if (space == OLD_DATA_SPACE &&
size > Page::kMaxNonCodeHeapObjectSize) {
space = LO_SPACE;
}
Object* result;
{ MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Partially initialize the object.
HeapObject::cast(result)->set_map_no_write_barrier(ascii_string_map());
String::cast(result)->set_length(length);
String::cast(result)->set_hash_field(String::kEmptyHashField);
ASSERT_EQ(size, HeapObject::cast(result)->Size());
return result;
}
MaybeObject* Heap::AllocateRawTwoByteString(int length,
PretenureFlag pretenure) {
if (length < 0 || length > SeqTwoByteString::kMaxLength) {
return Failure::OutOfMemoryException(0xc);
}
int size = SeqTwoByteString::SizeFor(length);
ASSERT(size <= SeqTwoByteString::kMaxSize);
AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
AllocationSpace retry_space = OLD_DATA_SPACE;
if (space == NEW_SPACE) {
if (size > kMaxObjectSizeInNewSpace) {
// Allocate in large object space, retry space will be ignored.
space = LO_SPACE;
} else if (size > Page::kMaxNonCodeHeapObjectSize) {
// Allocate in new space, retry in large object space.
retry_space = LO_SPACE;
}
} else if (space == OLD_DATA_SPACE &&
size > Page::kMaxNonCodeHeapObjectSize) {
space = LO_SPACE;
}
Object* result;
{ MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Partially initialize the object.
HeapObject::cast(result)->set_map_no_write_barrier(string_map());
String::cast(result)->set_length(length);
String::cast(result)->set_hash_field(String::kEmptyHashField);
ASSERT_EQ(size, HeapObject::cast(result)->Size());
return result;
}
MaybeObject* Heap::AllocateJSArray(
ElementsKind elements_kind,
PretenureFlag pretenure) {
Context* native_context = isolate()->context()->native_context();
JSFunction* array_function = native_context->array_function();
Map* map = array_function->initial_map();
Object* maybe_map_array = native_context->js_array_maps();
if (!maybe_map_array->IsUndefined()) {
Object* maybe_transitioned_map =
FixedArray::cast(maybe_map_array)->get(elements_kind);
if (!maybe_transitioned_map->IsUndefined()) {
map = Map::cast(maybe_transitioned_map);
}
}
return AllocateJSObjectFromMap(map, pretenure);
}
MaybeObject* Heap::AllocateJSArrayWithAllocationSite(
ElementsKind elements_kind,
Handle<Object> allocation_site_info_payload) {
Context* native_context = isolate()->context()->native_context();
JSFunction* array_function = native_context->array_function();
Map* map = array_function->initial_map();
Object* maybe_map_array = native_context->js_array_maps();
if (!maybe_map_array->IsUndefined()) {
Object* maybe_transitioned_map =
FixedArray::cast(maybe_map_array)->get(elements_kind);
if (!maybe_transitioned_map->IsUndefined()) {
map = Map::cast(maybe_transitioned_map);
}
}
return AllocateJSObjectFromMapWithAllocationSite(map,
allocation_site_info_payload);
}
MaybeObject* Heap::AllocateEmptyFixedArray() {
int size = FixedArray::SizeFor(0);
Object* result;
{ MaybeObject* maybe_result =
AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Initialize the object.
reinterpret_cast<FixedArray*>(result)->set_map_no_write_barrier(
fixed_array_map());
reinterpret_cast<FixedArray*>(result)->set_length(0);
return result;
}
MaybeObject* Heap::AllocateRawFixedArray(int length) {
if (length < 0 || length > FixedArray::kMaxLength) {
return Failure::OutOfMemoryException(0xd);
}
ASSERT(length > 0);
// Use the general function if we're forced to always allocate.
if (always_allocate()) return AllocateFixedArray(length, TENURED);
// Allocate the raw data for a fixed array.
int size = FixedArray::SizeFor(length);
return size <= kMaxObjectSizeInNewSpace
? new_space_.AllocateRaw(size)
: lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
}
MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
int len = src->length();
Object* obj;
{ MaybeObject* maybe_obj = AllocateRawFixedArray(len);
if (!maybe_obj->ToObject(&obj)) return maybe_obj;
}
if (InNewSpace(obj)) {
HeapObject* dst = HeapObject::cast(obj);
dst->set_map_no_write_barrier(map);
CopyBlock(dst->address() + kPointerSize,
src->address() + kPointerSize,
FixedArray::SizeFor(len) - kPointerSize);
return obj;
}
HeapObject::cast(obj)->set_map_no_write_barrier(map);
FixedArray* result = FixedArray::cast(obj);
result->set_length(len);
// Copy the content
AssertNoAllocation no_gc;
WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
return result;
}
MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
Map* map) {
int len = src->length();
Object* obj;
{ MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
if (!maybe_obj->ToObject(&obj)) return maybe_obj;
}
HeapObject* dst = HeapObject::cast(obj);
dst->set_map_no_write_barrier(map);
CopyBlock(
dst->address() + FixedDoubleArray::kLengthOffset,
src->address() + FixedDoubleArray::kLengthOffset,
FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
return obj;
}
MaybeObject* Heap::AllocateFixedArray(int length) {
ASSERT(length >= 0);
if (length == 0) return empty_fixed_array();
Object* result;
{ MaybeObject* maybe_result = AllocateRawFixedArray(length);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Initialize header.
FixedArray* array = reinterpret_cast<FixedArray*>(result);
array->set_map_no_write_barrier(fixed_array_map());
array->set_length(length);
// Initialize body.
ASSERT(!InNewSpace(undefined_value()));
MemsetPointer(array->data_start(), undefined_value(), length);
return result;
}
MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
if (length < 0 || length > FixedArray::kMaxLength) {
return Failure::OutOfMemoryException(0xe);
}
AllocationSpace space =
(pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
int size = FixedArray::SizeFor(length);
if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
// Too big for new space.
space = LO_SPACE;
} else if (space == OLD_POINTER_SPACE &&
size > Page::kMaxNonCodeHeapObjectSize) {
// Too big for old pointer space.
space = LO_SPACE;
}
AllocationSpace retry_space =
(size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
return AllocateRaw(size, space, retry_space);
}
MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
Heap* heap,
int length,
PretenureFlag pretenure,
Object* filler) {
ASSERT(length >= 0);
ASSERT(heap->empty_fixed_array()->IsFixedArray());
if (length == 0) return heap->empty_fixed_array();
ASSERT(!heap->InNewSpace(filler));
Object* result;
{ MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
HeapObject::cast(result)->set_map_no_write_barrier(heap->fixed_array_map());
FixedArray* array = FixedArray::cast(result);
array->set_length(length);
MemsetPointer(array->data_start(), filler, length);
return array;
}
MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
return AllocateFixedArrayWithFiller(this,
length,
pretenure,
undefined_value());
}
MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
PretenureFlag pretenure) {
return AllocateFixedArrayWithFiller(this,
length,
pretenure,
the_hole_value());
}
MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
if (length == 0) return empty_fixed_array();
Object* obj;
{ MaybeObject* maybe_obj = AllocateRawFixedArray(length);
if (!maybe_obj->ToObject(&obj)) return maybe_obj;
}
reinterpret_cast<FixedArray*>(obj)->set_map_no_write_barrier(
fixed_array_map());
FixedArray::cast(obj)->set_length(length);
return obj;
}
MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
int size = FixedDoubleArray::SizeFor(0);
Object* result;
{ MaybeObject* maybe_result =
AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
// Initialize the object.
reinterpret_cast<FixedDoubleArray*>(result)->set_map_no_write_barrier(
fixed_double_array_map());
reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
return result;
}
MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
int length,
PretenureFlag pretenure) {
if (length == 0) return empty_fixed_array();
Object* elements_object;
MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
FixedDoubleArray* elements =
reinterpret_cast<FixedDoubleArray*>(elements_object);
elements->set_map_no_write_barrier(fixed_double_array_map());
elements->set_length(length);
return elements;
}
MaybeObject* Heap::AllocateFixedDoubleArrayWithHoles(
int length,
PretenureFlag pretenure) {
if (length == 0) return empty_fixed_array();
Object* elements_object;
MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
FixedDoubleArray* elements =
reinterpret_cast<FixedDoubleArray*>(elements_object);
for (int i = 0; i < length; ++i) {
elements->set_the_hole(i);
}
elements->set_map_no_write_barrier(fixed_double_array_map());
elements->set_length(length);
return elements;
}
MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
PretenureFlag pretenure) {
if (length < 0 || length > FixedDoubleArray::kMaxLength) {
return Failure::OutOfMemoryException(0xf);
}
AllocationSpace space =
(pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
int size = FixedDoubleArray::SizeFor(length);
#ifndef V8_HOST_ARCH_64_BIT
size += kPointerSize;
#endif
if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
// Too big for new space.
space = LO_SPACE;
} else if (space == OLD_DATA_SPACE &&
size > Page::kMaxNonCodeHeapObjectSize) {
// Too big for old data space.
space = LO_SPACE;
}
AllocationSpace retry_space =
(size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
HeapObject* object;
{ MaybeObject* maybe_object = AllocateRaw(size, space, retry_space);
if (!maybe_object->To<HeapObject>(&object)) return maybe_object;
}
return EnsureDoubleAligned(this, object, size);
}
MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
Object* result;
{ MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(
hash_table_map());
ASSERT(result->IsHashTable());
return result;
}
MaybeObject* Heap::AllocateSymbol() {
// Statically ensure that it is safe to allocate symbols in paged spaces.
STATIC_ASSERT(Symbol::kSize <= Page::kNonCodeObjectAreaSize);
Object* result;
MaybeObject* maybe =
AllocateRaw(Symbol::kSize, OLD_POINTER_SPACE, OLD_POINTER_SPACE);
if (!maybe->ToObject(&result)) return maybe;
HeapObject::cast(result)->set_map_no_write_barrier(symbol_map());
// Generate a random hash value.
int hash;
int attempts = 0;
do {
hash = V8::RandomPrivate(isolate()) & Name::kHashBitMask;
attempts++;
} while (hash == 0 && attempts < 30);
if (hash == 0) hash = 1; // never return 0
Symbol::cast(result)->set_hash_field(
Name::kIsNotArrayIndexMask | (hash << Name::kHashShift));
Symbol::cast(result)->set_name(undefined_value());
ASSERT(result->IsSymbol());
return result;
}
MaybeObject* Heap::AllocateNativeContext() {
Object* result;
{ MaybeObject* maybe_result =
AllocateFixedArray(Context::NATIVE_CONTEXT_SLOTS);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
Context* context = reinterpret_cast<Context*>(result);
context->set_map_no_write_barrier(native_context_map());
context->set_js_array_maps(undefined_value());
ASSERT(context->IsNativeContext());
ASSERT(result->IsContext());
return result;
}
MaybeObject* Heap::AllocateGlobalContext(JSFunction* function,
ScopeInfo* scope_info) {
Object* result;
{ MaybeObject* maybe_result =
AllocateFixedArray(scope_info->ContextLength(), TENURED);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
Context* context = reinterpret_cast<Context*>(result);
context->set_map_no_write_barrier(global_context_map());
context->set_closure(function);
context->set_previous(function->context());
context->set_extension(scope_info);
context->set_global_object(function->context()->global_object());
ASSERT(context->IsGlobalContext());
ASSERT(result->IsContext());
return context;
}
MaybeObject* Heap::AllocateModuleContext(ScopeInfo* scope_info) {
Object* result;
{ MaybeObject* maybe_result =
AllocateFixedArray(scope_info->ContextLength(), TENURED);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
Context* context = reinterpret_cast<Context*>(result);
context->set_map_no_write_barrier(module_context_map());
// Instance link will be set later.
context->set_extension(Smi::FromInt(0));
return context;
}
MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
Object* result;
{ MaybeObject* maybe_result = AllocateFixedArray(length);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
Context* context = reinterpret_cast<Context*>(result);
context->set_map_no_write_barrier(function_context_map());
context->set_closure(function);
context->set_previous(function->context());
context->set_extension(Smi::FromInt(0));
context->set_global_object(function->context()->global_object());
return context;
}
MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
Context* previous,
String* name,
Object* thrown_object) {
STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
Object* result;
{ MaybeObject* maybe_result =
AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
Context* context = reinterpret_cast<Context*>(result);
context->set_map_no_write_barrier(catch_context_map());
context->set_closure(function);
context->set_previous(previous);
context->set_extension(name);
context->set_global_object(previous->global_object());
context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
return context;
}
MaybeObject* Heap::AllocateWithContext(JSFunction* function,
Context* previous,
JSObject* extension) {
Object* result;
{ MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
Context* context = reinterpret_cast<Context*>(result);
context->set_map_no_write_barrier(with_context_map());
context->set_closure(function);
context->set_previous(previous);
context->set_extension(extension);
context->set_global_object(previous->global_object());
return context;
}
MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
Context* previous,
ScopeInfo* scope_info) {
Object* result;
{ MaybeObject* maybe_result =
AllocateFixedArrayWithHoles(scope_info->ContextLength());
if (!maybe_result->ToObject(&result)) return maybe_result;
}
Context* context = reinterpret_cast<Context*>(result);
context->set_map_no_write_barrier(block_context_map());
context->set_closure(function);
context->set_previous(previous);
context->set_extension(scope_info);
context->set_global_object(previous->global_object());
return context;
}
MaybeObject* Heap::AllocateScopeInfo(int length) {
FixedArray* scope_info;
MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
scope_info->set_map_no_write_barrier(scope_info_map());
return scope_info;
}
MaybeObject* Heap::AllocateExternal(void* value) {
Foreign* foreign;
{ MaybeObject* maybe_result = AllocateForeign(static_cast<Address>(value));
if (!maybe_result->To(&foreign)) return maybe_result;
}
JSObject* external;
{ MaybeObject* maybe_result = AllocateJSObjectFromMap(external_map());
if (!maybe_result->To(&external)) return maybe_result;
}
external->SetInternalField(0, foreign);
return external;
}
MaybeObject* Heap::AllocateStruct(InstanceType type) {
Map* map;
switch (type) {
#define MAKE_CASE(NAME, Name, name) \
case NAME##_TYPE: map = name##_map(); break;
STRUCT_LIST(MAKE_CASE)
#undef MAKE_CASE
default:
UNREACHABLE();
return Failure::InternalError();
}
int size = map->instance_size();
AllocationSpace space =
(size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
Object* result;
{ MaybeObject* maybe_result = Allocate(map, space);
if (!maybe_result->ToObject(&result)) return maybe_result;
}
Struct::cast(result)->InitializeBody(size);
return result;
}
bool Heap::IsHeapIterable() {
return (!old_pointer_space()->was_swept_conservatively() &&
!old_data_space()->was_swept_conservatively());
}
void Heap::EnsureHeapIsIterable() {
ASSERT(IsAllocationAllowed());
if (!IsHeapIterable()) {
CollectAllGarbage(kMakeHeapIterableMask, "Heap::EnsureHeapIsIterable");
}
ASSERT(IsHeapIterable());
}
void Heap::AdvanceIdleIncrementalMarking(intptr_t step_size) {
incremental_marking()->Step(step_size,
IncrementalMarking::NO_GC_VIA_STACK_GUARD);
if (incremental_marking()->IsComplete()) {
bool uncommit = false;
if (gc_count_at_last_idle_gc_ == gc_count_) {
// No GC since the last full GC, the mutator is probably not active.
isolate_->compilation_cache()->Clear();
uncommit = true;
}
CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
gc_count_at_last_idle_gc_ = gc_count_;
if (uncommit) {
new_space_.Shrink();
UncommitFromSpace();
}
}
}
bool Heap::IdleNotification(int hint) {
// Hints greater than this value indicate that
// the embedder is requesting a lot of GC work.
const int kMaxHint = 1000;
// Minimal hint that allows to do full GC.
const int kMinHintForFullGC = 100;
intptr_t size_factor = Min(Max(hint, 20), kMaxHint) / 4;
// The size factor is in range [5..250]. The numbers here are chosen from
// experiments. If you changes them, make sure to test with
// chrome/performance_ui_tests --gtest_filter="GeneralMixMemoryTest.*
intptr_t step_size =
size_factor * IncrementalMarking::kAllocatedThreshold;
if (contexts_disposed_ > 0) {
if (hint >= kMaxHint) {
// The embedder is requesting a lot of GC work after context disposal,
// we age inline caches so that they don't keep objects from
// the old context alive.
AgeInlineCaches();
}
int mark_sweep_time = Min(TimeMarkSweepWouldTakeInMs(), 1000);
if (hint >= mark_sweep_time && !FLAG_expose_gc &&
incremental_marking()->IsStopped()) {
HistogramTimerScope scope(isolate_->counters()->gc_context());
CollectAllGarbage(kReduceMemoryFootprintMask,
"idle notification: contexts disposed");
} else {
AdvanceIdleIncrementalMarking(step_size);
contexts_disposed_ = 0;
}
// After context disposal there is likely a lot of garbage remaining, reset
// the idle notification counters in order to trigger more incremental GCs
// on subsequent idle notifications.
StartIdleRound();
return false;
}
if (!FLAG_incremental_marking || FLAG_expose_gc || Serializer::enabled()) {
return IdleGlobalGC();
}
// By doing small chunks of GC work in each IdleNotification,
// perform a round of incremental GCs and after that wait until
// the mutator creates enough garbage to justify a new round.
// An incremental GC progresses as follows:
// 1. many incremental marking steps,
// 2. one old space mark-sweep-compact,
// 3. many lazy sweep steps.
// Use mark-sweep-compact events to count incremental GCs in a round.
if (incremental_marking()->IsStopped()) {
if (!mark_compact_collector()->AreSweeperThreadsActivated() &&
!IsSweepingComplete() &&
!AdvanceSweepers(static_cast<int>(step_size))) {
return false;
}
}
if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
if (EnoughGarbageSinceLastIdleRound()) {
StartIdleRound();
} else {
return true;
}
}
int new_mark_sweeps = ms_count_ - ms_count_at_last_idle_notification_;
mark_sweeps_since_idle_round_started_ += new_mark_sweeps;
ms_count_at_last_idle_notification_ = ms_count_;
int remaining_mark_sweeps = kMaxMarkSweepsInIdleRound -
mark_sweeps_since_idle_round_started_;
if (remaining_mark_sweeps <= 0) {
FinishIdleRound();
return true;
}
if (incremental_marking()->IsStopped()) {
// If there are no more than two GCs left in this idle round and we are
// allowed to do a full GC, then make those GCs full in order to compact
// the code space.
// TODO(ulan): Once we enable code compaction for incremental marking,
// we can get rid of this special case and always start incremental marking.
if (remaining_mark_sweeps <= 2 && hint >= kMinHintForFullGC) {
CollectAllGarbage(kReduceMemoryFootprintMask,
"idle notification: finalize idle round");
} else {
incremental_marking()->Start();
}
}
if (!incremental_marking()->IsStopped()) {
AdvanceIdleIncrementalMarking(step_size);
}
return false;
}
bool Heap::IdleGlobalGC() {
static const int kIdlesBeforeScavenge = 4;
static const int kIdlesBeforeMarkSweep = 7;
static const int kIdlesBeforeMarkCompact = 8;
static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
static const unsigned int kGCsBetweenCleanup = 4;
if (!last_idle_notification_gc_count_init_) {
last_idle_notification_gc_count_ = gc_count_;
last_idle_notification_gc_count_init_ = true;
}
bool uncommit = true;
bool finished = false;
// Reset the number of idle notifications received when a number of
// GCs have taken place. This allows another round of cleanup based
// on idle notifications if enough work has been carried out to
// provoke a number of garbage collections.
if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
number_idle_notifications_ =
Min(number_idle_notifications_ + 1, kMaxIdleCount);
} else {
number_idle_notifications_ = 0;
last_idle_notification_gc_count_ = gc_count_;
}
if (number_idle_notifications_ == kIdlesBeforeScavenge) {
CollectGarbage(NEW_SPACE, "idle notification");
new_space_.Shrink();
last_idle_notification_gc_count_ = gc_count_;
} else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
// Before doing the mark-sweep collections we clear the
// compilation cache to avoid hanging on to source code and
// generated code for cached functions.
isolate_->compilation_cache()->Clear();
CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
new_space_.Shrink();
last_idle_notification_gc_count_ = gc_count_;
} else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
new_space_.Shrink();
last_idle_notification_gc_count_ = gc_count_;
number_idle_notifications_ = 0;
finished = true;
} else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
// If we have received more than kIdlesBeforeMarkCompact idle
// notifications we do not perform any cleanup because we don't
// expect to gain much by doing so.
finished = true;
}
if (uncommit) UncommitFromSpace();
return finished;
}
#ifdef DEBUG
void Heap::Print() {
if (!HasBeenSetUp()) return;
isolate()->PrintStack();
AllSpaces spaces(this);
for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
space->Print();
}
}
void Heap::ReportCodeStatistics(const char* title) {
PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
PagedSpace::ResetCodeStatistics();
// We do not look for code in new space, map space, or old space. If code
// somehow ends up in those spaces, we would miss it here.
code_space_->CollectCodeStatistics();
lo_space_->CollectCodeStatistics();
PagedSpace::ReportCodeStatistics();
}
// This function expects that NewSpace's allocated objects histogram is
// populated (via a call to CollectStatistics or else as a side effect of a
// just-completed scavenge collection).
void Heap::ReportHeapStatistics(const char* title) {
USE(title);
PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
title, gc_count_);
PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
old_gen_promotion_limit_);
PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
old_gen_allocation_limit_);
PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
PrintF("\n");
PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles(isolate_));
isolate_->global_handles()->PrintStats();
PrintF("\n");
PrintF("Heap statistics : ");
isolate_->memory_allocator()->ReportStatistics();
PrintF("To space : ");
new_space_.ReportStatistics();
PrintF("Old pointer space : ");
old_pointer_space_->ReportStatistics();
PrintF("Old data space : ");
old_data_space_->ReportStatistics();
PrintF("Code space : ");
code_space_->ReportStatistics();
PrintF("Map space : ");
map_space_->ReportStatistics();
PrintF("Cell space : ");
cell_space_->ReportStatistics();
PrintF("Large object space : ");
lo_space_->ReportStatistics();
PrintF(">>>>>> ========================================= >>>>>>\n");
}
#endif // DEBUG
bool Heap::Contains(HeapObject* value) {
return Contains(value->address());
}
bool Heap::Contains(Address addr) {
if (OS::IsOutsideAllocatedSpace(addr)) return false;
return HasBeenSetUp() &&
(new_space_.ToSpaceContains(addr) ||
old_pointer_space_->Contains(addr) ||
old_data_space_->Contains(addr) ||
code_space_->Contains(addr) ||
map_space_->Contains(addr) ||
cell_space_->Contains(addr) ||
lo_space_->SlowContains(addr));
}
bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
return InSpace(value->address(), space);
}
bool Heap::InSpace(Address addr, AllocationSpace space) {
if (OS::IsOutsideAllocatedSpace(addr)) return false;
if (!HasBeenSetUp()) return false;
switch (space) {
case NEW_SPACE:
return new_space_.ToSpaceContains(addr);
case OLD_POINTER_SPACE:
return old_pointer_space_->Contains(addr);
case OLD_DATA_SPACE:
return old_data_space_->Contains(addr);
case CODE_SPACE:
return code_space_->Contains(addr);
case MAP_SPACE:
return map_space_->Contains(addr);
case CELL_SPACE:
return cell_space_->Contains(addr);
case LO_SPACE:
return lo_space_->SlowContains(addr);
}
return false;
}
#ifdef VERIFY_HEAP
void Heap::Verify() {
CHECK(HasBeenSetUp());
store_buffer()->Verify();
VerifyPointersVisitor visitor;
IterateRoots(&visitor, VISIT_ONLY_STRONG);
new_space_.Verify();
old_pointer_space_->Verify(&visitor);
map_space_->Verify(&visitor);
VerifyPointersVisitor no_dirty_regions_visitor;
old_data_space_->Verify(&no_dirty_regions_visitor);
code_space_->Verify(&no_dirty_regions_visitor);
cell_space_->Verify(&no_dirty_regions_visitor);
lo_space_->Verify();
}
#endif
MaybeObject* Heap::InternalizeUtf8String(Vector<const char> string) {
Object* result = NULL;
Object* new_table;
{ MaybeObject* maybe_new_table =
string_table()->LookupUtf8String(string, &result);
if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
}
// Can't use set_string_table because StringTable::cast knows that
// StringTable is a singleton and checks for identity.
roots_[kStringTableRootIndex] = new_table;
ASSERT(result != NULL);
return result;
}
MaybeObject* Heap::InternalizeOneByteString(Vector<const uint8_t> string) {
Object* result = NULL;
Object* new_table;
{ MaybeObject* maybe_new_table =
string_table()->LookupOneByteString(string, &result);
if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
}
// Can't use set_string_table because StringTable::cast knows that
// StringTable is a singleton and checks for identity.
roots_[kStringTableRootIndex] = new_table;
ASSERT(result != NULL);
return result;
}
MaybeObject* Heap::InternalizeOneByteString(Handle<SeqOneByteString> string,
int from,
int length) {
Object* result = NULL;
Object* new_table;
{ MaybeObject* maybe_new_table =
string_table()->LookupSubStringOneByteString(string,
from,
length,
&result);
if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
}
// Can't use set_string_table because StringTable::cast knows that
// StringTable is a singleton and checks for identity.
roots_[kStringTableRootIndex] = new_table;
ASSERT(result != NULL);
return result;
}
MaybeObject* Heap::InternalizeTwoByteString(Vector<const uc16> string) {
Object* result = NULL;
Object* new_table;
{ MaybeObject* maybe_new_table =
string_table()->LookupTwoByteString(string, &result);
if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
}
// Can't use set_string_table because StringTable::cast knows that
// StringTable is a singleton and checks for identity.
roots_[kStringTableRootIndex] = new_table;
ASSERT(result != NULL);
return result;
}
MaybeObject* Heap::InternalizeString(String* string) {
if (string->IsInternalizedString()) return string;
Object* result = NULL;
Object* new_table;
{ MaybeObject* maybe_new_table =
string_table()->LookupString(string, &result);
if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
}
// Can't use set_string_table because StringTable::cast knows that
// StringTable is a singleton and checks for identity.
roots_[kStringTableRootIndex] = new_table;
ASSERT(result != NULL);
return result;
}
bool Heap::InternalizeStringIfExists(String* string, String** result) {
if (string->IsInternalizedString()) {
*result = string;
return true;
}
return string_table()->LookupStringIfExists(string, result);
}
void Heap::ZapFromSpace() {
NewSpacePageIterator it(new_space_.FromSpaceStart(),
new_space_.FromSpaceEnd());
while (it.has_next()) {
NewSpacePage* page = it.next();
for (Address cursor = page->area_start(), limit = page->area_end();
cursor < limit;
cursor += kPointerSize) {
Memory::Address_at(cursor) = kFromSpaceZapValue;
}
}
}
void Heap::IterateAndMarkPointersToFromSpace(Address start,
Address end,
ObjectSlotCallback callback) {
Address slot_address = start;
// We are not collecting slots on new space objects during mutation
// thus we have to scan for pointers to evacuation candidates when we
// promote objects. But we should not record any slots in non-black
// objects. Grey object's slots would be rescanned.
// White object might not survive until the end of collection
// it would be a violation of the invariant to record it's slots.
bool record_slots = false;
if (incremental_marking()->IsCompacting()) {
MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
record_slots = Marking::IsBlack(mark_bit);
}
while (slot_address < end) {
Object** slot = reinterpret_cast<Object**>(slot_address);
Object* object = *slot;
// If the store buffer becomes overfull we mark pages as being exempt from
// the store buffer. These pages are scanned to find pointers that point
// to the new space. In that case we may hit newly promoted objects and
// fix the pointers before the promotion queue gets to them. Thus the 'if'.
if (object->IsHeapObject()) {
if (Heap::InFromSpace(object)) {
callback(reinterpret_cast<HeapObject**>(slot),
HeapObject::cast(object));
Object* new_object = *slot;
if (InNewSpace(new_object)) {
SLOW_ASSERT(Heap::InToSpace(new_object));
SLOW_ASSERT(new_object->IsHeapObject());
store_buffer_.EnterDirectlyIntoStoreBuffer(
reinterpret_cast<Address>(slot));
}
SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
} else if (record_slots &&
MarkCompactCollector::IsOnEvacuationCandidate(object)) {
mark_compact_collector()->RecordSlot(slot, slot, object);
}
}
slot_address += kPointerSize;
}
}
#ifdef DEBUG
typedef bool (*CheckStoreBufferFilter)(Object** addr);
bool IsAMapPointerAddress(Object** addr) {
uintptr_t a = reinterpret_cast<uintptr_t>(addr);
int mod = a % Map::kSize;
return mod >= Map::kPointerFieldsBeginOffset &&
mod < Map::kPointerFieldsEndOffset;
}
bool EverythingsAPointer(Object** addr) {
return true;
}
static void CheckStoreBuffer(Heap* heap,
Object** current,
Object** limit,
Object**** store_buffer_position,
Object*** store_buffer_top,
CheckStoreBufferFilter filter,
Address special_garbage_start,
Address special_garbage_end) {
Map* free_space_map = heap->free_space_map();
for ( ; current < limit; current++) {
Object* o = *current;
Address current_address = reinterpret_cast<Address>(current);
// Skip free space.
if (o == free_space_map) {
Address current_address = reinterpret_cast<Address>(current);
FreeSpace* free_space =
FreeSpace::cast(HeapObject::FromAddress(current_address));
int skip = free_space->Size();
ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
ASSERT(skip > 0);
current_address += skip - kPointerSize;
current = reinterpret_cast<Object**>(current_address);
continue;
}
// Skip the current linear allocation space between top and limit which is
// unmarked with the free space map, but can contain junk.
if (current_address == special_garbage_start &&
special_garbage_end != special_garbage_start) {
current_address = special_garbage_end - kPointerSize;
current = reinterpret_cast<Object**>(current_address);
continue;
}
if (!(*filter)(current)) continue;
ASSERT(current_address < special_garbage_start ||
current_address >= special_garbage_end);
ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
// We have to check that the pointer does not point into new space
// without trying to cast it to a heap object since the hash field of
// a string can contain values like 1 and 3 which are tagged null
// pointers.
if (!heap->InNewSpace(o)) continue;
while (**store_buffer_position < current &&
*store_buffer_position < store_buffer_top) {
(*store_buffer_position)++;
}
if (**store_buffer_position != current ||
*store_buffer_position == store_buffer_top) {
Object** obj_start = current;
while (!(*obj_start)->IsMap()) obj_start--;
UNREACHABLE();
}
}
}
// Check that the store buffer contains all intergenerational pointers by
// scanning a page and ensuring that all pointers to young space are in the
// store buffer.
void Heap::OldPointerSpaceCheckStoreBuffer() {
OldSpace* space = old_pointer_space();
PageIterator pages(space);
store_buffer()->SortUniq();
while (pages.has_next()) {
Page* page = pages.next();
Object** current = reinterpret_cast<Object**>(page->area_start());
Address end = page->area_end();
Object*** store_buffer_position = store_buffer()->Start();
Object*** store_buffer_top = store_buffer()->Top();
Object** limit = reinterpret_cast<Object**>(end);
CheckStoreBuffer(this,
current,
limit,
&store_buffer_position,
store_buffer_top,
&EverythingsAPointer,
space->top(),
space->limit());
}
}
void Heap::MapSpaceCheckStoreBuffer() {
MapSpace* space = map_space();
PageIterator pages(space);
store_buffer()->SortUniq();
while (pages.has_next()) {
Page* page = pages.next();
Object** current = reinterpret_cast<Object**>(page->area_start());
Address end = page->area_end();
Object*** store_buffer_position = store_buffer()->Start();
Object*** store_buffer_top = store_buffer()->Top();
Object** limit = reinterpret_cast<Object**>(end);
CheckStoreBuffer(this,
current,
limit,
&store_buffer_position,
store_buffer_top,
&IsAMapPointerAddress,
space->top(),
space->limit());
}
}
void Heap::LargeObjectSpaceCheckStoreBuffer() {
LargeObjectIterator it(lo_space());
for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
// We only have code, sequential strings, or fixed arrays in large
// object space, and only fixed arrays can possibly contain pointers to
// the young generation.
if (object->IsFixedArray()) {
Object*** store_buffer_position = store_buffer()->Start();
Object*** store_buffer_top = store_buffer()->Top();
Object** current = reinterpret_cast<Object**>(object->address());
Object** limit =
reinterpret_cast<Object**>(object->address() + object->Size());
CheckStoreBuffer(this,
current,
limit,
&store_buffer_position,
store_buffer_top,
&EverythingsAPointer,
NULL,
NULL);
}
}
}
#endif
void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
IterateStrongRoots(v, mode);
IterateWeakRoots(v, mode);
}
void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
v->VisitPointer(reinterpret_cast<Object**>(&roots_[kStringTableRootIndex]));
v->Synchronize(VisitorSynchronization::kStringTable);
if (mode != VISIT_ALL_IN_SCAVENGE &&
mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
// Scavenge collections have special processing for this.
external_string_table_.Iterate(v);
error_object_list_.Iterate(v);
}
v->Synchronize(VisitorSynchronization::kExternalStringsTable);
}
void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
v->Synchronize(VisitorSynchronization::kStrongRootList);
v->VisitPointer(BitCast<Object**>(&hidden_string_));
v->Synchronize(VisitorSynchronization::kInternalizedString);
isolate_->bootstrapper()->Iterate(v);
v->Synchronize(VisitorSynchronization::kBootstrapper);
isolate_->Iterate(v);
v->Synchronize(VisitorSynchronization::kTop);
Relocatable::Iterate(v);
v->Synchronize(VisitorSynchronization::kRelocatable);
#ifdef ENABLE_DEBUGGER_SUPPORT
isolate_->debug()->Iterate(v);
if (isolate_->deoptimizer_data() != NULL) {
isolate_->deoptimizer_data()->Iterate(v);
}
#endif
v->Synchronize(VisitorSynchronization::kDebug);
isolate_->compilation_cache()->Iterate(v);
v->Synchronize(VisitorSynchronization::kCompilationCache);
// Iterate over local handles in handle scopes.
isolate_->handle_scope_implementer()->Iterate(v);
isolate_->IterateDeferredHandles(v);
v->Synchronize(VisitorSynchronization::kHandleScope);
// Iterate over the builtin code objects and code stubs in the
// heap. Note that it is not necessary to iterate over code objects
// on scavenge collections.
if (mode != VISIT_ALL_IN_SCAVENGE) {
isolate_->builtins()->IterateBuiltins(v);
}
v->Synchronize(VisitorSynchronization::kBuiltins);
// Iterate over global handles.
switch (mode) {
case VISIT_ONLY_STRONG:
isolate_->global_handles()->IterateStrongRoots(v);
break;
case VISIT_ALL_IN_SCAVENGE:
isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
break;
case VISIT_ALL_IN_SWEEP_NEWSPACE:
case VISIT_ALL:
isolate_->global_handles()->IterateAllRoots(v);
break;
}
v->Synchronize(VisitorSynchronization::kGlobalHandles);
// Iterate over pointers being held by inactive threads.
isolate_->thread_manager()->Iterate(v);
v->Synchronize(VisitorSynchronization::kThreadManager);
// Iterate over the pointers the Serialization/Deserialization code is
// holding.
// During garbage collection this keeps the partial snapshot cache alive.
// During deserialization of the startup snapshot this creates the partial
// snapshot cache and deserializes the objects it refers to. During
// serialization this does nothing, since the partial snapshot cache is
// empty. However the next thing we do is create the partial snapshot,
// filling up the partial snapshot cache with objects it needs as we go.
SerializerDeserializer::Iterate(v);
// We don't do a v->Synchronize call here, because in debug mode that will
// output a flag to the snapshot. However at this point the serializer and
// deserializer are deliberately a little unsynchronized (see above) so the
// checking of the sync flag in the snapshot would fail.
}
// TODO(1236194): Since the heap size is configurable on the command line
// and through the API, we should gracefully handle the case that the heap
// size is not big enough to fit all the initial objects.
bool Heap::ConfigureHeap(int max_semispace_size,
intptr_t max_old_gen_size,
intptr_t max_executable_size) {
if (HasBeenSetUp()) return false;
if (FLAG_stress_compaction) {
// This will cause more frequent GCs when stressing.
max_semispace_size_ = Page::kPageSize;
}
if (max_semispace_size > 0) {
if (max_semispace_size < Page::kPageSize) {
max_semispace_size = Page::kPageSize;
if (FLAG_trace_gc) {
PrintPID("Max semispace size cannot be less than %dkbytes\n",
Page::kPageSize >> 10);
}
}
max_semispace_size_ = max_semispace_size;
}
if (Snapshot::IsEnabled()) {
// If we are using a snapshot we always reserve the default amount
// of memory for each semispace because code in the snapshot has
// write-barrier code that relies on the size and alignment of new
// space. We therefore cannot use a larger max semispace size
// than the default reserved semispace size.
if (max_semispace_size_ > reserved_semispace_size_) {
max_semispace_size_ = reserved_semispace_size_;
if (FLAG_trace_gc) {
PrintPID("Max semispace size cannot be more than %dkbytes\n",
reserved_semispace_size_ >> 10);
}
}
} else {
// If we are not using snapshots we reserve space for the actual
// max semispace size.
reserved_semispace_size_ = max_semispace_size_;
}
if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
if (max_executable_size > 0) {
max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
}
// The max executable size must be less than or equal to the max old
// generation size.
if (max_executable_size_ > max_old_generation_size_) {
max_executable_size_ = max_old_generation_size_;
}
// The new space size must be a power of two to support single-bit testing
// for containment.
max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
external_allocation_limit_ = 16 * max_semispace_size_;
// The old generation is paged and needs at least one page for each space.
int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
Page::kPageSize),
RoundUp(max_old_generation_size_,
Page::kPageSize));
configured_ = true;
return true;
}
bool Heap::ConfigureHeapDefault() {
return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
static_cast<intptr_t>(FLAG_max_executable_size) * MB);
}
void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
*stats->start_marker = HeapStats::kStartMarker;
*stats->end_marker = HeapStats::kEndMarker;
*stats->new_space_size = new_space_.SizeAsInt();
*stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
*stats->old_pointer_space_size = old_pointer_space_->SizeOfObjects();
*stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
*stats->old_data_space_size = old_data_space_->SizeOfObjects();
*stats->old_data_space_capacity = old_data_space_->Capacity();
*stats->code_space_size = code_space_->SizeOfObjects();
*stats->code_space_capacity = code_space_->Capacity();
*stats->map_space_size = map_space_->SizeOfObjects();
*stats->map_space_capacity = map_space_->Capacity();
*stats->cell_space_size = cell_space_->SizeOfObjects();
*stats->cell_space_capacity = cell_space_->Capacity();
*stats->lo_space_size = lo_space_->Size();
isolate_->global_handles()->RecordStats(stats);
*stats->memory_allocator_size = isolate()->memory_allocator()->Size();
*stats->memory_allocator_capacity =
isolate()->memory_allocator()->Size() +
isolate()->memory_allocator()->Available();
*stats->os_error = OS::GetLastError();
isolate()->memory_allocator()->Available();
if (take_snapshot) {
HeapIterator iterator(this);
for (HeapObject* obj = iterator.next();
obj != NULL;
obj = iterator.next()) {
InstanceType type = obj->map()->instance_type();
ASSERT(0 <= type && type <= LAST_TYPE);
stats->objects_per_type[type]++;
stats->size_per_type[type] += obj->Size();
}
}
}
intptr_t Heap::PromotedSpaceSizeOfObjects() {
return old_pointer_space_->SizeOfObjects()
+ old_data_space_->SizeOfObjects()
+ code_space_->SizeOfObjects()
+ map_space_->SizeOfObjects()
+ cell_space_->SizeOfObjects()
+ lo_space_->SizeOfObjects();
}
intptr_t Heap::PromotedExternalMemorySize() {
if (amount_of_external_allocated_memory_
<= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
return amount_of_external_allocated_memory_
- amount_of_external_allocated_memory_at_last_global_gc_;
}
V8_DECLARE_ONCE(initialize_gc_once);
static void InitializeGCOnce() {
InitializeScavengingVisitorsTables();
NewSpaceScavenger::Initialize();
MarkCompactCollector::Initialize();
}
bool Heap::SetUp() {
#ifdef DEBUG
allocation_timeout_ = FLAG_gc_interval;
#endif
// Initialize heap spaces and initial maps and objects. Whenever something
// goes wrong, just return false. The caller should check the results and
// call Heap::TearDown() to release allocated memory.
//
// If the heap is not yet configured (e.g. through the API), configure it.
// Configuration is based on the flags new-space-size (really the semispace
// size) and old-space-size if set or the initial values of semispace_size_
// and old_generation_size_ otherwise.
if (!configured_) {
if (!ConfigureHeapDefault()) return false;
}
CallOnce(&initialize_gc_once, &InitializeGCOnce);
MarkMapPointersAsEncoded(false);
// Set up memory allocator.
if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
return false;
// Set up new space.
if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) {
return false;
}
// Initialize old pointer space.
old_pointer_space_ =
new OldSpace(this,
max_old_generation_size_,
OLD_POINTER_SPACE,
NOT_EXECUTABLE);
if (old_pointer_space_ == NULL) return false;
if (!old_pointer_space_->SetUp()) return false;
// Initialize old data space.
old_data_space_ =
new OldSpace(this,
max_old_generation_size_,
OLD_DATA_SPACE,
NOT_EXECUTABLE);
if (old_data_space_ == NULL) return false;
if (!old_data_space_->SetUp()) return false;
// Initialize the code space, set its maximum capacity to the old
// generation size. It needs executable memory.
// On 64-bit platform(s), we put all code objects in a 2 GB range of
// virtual address space, so that they can call each other with near calls.
if (code_range_size_ > 0) {
if (!isolate_->code_range()->SetUp(code_range_size_)) {
return false;
}
}
code_space_ =
new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
if (code_space_ == NULL) return false;
if (!code_space_->SetUp()) return false;
// Initialize map space.
map_space_ = new MapSpace(this, max_old_generation_size_, MAP_SPACE);
if (map_space_ == NULL) return false;
if (!map_space_->SetUp()) return false;
// Initialize global property cell space.
cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
if (cell_space_ == NULL) return false;
if (!cell_space_->SetUp()) return false;
// The large object code space may contain code or data. We set the memory
// to be non-executable here for safety, but this means we need to enable it
// explicitly when allocating large code objects.
lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
if (lo_space_ == NULL) return false;
if (!lo_space_->SetUp()) return false;
// Set up the seed that is used to randomize the string hash function.
ASSERT(hash_seed() == 0);
if (FLAG_randomize_hashes) {
if (FLAG_hash_seed == 0) {
set_hash_seed(
Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
} else {
set_hash_seed(Smi::FromInt(FLAG_hash_seed));
}
}
LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
LOG(isolate_, IntPtrTEvent("heap-available", Available()));
store_buffer()->SetUp();
if (FLAG_parallel_recompilation) relocation_mutex_ = OS::CreateMutex();
#ifdef DEBUG
relocation_mutex_locked_ = false;
#endif // DEBUG
return true;
}
bool Heap::CreateHeapObjects() {
// Create initial maps.
if (!CreateInitialMaps()) return false;
if (!CreateApiObjects()) return false;
// Create initial objects
if (!CreateInitialObjects()) return false;
native_contexts_list_ = undefined_value();
return true;
}
void Heap::SetStackLimits() {
ASSERT(isolate_ != NULL);
ASSERT(isolate_ == isolate());
// On 64 bit machines, pointers are generally out of range of Smis. We write
// something that looks like an out of range Smi to the GC.
// Set up the special root array entries containing the stack limits.
// These are actually addresses, but the tag makes the GC ignore it.
roots_[kStackLimitRootIndex] =
reinterpret_cast<Object*>(
(isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
roots_[kRealStackLimitRootIndex] =
reinterpret_cast<Object*>(
(isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
}
void Heap::TearDown() {
#ifdef VERIFY_HEAP
if (FLAG_verify_heap) {
Verify();
}
#endif
if (FLAG_print_cumulative_gc_stat) {
PrintF("\n");
PrintF("gc_count=%d ", gc_count_);
PrintF("mark_sweep_count=%d ", ms_count_);
PrintF("max_gc_pause=%.1f ", get_max_gc_pause());
PrintF("total_gc_time=%.1f ", total_gc_time_ms_);
PrintF("min_in_mutator=%.1f ", get_min_in_mutator());
PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
get_max_alive_after_gc());
PrintF("total_marking_time=%.1f ", marking_time());
PrintF("total_sweeping_time=%.1f ", sweeping_time());
PrintF("\n\n");
}
isolate_->global_handles()->TearDown();
external_string_table_.TearDown();
error_object_list_.TearDown();
new_space_.TearDown();
if (old_pointer_space_ != NULL) {
old_pointer_space_->TearDown();
delete old_pointer_space_;
old_pointer_space_ = NULL;
}
if (old_data_space_ != NULL) {
old_data_space_->TearDown();
delete old_data_space_;
old_data_space_ = NULL;
}
if (code_space_ != NULL) {
code_space_->TearDown();
delete code_space_;
code_space_ = NULL;
}
if (map_space_ != NULL) {
map_space_->TearDown();
delete map_space_;
map_space_ = NULL;
}
if (cell_space_ != NULL) {
cell_space_->TearDown();
delete cell_space_;
cell_space_ = NULL;
}
if (lo_space_ != NULL) {
lo_space_->TearDown();
delete lo_space_;
lo_space_ = NULL;
}
store_buffer()->TearDown();
incremental_marking()->TearDown();
isolate_->memory_allocator()->TearDown();
delete relocation_mutex_;
}
void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
ASSERT(callback != NULL);
GCPrologueCallbackPair pair(callback, gc_type);
ASSERT(!gc_prologue_callbacks_.Contains(pair));
return gc_prologue_callbacks_.Add(pair);
}
void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
ASSERT(callback != NULL);
for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
if (gc_prologue_callbacks_[i].callback == callback) {
gc_prologue_callbacks_.Remove(i);
return;
}
}
UNREACHABLE();
}
void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
ASSERT(callback != NULL);
GCEpilogueCallbackPair pair(callback, gc_type);
ASSERT(!gc_epilogue_callbacks_.Contains(pair));
return gc_epilogue_callbacks_.Add(pair);
}
void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
ASSERT(callback != NULL);
for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
if (gc_epilogue_callbacks_[i].callback == callback) {
gc_epilogue_callbacks_.Remove(i);
return;
}
}
UNREACHABLE();
}
#ifdef DEBUG
class PrintHandleVisitor: public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
for (Object** p = start; p < end; p++)
PrintF(" handle %p to %p\n",
reinterpret_cast<void*>(p),
reinterpret_cast<void*>(*p));
}
};
void Heap::PrintHandles() {
PrintF("Handles:\n");
PrintHandleVisitor v;
isolate_->handle_scope_implementer()->Iterate(&v);
}
#endif
Space* AllSpaces::next() {
switch (counter_++) {
case NEW_SPACE:
return heap_->new_space();
case OLD_POINTER_SPACE:
return heap_->old_pointer_space();
case OLD_DATA_SPACE:
return heap_->old_data_space();
case CODE_SPACE:
return heap_->code_space();
case MAP_SPACE:
return heap_->map_space();
case CELL_SPACE:
return heap_->cell_space();
case LO_SPACE:
return heap_->lo_space();
default:
return NULL;
}
}
PagedSpace* PagedSpaces::next() {
switch (counter_++) {
case OLD_POINTER_SPACE:
return heap_->old_pointer_space();
case OLD_DATA_SPACE:
return heap_->old_data_space();
case CODE_SPACE:
return heap_->code_space();
case MAP_SPACE:
return heap_->map_space();
case CELL_SPACE:
return heap_->cell_space();
default:
return NULL;
}
}
OldSpace* OldSpaces::next() {
switch (counter_++) {
case OLD_POINTER_SPACE:
return heap_->old_pointer_space();
case OLD_DATA_SPACE:
return heap_->old_data_space();
case CODE_SPACE:
return heap_->code_space();
default:
return NULL;
}
}
SpaceIterator::SpaceIterator(Heap* heap)
: heap_(heap),
current_space_(FIRST_SPACE),
iterator_(NULL),
size_func_(NULL) {
}
SpaceIterator::SpaceIterator(Heap* heap, HeapObjectCallback size_func)
: heap_(heap),
current_space_(FIRST_SPACE),
iterator_(NULL),
size_func_(size_func) {
}
SpaceIterator::~SpaceIterator() {
// Delete active iterator if any.
delete iterator_;
}
bool SpaceIterator::has_next() {
// Iterate until no more spaces.
return current_space_ != LAST_SPACE;
}
ObjectIterator* SpaceIterator::next() {
if (iterator_ != NULL) {
delete iterator_;
iterator_ = NULL;
// Move to the next space
current_space_++;
if (current_space_ > LAST_SPACE) {
return NULL;
}
}
// Return iterator for the new current space.
return CreateIterator();
}
// Create an iterator for the space to iterate.
ObjectIterator* SpaceIterator::CreateIterator() {
ASSERT(iterator_ == NULL);
switch (current_space_) {
case NEW_SPACE:
iterator_ = new SemiSpaceIterator(heap_->new_space(), size_func_);
break;
case OLD_POINTER_SPACE:
iterator_ =
new HeapObjectIterator(heap_->old_pointer_space(), size_func_);
break;
case OLD_DATA_SPACE:
iterator_ = new HeapObjectIterator(heap_->old_data_space(), size_func_);
break;
case CODE_SPACE:
iterator_ = new HeapObjectIterator(heap_->code_space(), size_func_);
break;
case MAP_SPACE:
iterator_ = new HeapObjectIterator(heap_->map_space(), size_func_);
break;
case CELL_SPACE:
iterator_ = new HeapObjectIterator(heap_->cell_space(), size_func_);
break;
case LO_SPACE:
iterator_ = new LargeObjectIterator(heap_->lo_space(), size_func_);
break;
}
// Return the newly allocated iterator;
ASSERT(iterator_ != NULL);
return iterator_;
}
class HeapObjectsFilter {
public:
virtual ~HeapObjectsFilter() {}
virtual bool SkipObject(HeapObject* object) = 0;
};
class UnreachableObjectsFilter : public HeapObjectsFilter {
public:
UnreachableObjectsFilter() {
MarkReachableObjects();
}
~UnreachableObjectsFilter() {
Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
}
bool SkipObject(HeapObject* object) {
MarkBit mark_bit = Marking::MarkBitFrom(object);
return !mark_bit.Get();
}
private:
class MarkingVisitor : public ObjectVisitor {
public:
MarkingVisitor() : marking_stack_(10) {}
void VisitPointers(Object** start, Object** end) {
for (Object** p = start; p < end; p++) {
if (!(*p)->IsHeapObject()) continue;
HeapObject* obj = HeapObject::cast(*p);
MarkBit mark_bit = Marking::MarkBitFrom(obj);
if (!mark_bit.Get()) {
mark_bit.Set();
marking_stack_.Add(obj);
}
}
}
void TransitiveClosure() {
while (!marking_stack_.is_empty()) {
HeapObject* obj = marking_stack_.RemoveLast();
obj->Iterate(this);
}
}
private:
List<HeapObject*> marking_stack_;
};
void MarkReachableObjects() {
Heap* heap = Isolate::Current()->heap();
MarkingVisitor visitor;
heap->IterateRoots(&visitor, VISIT_ALL);
visitor.TransitiveClosure();
}
AssertNoAllocation no_alloc;
};
HeapIterator::HeapIterator(Heap* heap)
: heap_(heap),
filtering_(HeapIterator::kNoFiltering),
filter_(NULL) {
Init();
}
HeapIterator::HeapIterator(Heap* heap,
HeapIterator::HeapObjectsFiltering filtering)
: heap_(heap),
filtering_(filtering),
filter_(NULL) {
Init();
}
HeapIterator::~HeapIterator() {
Shutdown();
}
void HeapIterator::Init() {
// Start the iteration.
space_iterator_ = new SpaceIterator(heap_);
switch (filtering_) {
case kFilterUnreachable:
filter_ = new UnreachableObjectsFilter;
break;
default:
break;
}
object_iterator_ = space_iterator_->next();
}
void HeapIterator::Shutdown() {
#ifdef DEBUG
// Assert that in filtering mode we have iterated through all
// objects. Otherwise, heap will be left in an inconsistent state.
if (filtering_ != kNoFiltering) {
ASSERT(object_iterator_ == NULL);
}
#endif
// Make sure the last iterator is deallocated.
delete space_iterator_;
space_iterator_ = NULL;
object_iterator_ = NULL;
delete filter_;
filter_ = NULL;
}
HeapObject* HeapIterator::next() {
if (filter_ == NULL) return NextObject();
HeapObject* obj = NextObject();
while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
return obj;
}
HeapObject* HeapIterator::NextObject() {
// No iterator means we are done.
if (object_iterator_ == NULL) return NULL;
if (HeapObject* obj = object_iterator_->next_object()) {
// If the current iterator has more objects we are fine.
return obj;
} else {
// Go though the spaces looking for one that has objects.
while (space_iterator_->has_next()) {
object_iterator_ = space_iterator_->next();
if (HeapObject* obj = object_iterator_->next_object()) {
return obj;
}
}
}
// Done with the last space.
object_iterator_ = NULL;
return NULL;
}
void HeapIterator::reset() {
// Restart the iterator.
Shutdown();
Init();
}
#ifdef DEBUG
Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
class PathTracer::MarkVisitor: public ObjectVisitor {
public:
explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
void VisitPointers(Object** start, Object** end) {
// Scan all HeapObject pointers in [start, end)
for (Object** p = start; !tracer_->found() && (p < end); p++) {
if ((*p)->IsHeapObject())
tracer_->MarkRecursively(p, this);
}
}
private:
PathTracer* tracer_;
};
class PathTracer::UnmarkVisitor: public ObjectVisitor {
public:
explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
void VisitPointers(Object** start, Object** end) {
// Scan all HeapObject pointers in [start, end)
for (Object** p = start; p < end; p++) {
if ((*p)->IsHeapObject())
tracer_->UnmarkRecursively(p, this);
}
}
private:
PathTracer* tracer_;
};
void PathTracer::VisitPointers(Object** start, Object** end) {
bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
// Visit all HeapObject pointers in [start, end)
for (Object** p = start; !done && (p < end); p++) {
if ((*p)->IsHeapObject()) {
TracePathFrom(p);
done = ((what_to_find_ == FIND_FIRST) && found_target_);
}
}
}
void PathTracer::Reset() {
found_target_ = false;
object_stack_.Clear();
}
void PathTracer::TracePathFrom(Object** root) {
ASSERT((search_target_ == kAnyGlobalObject) ||
search_target_->IsHeapObject());
found_target_in_trace_ = false;
Reset();
MarkVisitor mark_visitor(this);
MarkRecursively(root, &mark_visitor);
UnmarkVisitor unmark_visitor(this);
UnmarkRecursively(root, &unmark_visitor);
ProcessResults();
}
static bool SafeIsNativeContext(HeapObject* obj) {
return obj->map() == obj->GetHeap()->raw_unchecked_native_context_map();
}
void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
if (!(*p)->IsHeapObject()) return;
HeapObject* obj = HeapObject::cast(*p);
Object* map = obj->map();
if (!map->IsHeapObject()) return; // visited before
if (found_target_in_trace_) return; // stop if target found
object_stack_.Add(obj);
if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
(obj == search_target_)) {
found_target_in_trace_ = true;
found_target_ = true;
return;
}
bool is_native_context = SafeIsNativeContext(obj);
// not visited yet
Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
Address map_addr = map_p->address();
obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
// Scan the object body.
if (is_native_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
// This is specialized to scan Context's properly.
Object** start = reinterpret_cast<Object**>(obj->address() +
Context::kHeaderSize);
Object** end = reinterpret_cast<Object**>(obj->address() +
Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
mark_visitor->VisitPointers(start, end);
} else {
obj->IterateBody(map_p->instance_type(),
obj->SizeFromMap(map_p),
mark_visitor);
}
// Scan the map after the body because the body is a lot more interesting
// when doing leak detection.
MarkRecursively(&map, mark_visitor);
if (!found_target_in_trace_) // don't pop if found the target
object_stack_.RemoveLast();
}
void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
if (!(*p)->IsHeapObject()) return;
HeapObject* obj = HeapObject::cast(*p);
Object* map = obj->map();
if (map->IsHeapObject()) return; // unmarked already
Address map_addr = reinterpret_cast<Address>(map);
map_addr -= kMarkTag;
ASSERT_TAG_ALIGNED(map_addr);
HeapObject* map_p = HeapObject::FromAddress(map_addr);
obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
obj->IterateBody(Map::cast(map_p)->instance_type(),
obj->SizeFromMap(Map::cast(map_p)),
unmark_visitor);
}
void PathTracer::ProcessResults() {
if (found_target_) {
PrintF("=====================================\n");
PrintF("==== Path to object ====\n");
PrintF("=====================================\n\n");
ASSERT(!object_stack_.is_empty());
for (int i = 0; i < object_stack_.length(); i++) {
if (i > 0) PrintF("\n |\n |\n V\n\n");
Object* obj = object_stack_[i];
obj->Print();
}
PrintF("=====================================\n");
}
}
// Triggers a depth-first traversal of reachable objects from one
// given root object and finds a path to a specific heap object and
// prints it.
void Heap::TracePathToObjectFrom(Object* target, Object* root) {
PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
tracer.VisitPointer(&root);
}
// Triggers a depth-first traversal of reachable objects from roots
// and finds a path to a specific heap object and prints it.
void Heap::TracePathToObject(Object* target) {
PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
IterateRoots(&tracer, VISIT_ONLY_STRONG);
}
// Triggers a depth-first traversal of reachable objects from roots
// and finds a path to any global object and prints it. Useful for
// determining the source for leaks of global objects.
void Heap::TracePathToGlobal() {
PathTracer tracer(PathTracer::kAnyGlobalObject,
PathTracer::FIND_ALL,
VISIT_ALL);
IterateRoots(&tracer, VISIT_ONLY_STRONG);
}
#endif
static intptr_t CountTotalHolesSize(Heap* heap) {
intptr_t holes_size = 0;
OldSpaces spaces(heap);
for (OldSpace* space = spaces.next();
space != NULL;
space = spaces.next()) {
holes_size += space->Waste() + space->Available();
}
return holes_size;
}
GCTracer::GCTracer(Heap* heap,
const char* gc_reason,
const char* collector_reason)
: start_time_(0.0),
start_object_size_(0),
start_memory_size_(0),
gc_count_(0),
full_gc_count_(0),
allocated_since_last_gc_(0),
spent_in_mutator_(0),
promoted_objects_size_(0),
nodes_died_in_new_space_(0),
nodes_copied_in_new_space_(0),
nodes_promoted_(0),
heap_(heap),
gc_reason_(gc_reason),
collector_reason_(collector_reason) {
if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
start_time_ = OS::TimeCurrentMillis();
start_object_size_ = heap_->SizeOfObjects();
start_memory_size_ = heap_->isolate()->memory_allocator()->Size();
for (int i = 0; i < Scope::kNumberOfScopes; i++) {
scopes_[i] = 0;
}
in_free_list_or_wasted_before_gc_ = CountTotalHolesSize(heap);
allocated_since_last_gc_ =
heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
if (heap_->last_gc_end_timestamp_ > 0) {
spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
}
steps_count_ = heap_->incremental_marking()->steps_count();
steps_took_ = heap_->incremental_marking()->steps_took();
longest_step_ = heap_->incremental_marking()->longest_step();
steps_count_since_last_gc_ =
heap_->incremental_marking()->steps_count_since_last_gc();
steps_took_since_last_gc_ =
heap_->incremental_marking()->steps_took_since_last_gc();
}
GCTracer::~GCTracer() {
// Printf ONE line iff flag is set.
if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
double time = heap_->last_gc_end_timestamp_ - start_time_;
// Update cumulative GC statistics if required.
if (FLAG_print_cumulative_gc_stat) {
heap_->total_gc_time_ms_ += time;
heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
heap_->alive_after_last_gc_);
if (!first_gc) {
heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
spent_in_mutator_);
}
} else if (FLAG_trace_gc_verbose) {
heap_->total_gc_time_ms_ += time;
}
if (collector_ == SCAVENGER && FLAG_trace_gc_ignore_scavenger) return;
heap_->AddMarkingTime(scopes_[Scope::MC_MARK]);
if (FLAG_print_cumulative_gc_stat && !FLAG_trace_gc) return;
PrintPID("%8.0f ms: ", heap_->isolate()->time_millis_since_init());
if (!FLAG_trace_gc_nvp) {
int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
double end_memory_size_mb =
static_cast<double>(heap_->isolate()->memory_allocator()->Size()) / MB;
PrintF("%s %.1f (%.1f) -> %.1f (%.1f) MB, ",
CollectorString(),
static_cast<double>(start_object_size_) / MB,
static_cast<double>(start_memory_size_) / MB,
SizeOfHeapObjects(),
end_memory_size_mb);
if (external_time > 0) PrintF("%d / ", external_time);
PrintF("%.1f ms", time);
if (steps_count_ > 0) {
if (collector_ == SCAVENGER) {
PrintF(" (+ %.1f ms in %d steps since last GC)",
steps_took_since_last_gc_,
steps_count_since_last_gc_);
} else {
PrintF(" (+ %.1f ms in %d steps since start of marking, "
"biggest step %.1f ms)",
steps_took_,
steps_count_,
longest_step_);
}
}
if (gc_reason_ != NULL) {
PrintF(" [%s]", gc_reason_);
}
if (collector_reason_ != NULL) {
PrintF(" [%s]", collector_reason_);
}
PrintF(".\n");
} else {
PrintF("pause=%.1f ", time);
PrintF("mutator=%.1f ", spent_in_mutator_);
PrintF("gc=");
switch (collector_) {
case SCAVENGER:
PrintF("s");
break;
case MARK_COMPACTOR:
PrintF("ms");
break;
default:
UNREACHABLE();
}
PrintF(" ");
PrintF("external=%.1f ", scopes_[Scope::EXTERNAL]);
PrintF("mark=%.1f ", scopes_[Scope::MC_MARK]);
PrintF("sweep=%.1f ", scopes_[Scope::MC_SWEEP]);
PrintF("sweepns=%.1f ", scopes_[Scope::MC_SWEEP_NEWSPACE]);
PrintF("evacuate=%.1f ", scopes_[Scope::MC_EVACUATE_PAGES]);
PrintF("new_new=%.1f ", scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]);
PrintF("root_new=%.1f ", scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]);
PrintF("old_new=%.1f ", scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]);
PrintF("compaction_ptrs=%.1f ",
scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]);
PrintF("intracompaction_ptrs=%.1f ",
scopes_[Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]);
PrintF("misc_compaction=%.1f ", scopes_[Scope::MC_UPDATE_MISC_POINTERS]);
PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_object_size_);
PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
in_free_list_or_wasted_before_gc_);
PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize(heap_));
PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
PrintF("nodes_died_in_new=%d ", nodes_died_in_new_space_);
PrintF("nodes_copied_in_new=%d ", nodes_copied_in_new_space_);
PrintF("nodes_promoted=%d ", nodes_promoted_);
if (collector_ == SCAVENGER) {
PrintF("stepscount=%d ", steps_count_since_last_gc_);
PrintF("stepstook=%.1f ", steps_took_since_last_gc_);
} else {
PrintF("stepscount=%d ", steps_count_);
PrintF("stepstook=%.1f ", steps_took_);
PrintF("longeststep=%.1f ", longest_step_);
}
PrintF("\n");
}
heap_->PrintShortHeapStatistics();
}
const char* GCTracer::CollectorString() {
switch (collector_) {
case SCAVENGER:
return "Scavenge";
case MARK_COMPACTOR:
return "Mark-sweep";
}
return "Unknown GC";
}
int KeyedLookupCache::Hash(Map* map, Name* name) {
// Uses only lower 32 bits if pointers are larger.
uintptr_t addr_hash =
static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
}
int KeyedLookupCache::Lookup(Map* map, Name* name) {
int index = (Hash(map, name) & kHashMask);
for (int i = 0; i < kEntriesPerBucket; i++) {
Key& key = keys_[index + i];
if ((key.map == map) && key.name->Equals(name)) {
return field_offsets_[index + i];
}
}
return kNotFound;
}
void KeyedLookupCache::Update(Map* map, Name* name, int field_offset) {
if (!name->IsUniqueName()) {
String* internalized_string;
if (!HEAP->InternalizeStringIfExists(
String::cast(name), &internalized_string)) {
return;
}
name = internalized_string;
}
// This cache is cleared only between mark compact passes, so we expect the
// cache to only contain old space names.
ASSERT(!HEAP->InNewSpace(name));
int index = (Hash(map, name) & kHashMask);
// After a GC there will be free slots, so we use them in order (this may
// help to get the most frequently used one in position 0).
for (int i = 0; i< kEntriesPerBucket; i++) {
Key& key = keys_[index];
Object* free_entry_indicator = NULL;
if (key.map == free_entry_indicator) {
key.map = map;
key.name = name;
field_offsets_[index + i] = field_offset;
return;
}
}
// No free entry found in this bucket, so we move them all down one and
// put the new entry at position zero.
for (int i = kEntriesPerBucket - 1; i > 0; i--) {
Key& key = keys_[index + i];
Key& key2 = keys_[index + i - 1];
key = key2;
field_offsets_[index + i] = field_offsets_[index + i - 1];
}
// Write the new first entry.
Key& key = keys_[index];
key.map = map;
key.name = name;
field_offsets_[index] = field_offset;
}
void KeyedLookupCache::Clear() {
for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
}
void DescriptorLookupCache::Clear() {
for (int index = 0; index < kLength; index++) keys_[index].source = NULL;
}
#ifdef DEBUG
void Heap::GarbageCollectionGreedyCheck() {
ASSERT(FLAG_gc_greedy);
if (isolate_->bootstrapper()->IsActive()) return;
if (disallow_allocation_failure()) return;
CollectGarbage(NEW_SPACE);
}
#endif
TranscendentalCache::SubCache::SubCache(Type t)
: type_(t),
isolate_(Isolate::Current()) {
uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
uint32_t in1 = 0xffffffffu; // generated by the FPU.
for (int i = 0; i < kCacheSize; i++) {
elements_[i].in[0] = in0;
elements_[i].in[1] = in1;
elements_[i].output = NULL;
}
}
void TranscendentalCache::Clear() {
for (int i = 0; i < kNumberOfCaches; i++) {
if (caches_[i] != NULL) {
delete caches_[i];
caches_[i] = NULL;
}
}
}
void ExternalStringTable::CleanUp() {
int last = 0;
for (int i = 0; i < new_space_strings_.length(); ++i) {
if (new_space_strings_[i] == heap_->the_hole_value()) {
continue;
}
if (heap_->InNewSpace(new_space_strings_[i])) {
new_space_strings_[last++] = new_space_strings_[i];
} else {
old_space_strings_.Add(new_space_strings_[i]);
}
}
new_space_strings_.Rewind(last);
new_space_strings_.Trim();
last = 0;
for (int i = 0; i < old_space_strings_.length(); ++i) {
if (old_space_strings_[i] == heap_->the_hole_value()) {
continue;
}
ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
old_space_strings_[last++] = old_space_strings_[i];
}
old_space_strings_.Rewind(last);
old_space_strings_.Trim();
#ifdef VERIFY_HEAP
if (FLAG_verify_heap) {
Verify();
}
#endif
}
void ExternalStringTable::TearDown() {
new_space_strings_.Free();
old_space_strings_.Free();
}
// Update all references.
void ErrorObjectList::UpdateReferences() {
for (int i = 0; i < list_.length(); i++) {
HeapObject* object = HeapObject::cast(list_[i]);
MapWord first_word = object->map_word();
if (first_word.IsForwardingAddress()) {
list_[i] = first_word.ToForwardingAddress();
}
}
}
// Unforwarded objects in new space are dead and removed from the list.
void ErrorObjectList::UpdateReferencesInNewSpace(Heap* heap) {
if (list_.is_empty()) return;
if (!nested_) {
int write_index = 0;
for (int i = 0; i < list_.length(); i++) {
MapWord first_word = HeapObject::cast(list_[i])->map_word();
if (first_word.IsForwardingAddress()) {
list_[write_index++] = first_word.ToForwardingAddress();
}
}
list_.Rewind(write_index);
} else {
// If a GC is triggered during DeferredFormatStackTrace, we do not move
// objects in the list, just remove dead ones, as to not confuse the
// loop in DeferredFormatStackTrace.
for (int i = 0; i < list_.length(); i++) {
MapWord first_word = HeapObject::cast(list_[i])->map_word();
list_[i] = first_word.IsForwardingAddress()
? first_word.ToForwardingAddress()
: heap->the_hole_value();
}
}
}
void ErrorObjectList::DeferredFormatStackTrace(Isolate* isolate) {
// If formatting the stack trace causes a GC, this method will be
// recursively called. In that case, skip the recursive call, since
// the loop modifies the list while iterating over it.
if (nested_ || list_.is_empty() || isolate->has_pending_exception()) return;
nested_ = true;
HandleScope scope(isolate);
Handle<String> stack_key = isolate->factory()->stack_string();
int write_index = 0;
int budget = kBudgetPerGC;
for (int i = 0; i < list_.length(); i++) {
Object* object = list_[i];
JSFunction* getter_fun;
{ AssertNoAllocation assert;
// Skip possible holes in the list.
if (object->IsTheHole()) continue;
if (isolate->heap()->InNewSpace(object) || budget == 0) {
list_[write_index++] = object;
continue;
}
// Check whether the stack property is backed by the original getter.
LookupResult lookup(isolate);
JSObject::cast(object)->LocalLookupRealNamedProperty(*stack_key, &lookup);
if (!lookup.IsFound() || lookup.type() != CALLBACKS) continue;
Object* callback = lookup.GetCallbackObject();
if (!callback->IsAccessorPair()) continue;
Object* getter_obj = AccessorPair::cast(callback)->getter();
if (!getter_obj->IsJSFunction()) continue;
getter_fun = JSFunction::cast(getter_obj);
String* key = isolate->heap()->hidden_stack_trace_string();
if (key != getter_fun->GetHiddenProperty(key)) continue;
}
budget--;
HandleScope scope(isolate);
bool has_exception = false;
#ifdef DEBUG
Handle<Map> map(HeapObject::cast(object)->map(), isolate);
#endif
Handle<Object> object_handle(object, isolate);
Handle<Object> getter_handle(getter_fun, isolate);
Execution::Call(getter_handle, object_handle, 0, NULL, &has_exception);
ASSERT(*map == HeapObject::cast(*object_handle)->map());
if (has_exception) {
// Hit an exception (most likely a stack overflow).
// Wrap up this pass and retry after another GC.
isolate->clear_pending_exception();
// We use the handle since calling the getter might have caused a GC.
list_[write_index++] = *object_handle;
budget = 0;
}
}
list_.Rewind(write_index);
list_.Trim();
nested_ = false;
}
void ErrorObjectList::RemoveUnmarked(Heap* heap) {
for (int i = 0; i < list_.length(); i++) {
HeapObject* object = HeapObject::cast(list_[i]);
if (!Marking::MarkBitFrom(object).Get()) {
list_[i] = heap->the_hole_value();
}
}
}
void ErrorObjectList::TearDown() {
list_.Free();
}
void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
chunk->set_next_chunk(chunks_queued_for_free_);
chunks_queued_for_free_ = chunk;
}
void Heap::FreeQueuedChunks() {
if (chunks_queued_for_free_ == NULL) return;
MemoryChunk* next;
MemoryChunk* chunk;
for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
next = chunk->next_chunk();
chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
if (chunk->owner()->identity() == LO_SPACE) {
// StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
// If FromAnyPointerAddress encounters a slot that belongs to a large
// chunk queued for deletion it will fail to find the chunk because
// it try to perform a search in the list of pages owned by of the large
// object space and queued chunks were detached from that list.
// To work around this we split large chunk into normal kPageSize aligned
// pieces and initialize size, owner and flags field of every piece.
// If FromAnyPointerAddress encounters a slot that belongs to one of
// these smaller pieces it will treat it as a slot on a normal Page.
Address chunk_end = chunk->address() + chunk->size();
MemoryChunk* inner = MemoryChunk::FromAddress(
chunk->address() + Page::kPageSize);
MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1);
while (inner <= inner_last) {
// Size of a large chunk is always a multiple of
// OS::AllocateAlignment() so there is always
// enough space for a fake MemoryChunk header.
Address area_end = Min(inner->address() + Page::kPageSize, chunk_end);
// Guard against overflow.
if (area_end < inner->address()) area_end = chunk_end;
inner->SetArea(inner->address(), area_end);
inner->set_size(Page::kPageSize);
inner->set_owner(lo_space());
inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
inner = MemoryChunk::FromAddress(
inner->address() + Page::kPageSize);
}
}
}
isolate_->heap()->store_buffer()->Compact();
isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
next = chunk->next_chunk();
isolate_->memory_allocator()->Free(chunk);
}
chunks_queued_for_free_ = NULL;
}
void Heap::RememberUnmappedPage(Address page, bool compacted) {
uintptr_t p = reinterpret_cast<uintptr_t>(page);
// Tag the page pointer to make it findable in the dump file.
if (compacted) {
p ^= 0xc1ead & (Page::kPageSize - 1); // Cleared.
} else {
p ^= 0x1d1ed & (Page::kPageSize - 1); // I died.
}
remembered_unmapped_pages_[remembered_unmapped_pages_index_] =
reinterpret_cast<Address>(p);
remembered_unmapped_pages_index_++;
remembered_unmapped_pages_index_ %= kRememberedUnmappedPages;
}
void Heap::ClearObjectStats(bool clear_last_time_stats) {
memset(object_counts_, 0, sizeof(object_counts_));
memset(object_sizes_, 0, sizeof(object_sizes_));
if (clear_last_time_stats) {
memset(object_counts_last_time_, 0, sizeof(object_counts_last_time_));
memset(object_sizes_last_time_, 0, sizeof(object_sizes_last_time_));
}
}
static LazyMutex checkpoint_object_stats_mutex = LAZY_MUTEX_INITIALIZER;
void Heap::CheckpointObjectStats() {
ScopedLock lock(checkpoint_object_stats_mutex.Pointer());
Counters* counters = isolate()->counters();
#define ADJUST_LAST_TIME_OBJECT_COUNT(name) \
counters->count_of_##name()->Increment( \
static_cast<int>(object_counts_[name])); \
counters->count_of_##name()->Decrement( \
static_cast<int>(object_counts_last_time_[name])); \
counters->size_of_##name()->Increment( \
static_cast<int>(object_sizes_[name])); \
counters->size_of_##name()->Decrement( \
static_cast<int>(object_sizes_last_time_[name]));
INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
#undef ADJUST_LAST_TIME_OBJECT_COUNT
int index;
#define ADJUST_LAST_TIME_OBJECT_COUNT(name) \
index = FIRST_CODE_KIND_SUB_TYPE + Code::name; \
counters->count_of_CODE_TYPE_##name()->Increment( \
static_cast<int>(object_counts_[index])); \
counters->count_of_CODE_TYPE_##name()->Decrement( \
static_cast<int>(object_counts_last_time_[index])); \
counters->size_of_CODE_TYPE_##name()->Increment( \
static_cast<int>(object_sizes_[index])); \
counters->size_of_CODE_TYPE_##name()->Decrement( \
static_cast<int>(object_sizes_last_time_[index]));
CODE_KIND_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
#undef ADJUST_LAST_TIME_OBJECT_COUNT
#define ADJUST_LAST_TIME_OBJECT_COUNT(name) \
index = FIRST_FIXED_ARRAY_SUB_TYPE + name; \
counters->count_of_FIXED_ARRAY_##name()->Increment( \
static_cast<int>(object_counts_[index])); \
counters->count_of_FIXED_ARRAY_##name()->Decrement( \
static_cast<int>(object_counts_last_time_[index])); \
counters->size_of_FIXED_ARRAY_##name()->Increment( \
static_cast<int>(object_sizes_[index])); \
counters->size_of_FIXED_ARRAY_##name()->Decrement( \
static_cast<int>(object_sizes_last_time_[index]));
FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
#undef ADJUST_LAST_TIME_OBJECT_COUNT
memcpy(object_counts_last_time_, object_counts_, sizeof(object_counts_));
memcpy(object_sizes_last_time_, object_sizes_, sizeof(object_sizes_));
ClearObjectStats();
}
} } // namespace v8::internal
|
#include "doctest.h"
#include "snowman.hpp"
using namespace ariel;
#include <string>
#include <algorithm>
using namespace std;
string nospaces(string input) {
input.erase(remove(input.begin(),input.end(),' '),input.end());
input.erase(remove(input.begin(),input.end(),'\t'),input.end());
input.erase(remove(input.begin(),input.end(),'\r'),input.end());
input.erase(remove(input.begin(),input.end(),'\n'),input.end());
return input;
}
TEST_CASE("check with nospaces") {
CHECK(nospaces(snowman(11114411)) == nospaces(string(" \n _===_\n (.,.) \n ( : ) \n ( : )")));
CHECK(nospaces(snowman(33232124)) == nospaces(string(" _ \n /_\\ \n\\(o_O) \n (] [)>\n ( ) \n")));
}
TEST_CASE("test hats") {
CHECK(snowman(11114411) == string(" \n _===_\n (.,.) \n ( : ) \n ( : )"));
CHECK(snowman(21114411) == string(" ___ \n .....\n (.,.) \n ( : ) \n ( : )"));
CHECK(snowman(31114411) == string(" _ \n /_\\ \n (.,.) \n ( : ) \n ( : )"));
CHECK(snowman(41114411) == string(" ___ \n (_*_)\n (.,.) \n ( : ) \n ( : )"));
}
TEST_CASE("test base") {
CHECK(snowman(11114411) == string(" \n _===_\n (.,.) \n ( : ) \n ( : )"));
CHECK(snowman(11114412) == string(" \n _===_\n (.,.) \n ( : ) \n (\" \")"));
CHECK(snowman(11114413) == string(" \n _===_\n (.,.) \n ( : ) \n (___)"));
CHECK(snowman(11114414) == string(" \n _===_\n (.,.) \n ( : ) \n ( )"));
}
TEST_CASE("test torso") {
CHECK(snowman(11114411) == string(" \n _===_\n (.,.) \n ( : ) \n ( : )"));
CHECK(snowman(11114421) == string(" \n _===_\n (.,.) \n (] [) \n ( : )"));
CHECK(snowman(11114431) == string(" \n _===_\n (.,.) \n (> <) \n ( : )"));
CHECK(snowman(11114441) == string(" \n _===_\n (.,.) \n ( ) \n ( : )"));
}
TEST_CASE("test nose") {
CHECK(snowman(11114411) == string(" \n _===_\n (.,.) \n ( : ) \n ( : )"));
CHECK(snowman(12114411) == string(" \n _===_\n (...) \n ( : ) \n ( : )"));
CHECK(snowman(13114411) == string(" \n _===_\n (._.) \n ( : ) \n ( : )"));
CHECK(snowman(14114411) == string(" \n _===_\n (. .) \n ( : ) \n ( : )"));
}
TEST_CASE("test left eye") {
CHECK(snowman(33132124) == string(" _ \n /_\\ \n\\(._O) \n (] [)>\n ( ) \n"));
CHECK(snowman(33232124) == string(" _ \n /_\\ \n\\(o_O) \n (] [)>\n ( ) \n"));
CHECK(snowman(33332124) == string(" _ \n /_\\ \n\\(O_O) \n (] [)>\n ( ) \n"));
CHECK(snowman(33432124) == string(" _ \n /_\\ \n\\(-_O) \n (] [)>\n ( ) \n"));
}
TEST_CASE("test right eye") {
CHECK(snowman(33212124) == string(" _ \n /_\\ \n\\(o_.) \n (] [)>\n ( ) \n"));
CHECK(snowman(33222124) == string(" _ \n /_\\ \n\\(o_o) \n (] [)>\n ( ) \n"));
CHECK(snowman(33232124) == string(" _ \n /_\\ \n\\(o_O) \n (] [)>\n ( ) \n"));
CHECK(snowman(33242124) == string(" _ \n /_\\ \n\\(o_-) \n (] [)>\n ( ) \n"));
}
TEST_CASE("test left arm") {
CHECK(snowman(33231124) == string(" _ \n /_\\ \n (o_O) \n<(] [)>\n ( ) \n"));
CHECK(snowman(33232124) == string(" _ \n /_\\ \n\\(o_O) \n (] [)>\n ( ) \n"));
CHECK(snowman(33233124) == string(" _ \n /_\\ \n (o_O) \n/(] [)>\n ( ) \n"));
CHECK(snowman(33234124) == string(" _ \n /_\\ \n (o_O) \n (] [)>\n ( ) \n"));
}
TEST_CASE("test right arm") {
CHECK(snowman(33232124) == string(" _ \n /_\\ \n\\(o_O) \n (] [)>\n ( ) \n"));
CHECK(snowman(33232224) == string(" _ \n /_\\ \n\\(o_O)//\n (] [) \n ( ) \n"));
CHECK(snowman(33232324) == string(" _ \n /_\\ \n\\(o_O) \n (] [)\\\n ( ) \n"));
CHECK(snowman(33232424) == string(" _ \n /_\\ \n\\(o_O) \n (] [) \n ( ) \n"));
}
TEST_CASE("check length") {
string actual = snowman(11114411);
string expected = " \n _===_\n(.,.)\n( : )\n ( : ) ";
CHECK (actual.length() == expected.length());
}
TEST_CASE("check chars") {
string actual = snowman(33232124);
string expected = " _ \n /_\\ \n\\(o_O) \n (] [)>\n ( ) \n";
CHECK (actual == expected);
}
TEST_CASE("wrong input - digits greater than 4") {
CHECK_THROWS(snowman(62548521));
CHECK_THROWS(snowman(15423384));
CHECK_THROWS(snowman(11111119));
}
TEST_CASE("wrong input - digits smaller than 0") {
CHECK_THROWS(snowman(-62548521));
CHECK_THROWS(snowman(-15423384));
CHECK_THROWS(snowman(-11111119));
}
TEST_CASE("wrong input - less than 8 digits") {
CHECK_THROWS(snowman(233));
CHECK_THROWS(snowman(9));
CHECK_THROWS(snowman(14321));
}
TEST_CASE("wrong input - more than 8 digits") {
CHECK_THROWS(snowman(233412342));
CHECK_THROWS(snowman(1231124232));
CHECK_THROWS(snowman(143212111));
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "flush_target_candidates.h"
#include "flush_target_candidate.h"
#include "tls_stats.h"
namespace proton {
using search::SerialNum;
using Config = PrepareRestartFlushStrategy::Config;
using TlsReplayCost = FlushTargetCandidates::TlsReplayCost;
namespace {
SerialNum
calculateReplayStartSerial(vespalib::ConstArrayRef<FlushTargetCandidate> candidates,
size_t num_candidates,
const flushengine::TlsStats &tlsStats)
{
if (num_candidates == 0) {
return tlsStats.getFirstSerial();
}
if (num_candidates == candidates.size()) {
return tlsStats.getLastSerial() + 1;
}
return candidates[num_candidates].get_flushed_serial() + 1;
}
TlsReplayCost
calculateTlsReplayCost(const flushengine::TlsStats &tlsStats,
const Config &cfg,
SerialNum replayStartSerial)
{
SerialNum replayEndSerial = tlsStats.getLastSerial();
SerialNum numTotalOperations = replayEndSerial - tlsStats.getFirstSerial() + 1;
if (numTotalOperations == 0) {
return TlsReplayCost(0.0, 0.0);
}
double numBytesPerOperation =
(double)tlsStats.getNumBytes() / (double)numTotalOperations;
SerialNum numOperationsToReplay = replayEndSerial + 1 - replayStartSerial;
double numBytesToReplay = numBytesPerOperation * numOperationsToReplay;
return TlsReplayCost((numBytesToReplay * cfg.tlsReplayByteCost), (numOperationsToReplay * cfg.tlsReplayOperationCost));
}
double
calculateFlushTargetsWriteCost(vespalib::ConstArrayRef<FlushTargetCandidate> candidates,
size_t num_candidates)
{
double result = 0;
for (size_t i = 0; i < num_candidates; ++i) {
result += candidates[i].get_write_cost();
}
return result;
}
}
FlushTargetCandidates::FlushTargetCandidates(vespalib::ConstArrayRef<FlushTargetCandidate> candidates,
size_t num_candidates,
const flushengine::TlsStats &tlsStats,
const Config &cfg)
: _candidates(candidates),
_num_candidates(std::min(num_candidates, _candidates.size())),
_tlsReplayCost(calculateTlsReplayCost(tlsStats,
cfg,
calculateReplayStartSerial(_candidates,
_num_candidates,
tlsStats))),
_flushTargetsWriteCost(calculateFlushTargetsWriteCost(_candidates,
_num_candidates))
{
}
FlushContext::List
FlushTargetCandidates::getCandidates() const
{
FlushContext::List result;
result.reserve(_num_candidates);
for (const auto &candidate : _candidates) {
if (result.size() < _num_candidates || candidate.get_always_flush()) {
result.emplace_back(candidate.get_flush_context());
}
}
return result;
}
} // namespace proton
|
#pragma once
#include <ph/testing/testing.hpp>
#include <ph/core/core.hpp>
namespace ph::core
{
struct Testing : ph::testing::Testing
{
virtual void run () override
{
}
};
}
|
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *yaadi_strings[] = {
QT_TRANSLATE_NOOP("yaadi-core", " mints deleted\n"),
QT_TRANSLATE_NOOP("yaadi-core", " mints updated, "),
QT_TRANSLATE_NOOP("yaadi-core", " unconfirmed transactions removed\n"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"(1 = keep tx meta data e.g. account owner and payment request information, 2 "
"= drop tx meta data)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Allow JSON-RPC connections from specified source. Valid for <ip> are a "
"single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or "
"a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Bind to given address and whitelist peers connecting to it. Use [host]:port "
"notation for IPv6"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Bind to given address to listen for JSON-RPC connections. Use [host]:port "
"notation for IPv6. This option can be specified multiple times (default: "
"bind to all interfaces)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Calculated accumulator checkpoint is not what is recorded by block index"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Cannot obtain a lock on data directory %s. yaadi Core is probably already "
"running."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Change automatic finalized budget voting behavior. mode=auto: Vote for only "
"exact finalized budget match to my generated budget. (string, default: auto)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Continuously rate-limit free transactions to <n>*1000 bytes per minute "
"(default:%u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Create new files with system default permissions, instead of umask 077 (only "
"effective with disabled wallet functionality)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Delete all wallet transactions and only recover those parts of the "
"blockchain through -rescan on startup"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Delete all zerocoin spends and mints that have been recorded to the "
"blockchain database and reindex them (0-1, default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Disable all yaadi specific functionality (Masternodes, Zerocoin, SwiftX, "
"Budgeting) (0-1, default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Distributed under the MIT software license, see the accompanying file "
"COPYING or <http://www.opensource.org/licenses/mit-license.php>."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Enable SwiftX, show confirmations for locked transactions (bool, default: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Enable automatic wallet backups triggered after each zyaadi minting (0-1, "
"default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Enable or disable staking functionality for yaadi inputs (0-1, default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Enable or disable staking functionality for zyaadi inputs (0-1, default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Enable spork administration functionality with the appropriate private key."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Enter regression test mode, which uses a special chain in which blocks can "
"be solved instantly."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Error: Listening for incoming connections failed (listen returned error %s)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Error: The transaction is larger than the maximum allowed transaction size!"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Error: The transaction was rejected! This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds!"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Error: Unsupported argument -checklevel found. Checklevel must be level 4."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Error: Unsupported argument -socks found. Setting SOCKS version isn't "
"possible anymore, only SOCKS5 proxies are supported."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Execute command when a relevant alert is received or we see a really long "
"fork (%s in cmd is replaced by message)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Execute command when the best block changes and its size is over (%s in cmd "
"is replaced by block hash, %d with the block size)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Failed to find coin set amongst held coins with less than maxNumber of Spends"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Fees (in yaadi/Kb) smaller than this are considered zero fee for relaying "
"(default: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Fees (in yaadi/Kb) smaller than this are considered zero fee for transaction "
"creation (default: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Flush database activity from memory pool to disk log every <n> megabytes "
"(default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Found unconfirmed denominated outputs, will wait till they confirm to "
"continue."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"If paytxfee is not set, include enough fee so transactions begin "
"confirmation on average within n blocks (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"In rare cases, a spend with 7 coins exceeds our maximum allowable "
"transaction size, please retry spend using 6 or less coins"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"In this mode -genproclimit controls how many blocks are generated "
"immediately."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Insufficient or insufficient confirmed funds, you might need to wait a few "
"minutes and try again."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay "
"fee of %s to prevent stuck transactions)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Keep the specified amount available for spending at all times (default: 0)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Log transaction priority and fee per kB when mining blocks (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Maintain a full transaction index, used by the getrawtransaction rpc call "
"(default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Maximum size of data in data carrier transactions we relay and mine "
"(default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Maximum total fees to use in a single wallet transaction, setting too low "
"may abort large transactions (default: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Obfuscation uses exact denominated amounts to send funds, you might simply "
"need to anonymize some more coins."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Output debugging information (default: %u, supplying <category> is optional)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Preferred Denomination for automatically minted Zerocoin "
"(1/5/10/50/100/500/1000/5000), 0 for no preference. default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Query for peer addresses via DNS lookup, if low on addresses (default: 1 "
"unless -connect)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Randomize credentials for every proxy connection. This enables Tor stream "
"isolation (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Require high priority for relaying free or low-fee transactions (default:%u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Send trace/debug info to console instead of debug.log file (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Set the number of script verification threads (%u to %d, 0 = auto, <0 = "
"leave that many cores free, default: %d)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Set the number of threads for coin generation if enabled (-1 = all cores, "
"default: %d)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Show N confirmations for a successfully locked transaction (0-9999, default: "
"%u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Specify custom backup path to add a copy of any automatic zyaadi backup. If "
"set as dir, every backup generates a timestamped file. If set as file, will "
"rewrite to that file every backup. If backuppath is set as well, 4 backups "
"will happen"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Specify custom backup path to add a copy of any wallet backup. If set as "
"dir, every backup generates a timestamped file. If set as file, will rewrite "
"to that file every backup."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Support filtering of blocks and transaction with bloom filters (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"SwiftX requires inputs with at least 6 confirmations, you might need to wait "
"a few minutes and try again."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"staking or merchant applications!"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"This product includes software developed by the OpenSSL Project for use in "
"the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software "
"written by Eric Young and UPnP software written by Thomas Bernard."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Unable to bind to %s on this computer. yaadi Core is probably already running."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Unable to locate enough Obfuscation denominated funds for this transaction."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Unable to locate enough Obfuscation non-denominated funds for this "
"transaction that are not equal 10000 yaadi."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Unable to locate enough funds for this transaction that are not equal 10000 "
"yaadi."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: "
"%s)"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Warning: -maxtxfee is set very high! Fees this large could be paid on a "
"single transaction."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong yaadi Core will not work properly."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Warning: The network does not appear to fully agree! Some miners appear to "
"be experiencing issues."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Warning: We do not appear to fully agree with our peers! You may need to "
"upgrade, or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Whitelist peers connecting from the given netmask or IP address. Can be "
"specified multiple times."),
QT_TRANSLATE_NOOP("yaadi-core", ""
"Whitelisted peers cannot be DoS banned and their transactions are always "
"relayed, even if they are already in the mempool, useful e.g. for a gateway"),
QT_TRANSLATE_NOOP("yaadi-core", ""
"You must specify a masternodeprivkey in the configuration. Please see "
"documentation for help."),
QT_TRANSLATE_NOOP("yaadi-core", "(51472 could be used only on mainnet)"),
QT_TRANSLATE_NOOP("yaadi-core", "(default: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", "(default: 1)"),
QT_TRANSLATE_NOOP("yaadi-core", "(must be 51472 for mainnet)"),
QT_TRANSLATE_NOOP("yaadi-core", "<category> can be:"),
QT_TRANSLATE_NOOP("yaadi-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("yaadi-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("yaadi-core", "Accept public REST requests (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("yaadi-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("yaadi-core", "Already have that input."),
QT_TRANSLATE_NOOP("yaadi-core", "Always query for peer addresses via DNS lookup (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Attempt to force blockchain corruption recovery"),
QT_TRANSLATE_NOOP("yaadi-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("yaadi-core", "Automatically create Tor hidden service (default: %d)"),
QT_TRANSLATE_NOOP("yaadi-core", "Block creation options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Calculating missing accumulators..."),
QT_TRANSLATE_NOOP("yaadi-core", "Can't denominate: no compatible inputs left."),
QT_TRANSLATE_NOOP("yaadi-core", "Can't find random Masternode."),
QT_TRANSLATE_NOOP("yaadi-core", "Can't mix while sync in progress."),
QT_TRANSLATE_NOOP("yaadi-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("yaadi-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Cannot resolve -whitebind address: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("yaadi-core", "CoinSpend: Accumulator witness does not verify"),
QT_TRANSLATE_NOOP("yaadi-core", "Collateral not valid."),
QT_TRANSLATE_NOOP("yaadi-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("yaadi-core", "Connect through SOCKS5 proxy"),
QT_TRANSLATE_NOOP("yaadi-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("yaadi-core", "Connection options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"),
QT_TRANSLATE_NOOP("yaadi-core", "Copyright (C) 2014-%i The Dash Core Developers"),
QT_TRANSLATE_NOOP("yaadi-core", "Copyright (C) 2015-%i The yaadi Core Developers"),
QT_TRANSLATE_NOOP("yaadi-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("yaadi-core", "Could not parse masternode.conf"),
QT_TRANSLATE_NOOP("yaadi-core", "Debugging/Testing options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Delete blockchain folders and resync from scratch"),
QT_TRANSLATE_NOOP("yaadi-core", "Disable OS notifications for incoming transactions (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Disable safemode, override a real safe mode event (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("yaadi-core", "Display the stake modifier calculations in the debug.log file."),
QT_TRANSLATE_NOOP("yaadi-core", "Display verbose coin stake messages in the debug.log file."),
QT_TRANSLATE_NOOP("yaadi-core", "Do not load the wallet and disable wallet RPC calls"),
QT_TRANSLATE_NOOP("yaadi-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("yaadi-core", "Done loading"),
QT_TRANSLATE_NOOP("yaadi-core", "Enable automatic Zerocoin minting (0-1, default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Enable publish hash block in <address>"),
QT_TRANSLATE_NOOP("yaadi-core", "Enable publish hash transaction (locked via SwiftX) in <address>"),
QT_TRANSLATE_NOOP("yaadi-core", "Enable publish hash transaction in <address>"),
QT_TRANSLATE_NOOP("yaadi-core", "Enable publish raw block in <address>"),
QT_TRANSLATE_NOOP("yaadi-core", "Enable publish raw transaction (locked via SwiftX) in <address>"),
QT_TRANSLATE_NOOP("yaadi-core", "Enable publish raw transaction in <address>"),
QT_TRANSLATE_NOOP("yaadi-core", "Enable staking functionality (0-1, default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Enable the client to act as a masternode (0-1, default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Entries are full."),
QT_TRANSLATE_NOOP("yaadi-core", "Error connecting to Masternode."),
QT_TRANSLATE_NOOP("yaadi-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("yaadi-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("yaadi-core", "Error loading block database"),
QT_TRANSLATE_NOOP("yaadi-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("yaadi-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("yaadi-core", "Error loading wallet.dat: Wallet requires newer version of yaadi Core"),
QT_TRANSLATE_NOOP("yaadi-core", "Error opening block database"),
QT_TRANSLATE_NOOP("yaadi-core", "Error reading from database, shutting down."),
QT_TRANSLATE_NOOP("yaadi-core", "Error recovering public key."),
QT_TRANSLATE_NOOP("yaadi-core", "Error writing zerocoinDB to disk"),
QT_TRANSLATE_NOOP("yaadi-core", "Error"),
QT_TRANSLATE_NOOP("yaadi-core", "Error: A fatal internal error occured, see debug.log for details"),
QT_TRANSLATE_NOOP("yaadi-core", "Error: A fatal internal error occurred, see debug.log for details"),
QT_TRANSLATE_NOOP("yaadi-core", "Error: Can't select current denominated inputs"),
QT_TRANSLATE_NOOP("yaadi-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("yaadi-core", "Error: No valid utxo!"),
QT_TRANSLATE_NOOP("yaadi-core", "Error: Unsupported argument -tor found, use -onion."),
QT_TRANSLATE_NOOP("yaadi-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("yaadi-core", "Error: You already have pending entries in the Obfuscation pool"),
QT_TRANSLATE_NOOP("yaadi-core", "Failed to calculate accumulator checkpoint"),
QT_TRANSLATE_NOOP("yaadi-core", "Failed to create mint"),
QT_TRANSLATE_NOOP("yaadi-core", "Failed to deserialize"),
QT_TRANSLATE_NOOP("yaadi-core", "Failed to find Zerocoins in wallet.dat"),
QT_TRANSLATE_NOOP("yaadi-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("yaadi-core", "Failed to parse host:port string"),
QT_TRANSLATE_NOOP("yaadi-core", "Failed to read block"),
QT_TRANSLATE_NOOP("yaadi-core", "Failed to select a zerocoin"),
QT_TRANSLATE_NOOP("yaadi-core", "Failed to wipe zerocoinDB"),
QT_TRANSLATE_NOOP("yaadi-core", "Failed to write coin serial number into wallet"),
QT_TRANSLATE_NOOP("yaadi-core", "Fee (in yaadi/kB) to add to transactions you send (default: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", "Finalizing transaction."),
QT_TRANSLATE_NOOP("yaadi-core", "Force safe mode (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Found enough users, signing ( waiting %s )"),
QT_TRANSLATE_NOOP("yaadi-core", "Found enough users, signing ..."),
QT_TRANSLATE_NOOP("yaadi-core", "Generate coins (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "How many blocks to check at startup (default: %u, 0 = all)"),
QT_TRANSLATE_NOOP("yaadi-core", "If <category> is not supplied, output all debugging information."),
QT_TRANSLATE_NOOP("yaadi-core", "Importing..."),
QT_TRANSLATE_NOOP("yaadi-core", "Imports blocks from external blk000??.dat file"),
QT_TRANSLATE_NOOP("yaadi-core", "Include IP addresses in debug output (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Incompatible mode."),
QT_TRANSLATE_NOOP("yaadi-core", "Incompatible version."),
QT_TRANSLATE_NOOP("yaadi-core", "Incorrect or no genesis block found. Wrong datadir for network?"),
QT_TRANSLATE_NOOP("yaadi-core", "Information"),
QT_TRANSLATE_NOOP("yaadi-core", "Initialization sanity check failed. yaadi Core is shutting down."),
QT_TRANSLATE_NOOP("yaadi-core", "Input is not valid."),
QT_TRANSLATE_NOOP("yaadi-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("yaadi-core", "Insufficient funds."),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid -onion address or hostname: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid amount for -maxtxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid amount for -mintxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid amount for -reservebalance=<amount>"),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid amount"),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid masternodeprivkey. Please see documenation."),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid netmask specified in -whitelist: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid port detected in masternode.conf"),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid private key."),
QT_TRANSLATE_NOOP("yaadi-core", "Invalid script detected."),
QT_TRANSLATE_NOOP("yaadi-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Last Obfuscation was too recent."),
QT_TRANSLATE_NOOP("yaadi-core", "Last successful Obfuscation action was too recent."),
QT_TRANSLATE_NOOP("yaadi-core", "Limit size of signature cache to <n> entries (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Line: %d"),
QT_TRANSLATE_NOOP("yaadi-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Listen for connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("yaadi-core", "Loading block index..."),
QT_TRANSLATE_NOOP("yaadi-core", "Loading budget cache..."),
QT_TRANSLATE_NOOP("yaadi-core", "Loading masternode cache..."),
QT_TRANSLATE_NOOP("yaadi-core", "Loading masternode payment cache..."),
QT_TRANSLATE_NOOP("yaadi-core", "Loading sporks..."),
QT_TRANSLATE_NOOP("yaadi-core", "Loading wallet... (%3.2f %%)"),
QT_TRANSLATE_NOOP("yaadi-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("yaadi-core", "Location of the auth cookie (default: data dir)"),
QT_TRANSLATE_NOOP("yaadi-core", "Lock is already in place."),
QT_TRANSLATE_NOOP("yaadi-core", "Lock masternodes from masternode configuration file (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Lookup(): Invalid -proxy address or hostname: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Maintain at most <n> connections to peers (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Masternode options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Masternode queue is full."),
QT_TRANSLATE_NOOP("yaadi-core", "Masternode:"),
QT_TRANSLATE_NOOP("yaadi-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Mint did not make it into blockchain"),
QT_TRANSLATE_NOOP("yaadi-core", "Missing input transaction information."),
QT_TRANSLATE_NOOP("yaadi-core", "Mixing in progress..."),
QT_TRANSLATE_NOOP("yaadi-core", "Need address because change is not exact"),
QT_TRANSLATE_NOOP("yaadi-core", "Need to specify a port with -whitebind: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "No Masternodes detected."),
QT_TRANSLATE_NOOP("yaadi-core", "No compatible Masternode found."),
QT_TRANSLATE_NOOP("yaadi-core", "No funds detected in need of denominating."),
QT_TRANSLATE_NOOP("yaadi-core", "No matching denominations found for mixing."),
QT_TRANSLATE_NOOP("yaadi-core", "Node relay options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Non-standard public key detected."),
QT_TRANSLATE_NOOP("yaadi-core", "Not compatible with existing transactions."),
QT_TRANSLATE_NOOP("yaadi-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("yaadi-core", "Not in the Masternode list."),
QT_TRANSLATE_NOOP("yaadi-core", "Number of automatic wallet backups (default: 10)"),
QT_TRANSLATE_NOOP("yaadi-core", "Number of custom location backups to retain (default: %d)"),
QT_TRANSLATE_NOOP("yaadi-core", "Obfuscation is idle."),
QT_TRANSLATE_NOOP("yaadi-core", "Obfuscation request complete:"),
QT_TRANSLATE_NOOP("yaadi-core", "Obfuscation request incomplete:"),
QT_TRANSLATE_NOOP("yaadi-core", "Only accept block chain matching built-in checkpoints (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"),
QT_TRANSLATE_NOOP("yaadi-core", "Options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("yaadi-core", "Percentage of automatically minted Zerocoin (1-100, default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Preparing for resync..."),
QT_TRANSLATE_NOOP("yaadi-core", "Prepend debug output with timestamp (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Print version and exit"),
QT_TRANSLATE_NOOP("yaadi-core", "RPC server options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Randomly drop 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("yaadi-core", "Randomly fuzz 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("yaadi-core", "Rebuild block chain index from current blk000??.dat files"),
QT_TRANSLATE_NOOP("yaadi-core", "Receive and display P2P network alerts (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Reindex the yaadi and zyaadi money supply statistics"),
QT_TRANSLATE_NOOP("yaadi-core", "Reindex the accumulator database"),
QT_TRANSLATE_NOOP("yaadi-core", "Reindexing zerocoin database..."),
QT_TRANSLATE_NOOP("yaadi-core", "Reindexing zerocoin failed"),
QT_TRANSLATE_NOOP("yaadi-core", "Relay and mine data carrier transactions (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Relay non-P2SH multisig (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("yaadi-core", "Rescanning..."),
QT_TRANSLATE_NOOP("yaadi-core", "ResetMintZerocoin finished: "),
QT_TRANSLATE_NOOP("yaadi-core", "ResetSpentZerocoin finished: "),
QT_TRANSLATE_NOOP("yaadi-core", "Run a thread to flush wallet periodically (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("yaadi-core", "Selected coins value is less than payment target"),
QT_TRANSLATE_NOOP("yaadi-core", "Send transactions as zero-fee transactions if possible (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Session not complete!"),
QT_TRANSLATE_NOOP("yaadi-core", "Session timed out."),
QT_TRANSLATE_NOOP("yaadi-core", "Set database cache size in megabytes (%d to %d, default: %d)"),
QT_TRANSLATE_NOOP("yaadi-core", "Set external address:port to get to this masternode (example: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", "Set key pool size to <n> (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Set maximum block size in bytes (default: %d)"),
QT_TRANSLATE_NOOP("yaadi-core", "Set minimum block size in bytes (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Set the Maximum reorg depth (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Set the masternode private key"),
QT_TRANSLATE_NOOP("yaadi-core", "Set the number of threads to service RPC calls (default: %d)"),
QT_TRANSLATE_NOOP("yaadi-core", "Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Show all debugging options (usage: --help -help-debug)"),
QT_TRANSLATE_NOOP("yaadi-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("yaadi-core", "Signing failed."),
QT_TRANSLATE_NOOP("yaadi-core", "Signing timed out."),
QT_TRANSLATE_NOOP("yaadi-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("yaadi-core", "Specify configuration file (default: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"),
QT_TRANSLATE_NOOP("yaadi-core", "Specify data directory"),
QT_TRANSLATE_NOOP("yaadi-core", "Specify masternode configuration file (default: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", "Specify pid file (default: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("yaadi-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("yaadi-core", "Spend Valid"),
QT_TRANSLATE_NOOP("yaadi-core", "Spend unconfirmed change when sending transactions (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Staking options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Stop running after importing blocks from disk (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Submitted following entries to masternode: %u / %d"),
QT_TRANSLATE_NOOP("yaadi-core", "Submitted to masternode, waiting for more entries ( %u / %d ) %s"),
QT_TRANSLATE_NOOP("yaadi-core", "Submitted to masternode, waiting in queue %s"),
QT_TRANSLATE_NOOP("yaadi-core", "SwiftX options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Synchronization failed"),
QT_TRANSLATE_NOOP("yaadi-core", "Synchronization finished"),
QT_TRANSLATE_NOOP("yaadi-core", "Synchronization pending..."),
QT_TRANSLATE_NOOP("yaadi-core", "Synchronizing budgets..."),
QT_TRANSLATE_NOOP("yaadi-core", "Synchronizing masternode winners..."),
QT_TRANSLATE_NOOP("yaadi-core", "Synchronizing masternodes..."),
QT_TRANSLATE_NOOP("yaadi-core", "Synchronizing sporks..."),
QT_TRANSLATE_NOOP("yaadi-core", "Syncing zyaadi wallet..."),
QT_TRANSLATE_NOOP("yaadi-core", "The coin spend has been used"),
QT_TRANSLATE_NOOP("yaadi-core", "The new spend coin transaction did not verify"),
QT_TRANSLATE_NOOP("yaadi-core", "The selected mint coin is an invalid coin"),
QT_TRANSLATE_NOOP("yaadi-core", "The transaction did not verify"),
QT_TRANSLATE_NOOP("yaadi-core", "This help message"),
QT_TRANSLATE_NOOP("yaadi-core", "This is experimental software."),
QT_TRANSLATE_NOOP("yaadi-core", "This is intended for regression testing tools and app development."),
QT_TRANSLATE_NOOP("yaadi-core", "This is not a Masternode."),
QT_TRANSLATE_NOOP("yaadi-core", "Threshold for disconnecting misbehaving peers (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Too many spends needed"),
QT_TRANSLATE_NOOP("yaadi-core", "Tor control port password (default: empty)"),
QT_TRANSLATE_NOOP("yaadi-core", "Tor control port to use if onion listening enabled (default: %s)"),
QT_TRANSLATE_NOOP("yaadi-core", "Transaction Created"),
QT_TRANSLATE_NOOP("yaadi-core", "Transaction Mint Started"),
QT_TRANSLATE_NOOP("yaadi-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("yaadi-core", "Transaction amounts must be positive"),
QT_TRANSLATE_NOOP("yaadi-core", "Transaction created successfully."),
QT_TRANSLATE_NOOP("yaadi-core", "Transaction fees are too high."),
QT_TRANSLATE_NOOP("yaadi-core", "Transaction not valid."),
QT_TRANSLATE_NOOP("yaadi-core", "Transaction too large for fee policy"),
QT_TRANSLATE_NOOP("yaadi-core", "Transaction too large"),
QT_TRANSLATE_NOOP("yaadi-core", "Transmitting final transaction."),
QT_TRANSLATE_NOOP("yaadi-core", "Try to spend with a higher security level to include more coins"),
QT_TRANSLATE_NOOP("yaadi-core", "Trying to spend an already spent serial #, try again."),
QT_TRANSLATE_NOOP("yaadi-core", "Unable to bind to %s on this computer (bind returned error %s)"),
QT_TRANSLATE_NOOP("yaadi-core", "Unable to find transaction containing mint"),
QT_TRANSLATE_NOOP("yaadi-core", "Unable to sign spork message, wrong key?"),
QT_TRANSLATE_NOOP("yaadi-core", "Unable to start HTTP server. See debug log for details."),
QT_TRANSLATE_NOOP("yaadi-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "Unknown state: id = %u"),
QT_TRANSLATE_NOOP("yaadi-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("yaadi-core", "Use UPnP to map the listening port (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("yaadi-core", "Use a custom max chain reorganization depth (default: %u)"),
QT_TRANSLATE_NOOP("yaadi-core", "Use the test network"),
QT_TRANSLATE_NOOP("yaadi-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("yaadi-core", "Value is below the smallest available denomination (= 1) of zyaadi"),
QT_TRANSLATE_NOOP("yaadi-core", "Value more than Obfuscation pool maximum allows."),
QT_TRANSLATE_NOOP("yaadi-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("yaadi-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("yaadi-core", "Version 1 zyaadi require a security level of 100 to successfully spend."),
QT_TRANSLATE_NOOP("yaadi-core", "Wallet %s resides outside data directory %s"),
QT_TRANSLATE_NOOP("yaadi-core", "Wallet is locked."),
QT_TRANSLATE_NOOP("yaadi-core", "Wallet needed to be rewritten: restart yaadi Core to complete"),
QT_TRANSLATE_NOOP("yaadi-core", "Wallet options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Wallet window title"),
QT_TRANSLATE_NOOP("yaadi-core", "Warning"),
QT_TRANSLATE_NOOP("yaadi-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("yaadi-core", "Warning: Unsupported argument -benchmark ignored, use -debug=bench."),
QT_TRANSLATE_NOOP("yaadi-core", "Warning: Unsupported argument -debugnet ignored, use -debug=net."),
QT_TRANSLATE_NOOP("yaadi-core", "Will retry..."),
QT_TRANSLATE_NOOP("yaadi-core", "You don't have enough Zerocoins in your wallet"),
QT_TRANSLATE_NOOP("yaadi-core", "You need to rebuild the database using -reindex to change -txindex"),
QT_TRANSLATE_NOOP("yaadi-core", "Your entries added successfully."),
QT_TRANSLATE_NOOP("yaadi-core", "Your transaction was accepted into the pool!"),
QT_TRANSLATE_NOOP("yaadi-core", "Zapping all transactions from wallet..."),
QT_TRANSLATE_NOOP("yaadi-core", "ZeroMQ notification options:"),
QT_TRANSLATE_NOOP("yaadi-core", "Zerocoin options:"),
QT_TRANSLATE_NOOP("yaadi-core", "isValid(): Invalid -proxy address or hostname: '%s'"),
QT_TRANSLATE_NOOP("yaadi-core", "on startup"),
QT_TRANSLATE_NOOP("yaadi-core", "wallet.dat corrupt, salvage failed"),
};
|
/*
* Copyright 2021 BaiQiang
*
* Use of this source code is governed by a MIT license that can be
* found in the LICENSE file.
*/
#include "FlexLayout.h"
#include "LinearLayout.h"
#include "FlowLayout.h"
#include <vector>
#include <iostream>
#define COUNT 4
void genView(Layout* layout, int index) {
Item* item = new Item();
// item->setFlexGrow(1);
item->setWidth(500);
item->setHeight(300);
// item->setHeightPercent(0.25);
layout->addItem(item);
return;
switch (index) {
case 0:
item->setAlignSelf(AlignSelf::FLEX_END);
break;
case 1:
item->setFlexGrow(1);
break;
case 2:
item->setFlexBasisPercent(0.5);
break;
case 3:
item->setAlignSelf(AlignSelf::BASELINE);
break;
default:
break;
}
}
void measure(Layout* layout) {
for (int i = 0; i < COUNT; i++) {
genView(layout, i);
}
auto measureSpec = Item::MeasureSpec::makeMeasureSpec(10000, Item::MeasureSpec::AT_MOST);
layout->measure(measureSpec, measureSpec);
layout->layout(0, 0, layout->getMeasuredWidth(), layout->getMeasuredHeight());
for (int i = 0; i < COUNT; i++) {
std::cout << "w:" << layout->getChildAt(i)->getMeasuredWidth()
<< ", h:" << layout->getChildAt(i)->getMeasuredHeight()
<< ", l:" << layout->getChildAt(i)->getLeft()
<< ", t:" << layout->getChildAt(i)->getTop() << std::endl;
}
}
int main() {
FlexLayout flexLayout;
flexLayout.setFlexWrap(FlexWrap::WRAP);
flexLayout.setMaxLine(100);
flexLayout.setAlignItems(AlignItems::FLEX_START);
// layout.setJustifyContent(JustifyContent::CENTER);
FlowLayout flowLayout;
// measure(&flowLayout);
LinearLayout linearLayout;
linearLayout.setOrientation(LinearLayout::HORIZONTAL);
measure(&flowLayout);
}
|
#include <stdio.h>
#include <stdlib.h>
#include <RemoxlyApi.h>
#if defined(_WIN32)
# include <windows.h>
# define sleep_millis(x) Sleep(x)
#elif defined(__APPLE__)
# include <unistd.h>
# define sleep_millis(x) usleep(x * 1000)
#endif
/* ------------------------------------- */
#define EL_ID_VIEW_OPTION 1
#define EL_ID_SAVE_BUTTON 2
#define EL_ID_SET_OBJECT_NAME 3
/* ------------------------------------- */
static void on_gui_event(rx_context& rx, rx_element& el, void* user);
/* ------------------------------------- */
int main() {
printf("\n\nRemoxly Example\n\n");
rx_context* rx = rx_create(on_gui_event, NULL);
if (NULL == rx) {
printf("Error: failed to create the remoxly context.\n");
exit(EXIT_FAILURE);
}
/* Main section */
bool draw_enabled = false;
int num_particles = 0;
int num_passes = 0;
float max_force = 0.0f;
float gravity = 9.8f;
int max_lifetime = 100;
const char* view_opts[] = { "Front view", "Side view", "Camera path", NULL };
bool show_normals = false;
bool show_edges = false;
std::string filename;
rx_add_section(rx, "Main");
rx_add_group(rx, "Effects");
rx_add_toggle(rx, "Enable drawing", draw_enabled);
rx_add_slider_int(rx, "Number of particles", num_particles, 1, 1000000, 10);
rx_add_slider_int(rx, "Number of render passes", num_passes, 1, 16, 1);
rx_add_separator(rx);
rx_add_slider_float(rx, "Max force", max_force, 0.001f, 10.0f, 0.01f);
rx_add_slider_float(rx, "Gravity", gravity, 0.001f, 9.8f, 0.01f);
rx_add_slider_int(rx, "Max life time", max_lifetime, 1, 240, 1);
rx_add_separator(rx);
rx_add_select(rx, "View", EL_ID_VIEW_OPTION, view_opts);
rx_add_toggle(rx, "Show normals", show_normals);
rx_add_toggle(rx, "Show edges", show_edges);
rx_add_separator(rx);
rx_add_input(rx, "Filename", filename);
rx_add_button(rx, "Save properties", EL_ID_SAVE_BUTTON);
/* Properties Section */
bool show_name = false;
bool show_axis = false;
bool show_wire = false;
bool show_bounds = false;
int start_frame = 0;
int end_frame = 100;
std::string object_name;
rx_add_section(rx, "Object");
rx_add_group(rx, "Display");
rx_add_toggle(rx, "Name", show_name);
rx_add_toggle(rx, "Axis", show_axis);
rx_add_toggle(rx, "Wire", show_wire);
rx_add_toggle(rx, "Bounds", show_bounds);
rx_add_separator(rx);
rx_add_slider_int(rx, "Start frame", start_frame, 1, 1000, 1);
rx_add_slider_int(rx, "End frame", end_frame, 1, 1000, 1);
rx_add_separator(rx);
rx_add_input(rx, "Object name", object_name);
rx_add_button(rx, "Set object name", EL_ID_SET_OBJECT_NAME);
while (true) {
rx_update(rx);
sleep_millis(16);
}
return 0;
}
/* ------------------------------------- */
static void on_gui_event(rx_context& rx, rx_element& el, void* user) {
switch (rx_get_id(el)) {
case EL_ID_VIEW_OPTION: {
printf("View option changed.\n");
break;
}
case EL_ID_SAVE_BUTTON: {
printf("Save button pressed.\n");
break;
}
case EL_ID_SET_OBJECT_NAME: {
printf("Set object name.\n");
break;
}
default: {
printf("Error: unhandled remoxly element id.\n");
break;
}
}
}
/* ------------------------------------- */
|
#ifndef __CIGAR__
#define __CIGAR__
#include <vector>
#include <string>
#include "SAM_entry.hpp"
using namespace std;
namespace Cigar {
typedef struct {
unsigned long len;
char code;
} t_cigar;
vector<t_cigar> parse_cigar(string& cigar_txt);
string construct_cigar(vector<alignment_segment>& segments,
unsigned int read_length,
const string& genome_seq,
char strand = NULL);
char check_intron_consensus(unsigned long prev_exon_rend, unsigned long next_exon_lend,
const string& genome_seq, char strand);
}
#endif
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/monitor/v20180724/model/UnBindingAllPolicyObjectRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Monitor::V20180724::Model;
using namespace rapidjson;
using namespace std;
UnBindingAllPolicyObjectRequest::UnBindingAllPolicyObjectRequest() :
m_moduleHasBeenSet(false),
m_groupIdHasBeenSet(false)
{
}
string UnBindingAllPolicyObjectRequest::ToJsonString() const
{
Document d;
d.SetObject();
Document::AllocatorType& allocator = d.GetAllocator();
if (m_moduleHasBeenSet)
{
Value iKey(kStringType);
string key = "Module";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_module.c_str(), allocator).Move(), allocator);
}
if (m_groupIdHasBeenSet)
{
Value iKey(kStringType);
string key = "GroupId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_groupId, allocator);
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string UnBindingAllPolicyObjectRequest::GetModule() const
{
return m_module;
}
void UnBindingAllPolicyObjectRequest::SetModule(const string& _module)
{
m_module = _module;
m_moduleHasBeenSet = true;
}
bool UnBindingAllPolicyObjectRequest::ModuleHasBeenSet() const
{
return m_moduleHasBeenSet;
}
int64_t UnBindingAllPolicyObjectRequest::GetGroupId() const
{
return m_groupId;
}
void UnBindingAllPolicyObjectRequest::SetGroupId(const int64_t& _groupId)
{
m_groupId = _groupId;
m_groupIdHasBeenSet = true;
}
bool UnBindingAllPolicyObjectRequest::GroupIdHasBeenSet() const
{
return m_groupIdHasBeenSet;
}
|
#include "ARC_Modbus_Struct.h"
#include <string.h>
#include <stdlib.h>
namespace ARC_Modbus
{
Command_Parameter::Command_Parameter()
{
}
Command_Parameter::~Command_Parameter()
{
}
modbus_slave_base::modbus_slave_base()
{
this->Event_TxWork = 0;
this->CallBack_Coils = 0;
this->CallBack_InputCoils = 0;
this->CallBack_Register = 0;
this->CallBack_InputRegs = 0;
}
modbus_slave_base::~modbus_slave_base()
{
}
coder_base::coder_base()
{
}
coder_base::~coder_base()
{
}
void coder_base::Initial(int iSlaveID)
{
this->slave_id = iSlaveID;
}
short CRC16(const char *iBytes, unsigned short iLength)
{
// ref: free modbus lib mbcrc.c
static const unsigned char aucCRCHi[] = {
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40
};
static const unsigned char aucCRCLo[] = {
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7,
0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E,
0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9,
0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC,
0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32,
0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D,
0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38,
0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF,
0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1,
0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4,
0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB,
0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA,
0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0,
0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97,
0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E,
0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89,
0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83,
0x41, 0x81, 0x80, 0x40
};
unsigned char ucCRCHi = 0xFF;
unsigned char ucCRCLo = 0xFF;
int iIndex;
while (iLength--)
{
iIndex = ucCRCLo ^ *(iBytes++);
ucCRCLo = (unsigned char)(ucCRCHi ^ aucCRCHi[iIndex]);
ucCRCHi = aucCRCLo[iIndex];
}
return (unsigned short)(ucCRCHi << 8 | ucCRCLo);
}
char LRC_String(const char* iString, unsigned int iLength)
{
// https://just9x.wordpress.com/2009/09/03/modbus-asscii-lrc/
if (iLength % 2 != 0)
{
// 字串不是2的倍數沒辦法全部解成byte(2個字解成1個byte)
return 0;
}
else
{
unsigned char ucLRC = 0; /* LRC char initialized */
char temp_str[3];
temp_str[2] = 0;
char str2byte;
while (iLength)
{
memcpy(temp_str, iString, 2);
str2byte = (unsigned char)strtol(temp_str, 0, 16);
iString = iString + 2;
iLength -= 2;
ucLRC += str2byte; /* Add buffer byte without carry */
}
ucLRC = (char)(-((char)ucLRC));
return ucLRC;
}
}
char LRC(const char *iBytes, unsigned short iLength)
{
unsigned char ucLRC = 0; /* LRC char initialized */
while (iLength--)
{
ucLRC += *iBytes++; /* Add buffer byte without carry */
}
/* Return twos complement */
ucLRC = (char)(-((char)ucLRC));
return ucLRC;
}
modbus_master_base::modbus_master_base()
{
this->step = polling_step_send_request;
this->check_time = 0;
this->task_size = 0;
this->task_count = 0;
this->Event_TxWork = 0;
this->CallBack_WriteCoilsRequest = 0;
this->CallBack_WriteRegsRequest = 0;
}
modbus_master_base::~modbus_master_base()
{
}
bool modbus_master_base::Add_PollingTask(ARC_Modbus::PollingTaskRef iTask)
{
if (this->task_size >= MAX_TASK_SIZE)
{
return false;
}
else
{
this->task_lists[this->task_size++] = iTask;
return true;
}
}
void modbus_master_base::Clear_PollingTask()
{
this->task_size = 0;
this->task_count = 0;
for (int i = 0; i < MAX_TASK_SIZE; i++)
{
this->task_lists[i].Address = 0;
this->task_lists[i].Number = 0;
this->task_lists[i].SlaveID = 0;
this->task_lists[i].Type = PollingTaskType_None;
}
}
pkg::pkg()
{
}
pkg::~pkg()
{
}
void request_response_base::set_bit(char* iPtr, unsigned short iIndex, bool iEnable)
{
// http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c
int temp_idx = iIndex;
if (iEnable)
{
// Setting a bit, number |= 1 << x;
iPtr[temp_idx / 8] |= (1 << (temp_idx % 8));
}
else
{
// Clearing a bit, number ^= 1 << x;
iPtr[temp_idx / 8] &= ~(1 << (temp_idx % 8));
}
}
bool request_response_base::get_bit(char* iPtr, unsigned short iIndex)
{
// http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c
// Checking a bit, bit = (number >> x) & 1;
int temp_idx = iIndex;
return (iPtr[temp_idx / 8] >> (temp_idx % 8)) & 1;
}
void request_response_base::set_int16(char* iPtr, unsigned short iIndex, short iValue)
{
tu_convert16 cTool;
cTool.wValue = iValue;
iPtr[iIndex*2] = cTool.cValue[1];
iPtr[iIndex*2+1] = cTool.cValue[0];
}
short request_response_base::get_int16(char* iPtr, unsigned short iIndex)
{
tu_convert16 cTool;
cTool.cValue[1] = iPtr[iIndex*2];
cTool.cValue[0] = iPtr[iIndex*2+1];
return cTool.wValue;
}
PollingTaskRef::PollingTaskRef()
{
this->Address = 0;
this->Number = 0;
this->SlaveID = 0;
this->Type = PollingTaskType_None;
}
PollingTaskRef::~PollingTaskRef()
{
}
}
|
#include "DataFormats/METReco/interface/HcalCaloFlagTool.h"
#include <cstring>
#include <cstdio>
HcalCaloFlagTool::HcalCaloFlagTool(const std::string& releaseName)
: releaseName_(releaseName), standardFormat_(false), major_(0), minor_(0), patch_(0), subpatch_(0) {
int fields = sscanf(releaseName.c_str(), "CMSSW_%d_%d_%d_%d", &major_, &minor_, &patch_, &subpatch_);
if (fields >= 3)
standardFormat_ = true;
}
std::string HcalCaloFlagTool::getFieldName(HcalSubdetector sd, int bit) const { return ""; }
int HcalCaloFlagTool::getFieldWidth(HcalSubdetector sd, int bit) const { return 0; }
int HcalCaloFlagTool::getFieldStart(HcalSubdetector sd, const std::string& field) const { return 0; }
int HcalCaloFlagTool::getFieldWidth(HcalSubdetector sd, const std::string& field) const { return 0; }
bool HcalCaloFlagTool::hasField(HcalSubdetector sd, const std::string& field) const {
if (standardFormat_) {
if (major_ < 3)
return false;
}
return getFieldWidth(sd, field) > 0;
}
bool HcalCaloFlagTool::hasField(HcalSubdetector sd, int bit) const {
if (standardFormat_) {
if (major_ < 3)
return false;
}
return getFieldWidth(sd, bit) > 0;
}
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#include <stdio.h>
#include "rustllvm.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/AutoUpgrade.h"
#include "llvm/Support/CBindingWrapping.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#if LLVM_VERSION_GE(4, 0)
#include "llvm/Transforms/IPO/AlwaysInliner.h"
#endif
#include "llvm-c/Transforms/PassManagerBuilder.h"
using namespace llvm;
using namespace llvm::legacy;
extern cl::opt<bool> EnableARMEHABI;
typedef struct LLVMOpaquePass *LLVMPassRef;
typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
LLVMPassManagerBuilderRef)
extern "C" void LLVMInitializePasses() {
PassRegistry &Registry = *PassRegistry::getPassRegistry();
initializeCore(Registry);
initializeCodeGen(Registry);
initializeScalarOpts(Registry);
initializeVectorization(Registry);
initializeIPO(Registry);
initializeAnalysis(Registry);
#if LLVM_VERSION_EQ(3, 7)
initializeIPA(Registry);
#endif
initializeTransformUtils(Registry);
initializeInstCombine(Registry);
initializeInstrumentation(Registry);
initializeTarget(Registry);
}
enum class LLVMRustPassKind {
Other,
Function,
Module,
};
static LLVMRustPassKind to_rust(PassKind kind) {
switch (kind) {
case PT_Function:
return LLVMRustPassKind::Function;
case PT_Module:
return LLVMRustPassKind::Module;
default:
return LLVMRustPassKind::Other;
}
}
extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
StringRef SR(PassName);
PassRegistry *PR = PassRegistry::getPassRegistry();
const PassInfo *PI = PR->getPassInfo(SR);
if (PI) {
return wrap(PI->createPass());
}
return nullptr;
}
extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef rust_pass) {
assert(rust_pass);
Pass *pass = unwrap(rust_pass);
return to_rust(pass->getPassKind());
}
extern "C" void LLVMRustAddPass(LLVMPassManagerRef PM, LLVMPassRef rust_pass) {
assert(rust_pass);
Pass *pass = unwrap(rust_pass);
PassManagerBase *pm = unwrap(PM);
pm->add(pass);
}
#ifdef LLVM_COMPONENT_X86
#define SUBTARGET_X86 SUBTARGET(X86)
#else
#define SUBTARGET_X86
#endif
#ifdef LLVM_COMPONENT_ARM
#define SUBTARGET_ARM SUBTARGET(ARM)
#else
#define SUBTARGET_ARM
#endif
#ifdef LLVM_COMPONENT_AARCH64
#define SUBTARGET_AARCH64 SUBTARGET(AArch64)
#else
#define SUBTARGET_AARCH64
#endif
#ifdef LLVM_COMPONENT_MIPS
#define SUBTARGET_MIPS SUBTARGET(Mips)
#else
#define SUBTARGET_MIPS
#endif
#ifdef LLVM_COMPONENT_POWERPC
#define SUBTARGET_PPC SUBTARGET(PPC)
#else
#define SUBTARGET_PPC
#endif
#ifdef LLVM_COMPONENT_SYSTEMZ
#define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
#else
#define SUBTARGET_SYSTEMZ
#endif
#ifdef LLVM_COMPONENT_MSP430
#define SUBTARGET_MSP430 SUBTARGET(MSP430)
#else
#define SUBTARGET_MSP430
#endif
#define GEN_SUBTARGETS \
SUBTARGET_X86 \
SUBTARGET_ARM \
SUBTARGET_AARCH64 \
SUBTARGET_MIPS \
SUBTARGET_PPC \
SUBTARGET_SYSTEMZ \
SUBTARGET_MSP430
#define SUBTARGET(x) \
namespace llvm { \
extern const SubtargetFeatureKV x##FeatureKV[]; \
extern const SubtargetFeatureKV x##SubTypeKV[]; \
}
GEN_SUBTARGETS
#undef SUBTARGET
extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
const char *feature) {
TargetMachine *Target = unwrap(TM);
const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
const FeatureBitset &Bits = MCInfo->getFeatureBits();
const llvm::SubtargetFeatureKV *FeatureEntry;
#define SUBTARGET(x) \
if (MCInfo->isCPUStringValid(x##SubTypeKV[0].Key)) { \
FeatureEntry = x##FeatureKV; \
} else
GEN_SUBTARGETS { return false; }
#undef SUBTARGET
while (strcmp(feature, FeatureEntry->Key) != 0)
FeatureEntry++;
return (Bits & FeatureEntry->Value) == FeatureEntry->Value;
}
enum class LLVMRustCodeModel {
Other,
Default,
JITDefault,
Small,
Kernel,
Medium,
Large,
};
static CodeModel::Model from_rust(LLVMRustCodeModel model) {
switch (model) {
case LLVMRustCodeModel::Default:
return CodeModel::Default;
case LLVMRustCodeModel::JITDefault:
return CodeModel::JITDefault;
case LLVMRustCodeModel::Small:
return CodeModel::Small;
case LLVMRustCodeModel::Kernel:
return CodeModel::Kernel;
case LLVMRustCodeModel::Medium:
return CodeModel::Medium;
case LLVMRustCodeModel::Large:
return CodeModel::Large;
default:
llvm_unreachable("Bad CodeModel.");
}
}
enum class LLVMRustCodeGenOptLevel {
Other,
None,
Less,
Default,
Aggressive,
};
static CodeGenOpt::Level from_rust(LLVMRustCodeGenOptLevel level) {
switch (level) {
case LLVMRustCodeGenOptLevel::None:
return CodeGenOpt::None;
case LLVMRustCodeGenOptLevel::Less:
return CodeGenOpt::Less;
case LLVMRustCodeGenOptLevel::Default:
return CodeGenOpt::Default;
case LLVMRustCodeGenOptLevel::Aggressive:
return CodeGenOpt::Aggressive;
default:
llvm_unreachable("Bad CodeGenOptLevel.");
}
}
#if LLVM_RUSTLLVM
/// getLongestEntryLength - Return the length of the longest entry in the table.
///
static size_t getLongestEntryLength(ArrayRef<SubtargetFeatureKV> Table) {
size_t MaxLen = 0;
for (auto &I : Table)
MaxLen = std::max(MaxLen, std::strlen(I.Key));
return MaxLen;
}
extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
const TargetMachine *Target = unwrap(TM);
const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
const ArrayRef<SubtargetFeatureKV> CPUTable = MCInfo->getCPUTable();
unsigned MaxCPULen = getLongestEntryLength(CPUTable);
printf("Available CPUs for this target:\n");
for (auto &CPU : CPUTable)
printf(" %-*s - %s.\n", MaxCPULen, CPU.Key, CPU.Desc);
printf("\n");
}
extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
const TargetMachine *Target = unwrap(TM);
const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
printf("Available features for this target:\n");
for (auto &Feature : FeatTable)
printf(" %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
printf("\n");
printf("Use +feature to enable a feature, or -feature to disable it.\n"
"For example, rustc -C -target-cpu=mycpu -C "
"target-feature=+feature1,-feature2\n\n");
}
#else
extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
printf("Target CPU help is not supported by this LLVM version.\n\n");
}
extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
printf("Target features help is not supported by this LLVM version.\n\n");
}
#endif
extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
const char *triple, const char *cpu, const char *feature,
LLVMRustCodeModel rust_CM, LLVMRelocMode Reloc,
LLVMRustCodeGenOptLevel rust_OptLevel, bool UseSoftFloat,
bool PositionIndependentExecutable, bool FunctionSections,
bool DataSections) {
#if LLVM_VERSION_LE(3, 8)
Reloc::Model RM;
#else
Optional<Reloc::Model> RM;
#endif
auto CM = from_rust(rust_CM);
auto OptLevel = from_rust(rust_OptLevel);
switch (Reloc) {
case LLVMRelocStatic:
RM = Reloc::Static;
break;
case LLVMRelocPIC:
RM = Reloc::PIC_;
break;
case LLVMRelocDynamicNoPic:
RM = Reloc::DynamicNoPIC;
break;
default:
#if LLVM_VERSION_LE(3, 8)
RM = Reloc::Default;
#endif
break;
}
std::string Error;
Triple Trip(Triple::normalize(triple));
const llvm::Target *TheTarget =
TargetRegistry::lookupTarget(Trip.getTriple(), Error);
if (TheTarget == nullptr) {
LLVMRustSetLastError(Error.c_str());
return nullptr;
}
StringRef real_cpu = cpu;
if (real_cpu == "native") {
real_cpu = sys::getHostCPUName();
}
TargetOptions Options;
#if LLVM_VERSION_LE(3, 8)
Options.PositionIndependentExecutable = PositionIndependentExecutable;
#endif
Options.FloatABIType = FloatABI::Default;
if (UseSoftFloat) {
Options.FloatABIType = FloatABI::Soft;
}
Options.DataSections = DataSections;
Options.FunctionSections = FunctionSections;
TargetMachine *TM = TheTarget->createTargetMachine(
Trip.getTriple(), real_cpu, feature, Options, RM, CM, OptLevel);
return wrap(TM);
}
extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
delete unwrap(TM);
}
// Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis
// passes for a target to a pass manager. We export that functionality through
// this function.
extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM,
LLVMPassManagerRef PMR,
LLVMModuleRef M) {
PassManagerBase *PM = unwrap(PMR);
PM->add(
createTargetTransformInfoWrapperPass(unwrap(TM)->getTargetIRAnalysis()));
}
extern "C" void LLVMRustConfigurePassManagerBuilder(
LLVMPassManagerBuilderRef PMB, LLVMRustCodeGenOptLevel OptLevel,
bool MergeFunctions, bool SLPVectorize, bool LoopVectorize) {
// Ignore mergefunc for now as enabling it causes crashes.
// unwrap(PMB)->MergeFunctions = MergeFunctions;
unwrap(PMB)->SLPVectorize = SLPVectorize;
unwrap(PMB)->OptLevel = from_rust(OptLevel);
unwrap(PMB)->LoopVectorize = LoopVectorize;
}
// Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
// field of a PassManagerBuilder, we expose our own method of doing so.
extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMB,
LLVMModuleRef M,
bool DisableSimplifyLibCalls) {
Triple TargetTriple(unwrap(M)->getTargetTriple());
TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
if (DisableSimplifyLibCalls)
TLI->disableAllFunctions();
unwrap(PMB)->LibraryInfo = TLI;
}
// Unfortunately, the LLVM C API doesn't provide a way to create the
// TargetLibraryInfo pass, so we use this method to do so.
extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMB, LLVMModuleRef M,
bool DisableSimplifyLibCalls) {
Triple TargetTriple(unwrap(M)->getTargetTriple());
TargetLibraryInfoImpl TLII(TargetTriple);
if (DisableSimplifyLibCalls)
TLII.disableAllFunctions();
unwrap(PMB)->add(new TargetLibraryInfoWrapperPass(TLII));
}
// Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
// all the functions in a module, so we do that manually here. You'll find
// similar code in clang's BackendUtil.cpp file.
extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PM,
LLVMModuleRef M) {
llvm::legacy::FunctionPassManager *P =
unwrap<llvm::legacy::FunctionPassManager>(PM);
P->doInitialization();
// Upgrade all calls to old intrinsics first.
for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
++I)
if (!I->isDeclaration())
P->run(*I);
P->doFinalization();
}
extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
// Initializing the command-line options more than once is not allowed. So,
// check if they've already been initialized. (This could happen if we're
// being called from rustpkg, for example). If the arguments change, then
// that's just kinda unfortunate.
static bool initialized = false;
if (initialized)
return;
initialized = true;
cl::ParseCommandLineOptions(Argc, Argv);
}
enum class LLVMRustFileType {
Other,
AssemblyFile,
ObjectFile,
};
static TargetMachine::CodeGenFileType from_rust(LLVMRustFileType type) {
switch (type) {
case LLVMRustFileType::AssemblyFile:
return TargetMachine::CGFT_AssemblyFile;
case LLVMRustFileType::ObjectFile:
return TargetMachine::CGFT_ObjectFile;
default:
llvm_unreachable("Bad FileType.");
}
}
extern "C" LLVMRustResult
LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
LLVMModuleRef M, const char *path,
LLVMRustFileType rust_FileType) {
llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
auto FileType = from_rust(rust_FileType);
std::string ErrorInfo;
std::error_code EC;
raw_fd_ostream OS(path, EC, sys::fs::F_None);
if (EC)
ErrorInfo = EC.message();
if (ErrorInfo != "") {
LLVMRustSetLastError(ErrorInfo.c_str());
return LLVMRustResult::Failure;
}
unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false);
PM->run(*unwrap(M));
// Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
// stream (OS), so the only real safe place to delete this is here? Don't we
// wish this was written in Rust?
delete PM;
return LLVMRustResult::Success;
}
extern "C" void LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M,
const char *path) {
llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
std::string ErrorInfo;
std::error_code EC;
raw_fd_ostream OS(path, EC, sys::fs::F_None);
if (EC)
ErrorInfo = EC.message();
formatted_raw_ostream FOS(OS);
PM->add(createPrintModulePass(FOS));
PM->run(*unwrap(M));
}
extern "C" void LLVMRustPrintPasses() {
LLVMInitializePasses();
struct MyListener : PassRegistrationListener {
void passEnumerate(const PassInfo *info) {
#if LLVM_VERSION_GE(4, 0)
StringRef PassArg = info->getPassArgument();
StringRef PassName = info->getPassName();
if (!PassArg.empty()) {
// These unsigned->signed casts could theoretically overflow, but
// realistically never will (and even if, the result is implementation
// defined rather plain UB).
printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
(int)PassName.size(), PassName.data());
}
#else
if (info->getPassArgument() && *info->getPassArgument()) {
printf("%15s - %s\n", info->getPassArgument(), info->getPassName());
}
#endif
}
} listener;
PassRegistry *PR = PassRegistry::getPassRegistry();
PR->enumerateWith(&listener);
}
extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMB,
bool AddLifetimes) {
#if LLVM_VERSION_GE(4, 0)
unwrap(PMB)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
#else
unwrap(PMB)->Inliner = createAlwaysInlinerPass(AddLifetimes);
#endif
}
extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **symbols,
size_t len) {
llvm::legacy::PassManager passes;
#if LLVM_VERSION_LE(3, 8)
ArrayRef<const char *> ref(symbols, len);
passes.add(llvm::createInternalizePass(ref));
#else
auto PreserveFunctions = [=](const GlobalValue &GV) {
for (size_t i = 0; i < len; i++) {
if (GV.getName() == symbols[i]) {
return true;
}
}
return false;
};
passes.add(llvm::createInternalizePass(PreserveFunctions));
#endif
passes.run(*unwrap(M));
}
extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
++GV) {
GV->setDoesNotThrow();
Function *F = dyn_cast<Function>(GV);
if (F == nullptr)
continue;
for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
if (isa<InvokeInst>(I)) {
InvokeInst *CI = cast<InvokeInst>(I);
CI->setDoesNotThrow();
}
}
}
}
}
extern "C" void
LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
LLVMTargetMachineRef TMR) {
TargetMachine *Target = unwrap(TMR);
unwrap(Module)->setDataLayout(Target->createDataLayout());
}
extern "C" LLVMTargetDataRef LLVMRustGetModuleDataLayout(LLVMModuleRef M) {
return wrap(&unwrap(M)->getDataLayout());
}
extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
#if LLVM_VERSION_GE(3, 9)
unwrap(M)->setPIELevel(PIELevel::Level::Large);
#endif
}
|
/***************************************************************************
# Copyright (c) 2015, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#include "Framework.h"
#include "D3D12State.h"
#include "API/BlendState.h"
#include "API/RasterizerState.h"
#include "API/VertexLayout.h"
#include "glm/gtc/type_ptr.hpp"
namespace Falcor
{
D3D12_BLEND getD3D12BlendFunc(BlendState::BlendFunc func)
{
switch (func)
{
case BlendState::BlendFunc::Zero:
return D3D12_BLEND_ZERO;
case BlendState::BlendFunc::One:
return D3D12_BLEND_ONE;
case BlendState::BlendFunc::SrcColor:
return D3D12_BLEND_SRC_COLOR;
case BlendState::BlendFunc::OneMinusSrcColor:
return D3D12_BLEND_INV_SRC_COLOR;
case BlendState::BlendFunc::DstColor:
return D3D12_BLEND_DEST_COLOR;
case BlendState::BlendFunc::OneMinusDstColor:
return D3D12_BLEND_INV_DEST_COLOR;
case BlendState::BlendFunc::SrcAlpha:
return D3D12_BLEND_SRC_ALPHA;
case BlendState::BlendFunc::OneMinusSrcAlpha:
return D3D12_BLEND_INV_SRC_ALPHA;
case BlendState::BlendFunc::DstAlpha:
return D3D12_BLEND_DEST_ALPHA;
case BlendState::BlendFunc::OneMinusDstAlpha:
return D3D12_BLEND_INV_DEST_ALPHA;
case BlendState::BlendFunc::BlendFactor:
return D3D12_BLEND_BLEND_FACTOR;
case BlendState::BlendFunc::OneMinusBlendFactor:
return D3D12_BLEND_INV_BLEND_FACTOR;
case BlendState::BlendFunc::SrcAlphaSaturate:
return D3D12_BLEND_SRC_ALPHA_SAT;
case BlendState::BlendFunc::Src1Color:
return D3D12_BLEND_INV_SRC1_COLOR;
case BlendState::BlendFunc::OneMinusSrc1Color:
return D3D12_BLEND_INV_SRC1_COLOR;
case BlendState::BlendFunc::Src1Alpha:
return D3D12_BLEND_SRC1_ALPHA;
case BlendState::BlendFunc::OneMinusSrc1Alpha:
return D3D12_BLEND_INV_SRC1_ALPHA;
default:
should_not_get_here();
return (D3D12_BLEND)0;
}
}
D3D12_BLEND_OP getD3D12BlendOp(BlendState::BlendOp op)
{
switch (op)
{
case BlendState::BlendOp::Add:
return D3D12_BLEND_OP_ADD;
case BlendState::BlendOp::Subtract:
return D3D12_BLEND_OP_SUBTRACT;
case BlendState::BlendOp::ReverseSubtract:
return D3D12_BLEND_OP_REV_SUBTRACT;
case BlendState::BlendOp::Min:
return D3D12_BLEND_OP_MIN;
case BlendState::BlendOp::Max:
return D3D12_BLEND_OP_MAX;
default:
return (D3D12_BLEND_OP)0;
}
}
void initD3D12BlendDesc(const BlendState* pState, D3D12_BLEND_DESC& desc)
{
desc.AlphaToCoverageEnable = dxBool(pState->isAlphaToCoverageEnabled());
desc.IndependentBlendEnable = dxBool(pState->isIndependentBlendEnabled());
for (uint32_t rt = 0; rt < pState->getRtCount(); rt++)
{
const BlendState::Desc::RenderTargetDesc& rtDesc = pState->getRtDesc(rt);
D3D12_RENDER_TARGET_BLEND_DESC& d3dRtDesc = desc.RenderTarget[rt];
d3dRtDesc.BlendEnable = dxBool(rtDesc.blendEnabled);
d3dRtDesc.SrcBlend = getD3D12BlendFunc(rtDesc.srcRgbFunc);
d3dRtDesc.DestBlend = getD3D12BlendFunc(rtDesc.dstRgbFunc);
d3dRtDesc.BlendOp = getD3D12BlendOp(rtDesc.rgbBlendOp);
d3dRtDesc.SrcBlendAlpha = getD3D12BlendFunc(rtDesc.srcAlphaFunc);
d3dRtDesc.DestBlendAlpha = getD3D12BlendFunc(rtDesc.dstAlphaFunc);
d3dRtDesc.BlendOpAlpha = getD3D12BlendOp(rtDesc.alphaBlendOp);
d3dRtDesc.RenderTargetWriteMask = rtDesc.writeMask.writeRed ? D3D12_COLOR_WRITE_ENABLE_RED : 0;
d3dRtDesc.RenderTargetWriteMask |= rtDesc.writeMask.writeGreen ? D3D12_COLOR_WRITE_ENABLE_GREEN : 0;
d3dRtDesc.RenderTargetWriteMask |= rtDesc.writeMask.writeBlue ? D3D12_COLOR_WRITE_ENABLE_BLUE : 0;
d3dRtDesc.RenderTargetWriteMask |= rtDesc.writeMask.writeAlpha ? D3D12_COLOR_WRITE_ENABLE_ALPHA : 0;
}
}
D3D12_FILL_MODE getD3D12FillMode(RasterizerState::FillMode fill)
{
switch (fill)
{
case RasterizerState::FillMode::Wireframe:
return D3D12_FILL_MODE_WIREFRAME;
case RasterizerState::FillMode::Solid:
return D3D12_FILL_MODE_SOLID;
default:
should_not_get_here();
return (D3D12_FILL_MODE)0;
}
}
D3D12_CULL_MODE getD3D12CullMode(RasterizerState::CullMode cull)
{
switch (cull)
{
case Falcor::RasterizerState::CullMode::None:
return D3D12_CULL_MODE_NONE;
case Falcor::RasterizerState::CullMode::Front:
return D3D12_CULL_MODE_FRONT;
case Falcor::RasterizerState::CullMode::Back:
return D3D12_CULL_MODE_BACK;
default:
should_not_get_here();
return (D3D12_CULL_MODE)0;
}
}
void initD3D12RasterizerDesc(const RasterizerState* pState, D3D12_RASTERIZER_DESC& desc)
{
desc = {};
desc.FillMode = getD3D12FillMode(pState->getFillMode());
desc.CullMode = getD3D12CullMode(pState->getCullMode());
desc.FrontCounterClockwise = dxBool(pState->isFrontCounterCW());
desc.DepthBias = pState->getDepthBias();
desc.DepthBiasClamp = 0;
desc.SlopeScaledDepthBias = pState->getSlopeScaledDepthBias();
desc.DepthClipEnable = dxBool(!pState->isDepthClampEnabled()); // Depth-clamp disables depth-clip
// Set the line anti-aliasing mode
desc.AntialiasedLineEnable = dxBool(pState->isLineAntiAliasingEnabled());
desc.MultisampleEnable = desc.AntialiasedLineEnable;
desc.ConservativeRaster = pState->isConservativeRasterizationEnabled() ? D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON : D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
desc.ForcedSampleCount = pState->getForcedSampleCount();
}
D3D12_INPUT_CLASSIFICATION getD3D12InputClass(VertexBufferLayout::InputClass inClass)
{
switch (inClass)
{
case VertexBufferLayout::InputClass::PerVertexData:
return D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
case VertexBufferLayout::InputClass::PerInstanceData:
return D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA;
default:
should_not_get_here();
return (D3D12_INPUT_CLASSIFICATION) - 1;
}
}
void initD3D12VertexLayout(const VertexLayout* pLayout, InputLayoutDesc& layoutDesc)
{
layoutDesc.elements.clear();
layoutDesc.names.clear();
for (size_t vb = 0; vb < pLayout->getBufferCount(); vb++)
{
auto& pVB = pLayout->getBufferLayout(vb);
if (pVB)
{
for (uint32_t elemID = 0; elemID < pVB->getElementCount(); elemID++)
{
D3D12_INPUT_ELEMENT_DESC element;
element.AlignedByteOffset = pVB->getElementOffset(elemID);
element.Format = getDxgiFormat(pVB->getElementFormat(elemID));
element.InputSlot = (uint32_t)vb;
element.InputSlotClass = getD3D12InputClass(pVB->getInputClass());
element.InstanceDataStepRate = pVB->getInstanceStepRate();
const auto& SemanticName = pVB->getElementName(elemID);
layoutDesc.names.push_back(std::make_unique<char[]>(SemanticName.size() + 1));
char* name = layoutDesc.names.back().get();
memcpy(name, SemanticName.c_str(), SemanticName.size());
name[SemanticName.size()] = 0;
for (uint32_t arrayIndex = 0; arrayIndex < pVB->getElementArraySize(elemID); arrayIndex++)
{
element.SemanticName = name;
element.SemanticIndex = arrayIndex;
layoutDesc.elements.push_back(element);
element.AlignedByteOffset += getFormatBytesPerBlock(pVB->getElementFormat(elemID));
}
}
}
}
}
template<typename FalcorType>
D3D12_COMPARISON_FUNC getD3D12ComparisonFunc(FalcorType func)
{
switch (func)
{
case FalcorType::Disabled:
return D3D12_COMPARISON_FUNC_ALWAYS;
case FalcorType::Never:
return D3D12_COMPARISON_FUNC_NEVER;
case FalcorType::Always:
return D3D12_COMPARISON_FUNC_ALWAYS;
case FalcorType::Less:
return D3D12_COMPARISON_FUNC_LESS;
case FalcorType::Equal:
return D3D12_COMPARISON_FUNC_EQUAL;
case FalcorType::NotEqual:
return D3D12_COMPARISON_FUNC_NOT_EQUAL;
case FalcorType::LessEqual:
return D3D12_COMPARISON_FUNC_LESS_EQUAL;
case FalcorType::Greater:
return D3D12_COMPARISON_FUNC_GREATER;
case FalcorType::GreaterEqual:
return D3D12_COMPARISON_FUNC_GREATER_EQUAL;
default:
should_not_get_here();
return (D3D12_COMPARISON_FUNC)0;
}
}
D3D12_STENCIL_OP getD3D12StencilOp(DepthStencilState::StencilOp op)
{
switch (op)
{
case DepthStencilState::StencilOp::Keep:
return D3D12_STENCIL_OP_KEEP;
case DepthStencilState::StencilOp::Zero:
return D3D12_STENCIL_OP_ZERO;
case DepthStencilState::StencilOp::Replace:
return D3D12_STENCIL_OP_REPLACE;
case DepthStencilState::StencilOp::Increase:
return D3D12_STENCIL_OP_INCR;
case DepthStencilState::StencilOp::IncreaseSaturate:
return D3D12_STENCIL_OP_INCR_SAT;
case DepthStencilState::StencilOp::Decrease:
return D3D12_STENCIL_OP_DECR;
case DepthStencilState::StencilOp::DecreaseSaturate:
return D3D12_STENCIL_OP_DECR_SAT;
case DepthStencilState::StencilOp::Invert:
return D3D12_STENCIL_OP_INVERT;
default:
should_not_get_here();
return (D3D12_STENCIL_OP)0;
}
}
D3D12_DEPTH_STENCILOP_DESC getD3D12StencilOpDesc(const DepthStencilState::StencilDesc& desc)
{
D3D12_DEPTH_STENCILOP_DESC dxDesc;
dxDesc.StencilFunc = getD3D12ComparisonFunc(desc.func);
dxDesc.StencilDepthFailOp = getD3D12StencilOp(desc.depthFailOp);
dxDesc.StencilFailOp = getD3D12StencilOp(desc.stencilFailOp);
dxDesc.StencilPassOp = getD3D12StencilOp(desc.depthStencilPassOp);
return dxDesc;
}
void initD3DDepthStencilDesc(const DepthStencilState* pState, D3D12_DEPTH_STENCIL_DESC& desc)
{
desc.DepthEnable = dxBool(pState->isDepthTestEnabled());
desc.DepthFunc = getD3D12ComparisonFunc(pState->getDepthFunc());
desc.DepthWriteMask = pState->isDepthWriteEnabled() ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;
desc.StencilEnable = dxBool(pState->isStencilTestEnabled());
desc.StencilReadMask = pState->getStencilReadMask();
desc.StencilWriteMask = pState->getStencilWriteMask();
desc.FrontFace = getD3D12StencilOpDesc(pState->getStencilDesc(DepthStencilState::Face::Front));
desc.BackFace = getD3D12StencilOpDesc(pState->getStencilDesc(DepthStencilState::Face::Back));
}
D3D12_FILTER_TYPE getFilterType(Sampler::Filter filter)
{
switch (filter)
{
case Sampler::Filter::Point:
return D3D12_FILTER_TYPE_POINT;
case Sampler::Filter::Linear:
return D3D12_FILTER_TYPE_LINEAR;
default:
should_not_get_here();
return (D3D12_FILTER_TYPE)-1;
}
}
D3D12_FILTER getD3D12Filter(Sampler::Filter minFilter, Sampler::Filter magFilter, Sampler::Filter mipFilter, bool isComparison, bool isAnisotropic)
{
D3D12_FILTER filter;
D3D12_FILTER_REDUCTION_TYPE reduction = isComparison ? D3D12_FILTER_REDUCTION_TYPE_COMPARISON : D3D12_FILTER_REDUCTION_TYPE_STANDARD;
if (isAnisotropic)
{
filter = D3D12_ENCODE_ANISOTROPIC_FILTER(reduction);
}
else
{
D3D12_FILTER_TYPE dxMin = getFilterType(minFilter);
D3D12_FILTER_TYPE dxMag = getFilterType(magFilter);
D3D12_FILTER_TYPE dxMip = getFilterType(mipFilter);
filter = D3D12_ENCODE_BASIC_FILTER(dxMin, dxMag, dxMip, reduction);
}
return filter;
};
D3D12_TEXTURE_ADDRESS_MODE getD3D12AddressMode(Sampler::AddressMode mode)
{
switch (mode)
{
case Sampler::AddressMode::Wrap:
return D3D12_TEXTURE_ADDRESS_MODE_WRAP;
case Sampler::AddressMode::Mirror:
return D3D12_TEXTURE_ADDRESS_MODE_MIRROR;
case Sampler::AddressMode::Clamp:
return D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
case Sampler::AddressMode::Border:
return D3D12_TEXTURE_ADDRESS_MODE_BORDER;
case Sampler::AddressMode::MirrorOnce:
return D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE;
default:
should_not_get_here();
return (D3D12_TEXTURE_ADDRESS_MODE)-1;
}
}
void initD3D12SamplerDesc(const Sampler* pSampler, D3D12_SAMPLER_DESC& desc)
{
desc.Filter = getD3D12Filter(pSampler->getMinFilter(), pSampler->getMagFilter(), pSampler->getMipFilter(), (pSampler->getComparisonMode() != Sampler::ComparisonMode::Disabled), (pSampler->getMaxAnisotropy() > 1));
desc.AddressU = getD3D12AddressMode(pSampler->getAddressModeU());
desc.AddressV = getD3D12AddressMode(pSampler->getAddressModeV());
desc.AddressW = getD3D12AddressMode(pSampler->getAddressModeW());
desc.MipLODBias = pSampler->getLodBias();;
desc.MaxAnisotropy = pSampler->getMaxAnisotropy();
desc.ComparisonFunc = getD3D12ComparisonFunc(pSampler->getComparisonMode());
desc.MinLOD = pSampler->getMinLod();
desc.MaxLOD = pSampler->getMaxLod();
const glm::vec4& borderColor = pSampler->getBorderColor();
memcpy(desc.BorderColor, glm::value_ptr(borderColor), sizeof(borderColor));
}
D3D12_SHADER_VISIBILITY getShaderVisibility(ShaderVisibility visibility)
{
// D3D12 doesn't support a combination of flags, it's either ALL or a single stage
if (isPowerOf2(visibility) == false)
{
return D3D12_SHADER_VISIBILITY_ALL;
}
else if ((visibility & ShaderVisibility::Vertex) != ShaderVisibility::None)
{
return D3D12_SHADER_VISIBILITY_VERTEX;
}
else if ((visibility & ShaderVisibility::Pixel) != ShaderVisibility::None)
{
return D3D12_SHADER_VISIBILITY_PIXEL;
}
else if ((visibility & ShaderVisibility::Geometry) != ShaderVisibility::None)
{
return D3D12_SHADER_VISIBILITY_GEOMETRY;
}
else if ((visibility & ShaderVisibility::Domain) != ShaderVisibility::None)
{
return D3D12_SHADER_VISIBILITY_DOMAIN;
}
else if ((visibility & ShaderVisibility::Hull) != ShaderVisibility::None)
{
return D3D12_SHADER_VISIBILITY_HULL;
}
// If it was compute, it can't be anything else and so the first `if` would have handled it
should_not_get_here();
return (D3D12_SHADER_VISIBILITY)-1;
}
D3D12_DESCRIPTOR_RANGE_TYPE getRootDescRangeType(RootSignature::DescType type)
{
switch (type)
{
case RootSignature::DescType::TextureSrv:
case RootSignature::DescType::TypedBufferSrv:
case RootSignature::DescType::StructuredBufferSrv:
return D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
case RootSignature::DescType::TextureUav:
case RootSignature::DescType::TypedBufferUav:
case RootSignature::DescType::StructuredBufferUav:
return D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
case RootSignature::DescType::Cbv:
return D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
case RootSignature::DescType::Sampler:
return D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
default:
should_not_get_here();
return (D3D12_DESCRIPTOR_RANGE_TYPE)-1;
}
}
void convertRootCbvSet(const RootSignature::DescriptorSetLayout& set, D3D12_ROOT_PARAMETER& desc)
{
assert(set.getRangeCount() == 1);
const auto& range = set.getRange(0);
assert(range.type == RootSignature::DescType::Cbv && range.descCount == 1);
desc.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
desc.Descriptor.RegisterSpace = range.regSpace;
desc.Descriptor.ShaderRegister = range.baseRegIndex;
desc.ShaderVisibility = getShaderVisibility(set.getVisibility());
}
void convertRootDescTable(const RootSignature::DescriptorSetLayout& falcorSet, D3D12_ROOT_PARAMETER& desc, std::vector<D3D12_DESCRIPTOR_RANGE>& d3dRange)
{
desc.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
desc.ShaderVisibility = getShaderVisibility(falcorSet.getVisibility());
d3dRange.resize(falcorSet.getRangeCount());
desc.DescriptorTable.NumDescriptorRanges = (uint32_t)falcorSet.getRangeCount();
desc.DescriptorTable.pDescriptorRanges = d3dRange.data();
for (size_t i = 0; i < falcorSet.getRangeCount(); i++)
{
const auto& falcorRange = falcorSet.getRange(i);
d3dRange[i].BaseShaderRegister = falcorRange.baseRegIndex;
d3dRange[i].NumDescriptors = falcorRange.descCount;
d3dRange[i].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
d3dRange[i].RangeType = getRootDescRangeType(falcorRange.type);
d3dRange[i].RegisterSpace = falcorRange.regSpace;
}
}
void initD3D12RootParams(const RootSignature::Desc& desc, RootSignatureParams& params)
{
params.signatureSizeInBytes = 0;
params.d3dRanges.resize(desc.getSetsCount());
params.rootParams.resize(desc.getSetsCount());
params.elementByteOffset.resize(desc.getSetsCount());
for (size_t i = 0; i < desc.getSetsCount(); i++)
{
const auto& set = desc.getSet(i);
convertRootDescTable(set, params.rootParams[i], params.d3dRanges[i]);
params.elementByteOffset[i] = params.signatureSizeInBytes;
params.signatureSizeInBytes += 8;
}
}
void initD3D12GraphicsStateDesc(const GraphicsStateObject::Desc& gsoDesc, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, InputLayoutDesc& layoutDesc)
{
desc = {};
assert(gsoDesc.getProgramVersion());
#define get_shader_handle(_type) gsoDesc.getProgramVersion()->getShader(_type) ? gsoDesc.getProgramVersion()->getShader(_type)->getApiHandle() : D3D12_SHADER_BYTECODE{}
desc.VS = get_shader_handle(ShaderType::Vertex);
desc.PS = get_shader_handle(ShaderType::Pixel);
desc.GS = get_shader_handle(ShaderType::Geometry);
desc.HS = get_shader_handle(ShaderType::Hull);
desc.DS = get_shader_handle(ShaderType::Domain);
#undef get_shader_handle
initD3D12BlendDesc(gsoDesc.getBlendState().get(), desc.BlendState);
initD3D12RasterizerDesc(gsoDesc.getRasterizerState().get(), desc.RasterizerState);
initD3DDepthStencilDesc(gsoDesc.getDepthStencilState().get(), desc.DepthStencilState);
if (gsoDesc.getVertexLayout())
{
initD3D12VertexLayout(gsoDesc.getVertexLayout().get(), layoutDesc);
desc.InputLayout.NumElements = (uint32_t)layoutDesc.elements.size();
desc.InputLayout.pInputElementDescs = layoutDesc.elements.data();
}
desc.SampleMask = gsoDesc.getSampleMask();
desc.pRootSignature = gsoDesc.getRootSignature() ? gsoDesc.getRootSignature()->getApiHandle() : nullptr;
uint32_t numRtvs = 0;
for (uint32_t rt = 0; rt < Fbo::getMaxColorTargetCount(); rt++)
{
desc.RTVFormats[rt] = getDxgiFormat(gsoDesc.getFboDesc().getColorTargetFormat(rt));
if (desc.RTVFormats[rt] != DXGI_FORMAT_UNKNOWN)
{
numRtvs = rt + 1;
}
}
desc.NumRenderTargets = numRtvs;
desc.DSVFormat = getDxgiFormat(gsoDesc.getFboDesc().getDepthStencilFormat());
desc.SampleDesc.Count = gsoDesc.getFboDesc().getSampleCount();
desc.PrimitiveTopologyType = getD3DPrimitiveType(gsoDesc.getPrimitiveType());
}
}
|
#include <gtest/gtest.h>
#include "test_utility.h"
#include "tiex_match.h"
using namespace tiex;
using namespace tiex::internal;
static bool TestMakeBoundaryTime(const Boundary& boundary, const std::tm& tm, std::time_t expected_time) {
std::time_t actual_time = 0;
bool is_succeeded = MakeBoundaryTime(boundary, tm, actual_time);
if (! is_succeeded) {
return false;
}
return actual_time == expected_time;
}
TEST(Match, MakeBoundaryTime_Second) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
for (auto round : { true, false }) {
Boundary boundary;
boundary.unit = Unit::Second;
boundary.round = round;
boundary.value = boundary_value;
if (! TestMakeBoundaryTime(boundary, tm, expected_time)) {
return false;
}
}
return true;
};
auto tm = MakeTm(2017, 12, 3, 15, 33, 45);
ASSERT_TRUE(test(-60, tm, MakeTime(2017, 12, 3, 15, 32, 45)));
ASSERT_TRUE(test(-2, tm, MakeTime(2017, 12, 3, 15, 33, 43)));
ASSERT_TRUE(test(-1, tm, MakeTime(2017, 12, 3, 15, 33, 44)));
ASSERT_TRUE(test(0, tm, MakeTime(2017, 12, 3, 15, 33, 45)));
ASSERT_TRUE(test(1, tm, MakeTime(2017, 12, 3, 15, 33, 46)));
ASSERT_TRUE(test(2, tm, MakeTime(2017, 12, 3, 15, 33, 47)));
ASSERT_TRUE(test(60, tm, MakeTime(2017, 12, 3, 15, 34, 45)));
}
TEST(Match, MakeBoundaryTime_MinuteNoRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Minute;
boundary.round = false;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 19, 20, 34, 12);
ASSERT_TRUE(test(-60, tm, MakeTime(2018, 1, 19, 19, 34, 12)));
ASSERT_TRUE(test(-2, tm, MakeTime(2018, 1, 19, 20, 32, 12)));
ASSERT_TRUE(test(-1, tm, MakeTime(2018, 1, 19, 20, 33, 12)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 19, 20, 34, 12)));
ASSERT_TRUE(test(1, tm, MakeTime(2018, 1, 19, 20, 35, 12)));
ASSERT_TRUE(test(2, tm, MakeTime(2018, 1, 19, 20, 36, 12)));
ASSERT_TRUE(test(60, tm, MakeTime(2018, 1, 19, 21, 34, 12)));
}
TEST(Match, MakeBoundaryTime_MinuteRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Minute;
boundary.round = true;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 19, 20, 34, 12);
ASSERT_TRUE(test(-60, tm, MakeTime(2018, 1, 19, 19, 35, 0)));
ASSERT_TRUE(test(-2, tm, MakeTime(2018, 1, 19, 20, 33, 0)));
ASSERT_TRUE(test(-1, tm, MakeTime(2018, 1, 19, 20, 34, 0)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 19, 20, 34, 12)));
ASSERT_TRUE(test(1, tm, MakeTime(2018, 1, 19, 20, 35, 0)));
ASSERT_TRUE(test(2, tm, MakeTime(2018, 1, 19, 20, 36, 0)));
ASSERT_TRUE(test(60, tm, MakeTime(2018, 1, 19, 21, 34, 0)));
}
TEST(Match, MakeBoundaryTime_HourNoRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Hour;
boundary.round = false;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 25, 13, 16, 28);
ASSERT_TRUE(test(-24, tm, MakeTime(2018, 1, 24, 13, 16, 28)));
ASSERT_TRUE(test(-2, tm, MakeTime(2018, 1, 25, 11, 16, 28)));
ASSERT_TRUE(test(-1, tm, MakeTime(2018, 1, 25, 12, 16, 28)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 25, 13, 16, 28)));
ASSERT_TRUE(test(1, tm, MakeTime(2018, 1, 25, 14, 16, 28)));
ASSERT_TRUE(test(2, tm, MakeTime(2018, 1, 25, 15, 16, 28)));
ASSERT_TRUE(test(24, tm, MakeTime(2018, 1, 26, 13, 16, 28)));
}
TEST(Match, MakeBoundaryTime_HourRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Hour;
boundary.round = true;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 25, 13, 16, 28);
ASSERT_TRUE(test(-24, tm, MakeTime(2018, 1, 24, 14, 0, 0)));
ASSERT_TRUE(test(-2, tm, MakeTime(2018, 1, 25, 12, 0, 0)));
ASSERT_TRUE(test(-1, tm, MakeTime(2018, 1, 25, 13, 0, 0)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 25, 13, 16, 28)));
ASSERT_TRUE(test(1, tm, MakeTime(2018, 1, 25, 14, 0, 0)));
ASSERT_TRUE(test(2, tm, MakeTime(2018, 1, 25, 15, 0, 0)));
ASSERT_TRUE(test(24, tm, MakeTime(2018, 1, 26, 13, 0, 0)));
}
TEST(Match, MakeBoundaryTime_DayNoRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Day;
boundary.round = false;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 25, 13, 24, 3);
ASSERT_TRUE(test(-30, tm, MakeTime(2017, 12, 26, 13, 24, 3)));
ASSERT_TRUE(test(-2, tm, MakeTime(2018, 1, 23, 13, 24, 3)));
ASSERT_TRUE(test(-1, tm, MakeTime(2018, 1, 24, 13, 24, 3)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 25, 13, 24, 3)));
ASSERT_TRUE(test(1, tm, MakeTime(2018, 1, 26, 13, 24, 3)));
ASSERT_TRUE(test(2, tm, MakeTime(2018, 1, 27, 13, 24, 3)));
ASSERT_TRUE(test(30, tm, MakeTime(2018, 2, 24, 13, 24, 3)));
ASSERT_TRUE(test(-1, MakeTm(2016, 3, 1, 1, 2, 3), MakeTime(2016, 2, 29, 1, 2, 3)));
ASSERT_TRUE(test(-1, MakeTm(2018, 3, 1, 1, 2, 3), MakeTime(2018, 2, 28, 1, 2, 3)));
ASSERT_TRUE(test(-1, MakeTm(2018, 4, 1, 1, 2, 3), MakeTime(2018, 3, 31, 1, 2, 3)));
ASSERT_TRUE(test(-1, MakeTm(2018, 5, 1, 1, 2, 3), MakeTime(2018, 4, 30, 1, 2, 3)));
ASSERT_TRUE(test(1, MakeTm(2018, 2, 28, 1, 2, 3), MakeTime(2018, 3, 1, 1, 2, 3)));
ASSERT_TRUE(test(1, MakeTm(2016, 2, 29, 1, 2, 3), MakeTime(2016, 3, 1, 1, 2, 3)));
ASSERT_TRUE(test(1, MakeTm(2018, 3, 31, 1, 2, 3), MakeTime(2018, 4, 1, 1, 2, 3)));
ASSERT_TRUE(test(1, MakeTm(2018, 4, 30, 1, 2, 3), MakeTime(2018, 5, 1, 1, 2, 3)));
}
TEST(Match, MakeBoundaryTime_DayRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Day;
boundary.round = true;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 25, 13, 24, 3);
ASSERT_TRUE(test(-30, tm, MakeTime(2017, 12, 27, 0, 0, 0)));
ASSERT_TRUE(test(-2, tm, MakeTime(2018, 1, 24, 0, 0, 0)));
ASSERT_TRUE(test(-1, tm, MakeTime(2018, 1, 25, 0, 0, 0)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 25, 13, 24, 3)));
ASSERT_TRUE(test(1, tm, MakeTime(2018, 1, 26, 0, 0, 0)));
ASSERT_TRUE(test(2, tm, MakeTime(2018, 1, 27, 0, 0, 0)));
ASSERT_TRUE(test(30, tm, MakeTime(2018, 2, 24, 0, 0, 0)));
ASSERT_TRUE(test(-1, MakeTm(2016, 3, 1, 1, 2, 3), MakeTime(2016, 3, 1, 0, 0, 0)));
ASSERT_TRUE(test(-1, MakeTm(2018, 3, 1, 1, 2, 3), MakeTime(2018, 3, 1, 0, 0, 0)));
ASSERT_TRUE(test(-1, MakeTm(2018, 4, 1, 1, 2, 3), MakeTime(2018, 4, 1, 0, 0, 0)));
ASSERT_TRUE(test(-1, MakeTm(2018, 5, 1, 1, 2, 3), MakeTime(2018, 5, 1, 0, 0, 0)));
ASSERT_TRUE(test(1, MakeTm(2018, 2, 28, 1, 2, 3), MakeTime(2018, 3, 1, 0, 0, 0)));
ASSERT_TRUE(test(1, MakeTm(2016, 2, 29, 1, 2, 3), MakeTime(2016, 3, 1, 0, 0, 0)));
ASSERT_TRUE(test(1, MakeTm(2018, 3, 31, 1, 2, 3), MakeTime(2018, 4, 1, 0, 0, 0)));
ASSERT_TRUE(test(1, MakeTm(2018, 4, 30, 1, 2, 3), MakeTime(2018, 5, 1, 0, 0, 0)));
}
TEST(Match, MakeBoundaryTime_MonthNoRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Month;
boundary.round = false;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 26, 12, 21, 49);
ASSERT_TRUE(test(-12, tm, MakeTime(2017, 1, 26, 12, 21, 49)));
ASSERT_TRUE(test(-2, tm, MakeTime(2017, 11, 26, 12, 21, 49)));
ASSERT_TRUE(test(-1, tm, MakeTime(2017, 12, 26, 12, 21, 49)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 26, 12, 21, 49)));
ASSERT_TRUE(test(1, tm, MakeTime(2018, 2, 26, 12, 21, 49)));
ASSERT_TRUE(test(2, tm, MakeTime(2018, 3, 26, 12, 21, 49)));
ASSERT_TRUE(test(12, tm, MakeTime(2019, 1, 26, 12, 21, 49)));
}
TEST(Match, MakeBoundaryTime_MonthRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Month;
boundary.round = true;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 26, 12, 21, 49);
ASSERT_TRUE(test(-12, tm, MakeTime(2017, 2, 1, 0, 0, 0)));
ASSERT_TRUE(test(-2, tm, MakeTime(2017, 12, 1, 0, 0, 0)));
ASSERT_TRUE(test(-1, tm, MakeTime(2018, 1, 1, 0, 0, 0)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 26, 12, 21, 49)));
ASSERT_TRUE(test(1, tm, MakeTime(2018, 2, 1, 0, 0, 0)));
ASSERT_TRUE(test(2, tm, MakeTime(2018, 3, 1, 0, 0, 0)));
ASSERT_TRUE(test(12, tm, MakeTime(2019, 1, 1, 0, 0, 0)));
}
TEST(Match, MakeBoundaryTime_YearNoRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Year;
boundary.round = false;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 26, 12, 30, 33);
ASSERT_TRUE(test(-2, tm, MakeTime(2016, 1, 26, 12, 30, 33)));
ASSERT_TRUE(test(-1, tm, MakeTime(2017, 1, 26, 12, 30, 33)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 26, 12, 30, 33)));
ASSERT_TRUE(test(1, tm, MakeTime(2019, 1, 26, 12, 30, 33)));
ASSERT_TRUE(test(2, tm, MakeTime(2020, 1, 26, 12, 30, 33)));
}
TEST(Match, MakeBoundaryTime_YearRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Year;
boundary.round = true;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 26, 12, 30, 33);
ASSERT_TRUE(test(-2, tm, MakeTime(2017, 1, 1, 0, 0, 0)));
ASSERT_TRUE(test(-1, tm, MakeTime(2018, 1, 1, 0, 0, 0)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 26, 12, 30, 33)));
ASSERT_TRUE(test(1, tm, MakeTime(2019, 1, 1, 0, 0, 0)));
ASSERT_TRUE(test(2, tm, MakeTime(2020, 1, 1, 0, 0, 0)));
}
TEST(Match, MakeBoundaryTime_WeekNoRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Week;
boundary.round = false;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 26, 12, 35, 24);
ASSERT_TRUE(test(-2, tm, MakeTime(2018, 1, 12, 12, 35, 24)));
ASSERT_TRUE(test(-1, tm, MakeTime(2018, 1, 19, 12, 35, 24)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 26, 12, 35, 24)));
ASSERT_TRUE(test(1, tm, MakeTime(2018, 2, 2, 12, 35, 24)));
ASSERT_TRUE(test(2, tm, MakeTime(2018, 2, 9, 12, 35, 24)));
}
TEST(Match, MakeBoundaryTime_WeekRound) {
auto test = [](int boundary_value, const std::tm& tm, std::time_t expected_time) {
Boundary boundary;
boundary.unit = Unit::Week;
boundary.round = true;
boundary.value = boundary_value;
return TestMakeBoundaryTime(boundary, tm, expected_time);
};
auto tm = MakeTm(2018, 1, 26, 12, 35, 24);
ASSERT_TRUE(test(-2, tm, MakeTime(2018, 1, 14, 0, 0, 0)));
ASSERT_TRUE(test(-1, tm, MakeTime(2018, 1, 21, 0, 0, 0)));
ASSERT_TRUE(test(0, tm, MakeTime(2018, 1, 26, 12, 35, 24)));
ASSERT_TRUE(test(1, tm, MakeTime(2018, 1, 28, 0, 0, 0)));
ASSERT_TRUE(test(2, tm, MakeTime(2018, 2, 4, 0, 0, 0)));
}
TEST(Match, MakeBoundaryTime_Limit) {
auto test = [](int boundary_value, std::time_t expected_time) {
auto units = {
Unit::Second, Unit::Minute, Unit::Hour, Unit::Day, Unit::Week, Unit::Month, Unit::Year,
};
for (auto unit : units) {
for (auto round : { true, false }) {
Boundary boundary;
boundary.value = boundary_value;
boundary.unit = unit;
boundary.round = round;
std::tm tm = { 0 };
if (! TestMakeBoundaryTime(boundary, tm, expected_time)) {
return false;
}
}
}
return true;
};
ASSERT_TRUE(test(std::numeric_limits<int>::min(), std::numeric_limits<std::time_t>::min()));
ASSERT_TRUE(test(std::numeric_limits<int>::max(), std::numeric_limits<std::time_t>::max()));
}
|
/*
* Copyright (c) 2011-2018, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//!
//! \file vphal_render_vebox_g9_base.cpp
//! \brief Interface and structure specific for SKL (GEN9) Vebox
//! \details Interface and structure specific for SKL (GEN9) Vebox
//!
#include "vphal.h"
#include "vphal_render_vebox_base.h"
#include "vphal_render_vebox_g9_base.h"
#include "vphal_render_sfc_g9_base.h"
#include "vphal_render_vebox_util_base.h"
#include "vpkrnheader.h"
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
#include "igvpkrn_isa_g9.h"
#endif
#define MAX_INPUT_PREC_BITS 16
#define DOWNSHIFT_WITH_ROUND(x, n) (((x) + (((n) > 0) ? (1 << ((n) - 1)) : 0)) >> (n))
#define INTERP(x0, x1, x, y0, y1) ((uint32_t) floor(y0+(x-x0)*(y1-y0)/(double)(x1-x0)))
const char g_KernelDNDI_Str_g9[KERNEL_VEBOX_BASE_MAX][MAX_PATH] =
{
DBG_TEXT("Reserved"),
DBG_TEXT("UpdateDNState"),
};
// Kernel Params ---------------------------------------------------------------
const RENDERHAL_KERNEL_PARAM g_Vebox_KernelParam_g9[KERNEL_VEBOX_BASE_MAX] =
{
///* GRF_Count
// | BT_Count
// | | Sampler_Count
// | | | Thread_Count
// | | | | GRF_Start_Register
// | | | | | CURBE_Length
// | | | | | | block_width
// | | | | | | | block_height
// | | | | | | | | blocks_x
// | | | | | | | | | blocks_y
// | | | | | | | | | |*/
{ 0, 0, 0, VPHAL_USE_MEDIA_THREADS_MAX, 0, 0, 0, 0, 0, 0 }, // Reserved
{ 4, 34, 0, VPHAL_USE_MEDIA_THREADS_MAX, 0, 1, 64, 8, 1, 1 }, // UPDATEDNSTATE
};
const uint32_t dwDenoiseASDThreshold[NOISEFACTOR_MAX + 1] = {
512, 514, 516, 518, 520, 522, 524, 526, 528, 530, 532, 534, 536, 538, 540, 542,
544, 546, 548, 550, 552, 554, 556, 558, 560, 562, 564, 566, 568, 570, 572, 574,
576, 578, 580, 582, 584, 586, 588, 590, 592, 594, 596, 598, 600, 602, 604, 606,
608, 610, 612, 614, 616, 618, 620, 622, 624, 626, 628, 630, 632, 634, 636, 638,
640 };
const uint32_t dwDenoiseHistoryDelta[NOISEFACTOR_MAX + 1] = {
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
8 };
const uint32_t dwDenoiseMaximumHistory[NOISEFACTOR_MAX + 1] = {
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
208 };
const uint32_t dwDenoiseSTADThreshold[NOISEFACTOR_MAX + 1] = {
2048, 2052, 2056, 2060, 2064, 2068, 2072, 2076, 2080, 2084, 2088, 2092, 2096, 2100, 2104, 2108,
2112, 2116, 2120, 2124, 2128, 2132, 2136, 2140, 2144, 2148, 2152, 2156, 2160, 2164, 2168, 2172,
2176, 2180, 2184, 2188, 2192, 2196, 2200, 2204, 2208, 2212, 2216, 2220, 2224, 2228, 2232, 2236,
2240, 2244, 2248, 2252, 2256, 2260, 2264, 2268, 2272, 2276, 2280, 2284, 2288, 2292, 2296, 2300,
2304 };
const uint32_t dwDenoiseSCMThreshold[NOISEFACTOR_MAX + 1] = {
512, 514, 516, 518, 520, 522, 524, 526, 528, 530, 532, 534, 536, 538, 540, 542,
544, 546, 548, 550, 552, 554, 556, 558, 560, 562, 564, 566, 568, 570, 572, 574,
576, 578, 580, 582, 584, 586, 588, 590, 592, 594, 596, 598, 600, 602, 604, 606,
608, 610, 612, 614, 616, 618, 620, 622, 624, 626, 628, 630, 632, 634, 636, 638,
640 };
const uint32_t dwDenoiseMPThreshold[NOISEFACTOR_MAX + 1] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2 };
const uint32_t dwLTDThreshold[NOISEFACTOR_MAX + 1] = {
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
128 };
const uint32_t dwTDThreshold[NOISEFACTOR_MAX + 1] = {
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192 };
const uint32_t dwGoodNeighborThreshold[NOISEFACTOR_MAX + 1] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0 };
const uint32_t dwPixRangeThreshold0[NOISEFACTOR_MAX + 1] = {
32, 37, 42, 47, 52, 57, 62, 67, 72, 77, 82, 87, 92, 97, 102, 107,
112, 117, 122, 127, 132, 137, 142, 147, 152, 157, 162, 167, 172, 177, 182, 187,
192, 198, 204, 210, 216, 222, 228, 234, 240, 246, 252, 258, 264, 270, 276, 282,
288, 294, 300, 306, 312, 318, 324, 330, 336, 342, 348, 354, 360, 366, 372, 378,
384 };
const uint32_t dwPixRangeThreshold1[NOISEFACTOR_MAX + 1] = {
64, 70, 76, 82, 88, 94, 100, 106, 112, 118, 124, 130, 136, 142, 148, 154,
160, 166, 172, 178, 184, 190, 196, 202, 208, 214, 220, 226, 232, 238, 244, 250,
256, 266, 276, 286, 296, 306, 316, 326, 336, 346, 356, 366, 376, 386, 396, 406,
416, 426, 436, 446, 456, 466, 476, 486, 496, 506, 516, 526, 536, 546, 556, 566,
576 };
const uint32_t dwPixRangeThreshold2[NOISEFACTOR_MAX + 1] = {
128, 140, 152, 164, 176, 188, 200, 212, 224, 236, 248, 260, 272, 284, 296, 308,
320, 332, 344, 356, 368, 380, 392, 404, 416, 428, 440, 452, 464, 476, 488, 500,
512, 524, 536, 548, 560, 572, 584, 596, 608, 620, 632, 644, 656, 668, 680, 692,
704, 716, 728, 740, 752, 764, 776, 788, 800, 812, 824, 836, 848, 860, 872, 884,
896 };
const uint32_t dwPixRangeThreshold3[NOISEFACTOR_MAX + 1] = {
128, 144, 160, 176, 192, 208, 224, 240, 256, 272, 288, 304, 320, 336, 352, 368,
384, 400, 416, 432, 448, 464, 480, 496, 512, 528, 544, 560, 576, 592, 608, 624,
640, 660, 680, 700, 720, 740, 760, 780, 800, 820, 840, 860, 880, 900, 920, 940,
960, 980, 1000, 1020, 1040, 1060, 1080, 1100, 1120, 1140, 1160, 1180, 1200, 1220, 1240, 1260,
1280 };
const uint32_t dwPixRangeThreshold4[NOISEFACTOR_MAX + 1] = {
128, 152, 176, 200, 224, 248, 272, 296, 320, 344, 368, 392, 416, 440, 464, 488,
512, 536, 560, 584, 608, 632, 656, 680, 704, 728, 752, 776, 800, 824, 848, 872,
896, 928, 960, 992, 1024, 1056, 1088, 1120, 1152, 1184, 1216, 1248, 1280, 1312, 1344, 1376,
1408, 1440, 1472, 1504, 1536, 1568, 1600, 1632, 1664, 1696, 1728, 1760, 1792, 1824, 1856, 1888,
1920 };
const uint32_t dwPixRangeThreshold5[NOISEFACTOR_MAX + 1] = {
128, 164, 200, 236, 272, 308, 344, 380, 416, 452, 488, 524, 560, 596, 632, 668,
704, 740, 776, 812, 848, 884, 920, 956, 992, 1028, 1064, 1100, 1136, 1172, 1208, 1244,
1280, 1320, 1360, 1400, 1440, 1480, 1520, 1560, 1600, 1640, 1680, 1720, 1760, 1800, 1840, 1880,
1920, 1960, 2000, 2040, 2080, 2120, 2160, 2200, 2240, 2280, 2320, 2360, 2400, 2440, 2480, 2520,
2560 };
const uint32_t dwPixRangeWeight0[NOISEFACTOR_MAX + 1] = {
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16 };
const uint32_t dwPixRangeWeight1[NOISEFACTOR_MAX + 1] = {
9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
15 };
const uint32_t dwPixRangeWeight2[NOISEFACTOR_MAX + 1] = {
2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5,
6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
13 };
const uint32_t dwPixRangeWeight3[NOISEFACTOR_MAX + 1] = {
0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2,
2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7,
7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
10 };
const uint32_t dwPixRangeWeight4[NOISEFACTOR_MAX + 1] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4,
4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
7 };
const uint32_t dwPixRangeWeight5[NOISEFACTOR_MAX + 1] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4 };
const uint32_t dwLTDThresholdUV[NOISEFACTOR_MAX + 1] = {
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
8 };
const uint32_t dwTDThresholdUV[NOISEFACTOR_MAX + 1] = {
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
14 };
const uint32_t dwSTADThresholdUV[NOISEFACTOR_MAX + 1] = {
128, 128, 128, 128, 129, 129, 129, 129, 130, 130, 130, 130, 131, 131, 131, 131,
132, 132, 132, 132, 133, 133, 133, 133, 134, 134, 134, 134, 135, 135, 135, 135,
136, 136, 136, 136, 137, 137, 137, 137, 138, 138, 138, 138, 139, 139, 139, 139,
140, 140, 140, 140, 141, 141, 141, 141, 142, 142, 142, 142, 143, 143, 143, 143,
144 };
//!
//! \brief IsFormatMMCSupported
//! \details Check if the format of vebox output surface is supported by MMC
//! \param [in] Format
//! \return bool true if suported, otherwise not supported
//!
bool VPHAL_VEBOX_STATE_G9_BASE::IsFormatMMCSupported(
MOS_FORMAT Format)
{
bool bRet;
bRet = false;
if ((Format != Format_NV12) &&
(Format != Format_YUY2) &&
(Format != Format_YUYV) &&
(Format != Format_UYVY) &&
(Format != Format_YVYU) &&
(Format != Format_VYUY) &&
(Format != Format_AYUV) &&
(Format != Format_Y416) &&
(Format != Format_A8B8G8R8) &&
(Format != Format_A16B16G16R16))
{
VPHAL_RENDER_NORMALMESSAGE("Unsupported Format '0x%08x' for VEBOX MMC ouput.", Format);
goto finish;
}
bRet = true;
finish:
return bRet;
}
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::GetFFDISurfParams(
VPHAL_CSPACE &ColorSpace,
VPHAL_SAMPLE_TYPE &SampleType)
{
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
if (IS_VPHAL_OUTPUT_PIPE_SFC(pRenderData))
{
ColorSpace = m_sfcPipeState->GetInputColorSpace();
}
else
{
ColorSpace = m_currentSurface->ColorSpace;
}
// When IECP is enabled and Bob or interlaced scaling is selected for interlaced input,
// output surface's SampleType should be same to input's. Bob is being
// done in Composition part
if (pRenderData->bIECP &&
(m_currentSurface->pDeinterlaceParams &&
m_currentSurface->pDeinterlaceParams->DIMode == DI_MODE_BOB) ||
m_currentSurface->bInterlacedScaling)
{
SampleType = m_currentSurface->SampleType;
}
else
{
SampleType = SAMPLE_PROGRESSIVE;
}
return MOS_STATUS_SUCCESS;
}
//!
//! \brief Get Output surface params needed when allocate surfaces
//! \details Get Output surface params needed when allocate surfaces
//! \param [out] Format
//! Format of output surface
//! \param [out] TileType
//! Tile type of output surface
//! \return MOS_STATUS
//! Return MOS_STATUS_SUCCESS if success, otherwise failed
//!
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::GetOutputSurfParams(
MOS_FORMAT &Format,
MOS_TILE_TYPE &TileType)
{
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
if (pRenderData->bDeinterlace)
{
Format = Format_YUY2;
TileType = MOS_TILE_Y;
}
else
{
Format = IS_VPHAL_OUTPUT_PIPE_SFC(pRenderData) ?
m_sfcPipeState->GetInputFormat() :
m_currentSurface->Format;
TileType = m_currentSurface->TileType;
}
return MOS_STATUS_SUCCESS;
}
//!
//! \brief Check for DN only case
//! \details Check for DN only case
//! \return bool
//! Return true if DN only case, otherwise not
//!
bool VPHAL_VEBOX_STATE_G9_BASE::IsDNOnly()
{
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
return pRenderData->bDenoise &&
(!pRenderData->bDeinterlace) &&
(!IsQueryVarianceEnabled()) &&
(!IsIECPEnabled());
}
bool VPHAL_VEBOX_STATE_G9_BASE::IsFFDISurfNeeded()
{
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
if (pRenderData->bDeinterlace ||
IsQueryVarianceEnabled() ||
pRenderData->bIECP ||
(pRenderData->bDenoise && IS_VPHAL_OUTPUT_PIPE_SFC(pRenderData))) // DN + SFC needs IECP implicitly and outputs to DI surface
{
return true;
}
else
{
return false;
}
}
bool VPHAL_VEBOX_STATE_G9_BASE::IsFFDNSurfNeeded()
{
return GetLastExecRenderData()->bDenoise ? true : false;
}
bool VPHAL_VEBOX_STATE_G9_BASE::IsSTMMSurfNeeded()
{
return (GetLastExecRenderData()->bDenoise || GetLastExecRenderData()->bDeinterlace);
}
//!
//! \brief Vebox allocate resources
//! \details Allocate resources that will be used in Vebox
//! \return MOS_STATUS
//! Return MOS_STATUS_SUCCESS if successful, otherwise failed
//!
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::AllocateResources()
{
MOS_STATUS eStatus;
PMOS_INTERFACE pOsInterface;
PRENDERHAL_INTERFACE pRenderHal;
MOS_FORMAT format;
MOS_TILE_TYPE TileType;
uint32_t dwWidth;
uint32_t dwHeight;
uint32_t dwSize;
int32_t i;
bool bAllocated;
bool bDIEnable;
bool bSurfCompressed;
bool bFFDNSurfCompressed;
MOS_RESOURCE_MMC_MODE SurfCompressionMode;
MOS_RESOURCE_MMC_MODE FFDNSurfCompressionMode;
MHW_VEBOX_SURFACE_PARAMS MhwVeboxSurfaceParam;
PMHW_VEBOX_INTERFACE pVeboxInterface;
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
bAllocated = false;
bSurfCompressed = false;
bFFDNSurfCompressed = false;
SurfCompressionMode = MOS_MMC_DISABLED;
FFDNSurfCompressionMode = MOS_MMC_DISABLED;
pOsInterface = pVeboxState->m_pOsInterface;
pRenderHal = pVeboxState->m_pRenderHal;
pVeboxInterface = pVeboxState->m_pVeboxInterface;
GetOutputSurfParams(format, TileType);
// In DN only case, input, output and previous De-noised
// surfaces all should have precisely the same memory compression status.
// Either all these surfaces should be compressed together
// or none of them compressed at all.This is HW limitation.
if (IsDNOnly())
{
bSurfCompressed = pVeboxState->m_currentSurface->bCompressible;
SurfCompressionMode = pVeboxState->m_currentSurface->bIsCompressed ? MOS_MMC_HORIZONTAL : MOS_MMC_DISABLED;
}
// Only Tiled Y surfaces support MMC
else if (pVeboxState->bEnableMMC &&
(TileType == MOS_TILE_Y) &&
pVeboxState->IsFormatMMCSupported(format))
{
bSurfCompressed = true;
SurfCompressionMode = MOS_MMC_HORIZONTAL;
}
// Allocate FFDI/IECP surfaces----------------------------------------------
if (IsFFDISurfNeeded())
{
VPHAL_CSPACE ColorSpace;
VPHAL_SAMPLE_TYPE SampleType;
GetFFDISurfParams(ColorSpace, SampleType);
for (i = 0; i < pVeboxState->iNumFFDISurfaces; i++)
{
VPHAL_RENDER_CHK_STATUS(VpHal_ReAllocateSurface(
pOsInterface,
pVeboxState->FFDISurfaces[i],
"VeboxFFDISurface_g9",
format,
MOS_GFXRES_2D,
TileType,
pVeboxState->m_currentSurface->dwWidth,
pVeboxState->m_currentSurface->dwHeight,
bSurfCompressed,
SurfCompressionMode,
&bAllocated));
pVeboxState->FFDISurfaces[i]->SampleType = SampleType;
// Copy rect sizes so that if input surface state needs to adjust,
// output surface can be adjustted also.
pVeboxState->FFDISurfaces[i]->rcSrc = pVeboxState->m_currentSurface->rcSrc;
pVeboxState->FFDISurfaces[i]->rcDst = pVeboxState->m_currentSurface->rcDst;
// Copy max src rect
pVeboxState->FFDISurfaces[i]->rcMaxSrc = pVeboxState->m_currentSurface->rcMaxSrc;
// Copy Rotation, it's used in setting SFC state
pVeboxState->FFDISurfaces[i]->Rotation = pVeboxState->m_currentSurface->Rotation;
pVeboxState->FFDISurfaces[i]->ColorSpace = ColorSpace;
if (bAllocated)
{
// Report Compress Status
m_reporting->FFDICompressible = bSurfCompressed;
m_reporting->FFDICompressMode = (uint8_t)(SurfCompressionMode);
}
}
}
// When DI switch to DNDI, the first FFDN surface pitch doesn't match with
// the input surface pitch and cause the flicker issue
// Or for 2 clip playback in WMP, the first one is HW decoding, the second one is SW decoding,
// when the second clip playback starting without media pipeline recreation,
// the internal FFDNSurfaces are compressed, but VP input surface is uncompressed.
if ((pVeboxState->bDIEnabled && !pVeboxState->bDNEnabled && pRenderData->bDenoise) ||
((pVeboxState->m_currentSurface->bIsCompressed == false) && ((bSurfCompressed == true) || (pVeboxState->FFDNSurfaces[0]->bIsCompressed == true))))
{
bFFDNSurfCompressed = pVeboxState->m_currentSurface->bCompressible;
FFDNSurfCompressionMode = pVeboxState->m_currentSurface->bIsCompressed ? MOS_MMC_HORIZONTAL : MOS_MMC_DISABLED;
}
else
{
bFFDNSurfCompressed = bSurfCompressed;
FFDNSurfCompressionMode = SurfCompressionMode;
}
// Allocate FFDN surfaces---------------------------------------------------
if (IsFFDNSurfNeeded())
{
for (i = 0; i < VPHAL_NUM_FFDN_SURFACES; i++)
{
VPHAL_RENDER_CHK_STATUS(VpHal_ReAllocateSurface(
pOsInterface,
pVeboxState->FFDNSurfaces[i],
"VeboxFFDNSurface_g9",
pVeboxState->m_currentSurface->Format,
MOS_GFXRES_2D,
pVeboxState->m_currentSurface->TileType,
pVeboxState->m_currentSurface->dwWidth,
pVeboxState->m_currentSurface->dwHeight,
bFFDNSurfCompressed,
FFDNSurfCompressionMode,
&bAllocated));
// if allocated, pVeboxState->PreviousSurface is not valid for DN reference.
if (bAllocated)
{
// If DI is enabled, try to use app's reference if provided
if (pRenderData->bRefValid &&
pRenderData->bDeinterlace &&
(pVeboxState->m_currentSurface->pBwdRef != nullptr) &&
(pVeboxState->FFDNSurfaces[i]->dwPitch == pVeboxState->m_currentSurface->pBwdRef->dwPitch))
{
CopySurfaceValue(pVeboxState->m_previousSurface, pVeboxState->m_currentSurface->pBwdRef);
}
else
{
pRenderData->bRefValid = false;
}
}
// DN's output format should be same to input
pVeboxState->FFDNSurfaces[i]->SampleType =
pVeboxState->m_currentSurface->SampleType;
// Copy rect sizes so that if input surface state needs to adjust,
// output surface can be adjustted also.
pVeboxState->FFDNSurfaces[i]->rcSrc = pVeboxState->m_currentSurface->rcSrc;
pVeboxState->FFDNSurfaces[i]->rcDst = pVeboxState->m_currentSurface->rcDst;
// Copy max src rect
pVeboxState->FFDNSurfaces[i]->rcMaxSrc = pVeboxState->m_currentSurface->rcMaxSrc;
// Set Colorspace of FFDN
pVeboxState->FFDNSurfaces[i]->ColorSpace = pVeboxState->m_currentSurface->ColorSpace;
// Copy FrameID and parameters, as DN output will be used as next blt's current
pVeboxState->FFDNSurfaces[i]->FrameID = pVeboxState->m_currentSurface->FrameID;
pVeboxState->FFDNSurfaces[i]->pDenoiseParams = pVeboxState->m_currentSurface->pDenoiseParams;
if (bAllocated)
{
// Report Compress Status
m_reporting->FFDNCompressible = bFFDNSurfCompressed;
m_reporting->FFDNCompressMode = (uint8_t)(FFDNSurfCompressionMode);
}
}
}
// Adjust the rcMaxSrc of pRenderTarget when Vebox output is enabled
if (IS_VPHAL_OUTPUT_PIPE_VEBOX(pRenderData))
{
pRenderData->pRenderTarget->rcMaxSrc = pVeboxState->m_currentSurface->rcMaxSrc;
}
// Allocate STMM (Spatial-Temporal Motion Measure) Surfaces------------------
if (IsSTMMSurfNeeded())
{
if (pVeboxState->bEnableMMC)
{
bSurfCompressed = true;
SurfCompressionMode = MOS_MMC_HORIZONTAL;
}
else
{
bSurfCompressed = false;
SurfCompressionMode = MOS_MMC_DISABLED;
}
for (i = 0; i < VPHAL_NUM_STMM_SURFACES; i++)
{
VPHAL_RENDER_CHK_STATUS(VpHal_ReAllocateSurface(
pOsInterface,
&pVeboxState->STMMSurfaces[i],
"VeboxSTMMSurface_g9",
Format_STMM,
MOS_GFXRES_2D,
MOS_TILE_Y,
pVeboxState->m_currentSurface->dwWidth,
pVeboxState->m_currentSurface->dwHeight,
bSurfCompressed,
SurfCompressionMode,
&bAllocated));
if (bAllocated)
{
VPHAL_RENDER_CHK_STATUS(VeboxInitSTMMHistory(i));
// Report Compress Status
m_reporting->STMMCompressible = bSurfCompressed;
m_reporting->STMMCompressMode = (uint8_t)(SurfCompressionMode);
}
}
}
// Allocate Statistics State Surface----------------------------------------
// Width to be a aligned on 64 bytes and height is 1/4 the height
// Per frame information written twice per frame for 2 slices
// Surface to be a rectangle aligned with dwWidth to get proper dwSize
bDIEnable = pRenderData->bDeinterlace || IsQueryVarianceEnabled();
VPHAL_RENDER_CHK_STATUS(VpHal_InitVeboxSurfaceParams(
pVeboxState->m_currentSurface, &MhwVeboxSurfaceParam));
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->VeboxAdjustBoundary(
&MhwVeboxSurfaceParam,
&dwWidth,
&dwHeight,
bDIEnable));
dwWidth = MOS_ALIGN_CEIL(dwWidth, 64);
dwHeight = MOS_ROUNDUP_DIVIDE(dwHeight, 4) +
MOS_ROUNDUP_DIVIDE(VPHAL_VEBOX_STATISTICS_SIZE_G9 * sizeof(uint32_t), dwWidth);
dwSize = dwWidth * dwHeight;
VPHAL_RENDER_CHK_STATUS(VpHal_ReAllocateSurface(
pOsInterface,
&pVeboxState->VeboxStatisticsSurface,
"VeboxStatisticsSurface_g9",
Format_Buffer,
MOS_GFXRES_BUFFER,
MOS_TILE_LINEAR,
dwSize,
1,
false,
MOS_MMC_DISABLED,
&bAllocated));
if (bAllocated)
{
// initialize Statistics Surface
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnFillResource(
pOsInterface,
&(pVeboxState->VeboxStatisticsSurface.OsResource),
dwSize,
0));
pVeboxState->dwVeboxPerBlockStatisticsWidth = dwWidth;
pVeboxState->dwVeboxPerBlockStatisticsHeight = dwHeight -
MOS_ROUNDUP_DIVIDE(VPHAL_VEBOX_STATISTICS_SIZE_G9 * sizeof(uint32_t), dwWidth);
}
#if VEBOX_AUTO_DENOISE_SUPPORTED
// Allocate Temp Surface for Vebox Update kernels----------------------------------------
// the surface size is one Page
dwSize = MHW_PAGE_SIZE;
VPHAL_RENDER_CHK_STATUS(VpHal_ReAllocateSurface(
pOsInterface,
&pVeboxState->VeboxTempSurface,
"VeboxTempSurface_g9",
Format_Buffer,
MOS_GFXRES_BUFFER,
MOS_TILE_LINEAR,
dwSize,
1,
false,
MOS_MMC_DISABLED,
&bAllocated));
if (bAllocated)
{
// initialize Statistics Surface
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnFillResource(
pOsInterface,
&(pVeboxState->VeboxTempSurface.OsResource),
dwSize,
0));
}
// Allocate Spatial Attributes Configuration Surface for DN kernel Gen9+-----------
dwSize = MHW_PAGE_SIZE;
VPHAL_RENDER_CHK_STATUS(VpHal_ReAllocateSurface(
pOsInterface,
&pVeboxState->VeboxSpatialAttributesConfigurationSurface,
"VeboxSpatialAttributesConfigurationSurface_g9",
Format_RAW,
MOS_GFXRES_BUFFER,
MOS_TILE_LINEAR,
dwSize,
1,
false,
MOS_MMC_DISABLED,
&bAllocated));
if (bAllocated)
{
// initialize Spatial Attributes Configuration Surface
VPHAL_RENDER_CHK_STATUS(VeboxInitSpatialAttributesConfiguration());
}
#endif
finish:
if (eStatus != MOS_STATUS_SUCCESS)
{
pVeboxState->FreeResources();
}
return eStatus;
}
//!
//! \brief Vebox free resources
//! \details Free resources that are used in Vebox
//! \return void
//!
void VPHAL_VEBOX_STATE_G9_BASE::FreeResources()
{
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
int32_t i;
PMOS_INTERFACE pOsInterface = pVeboxState->m_pOsInterface;
// Free FFDI surfaces
for (i = 0; i < pVeboxState->iNumFFDISurfaces; i++)
{
if (pVeboxState->FFDISurfaces[i])
{
pOsInterface->pfnFreeResource(
pOsInterface,
&pVeboxState->FFDISurfaces[i]->OsResource);
}
}
// Free FFDN surfaces
for (i = 0; i < VPHAL_NUM_FFDN_SURFACES; i++)
{
if (pVeboxState->FFDNSurfaces[i])
{
pOsInterface->pfnFreeResource(
pOsInterface,
&pVeboxState->FFDNSurfaces[i]->OsResource);
}
}
// Free DI history buffers (STMM = Spatial-temporal motion measure)
for (i = 0; i < VPHAL_NUM_STMM_SURFACES; i++)
{
pOsInterface->pfnFreeResource(
pOsInterface,
&pVeboxState->STMMSurfaces[i].OsResource);
}
// Free Statistics data surface for VEBOX
pOsInterface->pfnFreeResource(
pOsInterface,
&pVeboxState->VeboxStatisticsSurface.OsResource);
#if VEBOX_AUTO_DENOISE_SUPPORTED
// Free Spatial Attributes Configuration Surface for DN kernel
pOsInterface->pfnFreeResource(
pOsInterface,
&pVeboxState->VeboxSpatialAttributesConfigurationSurface.OsResource);
// Free Temp Surface for VEBOX
pOsInterface->pfnFreeResource(
pOsInterface,
&pVeboxState->VeboxTempSurface.OsResource);
#endif
// Free SFC resources
if (MEDIA_IS_SKU(pVeboxState->m_pSkuTable, FtrSFCPipe) &&
m_sfcPipeState)
{
m_sfcPipeState->FreeResources();
}
}
//!
//! \brief Setup Vebox_DI_IECP Command params for VEBOX final output surface on G9
//! \details Setup Vebox_DI_IECP Command params for VEBOX final output surface on G9
//! \param [in] bDiScdEnable
//! Is DI/Variances report enabled
//! \param [in,out] pVeboxDiIecpCmdParams
//! Pointer to VEBOX_DI_IECP command parameters
//! \return MOS_STATUS
//! Return MOS_STATUS_SUCCESS if successful, otherwise failed
//!
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::SetupDiIecpStateForOutputSurf(
bool bDiScdEnable,
PMHW_VEBOX_DI_IECP_CMD_PARAMS pVeboxDiIecpCmdParams)
{
PMOS_INTERFACE pOsInterface;
PRENDERHAL_INTERFACE pRenderHal;
PMHW_VEBOX_INTERFACE pVeboxInterface;
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
MHW_VEBOX_SURFACE_CNTL_PARAMS VeboxSurfCntlParams;
PVPHAL_SURFACE pSurface;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
pOsInterface = pVeboxState->m_pOsInterface;
pRenderHal = pVeboxState->m_pRenderHal;
pVeboxInterface = pVeboxState->m_pVeboxInterface;
// VEBOX final output surface
if (IS_VPHAL_OUTPUT_PIPE_VEBOX(pRenderData))
{
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pRenderData->pRenderTarget->OsResource,
true,
true));
pVeboxDiIecpCmdParams->pOsResCurrOutput =
&pRenderData->pRenderTarget->OsResource;
pVeboxDiIecpCmdParams->dwCurrOutputSurfOffset =
pRenderData->pRenderTarget->dwOffset;
pVeboxDiIecpCmdParams->CurrOutputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.CurrentOutputSurfMemObjCtl;
if (IsFormatMMCSupported(pRenderData->pRenderTarget->Format) &&
(pRenderData->Component == COMPONENT_VPreP) &&
(pRenderData->pRenderTarget->CompressionMode == MOS_MMC_HORIZONTAL))
{
// Update control bits for Current Output Surf
pSurface = pRenderData->pRenderTarget;
MOS_ZeroMemory(&VeboxSurfCntlParams, sizeof(VeboxSurfCntlParams));
VeboxSurfCntlParams.bIsCompressed = pSurface->bIsCompressed;
VeboxSurfCntlParams.CompressionMode = pSurface->CompressionMode;
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->AddVeboxSurfaceControlBits(
&VeboxSurfCntlParams,
(uint32_t *)&(pVeboxDiIecpCmdParams->CurrOutputSurfCtrl.Value)));
}
}
else if (bDiScdEnable)
{
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pVeboxState->FFDISurfaces[pRenderData->iFrame1]->OsResource,
true,
true));
pVeboxDiIecpCmdParams->pOsResCurrOutput =
&pVeboxState->FFDISurfaces[pRenderData->iFrame1]->OsResource;
pVeboxDiIecpCmdParams->CurrOutputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.CurrentOutputSurfMemObjCtl;
// Update control bits for Current Output Surf
pSurface = pVeboxState->FFDISurfaces[pRenderData->iFrame1];
MOS_ZeroMemory(&VeboxSurfCntlParams, sizeof(VeboxSurfCntlParams));
VeboxSurfCntlParams.bIsCompressed = pSurface->bIsCompressed;
VeboxSurfCntlParams.CompressionMode = pSurface->CompressionMode;
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->AddVeboxSurfaceControlBits(
&VeboxSurfCntlParams,
(uint32_t *)&(pVeboxDiIecpCmdParams->CurrOutputSurfCtrl.Value)));
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pVeboxState->FFDISurfaces[pRenderData->iFrame0]->OsResource,
true,
true));
pVeboxDiIecpCmdParams->pOsResPrevOutput =
&pVeboxState->FFDISurfaces[pRenderData->iFrame0]->OsResource;
pVeboxDiIecpCmdParams->PrevOutputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.CurrentOutputSurfMemObjCtl;
// Update control bits for PrevOutput surface
pSurface = pVeboxState->FFDISurfaces[pRenderData->iFrame0];
MOS_ZeroMemory(&VeboxSurfCntlParams, sizeof(VeboxSurfCntlParams));
VeboxSurfCntlParams.bIsCompressed = pSurface->bIsCompressed;
VeboxSurfCntlParams.CompressionMode = pSurface->CompressionMode;
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->AddVeboxSurfaceControlBits(
&VeboxSurfCntlParams,
(uint32_t *)&(pVeboxDiIecpCmdParams->PrevOutputSurfCtrl.Value)));
}
else if (IsIECPEnabled()) // IECP output surface without DI
{
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pVeboxState->FFDISurfaces[pRenderData->iCurDNOut]->OsResource,
true,
true));
pVeboxDiIecpCmdParams->pOsResCurrOutput =
&pVeboxState->FFDISurfaces[pRenderData->iCurDNOut]->OsResource;
pVeboxDiIecpCmdParams->CurrOutputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.CurrentOutputSurfMemObjCtl;
// Update control bits for CurrOutputSurf surface
pSurface = pVeboxState->FFDISurfaces[pRenderData->iCurDNOut];
MOS_ZeroMemory(&VeboxSurfCntlParams, sizeof(VeboxSurfCntlParams));
VeboxSurfCntlParams.bIsCompressed = pSurface->bIsCompressed;
VeboxSurfCntlParams.CompressionMode = pSurface->CompressionMode;
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->AddVeboxSurfaceControlBits(
&VeboxSurfCntlParams,
(uint32_t *)&(pVeboxDiIecpCmdParams->CurrOutputSurfCtrl.Value)));
}
finish:
return eStatus;
}
//!
//! \brief Setup Vebox_DI_IECP Command params for Gen9
//! \details Setup Vebox_DI_IECP Command params for Gen9
//! \param [in] bDiScdEnable
//! Is DI/Variances report enabled
//! \param [in,out] pVeboxDiIecpCmdParams
//! Pointer to VEBOX_DI_IECP command parameters
//! \return MOS_STATUS
//! Return MOS_STATUS_SUCCESS if successful, otherwise failed
//!
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::SetupDiIecpState(
bool bDiScdEnable,
PMHW_VEBOX_DI_IECP_CMD_PARAMS pVeboxDiIecpCmdParams)
{
PMOS_INTERFACE pOsInterface;
PRENDERHAL_INTERFACE pRenderHal;
uint32_t dwWidth;
uint32_t dwHeight;
bool bDIEnable;
MOS_STATUS eStatus;
MHW_VEBOX_SURFACE_PARAMS MhwVeboxSurfaceParam;
PMHW_VEBOX_INTERFACE pVeboxInterface;
MHW_VEBOX_SURFACE_CNTL_PARAMS VeboxSurfCntlParams;
PVPHAL_SURFACE pSurface;
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
pOsInterface = pVeboxState->m_pOsInterface;
pRenderHal = pVeboxState->m_pRenderHal;
pVeboxInterface = pVeboxState->m_pVeboxInterface;
MOS_ZeroMemory(pVeboxDiIecpCmdParams, sizeof(*pVeboxDiIecpCmdParams));
// Align dwEndingX with surface state
bDIEnable = pRenderData->bDeinterlace || IsQueryVarianceEnabled();
VPHAL_RENDER_CHK_STATUS(VpHal_InitVeboxSurfaceParams(
pVeboxState->m_currentSurface, &MhwVeboxSurfaceParam));
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->VeboxAdjustBoundary(
&MhwVeboxSurfaceParam,
&dwWidth,
&dwHeight,
bDIEnable));
pVeboxDiIecpCmdParams->dwStartingX = 0;
pVeboxDiIecpCmdParams->dwEndingX = dwWidth - 1;
// Input Surface
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pVeboxState->m_currentSurface->OsResource,
false,
true));
pVeboxDiIecpCmdParams->pOsResCurrInput =
&pVeboxState->m_currentSurface->OsResource;
pVeboxDiIecpCmdParams->dwCurrInputSurfOffset =
pVeboxState->m_currentSurface->dwOffset;
pVeboxDiIecpCmdParams->CurrInputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.CurrentInputSurfMemObjCtl;
// Update control bits for current surface
pSurface = pVeboxState->m_currentSurface;
MOS_ZeroMemory(&VeboxSurfCntlParams, sizeof(VeboxSurfCntlParams));
VeboxSurfCntlParams.bIsCompressed = pSurface->bIsCompressed;
VeboxSurfCntlParams.CompressionMode = pSurface->CompressionMode;
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->AddVeboxSurfaceControlBits(
&VeboxSurfCntlParams,
(uint32_t *)&(pVeboxDiIecpCmdParams->CurrInputSurfCtrl.Value)));
// Reference surface
if (pRenderData->bRefValid)
{
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pVeboxState->m_previousSurface->OsResource,
false,
true));
pVeboxDiIecpCmdParams->pOsResPrevInput =
&pVeboxState->m_previousSurface->OsResource;
pVeboxDiIecpCmdParams->dwPrevInputSurfOffset =
pVeboxState->m_previousSurface->dwOffset;
pVeboxDiIecpCmdParams->PrevInputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.PreviousInputSurfMemObjCtl;
// Update control bits for PreviousSurface surface
pSurface = pVeboxState->m_previousSurface;
MOS_ZeroMemory(&VeboxSurfCntlParams, sizeof(VeboxSurfCntlParams));
VeboxSurfCntlParams.bIsCompressed = pSurface->bIsCompressed;
VeboxSurfCntlParams.CompressionMode = pSurface->CompressionMode;
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->AddVeboxSurfaceControlBits(
&VeboxSurfCntlParams,
(uint32_t *)&(pVeboxDiIecpCmdParams->PrevInputSurfCtrl.Value)));
}
// VEBOX final output surface
VPHAL_RENDER_CHK_STATUS(SetupDiIecpStateForOutputSurf(bDiScdEnable, pVeboxDiIecpCmdParams));
// DN intermediate output surface
if (IsFFDNSurfNeeded())
{
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pVeboxState->FFDNSurfaces[pRenderData->iCurDNOut]->OsResource,
true,
true));
pVeboxDiIecpCmdParams->pOsResDenoisedCurrOutput =
&pVeboxState->FFDNSurfaces[pRenderData->iCurDNOut]->OsResource;
pVeboxDiIecpCmdParams->DenoisedCurrOutputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.DnOutSurfMemObjCtl;
// Update control bits for DenoisedCurrOutputSurf surface
pSurface = pVeboxState->FFDNSurfaces[pRenderData->iCurDNOut];
MOS_ZeroMemory(&VeboxSurfCntlParams, sizeof(VeboxSurfCntlParams));
VeboxSurfCntlParams.bIsCompressed = pSurface->bIsCompressed;
VeboxSurfCntlParams.CompressionMode = pSurface->CompressionMode;
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->AddVeboxSurfaceControlBits(
&VeboxSurfCntlParams,
(uint32_t *)&(pVeboxDiIecpCmdParams->DenoisedCurrOutputSurfCtrl.Value)));
// For DN + SFC scenario, allocate FFDISurfaces also
// since this usage needs IECP implicitly
// For DN + DI + SFC, DI have registered FFDISurfaces, So don't register again
if (IS_VPHAL_OUTPUT_PIPE_SFC(pRenderData) && !bDiScdEnable)
{
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pVeboxState->FFDISurfaces[pRenderData->iCurDNOut]->OsResource,
true,
true));
pVeboxDiIecpCmdParams->pOsResCurrOutput =
&pVeboxState->FFDISurfaces[pRenderData->iCurDNOut]->OsResource;
pVeboxDiIecpCmdParams->CurrOutputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.CurrentOutputSurfMemObjCtl;
// Update control bits for CurrOutputSurf surface
pSurface = pVeboxState->FFDISurfaces[pRenderData->iCurDNOut];
MOS_ZeroMemory(&VeboxSurfCntlParams, sizeof(VeboxSurfCntlParams));
VeboxSurfCntlParams.bIsCompressed = pSurface->bIsCompressed;
VeboxSurfCntlParams.CompressionMode = pSurface->CompressionMode;
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->AddVeboxSurfaceControlBits(
&VeboxSurfCntlParams,
(uint32_t *)&(pVeboxDiIecpCmdParams->CurrOutputSurfCtrl.Value)));
}
}
// STMM surface
if (bDiScdEnable || IsSTMMSurfNeeded())
{
// STMM in
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pVeboxState->STMMSurfaces[pRenderData->iCurHistIn].OsResource,
false,
true));
pVeboxDiIecpCmdParams->pOsResStmmInput =
&pVeboxState->STMMSurfaces[pRenderData->iCurHistIn].OsResource;
pVeboxDiIecpCmdParams->StmmInputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.STMMInputSurfMemObjCtl;
// Update control bits for stmm input surface
pSurface = &(pVeboxState->STMMSurfaces[pRenderData->iCurHistIn]);
MOS_ZeroMemory(&VeboxSurfCntlParams, sizeof(VeboxSurfCntlParams));
VeboxSurfCntlParams.bIsCompressed = pSurface->bIsCompressed;
VeboxSurfCntlParams.CompressionMode = pSurface->CompressionMode;
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->AddVeboxSurfaceControlBits(
&VeboxSurfCntlParams,
(uint32_t *)&(pVeboxDiIecpCmdParams->StmmInputSurfCtrl.Value)));
// STMM out
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pVeboxState->STMMSurfaces[pRenderData->iCurHistOut].OsResource,
true,
true));
pVeboxDiIecpCmdParams->pOsResStmmOutput =
&pVeboxState->STMMSurfaces[pRenderData->iCurHistOut].OsResource;
pVeboxDiIecpCmdParams->StmmOutputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.STMMOutputSurfMemObjCtl;
// Update control bits for stmm output surface
pSurface = &(pVeboxState->STMMSurfaces[pRenderData->iCurHistOut]);
MOS_ZeroMemory(&VeboxSurfCntlParams, sizeof(VeboxSurfCntlParams));
VeboxSurfCntlParams.bIsCompressed = pSurface->bIsCompressed;
VeboxSurfCntlParams.CompressionMode = pSurface->CompressionMode;
VPHAL_RENDER_CHK_STATUS(pVeboxInterface->AddVeboxSurfaceControlBits(
&VeboxSurfCntlParams,
(uint32_t *)&(pVeboxDiIecpCmdParams->StmmOutputSurfCtrl.Value)));
}
// Statistics data: GNE, FMD
VPHAL_RENDER_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
&pVeboxState->VeboxStatisticsSurface.OsResource,
true,
true));
pVeboxDiIecpCmdParams->pOsResStatisticsOutput =
&pVeboxState->VeboxStatisticsSurface.OsResource;
pVeboxDiIecpCmdParams->StatisticsOutputSurfCtrl.Value =
pVeboxState->DnDiSurfMemObjCtl.StatisticsOutputSurfMemObjCtl;
finish:
return eStatus;
}
//!
//! \brief Vebox query statistics surface layout
//! \details Get Specific Layout Info like GNE Offset, size of per frame info inside
//! Vebox Statistics Surface for SKL+
//! SKL+ changes:
//! 1) ACE histogram is outside of Vebox Statistics Surface;
//! 2) Add White Balence Statistics;
//!
//! | Layout of Statistics surface when DI enabled and DN either On or Off on SKL+\n
//! | --------------------------------------------------------------\n
//! | | 16 bytes for x=0, Y=0 | 16 bytes for x=16, Y=0 | ...\n
//! | |-------------------------------------------------------------\n
//! | | 16 bytes for x=0, Y=4 | ...\n
//! | |------------------------------\n
//! | | ...\n
//! | |------------------------------\n
//! | | 16 bytes for x=0, Y=height-4| ...\n
//! | |-----------------------------------------------Pitch--------------\n
//! | | 17 DW Reserved | 2 DW STD0 | 2 DW GCC0 | 11 DW Reserved |\n
//! | |------------------------------------------------------------------\n
//! | | 11 DW FMD0 | 6 DW GNE0 | 2 DW STD0 | 2 DW GCC0 | 11 DW Reserved |\n
//! | |------------------------------------------------------------------\n
//! | | 17 DW Reserved | 2 DW STD1 | 2 DW GCC1 | 11 DW Reserved |\n
//! | |------------------------------------------------------------------\n
//! | | 11 DW FMD1 | 6 DW GNE1 | 2 DW STD1 | 2 DW GCC1 | 11 DW Reserved |\n
//! | -------------------------------------------------------------------\n
//! |\n
//! | Layout of Statistics surface when DN enabled and DI disabled\n
//! | --------------------------------------------------------------\n
//! | | 16 bytes for x=0, Y=0 | 16 bytes for x=16, Y=0 | ...\n
//! | |-------------------------------------------------------------\n
//! | | 16 bytes for x=0, Y=4 | ...\n
//! | |------------------------------\n
//! | | ...\n
//! | |------------------------------\n
//! | | 16 bytes for x=0, Y=height-4| ...\n
//! | |-----------------------------------------------Pitch--------------\n
//! | | 11 DW FMD0 | 6 DW GNE0 | 2 DW STD0 | 2 DW GCC0 | 11 DW Reserved |\n
//! | |------------------------------------------------------------------\n
//! | | 11 DW FMD1 | 6 DW GNE1 | 2 DW STD1 | 2 DW GCC1 | 11 DW Reserved |\n
//! | -------------------------------------------------------------------\n
//! |\n
//! | Layout of Statistics surface when both DN and DI are disabled\n
//! | ------------------------------------------------Pitch--------------\n
//! | | 17 DW White Balence0 | 2 DW STD0 | 2 DW GCC0 | 11 DW Reserved |\n
//! | |------------------------------------------------------------------\n
//! | | 17 DW White Balence1 | 2 DW STD1 | 2 DW GCC1 | 11 DW Reserved |\n
//! | -------------------------------------------------------------------\n
//! \param [in] QueryType
//! Query type
//! \param [out] pQuery
//! return layout type
//! \return MOS_STATUS
//! Return MOS_STATUS_SUCCESS if successful, otherwise failed
//!
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::VeboxQueryStatLayout(
VEBOX_STAT_QUERY_TYPE QueryType,
uint32_t* pQuery)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
VPHAL_RENDER_ASSERT(pQuery);
switch (QueryType)
{
case VEBOX_STAT_QUERY_GNE_OFFEST:
*pQuery = VPHAL_VEBOX_STATISTICS_SURFACE_GNE_OFFSET_G9;
break;
case VEBOX_STAT_QUERY_PER_FRAME_SIZE:
*pQuery = VPHAL_VEBOX_STATISTICS_PER_FRAME_SIZE_G9;
break;
case VEBOX_STAT_QUERY_FMD_OFFEST:
*pQuery = VPHAL_VEBOX_STATISTICS_SURFACE_FMD_OFFSET_G9;
break;
case VEBOX_STAT_QUERY_STD_OFFEST:
*pQuery = VPHAL_VEBOX_STATISTICS_SURFACE_STD_OFFSET_G9;
break;
default:
VPHAL_RENDER_ASSERTMESSAGE("Vebox Statistics Layout Query, type ('%d') is not implemented.", QueryType);
eStatus = MOS_STATUS_UNKNOWN;
break;
}
return eStatus;
}
//!
//! \brief Vebox get Luma default value
//! \details Initialize luma denoise paramters w/ default values.
//! \param [out] pLumaParams
//! Pointer to Luma DN parameter
//! \return void
//!
void VPHAL_VEBOX_STATE_G9_BASE::GetLumaDefaultValue(
PVPHAL_SAMPLER_STATE_DNDI_PARAM pLumaParams)
{
VPHAL_RENDER_ASSERT(pLumaParams);
pLumaParams->dwDenoiseASDThreshold = NOISE_ABSSUMTEMPORALDIFF_THRESHOLD_DEFAULT_G9;
pLumaParams->dwDenoiseHistoryDelta = NOISE_HISTORY_DELTA_DEFAULT;
pLumaParams->dwDenoiseMaximumHistory = NOISE_HISTORY_MAX_DEFAULT_G9;
pLumaParams->dwDenoiseSTADThreshold = NOISE_SUMABSTEMPORALDIFF_THRESHOLD_DEFAULT_G9;
pLumaParams->dwDenoiseSCMThreshold = NOISE_SPATIALCOMPLEXITYMATRIX_THRESHOLD_DEFAULT_G9;
pLumaParams->dwDenoiseMPThreshold = NOISE_NUMMOTIONPIXELS_THRESHOLD_DEFAULT_G9;
pLumaParams->dwLTDThreshold = NOISE_LOWTEMPORALPIXELDIFF_THRESHOLD_DEFAULT_G9;
pLumaParams->dwTDThreshold = NOISE_TEMPORALPIXELDIFF_THRESHOLD_DEFAULT_G9;
}
//!
//! \brief Vebox set DN parameter
//! \details Set denoise paramters for luma and chroma.
//! \param [in] pSrcSurface
//! Pointer to input surface of Vebox
//! \param [in] pLumaParams
//! Pointer to Luma DN parameter
//! \param [in] pChromaParams
//! Pointer to Chroma DN parameter
//! \return MOS_STATUS
//! Return MOS_STATUS_SUCCESS if successful, otherwise failed
//!
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::SetDNDIParams(
PVPHAL_SURFACE pSrcSurface,
PVPHAL_SAMPLER_STATE_DNDI_PARAM pLumaParams,
PVPHAL_DNUV_PARAMS pChromaParams)
{
MOS_STATUS eStatus;
PVPHAL_DENOISE_PARAMS pDNParams;
uint32_t dwDenoiseFactor;
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
VPHAL_RENDER_ASSERT(pSrcSurface);
VPHAL_RENDER_ASSERT(pLumaParams);
VPHAL_RENDER_ASSERT(pChromaParams);
VPHAL_RENDER_ASSERT(pRenderData);
eStatus = MOS_STATUS_SUCCESS;
pDNParams = pSrcSurface->pDenoiseParams;
VPHAL_RENDER_ASSERT(pDNParams);
// Set Luma DN params
if (pRenderData->bDenoise)
{
// Setup Denoise Params
GetLumaDefaultValue(pLumaParams);
// Initialize pixel range threshold array
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[0] = NOISE_BLF_RANGE_THRESHOLD_S0_DEFAULT;
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[1] = NOISE_BLF_RANGE_THRESHOLD_S1_DEFAULT;
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[2] = NOISE_BLF_RANGE_THRESHOLD_S2_DEFAULT;
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[3] = NOISE_BLF_RANGE_THRESHOLD_S3_DEFAULT;
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[4] = NOISE_BLF_RANGE_THRESHOLD_S4_DEFAULT;
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[5] = NOISE_BLF_RANGE_THRESHOLD_S5_DEFAULT;
// Initialize pixel range weight array
pRenderData->VeboxDNDIParams.dwPixRangeWeight[0] = NOISE_BLF_RANGE_WGTS0_DEFAULT;
pRenderData->VeboxDNDIParams.dwPixRangeWeight[1] = NOISE_BLF_RANGE_WGTS1_DEFAULT;
pRenderData->VeboxDNDIParams.dwPixRangeWeight[2] = NOISE_BLF_RANGE_WGTS2_DEFAULT;
pRenderData->VeboxDNDIParams.dwPixRangeWeight[3] = NOISE_BLF_RANGE_WGTS3_DEFAULT;
pRenderData->VeboxDNDIParams.dwPixRangeWeight[4] = NOISE_BLF_RANGE_WGTS4_DEFAULT;
pRenderData->VeboxDNDIParams.dwPixRangeWeight[5] = NOISE_BLF_RANGE_WGTS5_DEFAULT;
// Denoise Slider case (no auto DN detect)
if (!pDNParams->bAutoDetect)
{
dwDenoiseFactor = (uint32_t)pDNParams->fDenoiseFactor;
if (dwDenoiseFactor > NOISEFACTOR_MAX)
{
dwDenoiseFactor = NOISEFACTOR_MAX;
}
pLumaParams->dwDenoiseHistoryDelta = dwDenoiseHistoryDelta[dwDenoiseFactor];
pLumaParams->dwDenoiseMaximumHistory = dwDenoiseMaximumHistory[dwDenoiseFactor];
pLumaParams->dwDenoiseASDThreshold = dwDenoiseASDThreshold[dwDenoiseFactor];
pLumaParams->dwDenoiseSCMThreshold = dwDenoiseSCMThreshold[dwDenoiseFactor];
pLumaParams->dwDenoiseMPThreshold = dwDenoiseMPThreshold[dwDenoiseFactor];
pLumaParams->dwLTDThreshold = dwLTDThreshold[dwDenoiseFactor];
pLumaParams->dwTDThreshold = dwTDThreshold[dwDenoiseFactor];
pLumaParams->dwDenoiseSTADThreshold = dwDenoiseSTADThreshold[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[0] = dwPixRangeThreshold0[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[1] = dwPixRangeThreshold1[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[2] = dwPixRangeThreshold2[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[3] = dwPixRangeThreshold3[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[4] = dwPixRangeThreshold4[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeThreshold[5] = dwPixRangeThreshold5[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeWeight[0] = dwPixRangeWeight0[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeWeight[1] = dwPixRangeWeight1[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeWeight[2] = dwPixRangeWeight2[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeWeight[3] = dwPixRangeWeight3[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeWeight[4] = dwPixRangeWeight4[dwDenoiseFactor];
pRenderData->VeboxDNDIParams.dwPixRangeWeight[5] = dwPixRangeWeight5[dwDenoiseFactor];
}
}
// Set Chroma DN params
if (pRenderData->bChromaDenoise)
{
// Setup Denoise Params
pChromaParams->dwHistoryDeltaUV = NOISE_HISTORY_DELTA_DEFAULT;
pChromaParams->dwHistoryMaxUV = NOISE_HISTORY_MAX_DEFAULT;
// Denoise Slider case (no auto DN detect)
if (!pDNParams->bAutoDetect)
{
dwDenoiseFactor = (uint32_t)pDNParams->fDenoiseFactor;
if (dwDenoiseFactor > NOISEFACTOR_MAX)
{
dwDenoiseFactor = NOISEFACTOR_MAX;
}
pChromaParams->dwLTDThresholdU =
pChromaParams->dwLTDThresholdV = dwLTDThresholdUV[dwDenoiseFactor];
pChromaParams->dwTDThresholdU =
pChromaParams->dwTDThresholdV = dwTDThresholdUV[dwDenoiseFactor];
pChromaParams->dwSTADThresholdU =
pChromaParams->dwSTADThresholdV = dwSTADThresholdUV[dwDenoiseFactor];
}
}
if (pDNParams && pDNParams->bEnableHVSDenoise)
{
VPHAL_VEBOX_STATE::VeboxSetHVSDNParams(pSrcSurface);
}
return eStatus;
}
//!
//! \brief Get output surface of Vebox
//! \details Get output surface of Vebox in current operation
//! \param [in] bDiVarianceEnable
//! Is DI/Variances report enabled
//! \return PVPHAL_SURFACE
//! Corresponding output surface pointer
//!
PVPHAL_SURFACE VPHAL_VEBOX_STATE_G9_BASE::GetSurfOutput(
bool bDiVarianceEnable)
{
PVPHAL_SURFACE pSurface = nullptr;
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
if (IS_VPHAL_OUTPUT_PIPE_VEBOX(pRenderData)) // Vebox output pipe
{
pSurface = pRenderData->pRenderTarget;
}
else if (bDiVarianceEnable) // DNDI, DI, DI + IECP
{
pSurface = pVeboxState->FFDISurfaces[pRenderData->iFrame0];
}
else if (IsIECPEnabled()) // DN + IECP or IECP only
{
pSurface = pVeboxState->FFDISurfaces[pRenderData->iCurDNOut];
}
else if (pRenderData->bDenoise) // DN only
{
pSurface = pVeboxState->FFDNSurfaces[pRenderData->iCurDNOut];
}
else if (IS_VPHAL_OUTPUT_PIPE_SFC(pRenderData)) // Write to SFC
{
// Vebox o/p should not be written to memory
pSurface = nullptr;
}
else
{
VPHAL_RENDER_ASSERTMESSAGE("Unable to determine Vebox Output Surface.");
}
return pSurface;
}
//!
//! \brief Setup surface states for Vebox
//! \details Setup surface states for use in the current Vebox Operation
//! \param [in] bDiVarianceEnable
//! Is DI/Variances report enabled
//! \param [in,out] pVeboxSurfaceStateCmdParams
//! Pointer to VEBOX_SURFACE_STATE command parameters
//! \return void
//!
void VPHAL_VEBOX_STATE_G9_BASE::SetupSurfaceStates(
bool bDiVarianceEnable,
PVPHAL_VEBOX_SURFACE_STATE_CMD_PARAMS pVeboxSurfaceStateCmdParams)
{
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
MOS_ZeroMemory(pVeboxSurfaceStateCmdParams,
sizeof(VPHAL_VEBOX_SURFACE_STATE_CMD_PARAMS));
pVeboxSurfaceStateCmdParams->pSurfInput = pVeboxState->m_currentSurface;
pVeboxSurfaceStateCmdParams->pSurfOutput = pVeboxState->GetSurfOutput(bDiVarianceEnable);
pVeboxSurfaceStateCmdParams->pSurfSTMM = &pVeboxState->STMMSurfaces[pRenderData->iCurHistIn];
pVeboxSurfaceStateCmdParams->pSurfDNOutput = pVeboxState->FFDNSurfaces[pRenderData->iCurDNOut];
pVeboxSurfaceStateCmdParams->bDIEnable = bDiVarianceEnable;
}
bool VPHAL_VEBOX_STATE_G9_BASE::UseKernelResource()
{
return false; // can always use driver resource in clear memory
}
//!
//! \brief Setup Vebox_State Command parameter
//! \param [in] bDiVarianceEnable
//! Is DI/Variances report enabled
//! \param [in,out] pVeboxStateCmdParams
//! Pointer to VEBOX_STATE command parameters
//! \return MOS_STATUS
//! Return MOS_STATUS_SUCCESS if successful, otherwise failed
//!
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::SetupVeboxState(
bool bDiVarianceEnable,
PMHW_VEBOX_STATE_CMD_PARAMS pVeboxStateCmdParams)
{
PMHW_VEBOX_MODE pVeboxMode;
PMOS_INTERFACE pOsInterface;
MOS_STATUS eStatus;
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
pVeboxMode = &pVeboxStateCmdParams->VeboxMode;
pOsInterface = pVeboxState->m_pOsInterface;
eStatus = MOS_STATUS_SUCCESS;
MOS_ZeroMemory(pVeboxStateCmdParams, sizeof(*pVeboxStateCmdParams));
if (IS_VPHAL_OUTPUT_PIPE_SFC(pRenderData) ||
IS_VPHAL_OUTPUT_PIPE_VEBOX(pRenderData))
{
// On SKL, GlobalIECP must be enabled when the output pipe is Vebox or SFC
pVeboxMode->GlobalIECPEnable = true;
}
else
{
pVeboxMode->GlobalIECPEnable = IsIECPEnabled();
}
pVeboxMode->DIEnable = bDiVarianceEnable;
pVeboxMode->SFCParallelWriteEnable = IS_VPHAL_OUTPUT_PIPE_SFC(pRenderData) &&
(pRenderData->bDenoise || bDiVarianceEnable);
pVeboxMode->DNEnable = pRenderData->bDenoise;
pVeboxMode->DNDIFirstFrame = !pRenderData->bRefValid;
pVeboxMode->DIOutputFrames = SetDIOutputFrame(pRenderData, pVeboxState, pVeboxMode);
pVeboxMode->DisableEncoderStatistics = true;
if((pVeboxMode->DIEnable == false) &&
(pVeboxMode->DNEnable != false || pVeboxMode->HotPixelFilteringEnable != false) &&
((pVeboxState->bDisableTemporalDenoiseFilter) ||
(IS_RGB_CSPACE(pVeboxState->m_currentSurface->ColorSpace)) ||
(pVeboxMode->HotPixelFilteringEnable && (pVeboxMode->DNEnable == false) && (pVeboxMode->DIEnable == false))))
{
pVeboxMode->DisableTemporalDenoiseFilter = true;
// GlobalIECP or Demosaic must be enabled even if IECP not used
pVeboxMode->GlobalIECPEnable = true;
}
else
{
pVeboxMode->DisableTemporalDenoiseFilter = false;
}
pVeboxStateCmdParams->bUseVeboxHeapKernelResource
= UseKernelResource();
// This field must be set if 00b for products that don't have 2 slices.
if (MEDIA_IS_SKU(pVeboxState->m_pRenderHal->pSkuTable, FtrSingleVeboxSlice))
{
pVeboxMode->SingleSliceVeboxEnable = 0;
}
else
{
// Permanent program limitation that should go in all the configurations of SKLGT which have 2 VEBOXes (i.e. GT3 & GT4)
// VEBOX1 should be disabled whenever there is an VE-SFC workload.
// This is because we have only one SFC all the GT configurations and that SFC is tied to VEBOX0.Hence the programming restriction.
if (IS_VPHAL_OUTPUT_PIPE_SFC(pRenderData))
{
pVeboxMode->SingleSliceVeboxEnable = 1;
}
else
{
pVeboxMode->SingleSliceVeboxEnable = 0;
}
}
return eStatus;
}
//!
//! \brief Get the output pipe on SKL
//! \details There are 3 output pipes on SKL. Check which output pipe can be applied
//! \param [in] pcRenderParams
//! Pointer to VpHal render parameters
//! \param [in] pSrcSurface
//! Pointer to input surface of Vebox
//! \param [out] pbCompNeeded
//! return whether composition is needed after Vebox/SFC
//! \return VPHAL_OUTPUT_PIPE_MODE
//! return the output pipe mode
//!
VPHAL_OUTPUT_PIPE_MODE VPHAL_VEBOX_STATE_G9_BASE::GetOutputPipe(
PCVPHAL_RENDER_PARAMS pcRenderParams,
PVPHAL_SURFACE pSrcSurface,
bool* pbCompNeeded)
{
VPHAL_OUTPUT_PIPE_MODE OutputPipe;
bool bCompBypassFeasible;
bool bOutputPipeVeboxFeasible;
PVPHAL_SURFACE pTarget;
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
OutputPipe = VPHAL_OUTPUT_PIPE_MODE_COMP;
bCompBypassFeasible = IS_COMP_BYPASS_FEASIBLE(*pbCompNeeded, pcRenderParams, pSrcSurface);
if (!bCompBypassFeasible)
{
OutputPipe = VPHAL_OUTPUT_PIPE_MODE_COMP;
goto finish;
}
bOutputPipeVeboxFeasible = IS_OUTPUT_PIPE_VEBOX_FEASIBLE(pVeboxState, pcRenderParams, pSrcSurface);
if (bOutputPipeVeboxFeasible)
{
OutputPipe = VPHAL_OUTPUT_PIPE_MODE_VEBOX;
goto finish;
}
pTarget = pcRenderParams->pTarget[0];
// Check if SFC can be the output pipe
if (m_sfcPipeState)
{
OutputPipe = m_sfcPipeState->GetOutputPipe(
pSrcSurface,
pTarget,
pcRenderParams);
}
else
{
OutputPipe = VPHAL_OUTPUT_PIPE_MODE_COMP;
}
// Explore the potential to still output by VEBOX and perform quick color fill in composition
if (bCompBypassFeasible &&
OutputPipe == VPHAL_OUTPUT_PIPE_MODE_COMP &&
pcRenderParams->pColorFillParams &&
pSrcSurface->rcDst.left == pTarget->rcDst.left &&
pSrcSurface->rcDst.top == pTarget->rcDst.top &&
pSrcSurface->rcDst.right == pTarget->rcDst.right &&
pSrcSurface->rcDst.bottom < pTarget->rcDst.bottom)
{
int32_t lTargetBottom;
lTargetBottom = pTarget->rcDst.bottom;
pTarget->rcDst.bottom = pSrcSurface->rcDst.bottom;
// Check if Vebox can be the output pipe again
bOutputPipeVeboxFeasible = IS_OUTPUT_PIPE_VEBOX_FEASIBLE(pVeboxState, pcRenderParams, pSrcSurface);
if (bOutputPipeVeboxFeasible)
{
OutputPipe = VPHAL_OUTPUT_PIPE_MODE_VEBOX;
pTarget->bFastColorFill = true;
}
pTarget->rcDst.bottom = lTargetBottom;
}
finish:
*pbCompNeeded = (OutputPipe == VPHAL_OUTPUT_PIPE_MODE_COMP) ? true : false;
return OutputPipe;
}
//!
//! \brief Vebox is needed on SKL
//! \details Check if Vebox Render operation can be applied
//! \param [in] pcRenderParams
//! Pointer to VpHal render parameters
//! \param [in,out] pRenderPassData
//! Pointer to Render data
//! \return bool
//! return true if Vebox is needed, otherwise false
//!
bool VPHAL_VEBOX_STATE_G9_BASE::IsNeeded(
PCVPHAL_RENDER_PARAMS pcRenderParams,
RenderpassData *pRenderPassData)
{
PVPHAL_VEBOX_RENDER_DATA pRenderData;
PRENDERHAL_INTERFACE pRenderHal;
PVPHAL_SURFACE pRenderTarget;
bool bVeboxNeeded;
PMOS_INTERFACE pOsInterface;
MOS_STATUS eStatus;
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
PVPHAL_SURFACE pSrcSurface;
bVeboxNeeded = false;
VPHAL_RENDER_CHK_NULL(pVeboxState->m_pRenderHal);
VPHAL_RENDER_CHK_NULL(pVeboxState->m_pOsInterface);
pRenderHal = pVeboxState->m_pRenderHal;
pOsInterface = pVeboxState->m_pOsInterface;
pRenderTarget = pcRenderParams->pTarget[0];
pRenderData = GetLastExecRenderData();
pSrcSurface = pRenderPassData->pSrcSurface;
VPHAL_RENDER_CHK_NULL(pSrcSurface);
// Check whether VEBOX is available
// VTd doesn't support VEBOX
if (!MEDIA_IS_SKU(pVeboxState->m_pSkuTable, FtrVERing))
{
pRenderPassData->bCompNeeded = true;
goto finish;
}
// check if UserPtr enabling.
if (pcRenderParams->bUserPrt_16Align[0])
{
pRenderPassData->bCompNeeded = true;
goto finish;
}
// Check if the Surface size is greater than 64x16 which is the minimum Width and Height VEBOX can handle
if (pSrcSurface->dwWidth < MHW_VEBOX_MIN_WIDTH || pSrcSurface->dwHeight < MHW_VEBOX_MIN_HEIGHT)
{
pRenderPassData->bCompNeeded = true;
goto finish;
}
pRenderData->Init();
if (MEDIA_IS_SKU(m_pSkuTable, FtrSFCPipe) && m_sfcPipeState)
{
m_sfcPipeState->InitRenderData();
}
// Determine the output pipe before setting the rendering flags for Vebox and SFC
SET_VPHAL_OUTPUT_PIPE(
pRenderData,
GetOutputPipe(
pcRenderParams,
pSrcSurface,
&pRenderPassData->bCompNeeded));
// Set MMC State
SET_VPHAL_MMC_STATE(pRenderData, pVeboxState->bEnableMMC);
// Update execution state based on current and past events such as the
// # of future and past frames available.
pVeboxState->UpdateVeboxExecutionState(
pSrcSurface,
pRenderData->OutputPipe);
// Set Component
SET_VPHAL_COMPONENT(pRenderData, pcRenderParams->Component);
// Check if Vebox can be used to process the surface
if (pVeboxState->IsFormatSupported(pSrcSurface))
{
// Save Alpha passed by App to be used in Vebox
if (IS_VPHAL_OUTPUT_PIPE_VEBOX(pRenderData))
{
pRenderData->pAlphaParams = pcRenderParams->pCompAlpha;
}
// Setup Rendering Flags for Vebox
VeboxSetRenderingFlags(
pSrcSurface,
pRenderTarget);
// Vebox is needed if Vebox isn't bypassed
bVeboxNeeded = !pRenderData->bVeboxBypass;
}
// if ScalingPreference == VPHAL_SCALING_PREFER_SFC_FOR_VEBOX, use SFC only when VEBOX is required
if ((pSrcSurface->ScalingPreference == VPHAL_SCALING_PREFER_SFC_FOR_VEBOX) &&
(bVeboxNeeded == false))
{
VPHAL_RENDER_NORMALMESSAGE("DDI choose to use SFC only for VEBOX, and since VEBOX is not required, change to Composition.");
pRenderData->OutputPipe = VPHAL_OUTPUT_PIPE_MODE_COMP;
pRenderPassData->bCompNeeded = true;
}
// Check if we want to enable SFC processing
if (IS_VPHAL_OUTPUT_PIPE_SFC(pRenderData))
{
// Setup Rendering Flags for SFC pipe
m_sfcPipeState->SetRenderingFlags(
pcRenderParams->pColorFillParams,
pcRenderParams->pCompAlpha,
pSrcSurface,
pRenderTarget,
pRenderData);
// Update Vebox Rendering Flags when the output pipe is SFC.
// If input surface format is AYUV, and just have one layer as primary,Procamp can also enable.
// Those flags cannot be updated inside Vebox's SetRenderingFlags due to ScalingPreference option will
// turn back to composition when Vebox is not needed in above code.
pRenderData->bProcamp = (IS_YUV_FORMAT(pSrcSurface->Format) ||
(pSrcSurface->Format == Format_AYUV &&
pcRenderParams->uSrcCount == 1)) &&
pSrcSurface->pProcampParams &&
pSrcSurface->pProcampParams->bEnabled;
pRenderData->bBeCsc = IS_RGB_CSPACE(pSrcSurface->ColorSpace);
pRenderData->bIECP = pRenderData->bIECP ||
pRenderData->bProcamp ||
pRenderData->bBeCsc;
bVeboxNeeded = true;
}
finish:
return bVeboxNeeded;
}
//!
//! \brief Vebox get the back-end colorspace conversion matrix
//! \details When the i/o is A8R8G8B8 or X8R8G8B8, the transfer matrix
//! needs to be updated accordingly
//! \param [in] pSrcSurface
//! Pointer to input surface of Vebox
//! \param [in] pOutSurface
//! Pointer to output surface of Vebox
//! \return void
//!
void VPHAL_VEBOX_STATE_G9_BASE::VeboxGetBeCSCMatrix(
PVPHAL_SURFACE pSrcSurface,
PVPHAL_SURFACE pOutSurface)
{
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
float fTemp[3];
// Get the matrix to use for conversion
VpHal_GetCscMatrix(
pSrcSurface->ColorSpace,
pOutSurface->ColorSpace,
pVeboxState->fCscCoeff,
pVeboxState->fCscInOffset,
pVeboxState->fCscOutOffset);
// Vebox CSC converts RGB input to YUV for SFC
// Vebox only supports A8B8G8R8 input, swap the 1st and 3rd
// columns of the transfer matrix for A8R8G8B8 and X8R8G8B8
// This only happens when SFC output is used
if ((pSrcSurface->Format == Format_A8R8G8B8) ||
(pSrcSurface->Format == Format_X8R8G8B8))
{
fTemp[0] = pVeboxState->fCscCoeff[0];
fTemp[1] = pVeboxState->fCscCoeff[3];
fTemp[2] = pVeboxState->fCscCoeff[6];
pVeboxState->fCscCoeff[0] = pVeboxState->fCscCoeff[2];
pVeboxState->fCscCoeff[3] = pVeboxState->fCscCoeff[5];
pVeboxState->fCscCoeff[6] = pVeboxState->fCscCoeff[8];
pVeboxState->fCscCoeff[2] = fTemp[0];
pVeboxState->fCscCoeff[5] = fTemp[1];
pVeboxState->fCscCoeff[8] = fTemp[2];
}
}
#if VEBOX_AUTO_DENOISE_SUPPORTED
//!
//! \brief Load update kernel curbe data
//! \details Loads the static data of update kernel to curbe
//! \param [out] iCurbeOffsetOutDN
//! Pointer to DN kernel curbe offset
//! \return MOS_STATUS
//! Return MOS_STATUS_SUCCESS if successful, otherwise failed
//!
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::LoadUpdateDenoiseKernelStaticData(
int32_t* iCurbeOffsetOutDN)
{
PRENDERHAL_INTERFACE pRenderHal;
VEBOX_STATE_UPDATE_STATIC_DATA_G9 DNStaticData; // DN Update kernelStatic parameters
PMHW_VEBOX_INTERFACE pVeboxInterface;
PVPHAL_DENOISE_PARAMS pDenoiseParams; // Denoise
int32_t iOffset0, iOffset1;
MOS_STATUS eStatus;
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
pRenderHal = pVeboxState->m_pRenderHal;
pVeboxInterface = pVeboxState->m_pVeboxInterface;
eStatus = MOS_STATUS_SUCCESS;
// init the static data
MOS_ZeroMemory(&DNStaticData, sizeof(VEBOX_STATE_UPDATE_STATIC_DATA_G9));
pDenoiseParams = m_currentSurface->pDenoiseParams;
VPHAL_RENDER_ASSERT(pDenoiseParams);
// Get offset for slice0 and slice1
VPHAL_RENDER_CHK_STATUS(VeboxGetStatisticsSurfaceOffsets(
&iOffset0,
&iOffset1));
// Load DN update kernel CURBE data
if (pRenderData->bAutoDenoise)
{
// set the curbe data for DN update kernel
DNStaticData.DW00.OffsetToSlice0 = iOffset0;
DNStaticData.DW01.OffsetToSlice1 = iOffset1;
DNStaticData.DW02.FirstFrameFlag = pVeboxState->bFirstFrame;
DNStaticData.DW02.NoiseLevel = pDenoiseParams->NoiseLevel;
DNStaticData.DW03.RangeThrAdp2NLvl = 1;
DNStaticData.DW04.VeboxStatisticsSurface = BI_DN_STATISTICS_SURFACE;
DNStaticData.DW05.VeboxDndiStateSurface = BI_DN_VEBOX_STATE_SURFACE;
DNStaticData.DW06.VeboxTempSurface = BI_DN_TEMP_SURFACE;
DNStaticData.DW07.VeboxSpatialAttributesConfigurationSurface = BI_DN_SPATIAL_ATTRIBUTES_CONFIGURATION_SURFACE;
*iCurbeOffsetOutDN = pRenderHal->pfnLoadCurbeData(
pRenderHal,
pRenderData->pMediaState,
&DNStaticData,
sizeof(DNStaticData));
if (*iCurbeOffsetOutDN < 0)
{
eStatus = MOS_STATUS_UNKNOWN;
goto finish;
}
pRenderData->iCurbeLength += sizeof(DNStaticData);
}
finish:
return eStatus;
}
//!
//! \brief Setup surface states for Denoise
//! \details Setup Surface State for Vebox States Auto DN kernel
//! \return MOS_STATUS
//! Return MOS_STATUS_SUCCESS if successful, otherwise failed
//!
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::SetupSurfaceStatesForDenoise()
{
PRENDERHAL_INTERFACE pRenderHal;
PMOS_INTERFACE pOsInterface;
RENDERHAL_SURFACE_STATE_PARAMS SurfaceParams;
MOS_STATUS eStatus;
MOS_FORMAT tmpFormat;
bool bUseKernelResource;
const MHW_VEBOX_HEAP *pVeboxHeap = nullptr;
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
eStatus = MOS_STATUS_SUCCESS;
pRenderHal = pVeboxState->m_pRenderHal;
pOsInterface = pVeboxState->m_pOsInterface;
VPHAL_RENDER_CHK_STATUS(pVeboxState->m_pVeboxInterface->GetVeboxHeapInfo(
&pVeboxHeap));
VPHAL_RENDER_CHK_NULL(pVeboxHeap);
VPHAL_RENDER_CHK_NULL(pOsInterface);
VPHAL_RENDER_CHK_NULL(pOsInterface->osCpInterface);
bUseKernelResource = UseKernelResource();
MOS_ZeroMemory(&SurfaceParams, sizeof(SurfaceParams));
MOS_ZeroMemory(&pVeboxState->VeboxHeapResource, sizeof(VPHAL_SURFACE));
MOS_ZeroMemory(&pVeboxState->tmpResource, sizeof(VPHAL_SURFACE));
// Treat the 1D buffer as 2D surface
// VEBox State Surface
pVeboxState->VeboxHeapResource.Format = Format_L8;
pVeboxState->VeboxHeapResource.dwWidth = SECURE_BLOCK_COPY_KERNEL_SURF_WIDTH; // Hard code for secure Block Copy kernel
pVeboxState->VeboxHeapResource.dwPitch = SECURE_BLOCK_COPY_KERNEL_SURF_WIDTH; // Hard code for secure Block Copy kernel
pVeboxState->VeboxHeapResource.dwHeight =
MOS_ROUNDUP_DIVIDE(pVeboxHeap->uiInstanceSize, SECURE_BLOCK_COPY_KERNEL_SURF_WIDTH);
pVeboxState->VeboxHeapResource.dwOffset =
pVeboxHeap->uiInstanceSize *
pVeboxHeap->uiCurState;
pVeboxState->VeboxHeapResource.TileType = MOS_TILE_LINEAR;
pVeboxState->VeboxHeapResource.OsResource = bUseKernelResource ?
pVeboxHeap->KernelResource :
pVeboxHeap->DriverResource;
// Temp Surface: for Noise Level History
pVeboxState->tmpResource.Format = Format_L8;
pVeboxState->tmpResource.dwWidth = SECURE_BLOCK_COPY_KERNEL_SURF_WIDTH; // Hard code for secure Block Copy kernel
pVeboxState->tmpResource.dwPitch = SECURE_BLOCK_COPY_KERNEL_SURF_WIDTH; // Hard code for secure Block Copy kernel
pVeboxState->tmpResource.dwHeight =
MOS_ROUNDUP_DIVIDE(MHW_PAGE_SIZE, SECURE_BLOCK_COPY_KERNEL_SURF_WIDTH);
pVeboxState->tmpResource.dwOffset = 0;
pVeboxState->tmpResource.TileType = MOS_TILE_LINEAR;
pVeboxState->tmpResource.OsResource = pVeboxState->VeboxTempSurface.OsResource;
// Statistics Surface-----------------------------------------------------------
tmpFormat = pVeboxState->VeboxStatisticsSurface.Format;
pVeboxState->VeboxStatisticsSurface.Format = Format_RAW;
VPHAL_RENDER_CHK_STATUS(VpHal_CommonSetBufferSurfaceForHwAccess(
pRenderHal,
&pVeboxState->VeboxStatisticsSurface,
&pVeboxState->RenderHalVeboxStatisticsSurface,
nullptr,
pRenderData->iBindingTable,
BI_DN_STATISTICS_SURFACE,
false));
pVeboxState->VeboxStatisticsSurface.Format = tmpFormat;
// VEBox State Surface-----------------------------------------------------------
MOS_ZeroMemory(&SurfaceParams, sizeof(SurfaceParams));
SurfaceParams.Type = pRenderHal->SurfaceTypeDefault;
SurfaceParams.bRenderTarget = true;
SurfaceParams.bWidthInDword_Y = true;
SurfaceParams.bWidthInDword_UV = true;
SurfaceParams.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
SurfaceParams.bWidth16Align = false;
VPHAL_RENDER_CHK_STATUS(VpHal_CommonSetSurfaceForHwAccess(
pRenderHal,
&pVeboxState->VeboxHeapResource,
&pVeboxState->RenderHalVeboxHeapResource,
&SurfaceParams,
pRenderData->iBindingTable,
BI_DN_VEBOX_STATE_SURFACE,
true));
// VEBox Temp Surface-----------------------------------------------------------
MOS_ZeroMemory(&SurfaceParams, sizeof(SurfaceParams));
SurfaceParams.Type = pRenderHal->SurfaceTypeDefault;
SurfaceParams.bRenderTarget = true;
SurfaceParams.bWidthInDword_Y = true;
SurfaceParams.bWidthInDword_UV = true;
SurfaceParams.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
SurfaceParams.bWidth16Align = false;
// set bRenderTarget=false to skip first frame for PermeatePatchForHM().
if (pVeboxState->bFirstFrame && pOsInterface->osCpInterface->IsHMEnabled())
{
SurfaceParams.bRenderTarget = false;
}
VPHAL_RENDER_CHK_STATUS(VpHal_CommonSetSurfaceForHwAccess(
pRenderHal,
&pVeboxState->tmpResource,
&pVeboxState->RenderHalTmpResource,
&SurfaceParams,
pRenderData->iBindingTable,
BI_DN_TEMP_SURFACE,
true));
// Spatial Attributes Configuration Surface------------------------------------
MOS_ZeroMemory(&SurfaceParams, sizeof(SurfaceParams));
VPHAL_RENDER_CHK_STATUS(VpHal_CommonSetBufferSurfaceForHwAccess(
pRenderHal,
&pVeboxState->VeboxSpatialAttributesConfigurationSurface,
&pVeboxState->RenderHalVeboxSpatialAttributesConfigurationSurface,
&SurfaceParams,
pRenderData->iBindingTable,
BI_DN_SPATIAL_ATTRIBUTES_CONFIGURATION_SURFACE,
false));
finish:
return eStatus;
}
#endif
//!
//! \brief Setup kernels for Vebox auto mode features
//! \details Setup kernels that co-operate with Vebox auto mode features
//! \param [in] iKDTIndex
//! Index to Kernel Parameter Array (defined platform specific)
//! \return MOS_STATUS
//! Return MOS_STATUS_SUCCESS if successful, otherwise failed
//!
MOS_STATUS VPHAL_VEBOX_STATE_G9_BASE::SetupVeboxKernel(
int32_t iKDTIndex)
{
Kdll_CacheEntry *pCacheEntryTable; // Kernel Cache Entry table
Kdll_FilterEntry *pFilter; // Kernel Filter (points to base of filter array)
int32_t iKUID; // Kernel Unique ID (DNDI uses combined kernels)
int32_t iInlineLength; // Inline data length
MOS_STATUS eStatus; // Return code
PVPHAL_VEBOX_STATE_G9_BASE pVeboxState = this;
PVPHAL_VEBOX_RENDER_DATA pRenderData = GetLastExecRenderData();
// Initialize Variables
eStatus = MOS_STATUS_SUCCESS;
pFilter = &pVeboxState->SearchFilter[0];
pCacheEntryTable = pVeboxState->m_pKernelDllState->ComponentKernelCache.pCacheEntries;
// Initialize States
MOS_ZeroMemory(pFilter, sizeof(pVeboxState->SearchFilter));
MOS_ZeroMemory(&pRenderData->KernelEntry[iKDTIndex], sizeof(Kdll_CacheEntry));
#if VEBOX_AUTO_DENOISE_SUPPORTED
if (iKDTIndex == KERNEL_UPDATEDNSTATE)
{
iKUID = IDR_VP_UpdateDNState;
iInlineLength = 0; // No inline data
pRenderData->PerfTag = VPHAL_VEBOX_UPDATE_DN_STATE;
}
else // Incorrect index to kernel parameters array
#endif
{
VPHAL_RENDER_ASSERTMESSAGE(
"Incorrect index to kernel parameters array.");
eStatus = MOS_STATUS_UNKNOWN;
goto finish;
}
// Store pointer to Kernel Parameter
pRenderData->pKernelParam[iKDTIndex] =
&pVeboxState->pKernelParamTable[iKDTIndex];
// Set Parameters for Kernel Entry
pRenderData->KernelEntry[iKDTIndex].iKUID = iKUID;
pRenderData->KernelEntry[iKDTIndex].iKCID = -1;
pRenderData->KernelEntry[iKDTIndex].iFilterSize = 2;
pRenderData->KernelEntry[iKDTIndex].pFilter = pFilter;
pRenderData->KernelEntry[iKDTIndex].iSize = pCacheEntryTable[iKUID].iSize;
pRenderData->KernelEntry[iKDTIndex].pBinary = pCacheEntryTable[iKUID].pBinary;
// set the Inline Data length
pRenderData->iInlineLength = iInlineLength;
VPHAL_RENDER_NORMALMESSAGE(
"Vebox Kernels: %s", g_KernelDNDI_Str_g9[iKDTIndex]);
finish:
return eStatus;
}
//!
//! \brief Vebox format support check
//! \details Checks to see if Vebox operation is supported with source surface format
//! \param [in] pSrcSurface
//! Pointer to input surface of Vebox
//! \return bool
//! return true if input surface format is supported, otherwise false
//!
bool VPHAL_VEBOX_STATE_G9_BASE::IsFormatSupported(
PVPHAL_SURFACE pSrcSurface)
{
bool bRet;
bRet = false;
// Check if Sample Format is supported
// Vebox only support P016 format, P010 format can be supported by faking it as P016
if (pSrcSurface->Format != Format_NV12 &&
pSrcSurface->Format != Format_AYUV &&
pSrcSurface->Format != Format_Y416 &&
pSrcSurface->Format != Format_P010 &&
pSrcSurface->Format != Format_P016 &&
!IS_PA_FORMAT(pSrcSurface->Format))
{
VPHAL_RENDER_NORMALMESSAGE("Unsupported Source Format '0x%08x' for VEBOX.", pSrcSurface->Format);
goto finish;
}
bRet = true;
finish:
return bRet;
}
//!
//! \brief Vebox format support check
//! \details Checks to see if RT format is supported when Vebox output pipe is selected
//! \param [in] pSrcSurface
//! Pointer to Render source surface of VPP BLT
//! \param [in] pRTSurface
//! Pointer to Render target surface of VPP BLT
//! \return bool
//! return true if render target surface format is supported, otherwise false
//!
bool VPHAL_VEBOX_STATE_G9_BASE::IsRTFormatSupported(
PVPHAL_SURFACE pSrcSurface,
PVPHAL_SURFACE pRTSurface)
{
bool bRet;
bRet = false;
// Check if RT Format is supported by Vebox
if (IS_PA_FORMAT(pRTSurface->Format) ||
pRTSurface->Format == Format_NV12)
{
// Supported Vebox Render Target format. Vebox Pipe Output can be selected.
bRet = true;
}
if ((pSrcSurface->ColorSpace == CSpace_BT2020) &&
((pSrcSurface->Format == Format_P010) ||
(pSrcSurface->Format == Format_P016)) &&
IS_RGB32_FORMAT(pRTSurface->Format))
{
bRet = true;
}
return bRet;
}
//!
//! \brief Vebox format support check for DN
//! \details Check if the input surface format is supported for DN
//! \param [in] pSrcSurface
//! Pointer to input surface of Vebox
//! \return bool
//! return true if input surface format is supported, otherwise false
//!
bool VPHAL_VEBOX_STATE_G9_BASE::IsDnFormatSupported(
PVPHAL_SURFACE pSrcSurface)
{
bool bRet;
bRet = false;
VPHAL_RENDER_CHK_NULL_NO_STATUS(pSrcSurface);
if ((pSrcSurface->Format != Format_YUYV) &&
(pSrcSurface->Format != Format_VYUY) &&
(pSrcSurface->Format != Format_YVYU) &&
(pSrcSurface->Format != Format_UYVY) &&
(pSrcSurface->Format != Format_YUY2) &&
(pSrcSurface->Format != Format_Y8) &&
(pSrcSurface->Format != Format_NV12) &&
(pSrcSurface->Format != Format_A8B8G8R8) &&
(pSrcSurface->Format != Format_A16B16G16R16))
{
VPHAL_RENDER_NORMALMESSAGE("Unsupported Format '0x%08x' for VEBOX DN.", pSrcSurface->Format);
goto finish;
}
bRet = true;
finish:
return bRet;
}
//!
//! \brief Check if surface format is supported by DI
//! \details Check if surface format is supported by DI
//! \param [in] pSrc
//! Pointer to input surface of Vebox
//! \return bool
//! Return true if surface format is supported, otherwise return false
//!
bool VPHAL_VEBOX_STATE_G9_BASE::IsDiFormatSupported(
PVPHAL_SURFACE pSrc)
{
bool bRet = false;
VPHAL_RENDER_CHK_NULL_NO_STATUS(pSrc);
if (pSrc->Format != Format_AYUV &&
pSrc->Format != Format_Y410 &&
pSrc->Format != Format_Y416 &&
pSrc->Format != Format_P010 &&
pSrc->Format != Format_P016 &&
pSrc->Format != Format_A8B8G8R8 &&
pSrc->Format != Format_A8R8G8B8 &&
pSrc->Format != Format_B10G10R10A2 &&
pSrc->Format != Format_R10G10B10A2 &&
pSrc->Format != Format_A16B16G16R16 &&
pSrc->Format != Format_A16R16G16B16)
{
bRet = true;
}
else
{
bRet = false;
}
finish:
return bRet;
}
VphalSfcState* VPHAL_VEBOX_STATE_G9_BASE::CreateSfcState()
{
#if __VPHAL_SFC_SUPPORTED
VphalSfcState *sfcState = MOS_New(VphalSfcStateG9, m_pOsInterface, m_pRenderHal, m_pSfcInterface);
#else
VphalSfcState *sfcState = nullptr;
#endif
return sfcState;
}
VPHAL_VEBOX_STATE_G9_BASE::VPHAL_VEBOX_STATE_G9_BASE(
PMOS_INTERFACE pOsInterface,
PMHW_VEBOX_INTERFACE pVeboxInterface,
PMHW_SFC_INTERFACE pSfcInterface,
PRENDERHAL_INTERFACE pRenderHal,
PVPHAL_VEBOX_EXEC_STATE pVeboxExecState,
PVPHAL_RNDR_PERF_DATA pPerfData,
const VPHAL_DNDI_CACHE_CNTL &dndiCacheCntl,
MOS_STATUS *peStatus) :
VPHAL_VEBOX_STATE(pOsInterface, pVeboxInterface, pSfcInterface, pRenderHal, pVeboxExecState, pPerfData, dndiCacheCntl, peStatus)
{
// States
pKernelParamTable = (PRENDERHAL_KERNEL_PARAM)g_Vebox_KernelParam_g9;
iNumFFDISurfaces = 2; // PE on: 4 used. PE off: 2 used
#if defined(ENABLE_KERNELS) && !defined(_FULL_OPEN_SOURCE)
m_hvsKernelBinary = (uint8_t *)IGVP_HVS_DENOISE_G900;
m_hvsKernelBinarySize = IGVP_HVS_DENOISE_G900_SIZE;
#endif
}
|
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#include <complex>
#include <queue>
#include <set>
#include <unordered_set>
#include <list>
#include <chrono>
#include <random>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <stack>
#include <iomanip>
#include <fstream>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> p32;
typedef pair<ll, ll> p64;
typedef pair<double, double> pdd;
typedef vector<ll> v64;
typedef vector<int> v32;
typedef vector<vector<int>> vv32;
typedef vector<vector<ll>> vv64;
typedef vector<vector<p64>> vvp64;
typedef vector<p64> vp64;
typedef vector<p32> vp32;
ll MOD = 1000000007;
double eps = 1e-12;
#define forn(i, n) for (ll i = 0; i < n; i++)
#define forsn(i, s, e) for (ll i = s; i < e; i++)
#define rforn(i, s) for (ll i = s; i >= 0; i--)
#define rforsn(i, s, e) for (ll i = s; i >= e; i--)
#define ln "\n"
#define dbg(x) cout << #x << " = " << x << ln
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define INF 2e18
#define fast_cin() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL)
#define all(x) (x).begin(), (x).end()
#define sz(x) ((ll)(x).size())
vector<pair<ll, ll>> pf(ll n)
{
vector<pair<ll, ll>> prime;
for (int i = 2; i <= sqrt(n); i++)
{
if (n % i == 0)
{
int count = 0;
while (n % i == 0)
{
count++;
n = n / i;
}
prime.pb(mp(i, count));
}
}
if (n > 1)
{
prime.pb(mp(n, 1));
}
return prime;
}
void solve()
{
ll n,count=0;
cin >> n;
vector<pair<ll, ll>> v = pf(n);
for (int i = 0; i < v.size(); i++)
{
if(v[i].first%2!=0)
{
count+=v[i].second;
}
}
cout<<count<<endl;
}
int main()
{
fast_cin();
ll t;
cin >> t;
for (int it = 1; it <= t; it++)
{
solve();
}
return 0;
}
|
// _ _____ __________
// | | / / _ | / __/_ __/ Visibility
// | |/ / __ |_\ \ / / Across
// |___/_/ |_/___/ /_/ Space and Time
//
// SPDX-FileCopyrightText: (c) 2019 The VAST Contributors
// SPDX-License-Identifier: BSD-3-Clause
#include "vast/format/csv.hpp"
#define SUITE format
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast.hpp"
#include "vast/test/fixtures/actor_system.hpp"
#include "vast/test/fixtures/events.hpp"
#include "vast/test/test.hpp"
#include <algorithm>
using namespace vast;
using namespace std::string_literals;
namespace {
struct fixture : fixtures::deterministic_actor_system {
const record_type l0 = record_type{{"ts", time_type{}},
{"addr", address_type{}},
{"port", count_type{}}}
.name("l0");
const record_type l1 = record_type{{"s", string_type{}},
{"ptn", pattern_type{}},
{"lis", list_type{count_type{}}}}
.name("l1");
const record_type l2
= record_type{{"b", bool_type{}},
{"c", count_type{}},
{"r", real_type{}},
{"i", integer_type{}},
{"s", string_type{}},
{"a", address_type{}},
{"sn", subnet_type{}},
{"t", time_type{}},
{"d", duration_type{}},
{"d2", duration_type{}},
{"e", enumeration_type{{"FOO", "BAR", "BAZ"}}},
{"lc", list_type{count_type{}}},
{"lt", list_type{time_type{}}},
{"msa", map_type{string_type{}, address_type{}}},
{"mcs", map_type{count_type{}, string_type{}}}}
.name("l2");
const record_type l3 = record_type{
{"s1", string_type{}},
{"s2", string_type{}},
{"s2,3",
string_type{}}}.name("l3");
schema s;
fixture() {
s.add(l0);
s.add(l1);
s.add(l2);
s.add(l3);
}
const caf::settings options = {};
std::vector<table_slice>
run(std::string_view data, size_t max_events, size_t max_slice_size) {
auto in = std::make_unique<std::istringstream>(std::string{data});
format::csv::reader reader{options, std::move(in)};
reader.schema(s);
std::vector<table_slice> slices;
auto add_slice
= [&](table_slice slice) { slices.emplace_back(std::move(slice)); };
auto [err, num] = reader.read(max_events, max_slice_size, add_slice);
REQUIRE_EQUAL(err, caf::none);
size_t lines = std::count(data.begin(), data.end(), '\n');
REQUIRE_EQUAL(num, std::min(lines, max_events));
return slices;
}
};
} // namespace
FIXTURE_SCOPE(csv_reader_tests, fixture)
std::string_view l0_log0 = R"__(ts,addr,port
2011-08-12T13:00:36.349948Z,147.32.84.165,1027
2011-08-12T13:08:01.360925Z,147.32.84.165,3101
2011-08-12T13:08:01.360925Z,147.32.84.165,1029
2011-08-12T13:09:35.498887Z,147.32.84.165,1029
2011-08-12T13:14:36.012344Z,147.32.84.165,1041
2011-08-12T14:59:11.994970Z,147.32.84.165,1046
2011-08-12T14:59:12.448311Z,147.32.84.165,1047
2011-08-13T13:04:24.640406Z,147.32.84.165,1089)__";
TEST(csv reader - simple) {
auto slices = run(l0_log0, 8, 5);
REQUIRE_EQUAL(slices[0].layout(), l0);
CHECK(slices[1].at(0, 0, time_type{})
== data{unbox(to<vast::time>("2011-08-12T14:59:11.994970Z"))});
CHECK(slices[1].at(1, 2, count_type{}) == data{count{1047}});
}
std::string_view l0_log1 = R"__(ts,addr,port
2011-08-12T13:00:36.349948Z,147.32.84.165,1027
2011-08-12T13:08:01.360925Z,147.32.84.165,
2011-08-12T13:08:01.360925Z,,1029
2011-08-12T13:09:35.498887Z,147.32.84.165,1029
2011-08-12T13:14:36.012344Z,147.32.84.165,1041
,147.32.84.165,1046
,147.32.84.165,
,,)__";
TEST(csv reader - empty fields) {
auto slices = run(l0_log1, 8, 5);
REQUIRE_EQUAL(slices[0].layout(), l0);
CHECK(slices[1].at(0, 1, address_type{})
== data{unbox(to<address>("147.32.84.165"))});
CHECK(slices[1].at(1, 2, count_type{}) == data{caf::none});
}
std::string_view l1_log_string = R"__(s
hello
)__";
TEST(csv reader - string) {
auto slices = run(l1_log_string, 1, 1);
auto l1_string = record_type{{"s", string_type{}}}.name("l1");
REQUIRE_EQUAL(slices[0].layout(), l1_string);
CHECK(slices[0].at(0, 0, string_type{}) == data{"hello"});
}
std::string_view l1_log_pattern = R"__(ptn
hello
)__";
TEST(csv reader - pattern) {
auto slices = run(l1_log_pattern, 1, 1);
auto l1_pattern = record_type{{"ptn", pattern_type{}}}.name("l1");
REQUIRE_EQUAL(slices[0].layout(), l1_pattern);
CHECK(slices[0].at(0, 0, pattern_type{}) == data{pattern{"hello"}});
}
std::string_view l1_log0 = R"__(s,ptn,lis
hello,world,[1,2]
Tom,appeared,[42,1337]
on,the,[42,1337]
sidewalk,with,[42,1337]
a,bucket,[42,1337]
of,whitewash,[42,1337]
and,a,[42,1337]
long-handled,brush,[42,1337]
He,surveyed the,[42,1337]
fence,and,[42,1337]
all,gladness,[42,1337]
left,him,[42,1337]
and ,a,[42,1337]
deep,melancholy,[42,1337]
settled,down,[42,1337]
upon,his,[42,1337]
spirit,Thirty,[42,1337]
yards,of,[42,1337]
board, fence,[42,1337]
nine,feet,[42,1337]
high,Life,[42,1337]
to,him,[42,1337]
seemed,hollow,[42,1337]
and,existence,[42,1337]
but,a,[42,1337]
burden,Sighing,[42,1337]
,,)__";
TEST(csv reader - layout with container) {
auto slices = run(l1_log0, 20, 20);
REQUIRE_EQUAL(slices[0].layout(), l1);
CHECK(slices[0].at(10, 1, pattern_type{}) == data{pattern{"gladness"}});
auto xs = vast::list{};
xs.emplace_back(data{count{42}});
xs.emplace_back(data{count{1337}});
CHECK(slices[0].at(19, 2, list_type{count_type{}}) == data{xs});
}
std::string_view l1_log1 = R"__(s,ptn
hello,world
Tom,appeared
on,the
sidewalk,with
a,bucket
of,whitewash
and,a
long-handled,brush
He,surveyed the
fence,and
all,gladness
left,him
and ,a
deep,melancholy
settled,down
upon,his
spirit,Thirty
yards,of
board, fence
nine,feet
high,Life
to,him
seemed,hollow
and,existence
but,a
burden,Sighing
,,)__";
TEST(csv reader - sublayout construction) {
auto l1_sub = record_type{{"s", string_type{}}, {"ptn", pattern_type{}}}.name(
"l1");
auto slices = run(l1_log1, 20, 20);
REQUIRE_EQUAL(slices[0].layout(), l1_sub);
CHECK(slices[0].at(10, 1, pattern_type{}) == data{pattern{"gladness"}});
}
std::string_view l2_log_msa = R"__(msa
{ foo=1.2.3.4, bar=2001:db8:: })__";
TEST(csv reader - map string->address) {
auto slices = run(l2_log_msa, 1, 1);
auto t = map_type{string_type{}, address_type{}};
auto l2_msa = record_type{{"msa", t}}.name("l2");
REQUIRE_EQUAL(slices[0].layout(), l2_msa);
auto m = vast::map{};
m.emplace(data{"foo"}, unbox(to<address>("1.2.3.4")));
m.emplace(data{"bar"}, unbox(to<address>("2001:db8::")));
CHECK_EQUAL(materialize(slices[0].at(0, 0, t)), data{m});
}
std::string_view l2_log_vp = R"__(lc
[1, 2, 3, 4, 5]
[])__";
TEST(csv reader - list of count) {
auto slices = run(l2_log_vp, 2, 100);
auto t = list_type{count_type{}};
auto l2_vp = record_type{{"lc", t}}.name("l2");
REQUIRE_EQUAL(slices[0].layout(), l2_vp);
CHECK(slices[0].at(0, 0, t) == data{list{1u, 2u, 3u, 4u, 5u}});
CHECK(slices[0].at(1, 0, t) == data{list{}});
}
std::string_view l2_log_subnet = R"__(sn
1.2.3.4/20
2001:db8::/125)__";
TEST(csv reader - subnet) {
auto slices = run(l2_log_subnet, 2, 2);
auto l2_subnet = record_type{{"sn", subnet_type{}}}.name("l2");
REQUIRE_EQUAL(slices[0].layout(), l2_subnet);
CHECK(slices[0].at(0, 0, subnet_type{})
== data{unbox(to<subnet>("1.2.3.4/20"))});
CHECK(slices[0].at(1, 0, subnet_type{})
== data{unbox(to<subnet>("2001:db8::/125"))});
}
std::string_view l2_log_duration = R"__(d,d2
42s,5days)__";
TEST(csv reader - duration) {
auto slices = run(l2_log_duration, 1, 1);
auto l2_duration = record_type{{"d", duration_type{}},
{"d2", duration_type{}}}
.name("l2");
REQUIRE_EQUAL(slices[0].layout(), l2_duration);
CHECK(slices[0].at(0, 0, duration_type{})
== data{unbox(to<duration>("42s"))});
}
std::string_view l2_log_reord = R"__(msa, c, r, i, b, a, sn, d, e, t, lc, lt
{ foo=1.2.3.4, bar=2001:db8:: },424242,4.2,-1337,T,147.32.84.165,192.168.0.1/24,42s,BAZ,2011-08-12+14:59:11.994970,[ 5555,0],[ 2019-04-30T11:46:13Z ])__";
// FIXME: Parsing maps in csv is broken, see ch12358.
// = R"__(msa, c, r, i, b, a, sn, d, e, t, lc, lt, mcs
// { foo=1.2.3.4, bar=2001:db8::
// },424242,4.2,-1337,T,147.32.84.165,42/udp,192.168.0.1/24,42s,BAZ,2011-08-12+14:59:11.994970,
// [ 5555/tcp, 0/icmp ],[ 2019-04-30T11:46:13Z ],{ 1=FOO, 1024=BAR! })__";
TEST(csv reader - reordered layout) {
auto slices = run(l2_log_reord, 1, 1);
auto l2_sub = record_type{{"msa", map_type{string_type{}, address_type{}}},
{"c", count_type{}},
{"r", real_type{}},
{"i", integer_type{}},
{"b", bool_type{}},
{"a", address_type{}},
{"sn", subnet_type{}},
{"d", duration_type{}},
{"e", enumeration_type{{"FOO", "BAR", "BAZ"}}},
{"t", time_type{}},
{"lc", list_type{count_type{}}},
{"lt", list_type{time_type{}}},
// FIXME: Parsing maps in csv is broken, see ch12358.
// {"mcs", map_type{count_type{}, string_type{}}}
}
.name("l2");
REQUIRE_EQUAL(slices[0].layout(), l2_sub);
CHECK(slices[0].at(0, 0, l2_sub.at("msa")->type)
== data{map{{data{"foo"}, unbox(to<address>("1.2.3.4"))},
{data{"bar"}, unbox(to<address>("2001:db8::"))}}});
CHECK(slices[0].at(0, 1, l2_sub.at("c")->type) == data{count{424242}});
CHECK(slices[0].at(0, 2, l2_sub.at("r")->type) == data{real{4.2}});
CHECK(slices[0].at(0, 3, l2_sub.at("i")->type) == data{integer{-1337}});
CHECK(slices[0].at(0, 4, l2_sub.at("b")->type) == data{true});
CHECK(slices[0].at(0, 5, l2_sub.at("a")->type)
== data{unbox(to<address>("147.32.84.165"))});
CHECK(slices[0].at(0, 6, l2_sub.at("sn")->type)
== data{unbox(to<subnet>("192.168.0.1/24"))});
CHECK(slices[0].at(0, 7, l2_sub.at("d")->type)
== data{unbox(to<duration>("42s"))});
CHECK(slices[0].at(0, 8, l2_sub.at("e")->type) == data{enumeration{2}});
CHECK(slices[0].at(0, 9, l2_sub.at("t")->type)
== data{unbox(to<vast::time>("2011-08-12+14:59:11.994970"))});
CHECK(slices[0].at(0, 10, l2_sub.at("lc")->type) == data{list{5555u, 0u}});
CHECK(slices[0].at(0, 11, l2_sub.at("lt")->type)
== data{list{unbox(to<vast::time>("2019-04-30T11:46:13Z"))}});
auto m = map{};
m[1u] = data{"FOO"};
m[1024u] = data{"BAR!"};
// FIXME: Parsing maps in csv is broken, see ch12358.
// CHECK_EQUAL(materialize(slices[0].at(0, 14)), data{m});
}
std::string_view l2_line_endings = "d,d2\r\n42s,5days\n10s,1days\r\n";
TEST(csv reader - line endings) {
auto slices = run(l2_line_endings, 2, 2);
auto l2_duration
= record_type{{"d", duration_type{}}, {"d2", duration_type{}}}.name("l2");
REQUIRE_EQUAL(slices[0].layout(), l2_duration);
CHECK(slices[0].at(0, 0, duration_type{})
== data{unbox(to<duration>("42s"))});
CHECK(slices[0].at(0, 1, duration_type{})
== data{unbox(to<duration>("5days"))});
CHECK(slices[0].at(1, 0, duration_type{})
== data{unbox(to<duration>("10s"))});
CHECK(slices[0].at(1, 1, duration_type{})
== data{unbox(to<duration>("1days"))});
}
std::string_view l3_quoted_strings_header = R"__(s1,"s2,3"
a,b
c,d)__";
TEST(csv reader - quoted strings in header) {
auto slices = run(l3_quoted_strings_header, 2, 2);
auto l3_strings
= record_type{{"s1", string_type{}}, {"s2,3", string_type{}}}.name("l3");
REQUIRE_EQUAL(slices[0].layout(), l3_strings);
CHECK(slices[0].at(0, 0, string_type{}) == data{"a"});
CHECK(slices[0].at(0, 1, string_type{}) == data{"b"});
CHECK(slices[0].at(1, 0, string_type{}) == data{"c"});
CHECK(slices[0].at(1, 1, string_type{}) == data{"d"});
}
std::string_view l3_quoted_strings_1 = R"__(s1
"hello, world")__";
std::string_view l3_quoted_strings_2 = R"__(s1,s2
a,"b,c"
"d,e,\"f",\"g)__";
TEST(csv reader - quoted string) {
{
auto slices = run(l3_quoted_strings_1, 1, 1);
auto l3_strings = record_type{{"s1", string_type{}}}.name("l3");
REQUIRE_EQUAL(slices[0].layout(), l3_strings);
CHECK(slices[0].at(0, 0, string_type{}) == data{"hello, world"});
}
{
auto slices = run(l3_quoted_strings_2, 2, 2);
auto l3_strings
= record_type{{"s1", string_type{}}, {"s2", string_type{}}}.name("l3");
REQUIRE_EQUAL(slices[0].layout(), l3_strings);
CHECK(slices[0].at(0, 0, string_type{}) == data{"a"});
CHECK(slices[0].at(0, 1, string_type{}) == data{"b,c"});
CHECK(slices[0].at(1, 0, string_type{}) == data{"d,e,\"f"});
CHECK(slices[0].at(1, 1, string_type{}) == data{"\\\"g"});
}
}
FIXTURE_SCOPE_END()
|
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2020 RDK Management
*
* 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 <fcntl.h>
#include "RemoteAdministrator.h"
#include "RemoteControl.h"
namespace WPEFramework {
namespace Plugin {
static const string DefaultMappingTable(_T("default"));
static Core::ProxyPoolType<Web::JSONBodyType<RemoteControl::Data>> jsonResponseFactory(4);
static Core::ProxyPoolType<Web::JSONBodyType<PluginHost::VirtualInput::KeyMap::KeyMapEntry>> jsonCodeFactory(1);
SERVICE_REGISTRATION(RemoteControl, 1, 0);
class KeyActivity {
private:
// -------------------------------------------------------------------
// This object should not be copied or assigned. Prevent the copy
// constructor and assignment constructor from being used. Compiler
// generated assignment and copy methods will be blocked by the
// following statments.
// Define them but do not implement them, compile error/link error.
// -------------------------------------------------------------------
KeyActivity(const KeyActivity& a_Copy) = delete;
KeyActivity& operator=(const KeyActivity& a_RHS) = delete;
public:
KeyActivity(const string& mapName, const uint32_t code, const bool pressed)
: _text(Core::ToString(Trace::Format(_T("Inserted Code: [%s:%08X] state %s."), mapName.c_str(), code, (pressed ? _T("pressed") : _T("released")))))
{
}
~KeyActivity()
{
}
public:
inline const char* Data() const
{
return (_text.c_str());
}
inline uint16_t Length() const
{
return (static_cast<uint16_t>(_text.length()));
}
private:
const std::string _text;
};
class UnknownKey {
private:
// -------------------------------------------------------------------
// This object should not be copied or assigned. Prevent the copy
// constructor and assignment constructor from being used. Compiler
// generated assignment and copy methods will be blocked by the
// following statments.
// Define them but do not implement them, compile error/link error.
// -------------------------------------------------------------------
UnknownKey(const UnknownKey& a_Copy) = delete;
UnknownKey& operator=(const UnknownKey& a_RHS) = delete;
public:
UnknownKey(const string& mapName, const uint32_t code, const bool pressed, const uint32_t result)
{
const TCHAR* text(pressed ? _T("pressed") : _T("released"));
if (result == Core::ERROR_UNKNOWN_TABLE) {
_text = Core::ToString(Trace::Format(_T("Invalid table: [%s,%08X]"), mapName.c_str(), code));
} else if (result == Core::ERROR_UNKNOWN_KEY) {
_text = Core::ToString(Trace::Format(_T("Unknown: [%s:%08X] state %s, blocked."), mapName.c_str(), code, text));
}
}
~UnknownKey()
{
}
public:
inline const char* Data() const
{
return (_text.c_str());
}
inline uint16_t Length() const
{
return (static_cast<uint16_t>(_text.length()));
}
private:
std::string _text;
};
static Core::ProxyPoolType<Web::TextBody> _remoteInfo(2);
static string MappingFile(const string& fileName, const string& directory1, const string& directory2)
{
string result(directory1 + fileName);
Core::File testObject(directory1 + fileName);
if ((testObject.Exists() == false) || (testObject.IsDirectory() == true)) {
result = directory2 + fileName;
testObject = result;
if ((testObject.Exists() == false) || (testObject.IsDirectory() == true)) {
result.clear();
}
}
return (result);
}
#ifdef __WINDOWS__
#pragma warning(disable : 4355)
#endif
RemoteControl::RemoteControl()
: _skipURL(0)
, _virtualDevices()
, _inputHandler(PluginHost::InputHandler::Handler())
, _persistentPath()
, _feedback(*this)
{
ASSERT(_inputHandler != nullptr);
RegisterAll();
}
#ifdef __WINDOWS__
#pragma warning(default : 4355)
#endif
/* virtual */ RemoteControl::~RemoteControl()
{
UnregisterAll();
}
/* virtual */ const string RemoteControl::Initialize(PluginHost::IShell* service)
{
string result;
RemoteControl::Config config;
config.FromString(service->ConfigLine());
string mappingFile(MappingFile(config.MapFile.Value(), service->PersistentPath(), service->DataPath()));
// First check that we at least can create a default lookup table.
if (_inputHandler == nullptr) {
result = "Could not configure remote control.";
} else {
TRACE(Trace::Information, (_T("Opening default map file: %s"), mappingFile.c_str()));
// Keep this path for save operation
_persistentPath = service->PersistentPath();
// Seems like we have a default mapping file. Load it..
PluginHost::VirtualInput::KeyMap& map(_inputHandler->Table(DefaultMappingTable));
if (mappingFile.empty() == true) {
map.PassThrough(config.PassOn.Value());
} else {
if (map.Load(mappingFile) == Core::ERROR_NONE) {
map.PassThrough(config.PassOn.Value());
} else {
map.PassThrough(false);
}
}
Remotes::RemoteAdministrator& admin(Remotes::RemoteAdministrator::Instance());
// Strawl over all remotes (inputs) and see if you need to load mapping tables.
Remotes::RemoteAdministrator::Iterator index(admin.Producers());
Core::JSON::ArrayType<RemoteControl::Config::Device>::Iterator configList(config.Devices.Elements());
while (index.Next() == true) {
string producer((*index)->Name());
string loadName(producer);
TRACE(Trace::Information, (_T("Searching map file for: %s"), loadName.c_str()));
configList.Reset();
while ((configList.Next() == true) && (configList.Current().Name.Value() != loadName)) { /* intentionally left empty */
}
if (configList.IsValid() == true) {
(*index)->Configure(configList.Current().Settings.Value());
// We found an overruling name.
loadName = configList.Current().MapFile.Value();
} else {
(*index)->Configure(EMPTY_STRING);
loadName += _T(".json");
}
// See if we need to load a table.
string specific(MappingFile(loadName, service->PersistentPath(), service->DataPath()));
if ((specific.empty() == false) && (specific != mappingFile)) {
TRACE(Trace::Information, (_T("Opening map file: %s"), specific.c_str()));
// Get our selves a table..
PluginHost::VirtualInput::KeyMap& map(_inputHandler->Table(producer.c_str()));
map.Load(specific);
if (configList.IsValid() == true) {
map.PassThrough(configList.Current().PassOn.Value());
}
}
}
configList = config.Virtuals.Elements();
while (configList.Next() == true) {
// Configure the virtual inputs.
string loadName(configList.Current().MapFile.Value());
if (loadName.empty() == true) {
loadName = configList.Current().Name.Value() + _T(".json");
}
// See if we need to load a table.
string specific(MappingFile(loadName, service->PersistentPath(), service->DataPath()));
if ((specific.empty() == false) && (specific != mappingFile)) {
TRACE(Trace::Information, (_T("Opening map file: %s"), specific.c_str()));
// Get our selves a table..de
PluginHost::VirtualInput::KeyMap& map(_inputHandler->Table(configList.Current().Name.Value()));
map.Load(specific);
map.PassThrough(configList.Current().PassOn.Value());
}
_virtualDevices.push_back(configList.Current().Name.Value());
}
if (config.PostLookupFile.IsSet() == true) {
string mappingFile(MappingFile(config.PostLookupFile.Value(), service->PersistentPath(), service->DataPath()));
if (mappingFile.empty() == false) {
_inputHandler->PostLookup(EMPTY_STRING, mappingFile);
}
}
auto postLookup(config.Links.Elements());
while (postLookup.Next() == true) {
string mappingFile(MappingFile(postLookup.Current().MapFile.Value(), service->PersistentPath(), service->DataPath()));
if ((mappingFile.empty() == false) && (postLookup.Current().Name.Value().empty() == false)) {
_inputHandler->PostLookup(postLookup.Current().Name.Value(), mappingFile);
}
}
_skipURL = static_cast<uint32_t>(service->WebPrefix().length());
uint16_t repeatLimit = ((config.ReleaseTimeout.Value() - config.RepeatStart.Value()) / config.RepeatInterval.Value()) + 1;
_inputHandler->Interval(config.RepeatStart.Value(), config.RepeatInterval.Value(), repeatLimit);
_inputHandler->Default(DefaultMappingTable);
admin.Callback(static_cast<IKeyHandler*>(this));
admin.Callback(static_cast<IWheelHandler*>(this));
admin.Callback(static_cast<IPointerHandler*>(this));
admin.Callback(static_cast<ITouchHandler*>(this));
_inputHandler->Register(&_feedback);
}
// On succes return nullptr, to indicate there is no error text.
return (result);
}
/* virtual */ void RemoteControl::Deinitialize(PluginHost::IShell* service)
{
_inputHandler->Unregister(&_feedback);
Remotes::RemoteAdministrator& admin(Remotes::RemoteAdministrator::Instance());
Remotes::RemoteAdministrator::Iterator index(admin.Producers());
// Clear all injected device key maps
while (index.Next() == true) {
_inputHandler->ClearTable((*index)->Name().c_str());
}
// Clear default key map
_inputHandler->Default(EMPTY_STRING);
_inputHandler->ClearTable(DefaultMappingTable);
// CLear the virtual devices.
_virtualDevices.clear();
Remotes::RemoteAdministrator::Instance().RevokeAll();
}
/* virtual */ string RemoteControl::Information() const
{
// No additional info to report.
return (EMPTY_STRING);
}
/* virtual */ void RemoteControl::Inbound(Web::Request& request)
{
request.Body(Core::proxy_cast<Web::IBody>(jsonCodeFactory.Element()));
jsonCodeFactory.Element().Release();
}
/* virtual */ Core::ProxyType<Web::Response> RemoteControl::Process(const Web::Request& request)
{
ASSERT(_skipURL <= request.Path.length());
Core::ProxyType<Web::Response> result;
Core::TextSegmentIterator index(Core::TextFragment(request.Path, _skipURL, static_cast<uint32_t>(request.Path.length()) - _skipURL), false, '/');
// By default, we are in front of any element, jump onto the first element, which is if, there is something an empty slot.
index.Next();
// If there is nothing or only a slashe, we will now jump over it, and otherwise, we have data.
if (request.Verb == Web::Request::HTTP_GET) {
result = GetMethod(index, request);
} else if (request.Verb == Web::Request::HTTP_PUT) {
result = PutMethod(index, request);
} else if (request.Verb == Web::Request::HTTP_POST) {
result = PostMethod(index, request);
} else if (request.Verb == Web::Request::HTTP_DELETE) {
result = DeleteMethod(index, request);
} else {
result = PluginHost::IFactories::Instance().Response();
result->ErrorCode = Web::STATUS_NOT_IMPLEMENTED;
result->Message = string(_T("Unknown request path specified."));
}
return (result);
}
/* virtual */ uint32_t RemoteControl::KeyEvent(const bool pressed, const uint32_t code, const string& mapName)
{
uint32_t result = _inputHandler->KeyEvent(pressed, code, mapName);
if (result == Core::ERROR_NONE) {
TRACE(KeyActivity, (mapName, code, pressed));
} else {
TRACE(UnknownKey, (mapName, code, pressed, result));
}
return (result);
}
/* virtual */ void RemoteControl::ProducerEvent(const string& producerName, const Exchange::ProducerEvents event)
{
_eventLock.Lock();
std::list<Exchange::IRemoteControl::INotification*>::iterator index(_notificationClients.begin());
TRACE(Trace::Information, (_T("Got an event from %s producer"), producerName));
while (index != _notificationClients.end()) {
TRACE(Trace::Information, (_T("Sending an event to client")));
(*index)->Event(producerName, event);
index++;
}
_eventLock.Unlock();
}
/* virtual */ uint32_t RemoteControl::AxisEvent(const int16_t x, const int16_t y)
{
return (_inputHandler->AxisEvent(x, y));
}
/* virtual */ uint32_t RemoteControl::PointerButtonEvent(const bool pressed, const uint8_t button)
{
return (_inputHandler->PointerButtonEvent(pressed, button));
}
/* virtual */ uint32_t RemoteControl::PointerMotionEvent(const int16_t x, const int16_t y)
{
return (_inputHandler->PointerMotionEvent(x, y));
}
/* virtual */ uint32_t RemoteControl::TouchEvent(const uint8_t index, const ITouchHandler::touchstate state, const uint16_t x, const uint16_t y)
{
return (_inputHandler->TouchEvent(index, ((state == touchstate::TOUCH_MOTION)? 0 : ((state == touchstate::TOUCH_RELEASED)? 1 : 2)), x, y));
}
bool RemoteControl::ParseRequestBody(const Web::Request& request, uint32_t& code, uint16_t& key, uint32_t& modifiers)
{
bool parsed = false;
if (request.HasBody() == true) {
const PluginHost::VirtualInput::KeyMap::KeyMapEntry& data = *(request.Body<const Web::JSONBodyType<PluginHost::VirtualInput::KeyMap::KeyMapEntry>>());
if (data.Code.IsSet() == true) {
code = data.Code.Value();
if (data.Key.IsSet())
key = data.Key.Value();
if (data.Modifiers.IsSet()) {
Core::JSON::ArrayType<Core::JSON::EnumType<PluginHost::VirtualInput::KeyMap::modifier>>::ConstIterator flags(data.Modifiers.Elements());
while (flags.Next() == true) {
switch (flags.Current().Value()) {
case PluginHost::VirtualInput::KeyMap::modifier::LEFTSHIFT:
case PluginHost::VirtualInput::KeyMap::modifier::RIGHTSHIFT:
case PluginHost::VirtualInput::KeyMap::modifier::LEFTALT:
case PluginHost::VirtualInput::KeyMap::modifier::RIGHTALT:
case PluginHost::VirtualInput::KeyMap::modifier::LEFTCTRL:
case PluginHost::VirtualInput::KeyMap::modifier::RIGHTCTRL:
modifiers |= flags.Current().Value();
break;
default:
ASSERT(false);
break;
}
}
}
parsed = true;
}
}
return (parsed);
}
Core::ProxyType<Web::IBody> RemoteControl::CreateResponseBody(const uint32_t code, const uint32_t key, uint16_t modifiers) const
{
Core::ProxyType<Web::JSONBodyType<PluginHost::VirtualInput::KeyMap::KeyMapEntry>>
response(jsonCodeFactory.Element());
response->Code = code;
response->Key = key;
uint16_t flag(1);
while (modifiers != 0) {
if ((modifiers & 0x01) != 0) {
switch (flag) {
case PluginHost::VirtualInput::KeyMap::modifier::LEFTSHIFT:
case PluginHost::VirtualInput::KeyMap::modifier::RIGHTSHIFT:
case PluginHost::VirtualInput::KeyMap::modifier::LEFTALT:
case PluginHost::VirtualInput::KeyMap::modifier::RIGHTALT:
case PluginHost::VirtualInput::KeyMap::modifier::LEFTCTRL:
case PluginHost::VirtualInput::KeyMap::modifier::RIGHTCTRL: {
Core::JSON::EnumType<PluginHost::VirtualInput::KeyMap::modifier>& jsonRef = response->Modifiers.Add();
jsonRef = static_cast<PluginHost::VirtualInput::KeyMap::modifier>(flag);
break;
}
default:
ASSERT(false);
break;
}
}
flag = flag << 1;
modifiers = modifiers >> 1;
}
return (Core::proxy_cast<Web::IBody>(response));
}
Core::ProxyType<Web::Response> RemoteControl::GetMethod(Core::TextSegmentIterator& index, const Web::Request& request) const
{
Core::ProxyType<Web::Response> result(PluginHost::IFactories::Instance().Response());
result->ErrorCode = Web::STATUS_NOT_FOUND;
result->Message = string(_T("Unknown request path specified."));
if (index.IsValid() == true && index.Next() == true) {
// Perform operations on that specific device
const string deviceName = index.Current().Text();
if ((IsVirtualDevice(deviceName)) || (IsPhysicalDevice(deviceName))) {
// GET .../RemoteControl/<DEVICE_NAME>?Code=XXX : Get code of DEVICE_NAME
if (request.Query.IsSet() == true) {
Core::URL::KeyValue options(request.Query.Value());
Core::NumberType<uint32_t> code(options.Number<uint32_t>(_T("Code"), static_cast<uint32_t>(~0)));
result->ErrorCode = Web::STATUS_NOT_FOUND;
result->Message = string(_T("Key does not exist in ") + deviceName);
if (code.Value() != static_cast<uint32_t>(~0)) {
// Load default or specific device mapping
PluginHost::VirtualInput::KeyMap& map(_inputHandler->Table(deviceName));
const PluginHost::VirtualInput::KeyMap::ConversionInfo* codeElements = map[code];
if (codeElements != nullptr) {
result->ErrorCode = Web::STATUS_OK;
result->Message = string(_T("Get key info of ") + deviceName);
result->ContentType = Web::MIMETypes::MIME_JSON;
result->Body(CreateResponseBody(code, codeElements->Code, codeElements->Modifiers));
}
} else {
result->ErrorCode = Web::STATUS_BAD_REQUEST;
result->Message = string(_T("No key code in request"));
}
}
// GET .../RemoteControl/<DEVICE_NAME> : Return metadata of specific DEVICE_NAME
else {
if (IsVirtualDevice(deviceName) == true) {
result->ErrorCode = Web::STATUS_NO_CONTENT;
result->Message = string(_T("Virtual device is loaded"));
} else if (IsPhysicalDevice(deviceName) == true) {
uint32_t error = Remotes::RemoteAdministrator::Instance().Error(deviceName);
if (error == Core::ERROR_NONE) {
result->ErrorCode = Web::STATUS_OK;
result->Message = string(_T("Physical device is loaded"));
Core::ProxyType<Web::TextBody> body(_remoteInfo.Element());
(*body) = Remotes::RemoteAdministrator::Instance().MetaData(deviceName);
result->Body<Web::TextBody>(body);
} else {
result->ErrorCode = Web::STATUS_BAD_GATEWAY;
result->Message = string(_T("Error during loading of device. ErrorCode: ")) + Core::NumberType<uint32_t>(error).Text();
}
}
}
}
}
// GET .../RemoteControl : Return name-list of all registered devices
else {
Core::ProxyType<Web::JSONBodyType<Data>> response(jsonResponseFactory.Element());
// Add virtual devices
std::list<string>::const_iterator index(_virtualDevices.begin());
while (index != _virtualDevices.end()) {
Core::JSON::String newElement;
newElement = *index;
response->Devices.Add(newElement);
index++;
}
// Look at specific devices, if we have, append them to response
Remotes::RemoteAdministrator& admin(Remotes::RemoteAdministrator::Instance());
Remotes::RemoteAdministrator::Iterator remoteDevices(admin.Producers());
while (remoteDevices.Next() == true) {
Core::JSON::String newElement;
newElement = (*remoteDevices)->Name();
response->Devices.Add(newElement);
}
result->ErrorCode = Web::STATUS_OK;
result->Message = string(_T("List of loaded remote devices"));
result->ContentType = Web::MIMETypes::MIME_JSON;
result->Body(Core::proxy_cast<Web::IBody>(response));
}
return (result);
}
Core::ProxyType<Web::Response> RemoteControl::PutMethod(Core::TextSegmentIterator& index, const Web::Request& request)
{
Core::ProxyType<Web::Response> result(PluginHost::IFactories::Instance().Response());
result->ErrorCode = Web::STATUS_NOT_FOUND;
result->Message = string(_T("Unknown request path specified."));
// This is a PUT request, search command
// PUT RemoteControl/<DEVICE_NAME>?Code=XXX
if (index.IsValid() == true && index.Next() == true) {
// Perform operations on that specific device
const string deviceName(index.Current().Text());
const bool physical(IsPhysicalDevice(deviceName));
if ((physical == true) || (IsVirtualDevice(deviceName))) {
if (index.Next() == true) {
bool pressed = false;
// PUT .../RemoteControl/<DEVICE_NAME>/Pair: activate pairing mode of specific DEVICE_NAME
if (index.Current() == _T("Pair")) {
if ((physical == true) && (Remotes::RemoteAdministrator::Instance().Pair(deviceName) == true)) {
result->ErrorCode = Web::STATUS_OK;
result->Message = string(_T("Pairing mode active: ") + deviceName);
} else {
result->ErrorCode = Web::STATUS_NOT_IMPLEMENTED;
result->Message = string(_T("Failed to activate pairing: ") + deviceName);
}
}
// PUT .../RemoteControl/<DEVICE_NAME>/Unpair : unpair specific DEVICE_NAME & bindId
if (index.Current() == _T("Unpair")) {
if (index.Next() == true) {
if (Remotes::RemoteAdministrator::Instance().Unpair(deviceName, index.Current().Text()) == true) {
result->ErrorCode = Web::STATUS_OK;
result->Message = string(_T("Unpaired ") + deviceName);
} else {
result->ErrorCode = Web::STATUS_NOT_IMPLEMENTED;
result->Message = string(_T("Failed to unpair: ") + deviceName);
}
}
}
// PUT .../RemoteControl/<DEVICE_NAME>/Send : send a code to DEVICE_NAME
else if (index.Current() == _T("Send")) {
uint32_t code = 0;
uint16_t key = 0;
uint32_t modifiers = 0;
if (ParseRequestBody(request, code, key, modifiers) == true) {
result->ErrorCode = Web::STATUS_NOT_FOUND;
result->Message = string(_T("Key does not exist in ") + deviceName);
if (code != 0) {
uint32_t errCode = KeyEvent(true, code, deviceName);
if (errCode == Core::ERROR_NONE) {
errCode = KeyEvent(false, code, deviceName);
if (errCode == Core::ERROR_NONE) {
result->ErrorCode = Web::STATUS_ACCEPTED;
result->Message = string(_T("Soft key is sent to ") + deviceName);
}
}
}
} else {
result->ErrorCode = Web::STATUS_BAD_REQUEST;
result->Message = string(_T("No key code in request"));
}
}
// PUT .../RemoteControl/<DEVICE_NAME>/Press|Release : send a code to DEVICE_NAME
else if (((pressed = (index.Current() == _T("Press"))) == true) || (index.Current() == _T("Release"))) {
uint32_t code = 0;
uint16_t key = 0;
uint32_t modifiers = 0;
if (ParseRequestBody(request, code, key, modifiers) == true) {
result->ErrorCode = Web::STATUS_NOT_FOUND;
result->Message = string(_T("Key does not exist in ") + deviceName);
if ((code != 0) && (KeyEvent(pressed, code, deviceName) == Core::ERROR_NONE)) {
result->ErrorCode = Web::STATUS_ACCEPTED;
result->Message = string(_T("Soft key is sent to ") + deviceName);
}
} else {
result->ErrorCode = Web::STATUS_BAD_REQUEST;
result->Message = string(_T("No key code in request"));
}
}
// PUT .../RemoteControl/<DEVICE_NAME>/Save : Save the loaded key map as DEVICE_NAME.json into persistent path
else if (index.Current() == _T("Save")) {
result->ErrorCode = Web::STATUS_INTERNAL_SERVER_ERROR;
result->Message = string(_T("File is not created"));
string fileName;
if (_persistentPath.empty() == false) {
Core::Directory directory(_persistentPath.c_str());
if (directory.CreatePath()) {
fileName = _persistentPath + deviceName + _T(".json");
}
}
if (fileName.empty() == false) {
// Seems like we have a default mapping file. Load it..
PluginHost::VirtualInput::KeyMap& map(_inputHandler->Table(deviceName));
if (map.Save(fileName) == Core::ERROR_NONE) {
result->ErrorCode = Web::STATUS_OK;
result->Message = string(_T("File is created: " + fileName));
}
}
}
// PUT .../RemoteControl/<DEVICE_NAME>/Load : Re-load DEVICE_NAME.json into memory
else if (index.Current() == _T("Load")) {
result->ErrorCode = Web::STATUS_NOT_FOUND;
result->Message = string(_T("File does not exist"));
string fileName;
if (_persistentPath.empty() == false) {
Core::Directory directory(_persistentPath.c_str());
if (directory.CreatePath()) {
fileName = _persistentPath + deviceName + _T(".json");
}
}
if (fileName.empty() == false) {
PluginHost::VirtualInput::KeyMap& map(_inputHandler->Table(deviceName));
if (map.Load(fileName) == Core::ERROR_NONE) {
result->ErrorCode = Web::STATUS_OK;
result->Message = string(_T("File is reloaded: " + deviceName));
}
}
}
} else {
uint32_t code = 0;
uint16_t key = 0;
uint32_t modifiers = 0;
result->ErrorCode = Web::STATUS_BAD_REQUEST;
result->Message = string(_T("Bad json data format"));
if (ParseRequestBody(request, code, key, modifiers) == true) {
// Valid code-key pair
if (code != 0 && key != 0) {
// Load default or specific device mapping
PluginHost::VirtualInput::KeyMap& map(_inputHandler->Table(deviceName));
if (map.Add(code, key, modifiers) == true) {
result->ErrorCode = Web::STATUS_CREATED;
result->Message = string(_T("Code is added"));
} else {
result->ErrorCode = Web::STATUS_FORBIDDEN;
result->Message = string(_T("Code already exists"));
}
}
}
}
}
}
return (result);
}
Core::ProxyType<Web::Response> RemoteControl::DeleteMethod(Core::TextSegmentIterator& index, const Web::Request& request)
{
Core::ProxyType<Web::Response> result(PluginHost::IFactories::Instance().Response());
result->ErrorCode = Web::STATUS_NOT_IMPLEMENTED;
result->Message = string(_T("Unknown request path specified."));
// DELETE .../RemoteControl/<DEVICE_NAME>: delete code from mapping of DEVICE_NAME
if (index.IsValid() == true && index.Next() == true) {
// Perform operations on that specific device
const string deviceName(index.Current().Text());
const bool physical(IsPhysicalDevice(deviceName));
if ((physical == true) || (IsVirtualDevice(deviceName))) {
if (index.Next() == false) {
uint32_t code = 0;
uint16_t key = 0;
uint32_t modifiers = 0;
result->ErrorCode = Web::STATUS_BAD_REQUEST;
result->Message = string(_T("Bad json data format"));
if (ParseRequestBody(request, code, key, modifiers) == true) {
if (code != 0) {
// Load default or specific device mapping
PluginHost::VirtualInput::KeyMap& map(_inputHandler->Table(deviceName));
map.Delete(code);
result->ErrorCode = Web::STATUS_OK;
result->Message = string(_T("Code is deleted"));
} else {
result->ErrorCode = Web::STATUS_FORBIDDEN;
result->Message = string(_T("Key does not exist in ") + deviceName);
}
}
}
}
}
return (result);
}
Core::ProxyType<Web::Response> RemoteControl::PostMethod(Core::TextSegmentIterator& index, const Web::Request& request)
{
Core::ProxyType<Web::Response> result(PluginHost::IFactories::Instance().Response());
result->ErrorCode = Web::STATUS_NOT_FOUND;
result->Message = string(_T("Unknown request path specified."));
// POST .../RemoteControl/<DEVICE_NAME> : Modify a new pair in specific DEVICE_NAME
if (index.IsValid() == true && index.Next() == true) {
// Perform operations on that specific device
const string deviceName(index.Current().Text());
const bool physical(IsPhysicalDevice(deviceName));
if ((physical == true) || (IsVirtualDevice(deviceName))) {
if (index.Next() == false) {
uint32_t code = 0;
uint16_t key = 0;
uint32_t modifiers = 0;
result->ErrorCode = Web::STATUS_BAD_REQUEST;
result->Message = string(_T("Bad json data format"));
if (ParseRequestBody(request, code, key, modifiers) == true) {
// Valid code-key pair
if (code != 0 && key != 0) {
// Load default or specific device mapping
PluginHost::VirtualInput::KeyMap& map(_inputHandler->Table(deviceName));
if (map.Modify(code, key, modifiers) == true) {
result->ErrorCode = Web::STATUS_OK;
result->Message = string(_T("Code is modified"));
} else {
result->ErrorCode = Web::STATUS_FORBIDDEN;
result->Message = string(_T("Code does not exist"));
}
}
}
}
}
}
return (result);
}
void RemoteControl::RegisterEvents(IRemoteControl::INotification* sink)
{
_eventLock.Lock();
//Make sure a sink is not registered multiple times.
if (std::find(_notificationClients.begin(), _notificationClients.end(), sink) != _notificationClients.end())
return;
TRACE(Trace::Information , (_T("Registered a client with RemoteControl")));
_notificationClients.push_back(sink);
sink->AddRef();
_eventLock.Unlock();
}
void RemoteControl::UnregisterEvents(IRemoteControl::INotification* sink)
{
_eventLock.Lock();
std::list<Exchange::IRemoteControl::INotification*>::iterator index(std::find(_notificationClients.begin(), _notificationClients.end(), sink));
// Make sure you do not unregister something you did not register !!!
if (index == _notificationClients.end())
return;
if (index != _notificationClients.end()) {
(*index)->Release();
_notificationClients.erase(index);
}
_eventLock.Unlock();
}
void RemoteControl::Activity(const IVirtualInput::KeyData::type type, const uint32_t code)
{
// Lets call the JSONRPC method:
if ( (type == IVirtualInput::KeyData::type::RELEASED) || (type == IVirtualInput::KeyData::type::PRESSED) ) {
string keyCode (Core::NumberType<uint32_t>(code).Text());
event_keypressed(keyCode, (type == IVirtualInput::KeyData::type::PRESSED));
}
}
}
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 vrc Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "init.h"
#include "main.h"
#include "masternodeconfig.h"
#include "noui.h"
#include "rpcserver.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called vrc (https://mirq.io),
* which enables instant payments to anyone, anywhere in the world. vrc uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
static bool fDaemon;
void DetectShutdownThread(boost::thread_group* threadGroup)
{
bool fShutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!fShutdown) {
MilliSleep(200);
fShutdown = ShutdownRequested();
}
if (threadGroup) {
threadGroup->interrupt_all();
threadGroup->join_all();
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
//
// Parameters
//
// If Qt is used, parameters/vrc.conf are parsed in qt/vrc.cpp's main()
ParseParameters(argc, argv);
// Process help and version before taking care about datadir
if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) {
std::string strUsage = _("vrc Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";
if (mapArgs.count("-version")) {
strUsage += LicenseInfo();
} else {
strUsage += "\n" + _("Usage:") + "\n" +
" vrcd [options] " + _("Start vrc Daemon") + "\n";
strUsage += "\n" + HelpMessage(HMM_BITCOIND);
}
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
try {
if (!boost::filesystem::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
try {
ReadConfigFile(mapArgs, mapMultiArgs);
} catch (std::exception& e) {
fprintf(stderr, "Error reading configuration file: %s\n", e.what());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
if (!SelectParamsFromCommandLine()) {
fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
return false;
}
// parse masternode.conf
std::string strErr;
if (!masternodeConfig.read(strErr)) {
fprintf(stderr, "Error reading masternode configuration file: %s\n", strErr.c_str());
return false;
}
// Command-line RPC
bool fCommandLine = false;
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "vrc:"))
fCommandLine = true;
if (fCommandLine) {
fprintf(stderr, "Error: There is no RPC client functionality in vrcd anymore. Use the vrc-cli utility instead.\n");
exit(1);
}
#ifndef WIN32
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon) {
fprintf(stdout, "vrc server starting\n");
// Daemonize
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
SoftSetBoolArg("-server", true);
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
} catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
// threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
// the startup-failure cases to make sure they don't result in a hang due to some
// thread-blocking-waiting-for-another-thread-during-startup case
}
if (detectShutdownThread) {
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect vrcd signal handlers
noui_connect();
return (AppInit(argc, argv) ? 0 : 1);
}
|
//===----------------------------------------------------------------------===//
//
// BusTub
//
// transaction_manager.cpp
//
// Identification: src/concurrency/transaction_manager.cpp
//
// Copyright (c) 2015-2019, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "concurrency/transaction_manager.h"
#include <unordered_map>
#include <unordered_set>
#include "storage/table/table_heap.h"
namespace bustub {
std::unordered_map<txn_id_t, Transaction *> TransactionManager::txn_map = {};
Transaction *TransactionManager::Begin(Transaction *txn) {
// Acquire the global transaction latch in shared mode.
global_txn_latch_.RLock();
if (txn == nullptr) {
txn = new Transaction(next_txn_id_++);
}
if (enable_logging) {
LogRecord log_record = LogRecord(txn->GetTransactionId(), txn->GetPrevLSN(), LogRecordType::BEGIN);
log_manager_->AppendLogRecord(&log_record);
}
txn_map[txn->GetTransactionId()] = txn;
return txn;
}
void TransactionManager::Commit(Transaction *txn) {
txn->SetState(TransactionState::COMMITTED);
// Perform all deletes before we commit.
auto write_set = txn->GetWriteSet();
while (!write_set->empty()) {
auto &item = write_set->back();
auto table = item.table_;
if (item.wtype_ == WType::DELETE) {
// Note that this also releases the lock when holding the page latch.
table->ApplyDelete(item.rid_, txn);
}
write_set->pop_back();
}
write_set->clear();
if (enable_logging) {
// TODO(student): add logging here
LogRecord log_record = LogRecord(txn->GetTransactionId(), txn->GetPrevLSN(), LogRecordType::COMMIT);
log_manager_->AppendLogRecord(&log_record);
log_manager_->SyncFlush(true);
}
// Release all the locks.
ReleaseLocks(txn);
// Release the global transaction latch.
global_txn_latch_.RUnlock();
}
void TransactionManager::Abort(Transaction *txn) {
txn->SetState(TransactionState::ABORTED);
// Rollback before releasing the lock.
auto write_set = txn->GetWriteSet();
while (!write_set->empty()) {
auto &item = write_set->back();
auto table = item.table_;
if (item.wtype_ == WType::DELETE) {
table->RollbackDelete(item.rid_, txn);
} else if (item.wtype_ == WType::INSERT) {
// Note that this also releases the lock when holding the page latch.
table->ApplyDelete(item.rid_, txn);
} else if (item.wtype_ == WType::UPDATE) {
table->UpdateTuple(item.tuple_, item.rid_, txn);
}
write_set->pop_back();
}
write_set->clear();
if (enable_logging) {
// TODO(student): add logging here
LogRecord log_record = LogRecord(txn->GetTransactionId(), txn->GetPrevLSN(), LogRecordType::ABORT);
log_manager_->AppendLogRecord(&log_record);
}
// Release all the locks.
ReleaseLocks(txn);
// Release the global transaction latch.
global_txn_latch_.RUnlock();
}
void TransactionManager::BlockAllTransactions() { global_txn_latch_.WLock(); }
void TransactionManager::ResumeTransactions() { global_txn_latch_.WUnlock(); }
} // namespace bustub
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ngraph/builder/split.hpp"
#include "ngraph/opsets/opset1.hpp"
using namespace ngraph;
OutputVector builder::opset1::split(const Output<Node>& value,
const std::vector<size_t>& split_lengths,
int64_t axis)
{
const auto axis_node = ngraph::opset1::Constant::create(element::i64, Shape{}, {axis});
const auto split_lengths_node =
ngraph::opset1::Constant::create(element::u64, Shape{split_lengths.size()}, split_lengths);
const auto variadic_split =
std::make_shared<ngraph::opset1::VariadicSplit>(value, axis_node, split_lengths_node);
return variadic_split->outputs();
}
OutputVector builder::opset1::split(const Output<Node>& value, size_t num_splits, int64_t axis)
{
const auto axis_node = ngraph::opset1::Constant::create(element::i64, Shape{}, {axis});
const auto split = std::make_shared<ngraph::opset1::Split>(value, axis_node, num_splits);
return split->outputs();
}
|
#include <muse_mcl_2d/impl/resampling/stratified_2d.hpp>
#include <muse_smc/resampling/impl/stratified.hpp>
namespace muse_mcl_2d {
void Stratified::doApply(sample_set_t& sample_set)
{
muse_smc::impl::Stratified<sample_set_t, uniform_sampling_t>::apply(sample_set);
}
void Stratified::doApplyRecovery(sample_set_t& sample_set)
{
muse_smc::impl::Stratified<sample_set_t, uniform_sampling_t>::applyRecovery(uniform_pose_sampler_,
recovery_random_pose_probability_,
sample_set);
}
}
CLASS_LOADER_REGISTER_CLASS(muse_mcl_2d::Stratified, muse_mcl_2d::Resampling2D)
|
/*
* This file is part of liblcf. Copyright (c) 2020 liblcf authors.
* https://github.com/EasyRPG/liblcf - https://easyrpg.org
*
* liblcf is Free/Libre Open Source Software, released under the MIT License.
* For the full copyright and license information, please view the COPYING
* file that was distributed with this source code.
*/
#include "lcf/config.h"
#include "lcf/scope_guard.h"
#if LCF_SUPPORT_ICU
# include <unicode/ucsdet.h>
# include <unicode/ucnv.h>
# include <unicode/normalizer2.h>
# include <unicode/unistr.h>
#else
# ifdef _MSC_VER
# error MSVC builds require ICU
# endif
#endif
#ifdef _WIN32
# include <windows.h>
#else
# if !LCF_SUPPORT_ICU
# include <iconv.h>
# endif
# include <locale>
#endif
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <vector>
#include "lcf/data.h"
#include "lcf/inireader.h"
#include "lcf/ldb/reader.h"
#include "lcf/reader_util.h"
namespace lcf {
namespace ReaderUtil {
}
std::string ReaderUtil::CodepageToEncoding(int codepage) {
if (codepage == 0)
return std::string();
if (codepage == 932) {
#if LCF_SUPPORT_ICU
return "ibm-943_P15A-2003";
#else
return "SHIFT_JIS";
#endif
}
if (codepage == 949) {
#if LCF_SUPPORT_ICU
return "windows-949-2000";
#else
return "cp949";
#endif
}
std::ostringstream out;
#if LCF_SUPPORT_ICU
out << "windows-" << codepage;
#else
out << "CP" << codepage;
#endif
// Looks like a valid codepage
std::string outs = out.str();
return outs;
}
std::string ReaderUtil::DetectEncoding(std::istream& filestream) {
std::vector<std::string> encodings = DetectEncodings(filestream);
if (encodings.empty()) {
return "";
}
return encodings.front();
}
std::string ReaderUtil::DetectEncoding(StringView data) {
std::vector<std::string> encodings = DetectEncodings(data);
if (encodings.empty()) {
return "";
}
return encodings.front();
}
std::vector<std::string> ReaderUtil::DetectEncodings(std::istream& filestream) {
#if LCF_SUPPORT_ICU
std::ostringstream text;
// Populate Data::terms and Data::system or will empty by default even if load fails
LDB_Reader::Load(filestream, "");
text <<
Data::terms.menu_save <<
Data::terms.menu_quit <<
Data::terms.new_game <<
Data::terms.load_game <<
Data::terms.exit_game <<
Data::terms.status <<
Data::terms.row <<
Data::terms.order <<
Data::terms.wait_on <<
Data::terms.wait_off <<
Data::terms.level <<
Data::terms.health_points <<
Data::terms.spirit_points <<
Data::terms.normal_status <<
Data::terms.exp_short <<
Data::terms.lvl_short <<
Data::terms.hp_short <<
Data::terms.sp_short <<
Data::terms.sp_cost <<
Data::terms.attack <<
Data::terms.defense <<
Data::terms.spirit <<
Data::terms.agility <<
Data::terms.weapon <<
Data::terms.shield <<
Data::terms.armor <<
Data::terms.helmet <<
Data::terms.accessory <<
Data::terms.save_game_message <<
Data::terms.load_game_message <<
Data::terms.file <<
Data::terms.exit_game_message <<
Data::terms.yes <<
Data::terms.no <<
Data::system.boat_name <<
Data::system.ship_name <<
Data::system.airship_name <<
Data::system.title_name <<
Data::system.gameover_name <<
Data::system.system_name <<
Data::system.system2_name <<
Data::system.battletest_background <<
Data::system.frame_name;
return ReaderUtil::DetectEncodings(text.str());
#else
return std::vector<std::string>();
#endif
}
std::vector<std::string> ReaderUtil::DetectEncodings(StringView data) {
std::vector<std::string> encodings;
#if LCF_SUPPORT_ICU
if (!data.empty()) {
UErrorCode status = U_ZERO_ERROR;
UCharsetDetector* detector = ucsdet_open(&status);
auto s = std::string(data);
ucsdet_setText(detector, s.c_str(), s.length(), &status);
int32_t matches_count;
const UCharsetMatch** matches = ucsdet_detectAll(detector, &matches_count, &status);
if (matches != NULL) {
// Collect all candidates, most confident comes first
for (int i = 0; i < matches_count; ++i) {
std::string encoding = ucsdet_getName(matches[i], &status);
// Fixes to ensure proper Windows encodings
if (encoding == "Shift_JIS") {
encodings.push_back("ibm-943_P15A-2003"); // Japanese with \ as backslash
} else if (encoding == "EUC-KR") {
encodings.push_back("windows-949-2000"); // Korean with \ as backlash
} else if (encoding == "GB18030") {
encodings.push_back("windows-936-2000"); // Simplified Chinese
} else if (encoding == "ISO-8859-1" || encoding == "windows-1252") {
encodings.push_back("ibm-5348_P100-1997"); // Occidental with Euro
} else if (encoding == "ISO-8859-2" || encoding == "windows-1250") {
encodings.push_back("ibm-5346_P100-1998"); // Central Europe with Euro
} else if (encoding == "ISO-8859-5" || encoding == "windows-1251") {
encodings.push_back("ibm-5347_P100-1998"); // Cyrillic with Euro
} else if (encoding == "ISO-8859-6" || encoding == "windows-1256") {
encodings.push_back("ibm-9448_X100-2005"); // Arabic with Euro + 8 chars
} else if (encoding == "ISO-8859-7" || encoding == "windows-1253") {
encodings.push_back("ibm-5349_P100-1998"); // Greek with Euro
} else if (encoding == "ISO-8859-8" || encoding == "windows-1255") {
encodings.push_back("ibm-9447_P100-2002"); // Hebrew with Euro
} else {
encodings.push_back(encoding);
}
}
}
ucsdet_close(detector);
}
#endif
return encodings;
}
std::string ReaderUtil::GetEncoding(const std::string& ini_file) {
INIReader ini(ini_file);
if (ini.ParseError() != -1) {
std::string encoding = ini.Get("EasyRPG", "Encoding", std::string());
if (!encoding.empty()) {
return ReaderUtil::CodepageToEncoding(atoi(encoding.c_str()));
}
}
return std::string();
}
std::string ReaderUtil::GetEncoding(std::istream& filestream) {
INIReader ini(filestream);
if (ini.ParseError() != -1) {
std::string encoding = ini.Get("EasyRPG", "Encoding", std::string());
if (!encoding.empty()) {
return ReaderUtil::CodepageToEncoding(atoi(encoding.c_str()));
}
}
return std::string();
}
std::string ReaderUtil::GetLocaleEncoding() {
#ifdef _WIN32
int codepage = GetACP();
#elif __ANDROID__
// No std::locale support in NDK
// Doesn't really matter because the Android version auto-detects via ICU
int codepage = 1252;
#else
int codepage = 1252;
std::locale loc = std::locale("");
// Gets the language and culture part only
std::string loc_full = loc.name().substr(0, loc.name().find_first_of("@."));
// Gets the language part only
std::string loc_lang = loc.name().substr(0, loc.name().find_first_of("_"));
if (loc_lang == "th") codepage = 874;
else if (loc_lang == "ja") codepage = 932;
else if (loc_full == "zh_CN" ||
loc_full == "zh_SG") codepage = 936;
else if (loc_lang == "ko") codepage = 949;
else if (loc_full == "zh_TW" ||
loc_full == "zh_HK") codepage = 950;
else if (loc_lang == "cs" ||
loc_lang == "hu" ||
loc_lang == "pl" ||
loc_lang == "ro" ||
loc_lang == "hr" ||
loc_lang == "sk" ||
loc_lang == "sl") codepage = 1250;
else if (loc_lang == "ru") codepage = 1251;
else if (loc_lang == "ca" ||
loc_lang == "da" ||
loc_lang == "de" ||
loc_lang == "en" ||
loc_lang == "es" ||
loc_lang == "fi" ||
loc_lang == "fr" ||
loc_lang == "it" ||
loc_lang == "nl" ||
loc_lang == "nb" ||
loc_lang == "pt" ||
loc_lang == "sv" ||
loc_lang == "eu") codepage = 1252;
else if (loc_lang == "el") codepage = 1253;
else if (loc_lang == "tr") codepage = 1254;
else if (loc_lang == "he") codepage = 1255;
else if (loc_lang == "ar") codepage = 1256;
else if (loc_lang == "et" ||
loc_lang == "lt" ||
loc_lang == "lv") codepage = 1257;
else if (loc_lang == "vi") codepage = 1258;
#endif
return CodepageToEncoding(codepage);
}
std::string ReaderUtil::Recode(StringView str_to_encode, StringView source_encoding) {
return ReaderUtil::Recode(str_to_encode, source_encoding, "UTF-8");
}
std::string ReaderUtil::Recode(StringView str_to_encode,
StringView src_enc,
StringView dst_enc) {
if (src_enc.empty() || dst_enc.empty() || str_to_encode.empty()) {
return ToString(str_to_encode);
}
auto src_cp = SvAtoi(src_enc);
const auto& src_enc_str = src_cp > 0
? ReaderUtil::CodepageToEncoding(src_cp)
: ToString(src_enc);
auto dst_cp = SvAtoi(dst_enc);
const auto& dst_enc_str = dst_cp > 0
? ReaderUtil::CodepageToEncoding(dst_cp)
: ToString(dst_enc);
#if LCF_SUPPORT_ICU
auto status = U_ZERO_ERROR;
auto conv_from = ucnv_open(src_enc_str.c_str(), &status);
if (status != U_ZERO_ERROR && status != U_AMBIGUOUS_ALIAS_WARNING) {
fprintf(stderr, "liblcf: ucnv_open() error for source encoding \"%s\": %s\n", src_enc_str.c_str(), u_errorName(status));
return std::string();
}
status = U_ZERO_ERROR;
auto conv_from_sg = makeScopeGuard([&]() { ucnv_close(conv_from); });
auto conv_to = ucnv_open(dst_enc_str.c_str(), &status);
if (status != U_ZERO_ERROR && status != U_AMBIGUOUS_ALIAS_WARNING) {
fprintf(stderr, "liblcf: ucnv_open() error for dest encoding \"%s\": %s\n", dst_enc_str.c_str(), u_errorName(status));
return std::string();
}
auto conv_to_sg = makeScopeGuard([&]() { ucnv_close(conv_to); });
status = U_ZERO_ERROR;
std::string result(str_to_encode.size() * 4, '\0');
auto* src = str_to_encode.data();
auto* dst = &result.front();
ucnv_convertEx(conv_to, conv_from,
&dst, dst + result.size(),
&src, src + str_to_encode.size(),
nullptr, nullptr, nullptr, nullptr,
true, true,
&status);
if (U_FAILURE(status)) {
fprintf(stderr, "liblcf: ucnv_convertEx() error when encoding \"%.*s\": %s\n", (int)str_to_encode.length(), str_to_encode.data(), u_errorName(status));
return std::string();
}
result.resize(dst - result.c_str());
result.shrink_to_fit();
return result;
#else
iconv_t cd = iconv_open(dst_enc_str.c_str(), src_enc_str.c_str());
if (cd == (iconv_t)-1)
return ToString(str_to_encode);
char *src = const_cast<char *>(str_to_encode.data());
size_t src_left = str_to_encode.size();
size_t dst_size = str_to_encode.size() * 5 + 10;
char *dst = new char[dst_size];
size_t dst_left = dst_size;
# ifdef ICONV_CONST
char ICONV_CONST *p = src;
# else
char *p = src;
# endif
char *q = dst;
size_t status = iconv(cd, &p, &src_left, &q, &dst_left);
iconv_close(cd);
if (status == (size_t) -1 || src_left > 0) {
delete[] dst;
return std::string();
}
*q++ = '\0';
std::string result(dst);
delete[] dst;
return result;
#endif
}
std::string ReaderUtil::Normalize(StringView str) {
#if LCF_SUPPORT_ICU
icu::UnicodeString uni = icu::UnicodeString(str.data(), str.length(), "utf-8").toLower();
UErrorCode err = U_ZERO_ERROR;
std::string res;
const icu::Normalizer2* norm = icu::Normalizer2::getNFKCInstance(err);
if (U_FAILURE(err)) {
static bool err_reported = false;
if (!err_reported) {
fprintf(stderr, "Normalizer2::getNFKCInstance failed (%s). \"nrm\" is probably missing in the ICU data file. Unicode normalization will not work!\n", u_errorName(err));
err_reported = true;
}
uni.toUTF8String(res);
return res;
}
icu::UnicodeString f = norm->normalize(uni, err);
if (U_FAILURE(err)) {
uni.toUTF8String(res);
} else {
f.toUTF8String(res);
}
return res;
#else
auto result = std::string(str);
std::transform(result.begin(), result.end(), result.begin(), tolower);
return result;
#endif
}
} //namespace lcf
|
/*
* File : pbzip2.cpp
*
* Title : Parallel BZIP2 (pbzip2)
*
* Author: Jeff Gilchrist (http://gilchrist.ca/jeff/)
* - Modified producer/consumer threading code from
* Andrae Muys <andrae@humbug.org.au.au>
* - uses libbzip2 by Julian Seward (http://sources.redhat.com/bzip2/)
*
* Date : August 30, 2005
*
*
* Contributions
* -------------
* Bryan Stillwell <bryan@bokeoa.com> - code cleanup, RPM spec, prep work
* for inclusion in Fedora Extras
* Dru Lemley [http://lemley.net/smp.html] - help with large file support
* Kir Kolyshkin <kir@sacred.ru> - autodetection for # of CPUs
* Joergen Ramskov <joergen@ramskov.org> - initial version of man page
* Peter Cordes <peter@cordes.ca> - code cleanup
* Kurt Fitzner <kfitzner@excelcia.org> - port to MinGW for Windows
* Oliver Falk <oliver@linux-kernel.at> - RPM spec update
* Jindrich Novy <jnovy@redhat.com> - code cleanup and bug fixes
*
* Specials thanks for suggestions and testing: Phillippe Welsh,
* James Terhune, Dru Lemley, Bryan Stillwell, George Chalissery,
* Kir Kolyshkin, Madhu Kangara, Mike Furr, Joergen Ramskov, Kurt Fitzner,
* Peter Cordes, Oliver Falk, and Jindrich Novy.
*
*
* This program, "pbzip2" is copyright (C) 2003-2005 Jeff Gilchrist.
* All rights reserved.
*
* The library "libbzip2" which pbzip2 uses, is copyright
* (C) 1996-2002 Julian R Seward. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Altered source versions must be plainly marked as such, and must
* not be misrepresented as being the original software.
*
* 4. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Jeff Gilchrist, Ottawa, Canada.
* pbzip2@compression.ca
* pbzip2 version 0.9.4 of August 30, 2005
*
*/
#include <vector>
#include <sys/stat.h>
#include <sys/time.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <utime.h>
#include <unistd.h>
#include <bzlib.h>
#ifdef WIN32
#include <windows.h>
#endif
// uncomment for debug output
//#define PBZIP_DEBUG
#ifdef WIN32
#define usleep(x) Sleep(x/1000)
#ifndef _TIMEVAL_DEFINED /* also in winsock[2].h */
#define _TIMEVAL_DEFINED
struct timeval {
long tv_sec;
long tv_usec;
};
#endif
#endif
#ifndef WIN32
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
#else
#define FILE_MODE (S_IRUSR | S_IWUSR )
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
typedef struct
{
char *buf;
unsigned int bufSize;
} outBuff;
typedef struct
{
char **buf;
unsigned int *bufSize;
int *blockNum;
long head, tail;
int full, empty;
pthread_mutex_t *mut;
pthread_cond_t *notFull, *notEmpty;
} queue;
typedef struct
{
off_t dataStart;
off_t dataSize;
} bz2BlockListing;
//
// GLOBALS
//
static int allDone = 0;
static int QUEUESIZE = 2;
static int NumBlocks = 0;
static int Verbosity = 0;
static int QuietMode = 0;
static int OutputStdOut = 0;
static int BWTblockSize = 9;
static int FileListCount = 0;
static std::vector <outBuff> OutputBuffer;
static pthread_mutex_t *OutMutex = NULL;
static pthread_mutex_t *MemMutex = NULL;
static struct stat fileMetaData;
static char *sigInFilename = NULL;
static char *sigOutFilename = NULL;
static char BWTblockSizeChar = '9';
void mySignalCatcher(int);
char *memstr(char *, int, char *, int);
int producer_decompress(int, off_t, queue *);
void *consumer_decompress(void *);
void *fileWriter(void *);
int producer(int, int, off_t, int, queue *);
void *consumer(void *);
queue *queueInit(int);
void queueDelete(queue *);
void queueAdd(queue *, char *, unsigned int, int);
char *queueDel(queue *, unsigned int *, int *);
int getFileMetaData(char *);
int writeFileMetaData(char *);
int testBZ2ErrorHandling(int, BZFILE *, int);
int testCompressedData(char *);
/*
*********************************************************
*/
void mySignalCatcher(int n)
{
struct stat statBuf;
int ret = 0;
fprintf(stderr, "\n *Control-C or similar caught, quitting...\n");
#ifdef PBZIP_DEBUG
fprintf(stderr, " Infile: %s Outfile: %s\n", sigInFilename, sigOutFilename);
#endif
// only cleanup files if we did something with them
if ((sigInFilename == NULL) || (sigOutFilename == NULL))
exit(1);
// check to see if input file still exists
ret = stat(sigInFilename, &statBuf);
if (ret == 0)
{
// only want to remove output file if input still exists
if (QuietMode != 1)
fprintf(stderr, "Deleting output file: %s, if it exists...\n", sigOutFilename);
ret = remove(sigOutFilename);
if (ret != 0)
fprintf(stderr, " *WARNING: Deletion of output file (apparently) failed.\n");
}
else
{
fprintf(stderr, " *WARNING: Output file was not deleted since input file no longer exists.\n");
fprintf(stderr, " *WARNING: Output file: %s, may be incomplete!\n", sigOutFilename);
}
exit(1);
}
/*
*********************************************************
This function will search the array pointed to by
searchBuf[] for the string searchString[] and return
a pointer to the start of the searchString[] if found
otherwise return NULL if not found.
*/
char *memstr(char *searchBuf, int searchBufSize, char *searchString, int searchStringSize)
{
int i;
int j;
int notFound = 0;
for (i=0; i < searchBufSize; i++)
{
if ((searchBufSize - 1 - i) < searchStringSize)
break;
if (searchBuf[i] == searchString[0])
{
notFound = 0;
// we found first character now check rest
for (j=1; j < searchStringSize; j++)
{
if (searchBuf[i+j] != searchString[j])
{ notFound = 1;
break;
}
}
// we found the first occurance of the string so we are done
if (notFound == 0)
{
#ifdef PBZIP_DEBUG
fprintf(stderr, " memstr(): Found substring at byte: %d [%x]\n", i, &searchBuf[i]);
#endif
return &searchBuf[i];
}
}
}
return NULL;
}
/*
*********************************************************
This function works in two passes of the input file.
The first pass will look for BZIP2 headers in the file
and note their location and size of the sections.
The second pass will read in those BZIP2 sections and
pass them off the the selected CPU(s) for decompression.
*/
int producer_decompress(int hInfile, off_t fileSize, queue *fifo)
{
std::vector <bz2BlockListing> bz2BlockList;
outBuff TempOutBuffer;
bz2BlockListing TempBlockListing;
char *FileData = NULL;
char bz2Header[] = {"BZh91AY&SY"}; // for 900k BWT block size
off_t bytesLeft = 0;
off_t inSize = 100000;
int blockNum = 0;
off_t ret = 0;
int i;
int bz2NumBlocks = 0;
char *startPointer = NULL;
off_t currentByte = 0;
off_t startByte = 0;
TempOutBuffer.buf = NULL;
TempOutBuffer.bufSize = 0;
// set search header to value in file
bz2Header[3] = BWTblockSizeChar;
// go to start of file
ret = lseek(hInfile, 0, SEEK_SET);
if (ret != 0)
{
fprintf(stderr, " *ERROR: Could not seek to beginning of file [%llu]! Skipping...\n", (unsigned long long)ret);
close(hInfile);
allDone = 1;
return -1;
}
// scan input file for BZIP2 block markers (BZh91AY&SY)
pthread_mutex_lock(MemMutex);
// allocate memory to read in file
FileData = NULL;
FileData = new char[inSize];
pthread_mutex_unlock(MemMutex);
// make sure memory was allocated properly
if (FileData == NULL)
{
fprintf(stderr, " *ERROR: Could not allocate memory (FileData)! Skipping...\n");
close(hInfile);
allDone = 1;
return -1;
}
// keep going until all the file is scanned for BZIP2 blocks
bytesLeft = fileSize;
while (bytesLeft > 0)
{
if (currentByte == 0)
{
#ifdef PBZIP_DEBUG
fprintf(stderr, " -> Bytes To Read: %llu bytes...\n", inSize);
#endif
// read file data
ret = read(hInfile, (char *) FileData, inSize);
}
else
{
// copy end section of previous buffer to new just in case the BZIP2 header is
// located between two buffer boundaries
memcpy(FileData, FileData+inSize-(strlen(bz2Header)-1), strlen(bz2Header)-1);
#ifdef PBZIP_DEBUG
fprintf(stderr, " -> Bytes To Read: %llu bytes...\n", inSize-(strlen(bz2Header)-1));
#endif
// read file data minus overflow from previous buffer
ret = read(hInfile, (char *) FileData+strlen(bz2Header)-1, inSize-(strlen(bz2Header)-1));
}
#ifdef PBZIP_DEBUG
fprintf(stderr, " -> Total Bytes Read: %llu bytes...\n\n", ret);
#endif
if (ret < 0)
{
fprintf(stderr, " *ERROR: Could not read from fibz2NumBlocksle! Skipping...\n");
close(hInfile);
pthread_mutex_lock(MemMutex);
if (FileData != NULL)
delete [] FileData;
pthread_mutex_unlock(MemMutex);
allDone = 1;
return -1;
}
// scan buffer for bzip2 start header
if (currentByte == 0)
startPointer = memstr(FileData, ret, bz2Header, strlen(bz2Header));
else
startPointer = memstr(FileData, ret+(strlen(bz2Header)-1), bz2Header, strlen(bz2Header));
while (startPointer != NULL)
{
if (currentByte == 0)
startByte = startPointer - FileData + currentByte;
else
startByte = startPointer - FileData + currentByte - (strlen(bz2Header) - 1);
#ifdef PBZIP_DEBUG
fprintf(stderr, " Found substring at: %x\n", startPointer);
fprintf(stderr, " startByte = %llu\n", startByte);
fprintf(stderr, " bz2NumBlocks = %d\n", bz2NumBlocks);
#endif
// add data to end of block list
TempBlockListing.dataStart = startByte;
TempBlockListing.dataSize = 0;
bz2BlockList.push_back(TempBlockListing);
bz2NumBlocks++;
if (currentByte == 0)
{
startPointer = memstr(startPointer+1, ret-(startPointer-FileData)-1, bz2Header, strlen(bz2Header));
}
else
{
startPointer = memstr(startPointer+1, ret-(startPointer-FileData)-1+(strlen(bz2Header)-1), bz2Header, strlen(bz2Header));
}
}
currentByte += ret;
bytesLeft -= ret;
} // while
pthread_mutex_lock(MemMutex);
if (FileData != NULL)
delete [] FileData;
NumBlocks = bz2NumBlocks;
pthread_mutex_unlock(MemMutex);
// calculate data sizes for each block
for (i=0; i < bz2NumBlocks; i++)
{
if (i == bz2NumBlocks-1)
{
// special case for last block
bz2BlockList[i].dataSize = fileSize - bz2BlockList[i].dataStart;
}
else if (i == 0)
{
// special case for first block
bz2BlockList[i].dataSize = bz2BlockList[i+1].dataStart;
}
else
{
// normal case
bz2BlockList[i].dataSize = bz2BlockList[i+1].dataStart - bz2BlockList[i].dataStart;
}
#ifdef PBZIP_DEBUG
fprintf(stderr, " bz2BlockList[%d].dataStart = %llu\n", i, bz2BlockList[i].dataStart);
fprintf(stderr, " bz2BlockList[%d].dataSize = %llu\n", i, bz2BlockList[i].dataSize);
#endif
}
// keep going until all the blocks are processed
for (i=0; i < bz2NumBlocks; i++)
{
// go to start of block position in file
ret = lseek(hInfile, bz2BlockList[i].dataStart, SEEK_SET);
if (ret != bz2BlockList[i].dataStart)
{
fprintf(stderr, " *ERROR: Could not seek to beginning of file [%llu]! Skipping...\n", (unsigned long long)ret);
close(hInfile);
allDone = 1;
return -1;
}
// set buffer size
inSize = bz2BlockList[i].dataSize;
#ifdef PBZIP_DEBUG
fprintf(stderr, " -> Bytes To Read: %llu bytes...\n", inSize);
#endif
if (QuietMode != 1)
{
// give warning to user if block is larger than 250 million bytes
if (inSize > 250000000)
{
fprintf(stderr, " *WARNING: Compressed block size is large [%llu bytes].\n", (unsigned long long)inSize);
fprintf(stderr, " If program aborts, use regular BZIP2 to decompress.\n");
}
}
pthread_mutex_lock(MemMutex);
// allocate memory to read in file
FileData = NULL;
FileData = new char[inSize];
pthread_mutex_unlock(MemMutex);
// make sure memory was allocated properly
if (FileData == NULL)
{
fprintf(stderr, " *ERROR: Could not allocate memory (FileData)! Skipping...\n");
close(hInfile);
allDone = 1;
return -1;
}
// read file data
ret = read(hInfile, (char *) FileData, inSize);
#ifdef PBZIP_DEBUG
fprintf(stderr, " -> Total Bytes Read: %llu bytes...\n\n", ret);
#endif
// check to make sure all the data we expected was read in
if (ret == 0)
{
pthread_mutex_lock(MemMutex);
if (FileData != NULL)
delete [] FileData;
pthread_mutex_unlock(MemMutex);
break;
}
else if (ret < 0)
{
fprintf(stderr, " *ERROR: Could not read from file! Skipping...\n");
close(hInfile);
pthread_mutex_lock(MemMutex);
if (FileData != NULL)
delete [] FileData;
pthread_mutex_unlock(MemMutex);
allDone = 1;
return -1;
}
else if (ret != inSize)
{
fprintf(stderr, " *ERROR: Could not read enough data from file! Skipping...\n");
close(hInfile);
pthread_mutex_lock(MemMutex);
if (FileData != NULL)
delete [] FileData;
pthread_mutex_unlock(MemMutex);
allDone = 1;
return -1;
}
// add one element to the output buffer
pthread_mutex_lock(OutMutex);
OutputBuffer.push_back(TempOutBuffer);
pthread_mutex_unlock(OutMutex);
// add data to the decompression queue
pthread_mutex_lock (fifo->mut);
while (fifo->full) {
#ifdef PBZIP_DEBUG
printf ("producer: queue FULL.\n");
#endif
pthread_cond_wait (fifo->notFull, fifo->mut);
}
#ifdef PBZIP_DEBUG
fprintf(stderr, "producer: Buffer: %x Size: %llu Block: %d\n", FileData, inSize, blockNum);
#endif
queueAdd(fifo, FileData, inSize, blockNum);
pthread_mutex_unlock (fifo->mut);
pthread_cond_signal (fifo->notEmpty);
blockNum++;
} // for
close(hInfile);
allDone = 1;
return 0;
}
/*
*********************************************************
*/
void *consumer_decompress(void *q)
{
struct timespec waitTimer;
#ifndef WIN32
struct timeval tv;
struct timezone tz;
#else
SYSTEMTIME systemtime;
LARGE_INTEGER filetime;
#endif
queue *fifo;
char *FileData = NULL;
char *DecompressedData = NULL;
unsigned int inSize = 0;
unsigned int outSize = 0;
int blockNum = -1;
int ret = -1;
int pret = -1;
fifo = (queue *)q;
for (;;)
{
pthread_mutex_lock(fifo->mut);
while (fifo->empty)
{
#ifdef PBZIP_DEBUG
printf ("consumer: queue EMPTY.\n");
#endif
if (allDone == 1)
{
pthread_mutex_unlock(fifo->mut);
#ifdef PBZIP_DEBUG
printf ("consumer: exiting2\n");
#endif
return (NULL);
}
// only wait for the queue notEmpty signal for 1 second before checking if
// the producer is finished putting work into the queue
#ifndef WIN32
gettimeofday(&tv, &tz);
waitTimer.tv_sec = tv.tv_sec + 1;
waitTimer.tv_nsec = tv.tv_usec * 1000;
#else
GetSystemTime(&systemtime);
SystemTimeToFileTime(&systemtime, (FILETIME *)&filetime);
waitTimer.tv_sec = filetime.QuadPart / 10000000;
waitTimer.tv_nsec = filetime.QuadPart - ((LONGLONG)waitTimer.tv_sec * 10000000) * 10;
waitTimer.tv_sec++;
#endif
#ifdef PBZIP_DEBUG
fprintf(stderr, "consumer: waitTimer.tv_sec: %d waitTimer.tv_nsec: %d\n", waitTimer.tv_sec, waitTimer.tv_nsec);
#endif
pret = pthread_cond_timedwait(fifo->notEmpty, fifo->mut, &waitTimer);
// we are not using a compatible pthreads library so abort
if (pret == EINVAL)
{
fprintf(stderr, " *ERROR: pthread_cond_timedwait() call invalid. This machine\n");
fprintf(stderr, " does not have compatible pthreads library. Skipping.\n");
exit(1);
}
}
FileData = queueDel(fifo, &inSize, &blockNum);
#ifdef PBZIP_DEBUG
fprintf(stderr, "consumer: Buffer: %x Size: %u Block: %d\n", FileData, inSize, blockNum);
#endif
pthread_mutex_unlock(fifo->mut);
pthread_cond_signal(fifo->notFull);
#ifdef PBZIP_DEBUG
printf ("consumer: recieved %d.\n", blockNum);
#endif
outSize = 900000;
pthread_mutex_lock(MemMutex);
// allocate memory for decompressed data (start with default 900k block size)
DecompressedData = new char[outSize];
pthread_mutex_unlock(MemMutex);
// make sure memory was allocated properly
if (DecompressedData == NULL)
{
fprintf(stderr, " *ERROR: Could not allocate memory (DecompressedData)! Skipping...\n");
return (NULL);
}
// decompress the memory buffer (verbose=0)
ret = BZ2_bzBuffToBuffDecompress(DecompressedData, &outSize, FileData, inSize, 0, Verbosity);
while (ret == BZ_OUTBUFF_FULL)
{
#ifdef PBZIP_DEBUG
fprintf(stderr, "Increasing DecompressedData buffer size: %d -> %d\n", outSize, outSize*4);
#endif
pthread_mutex_lock(MemMutex);
if (DecompressedData != NULL)
delete [] DecompressedData;
DecompressedData = NULL;
// increase buffer space
outSize = outSize * 4;
// allocate memory for decompressed data (start with default 900k block size)
DecompressedData = new char[outSize];
pthread_mutex_unlock(MemMutex);
// make sure memory was allocated properly
if (DecompressedData == NULL)
{
fprintf(stderr, " *ERROR: Could not allocate memory (DecompressedData)! Skipping...\n");
return (NULL);
}
// decompress the memory buffer (verbose=0)
ret = BZ2_bzBuffToBuffDecompress(DecompressedData, &outSize, FileData, inSize, 0, Verbosity);
} // while
if ((ret != BZ_OK) && (ret != BZ_OUTBUFF_FULL))
fprintf(stderr, " *ERROR during decompression: %d\n", ret);
#ifdef PBZIP_DEBUG
fprintf(stderr, "\n Compressed Block Size: %u\n", inSize);
fprintf(stderr, " Original Block Size: %u\n", outSize);
#endif
// store data to be written in output bin
pthread_mutex_lock(OutMutex);
OutputBuffer[blockNum].buf = DecompressedData;
OutputBuffer[blockNum].bufSize = outSize;
pthread_mutex_unlock(OutMutex);
#ifdef PBZIP_DEBUG
fprintf(stderr, " OutputBuffer[%d].buf = %x\n", blockNum, OutputBuffer[blockNum].buf);
fprintf(stderr, " OutputBuffer[%d].bufSize = %u\n", blockNum, OutputBuffer[blockNum].bufSize);
#endif
if (FileData != NULL)
{
pthread_mutex_lock(MemMutex);
delete [] FileData;
FileData = NULL;
pthread_mutex_unlock(MemMutex);
}
} // for
#ifdef PBZIP_DEBUG
printf ("consumer: exiting\n");
#endif
return (NULL);
}
/*
*********************************************************
*/
void *fileWriter(void *outname)
{
char *OutFilename;
off_t CompressedSize = 0;
int percentComplete = 0;
int hOutfile = 1; // default to stdout
int currBlock = 0;
int ret = -1;
OutFilename = (char *) outname;
// write to file instead of stdout
if (OutputStdOut == 0)
{
hOutfile = open(OutFilename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, FILE_MODE);
// check to see if file creation was successful
if (hOutfile == -1)
{
fprintf(stderr, " *ERROR: Could not create output file [%s]!\n", OutFilename);
return (NULL);
}
}
while ((currBlock < NumBlocks) || (allDone == 0))
{
if ((OutputBuffer.size() == 0) || (OutputBuffer[currBlock].bufSize < 1) || (OutputBuffer[currBlock].buf == NULL))
{
// sleep a little so we don't go into a tight loop using up all the CPU
usleep(50000);
continue;
}
#ifdef PBZIP_DEBUG
fprintf(stderr, "fileWriter: Buffer: %x Size: %u Block: %d\n", OutputBuffer[currBlock].buf, OutputBuffer[currBlock].bufSize, currBlock);
#endif
// write data to the output file
ret = write(hOutfile, OutputBuffer[currBlock].buf, OutputBuffer[currBlock].bufSize);
#ifdef PBZIP_DEBUG
fprintf(stderr, "\n -> Total Bytes Written[%d]: %d bytes...\n", currBlock, ret);
#endif
CompressedSize += ret;
if (ret <= 0)
{
fprintf(stderr, " *ERROR: Could not write to file! Skipping...\n");
if (OutputStdOut == 0)
close(hOutfile);
pthread_mutex_lock(MemMutex);
if (OutputBuffer[currBlock].buf != NULL)
delete [] OutputBuffer[currBlock].buf;
pthread_mutex_unlock(MemMutex);
return (NULL);
}
pthread_mutex_lock(MemMutex);
if (OutputBuffer[currBlock].buf != NULL)
delete [] OutputBuffer[currBlock].buf;
pthread_mutex_unlock(MemMutex);
currBlock++;
// print current completion status
percentComplete = 100 * currBlock / NumBlocks;
if (QuietMode != 1)
{
fprintf(stderr, "Completed: %d%% \r", percentComplete);
fflush(stderr);
}
} // while
if (OutputStdOut == 0)
close(hOutfile);
if (QuietMode != 1)
{
fprintf(stderr, " Output Size: %llu bytes\n", (unsigned long long)CompressedSize);
}
return (NULL);
}
/*
*********************************************************
*/
int producer(int hInfile, off_t fileSize, int blockSize, queue *fifo)
{
char *FileData = NULL;
off_t bytesLeft = 0;
off_t inSize = 0;
int blockNum = 0;
int ret = 0;
int pret = -1;
bytesLeft = fileSize;
// keep going until all the file is processed
while (bytesLeft > 0)
{
// set buffer size
if (bytesLeft > blockSize)
inSize = blockSize;
else
inSize = bytesLeft;
#ifdef PBZIP_DEBUG
fprintf(stderr, " -> Bytes To Read: %llu bytes...\n", inSize);
#endif
pthread_mutex_lock(MemMutex);
// allocate memory to read in file
FileData = NULL;
FileData = new char[inSize];
pthread_mutex_unlock(MemMutex);
// make sure memory was allocated properly
if (FileData == NULL)
{
fprintf(stderr, " *ERROR: Could not allocate memory (FileData)! Skipping...\n");
close(hInfile);
allDone = 1;
return -1;
}
// read file data
ret = read(hInfile, (char *) FileData, inSize);
#ifdef PBZIP_DEBUG
fprintf(stderr, " -> Total Bytes Read: %d bytes...\n\n", ret);
#endif
if (ret == 0)
{
pthread_mutex_lock(MemMutex);
if (FileData != NULL)
delete [] FileData;
pthread_mutex_unlock(MemMutex);
break;
}
else if (ret < 0)
{
fprintf(stderr, " *ERROR: Could not read from file! Skipping...\n");
close(hInfile);
pthread_mutex_lock(MemMutex);
if (FileData != NULL)
delete [] FileData;
pthread_mutex_unlock(MemMutex);
allDone = 1;
return -1;
}
// set bytes left after read
bytesLeft -= ret;
// check to make sure all the data we expected was read in
if (ret != inSize)
inSize = ret;
#ifdef PBZIP_DEBUG
fprintf(stderr, "producer: Going into fifo-mut lock (blockNum: %d)\n", blockNum);
#endif
// add data to the compression queue
pthread_mutex_lock(fifo->mut);
while (fifo->full)
{
#ifdef PBZIP_DEBUG
printf ("producer: queue FULL.\n");
#endif
pret = pthread_cond_wait(fifo->notFull, fifo->mut);
if (pret != 0)
fprintf(stderr, "producer: *ERROR: pthread_cond_wait error = %d\n", pret);
}
#ifdef PBZIP_DEBUG
fprintf(stderr, "producer: Buffer: %x Size: %llu Block: %d\n", FileData, inSize, blockNum);
#endif
queueAdd(fifo, FileData, inSize, blockNum);
pthread_mutex_unlock(fifo->mut);
pthread_cond_signal(fifo->notEmpty);
blockNum++;
} // while
close(hInfile);
allDone = 1;
return 0;
}
/*
*********************************************************
*/
void *consumer (void *q)
{
struct timespec waitTimer;
#ifndef WIN32
struct timeval tv;
struct timezone tz;
#else
SYSTEMTIME systemtime;
LARGE_INTEGER filetime;
#endif
queue *fifo;
char *FileData = NULL;
char *CompressedData = NULL;
unsigned int inSize = 0;
unsigned int outSize = 0;
int blockNum = -1;
int ret = -1;
int pret = -1;
fifo = (queue *)q;
for (;;)
{
pthread_mutex_lock(fifo->mut);
while (fifo->empty)
{
#ifdef PBZIP_DEBUG
printf ("consumer: queue EMPTY.\n");
#endif
if (allDone == 1)
{
pthread_mutex_unlock(fifo->mut);
#ifdef PBZIP_DEBUG
printf ("consumer: exiting2\n");
#endif
return (NULL);
}
// only wait for the queue notEmpty signal for 1 second before checking if
// the producer is finished putting work into the queue
#ifndef WIN32
gettimeofday(&tv, &tz);
waitTimer.tv_sec = tv.tv_sec + 1;
waitTimer.tv_nsec = tv.tv_usec * 1000;
#else
GetSystemTime(&systemtime);
SystemTimeToFileTime(&systemtime, (FILETIME *)&filetime);
waitTimer.tv_sec = filetime.QuadPart / 10000000;
waitTimer.tv_nsec = filetime.QuadPart - ((LONGLONG)waitTimer.tv_sec * 10000000) * 10;
waitTimer.tv_sec++;
#endif
#ifdef PBZIP_DEBUG
fprintf(stderr, "consumer: waitTimer.tv_sec: %d waitTimer.tv_nsec: %d\n", waitTimer.tv_sec, waitTimer.tv_nsec);
#endif
pret = pthread_cond_timedwait(fifo->notEmpty, fifo->mut, &waitTimer);
// we are not using a compatible pthreads library so abort
if (pret == EINVAL)
{
fprintf(stderr, " *ERROR: pthread_cond_timedwait() call invalid. This machine\n");
fprintf(stderr, " does not have compatible pthreads library. Skipping.\n");
exit(-1);
}
}
FileData = queueDel(fifo, &inSize, &blockNum);
#ifdef PBZIP_DEBUG
fprintf(stderr, "consumer: Buffer: %x Size: %u Block: %d\n", FileData, inSize, blockNum);
#endif
pthread_mutex_unlock(fifo->mut);
pret = pthread_cond_signal(fifo->notFull);
if (pret != 0)
fprintf(stderr, "consumer: *ERROR: pthread_cond_signal error = %d\n", pret);
#ifdef PBZIP_DEBUG
printf ("consumer: recieved %d.\n", blockNum);
#endif
outSize = (int) ((inSize*1.01)+600);
pthread_mutex_lock(MemMutex);
// allocate memory for compressed data
CompressedData = new char[outSize];
pthread_mutex_unlock(MemMutex);
// make sure memory was allocated properly
if (CompressedData == NULL)
{
fprintf(stderr, " *ERROR: Could not allocate memory (CompressedData)! Skipping...\n");
return (NULL);
}
// compress the memory buffer (blocksize=9*100k, verbose=0, worklevel=30)
ret = BZ2_bzBuffToBuffCompress(CompressedData, &outSize, FileData, inSize, BWTblockSize, Verbosity, 30);
if (ret != BZ_OK)
fprintf(stderr, " *ERROR during compression: %d\n", ret);
#ifdef PBZIP_DEBUG
fprintf(stderr, "\n Original Block Size: %u\n", inSize);
fprintf(stderr, " Compressed Block Size: %u\n", outSize);
#endif
// store data to be written in output bin
pthread_mutex_lock(OutMutex);
OutputBuffer[blockNum].buf = CompressedData;
OutputBuffer[blockNum].bufSize = outSize;
pthread_mutex_unlock(OutMutex);
if (FileData != NULL)
{
pthread_mutex_lock(MemMutex);
delete [] FileData;
FileData = NULL;
pthread_mutex_unlock(MemMutex);
}
} // for
#ifdef PBZIP_DEBUG
printf ("consumer: exiting\n");
#endif
return (NULL);
}
/*
*********************************************************
*/
queue *queueInit(int queueSize)
{
queue *q;
QUEUESIZE = queueSize;
q = new queue;
if (q == NULL)
return NULL;
q->buf = NULL;
q->buf = new char*[queueSize];
if (q->buf == NULL)
return NULL;
q->bufSize = NULL;
q->bufSize = new unsigned int[queueSize];
if (q->bufSize == NULL)
return NULL;
q->blockNum = NULL;
q->blockNum = new int[queueSize];
if (q->blockNum == NULL)
return NULL;
q->empty = 1;
q->full = 0;
q->head = 0;
q->tail = 0;
q->mut = NULL;
q->mut = new pthread_mutex_t;
if (q->mut == NULL)
return NULL;
pthread_mutex_init(q->mut, NULL);
q->notFull = NULL;
q->notFull = new pthread_cond_t;
if (q->notFull == NULL)
return NULL;
pthread_cond_init(q->notFull, NULL);
q->notEmpty = NULL;
q->notEmpty = new pthread_cond_t;
if (q->notEmpty == NULL)
return NULL;
pthread_cond_init(q->notEmpty, NULL);
return (q);
}
/*
*********************************************************
*/
void queueDelete (queue *q)
{
if (q == NULL)
return;
if (q->mut != NULL)
{
pthread_mutex_destroy(q->mut);
delete q->mut;
q->mut = NULL;
}
if (q->notFull != NULL)
{
pthread_cond_destroy(q->notFull);
delete q->notFull;
q->notFull = NULL;
}
if (q->notEmpty != NULL)
{
pthread_cond_destroy(q->notEmpty);
delete q->notEmpty;
q->notEmpty = NULL;
}
delete q;
q = NULL;
return;
}
/*
*********************************************************
*/
void queueAdd (queue *q, char *in, unsigned int bufSize, int blockNum)
{
q->buf[q->tail] = in;
q->bufSize[q->tail] = bufSize;
q->blockNum[q->tail] = blockNum;
q->tail++;
if (q->tail == QUEUESIZE)
q->tail = 0;
if (q->tail == q->head)
q->full = 1;
q->empty = 0;
return;
}
/*
*********************************************************
*/
char *queueDel (queue *q, unsigned int *bufSize, int *blockNum)
{
char *out;
out = q->buf[q->head];
*bufSize = q->bufSize[q->head];
*blockNum = q->blockNum[q->head];
q->head++;
if (q->head == QUEUESIZE)
q->head = 0;
if (q->head == q->tail)
q->empty = 1;
q->full = 0;
return out;
}
/*
*********************************************************
Much of the code in this function is taken from bzip2.c
*/
int testBZ2ErrorHandling(int bzerr, BZFILE* bzf, int streamNo)
{
int bzerr_dummy;
BZ2_bzReadClose(&bzerr_dummy, bzf);
switch (bzerr)
{
case BZ_CONFIG_ERROR:
fprintf(stderr, " *ERROR: Integers are not the right size for libbzip2. Aborting!\n");
exit(3);
break;
case BZ_IO_ERROR:
fprintf(stderr, " *ERROR: Integers are not the right size for libbzip2. Aborting!\n");
return 1;
break;
case BZ_DATA_ERROR:
fprintf(stderr, " *ERROR: Data integrity (CRC) error in data! Skipping...\n");
return -1;
break;
case BZ_MEM_ERROR:
fprintf(stderr, " *ERROR: Could NOT allocate enough memory. Aborting!\n");
return 1;
break;
case BZ_UNEXPECTED_EOF:
fprintf(stderr, " *ERROR: File ends unexpectedly! Skipping...\n");
return -1;
break;
case BZ_DATA_ERROR_MAGIC:
if (streamNo == 1)
{
fprintf(stderr, " *ERROR: Bad magic number (file not created by bzip2)! Skipping...\n");
return -1;
}
else
{
if (QuietMode != 1)
fprintf(stderr, " *Warning: Trailing garbage after EOF ignored!\n");
return 0;
}
default:
fprintf(stderr, " *ERROR: Unexpected error. Aborting!\n");
exit(3);
}
return 0;
}
/*
*********************************************************
Much of the code in this function is taken from bzip2.c
*/
int testCompressedData(char *fileName)
{
FILE *zStream = NULL;
int ret = 0;
BZFILE* bzf = NULL;
unsigned char obuf[5000];
unsigned char unused[BZ_MAX_UNUSED];
unsigned char *unusedTmp;
int bzerr, bzerr_dummy, nread, streamNo;
int nUnused;
int i;
nUnused = 0;
streamNo = 0;
// open the file for reading
zStream = fopen(fileName, "rb");
if (zStream == NULL)
{
fprintf(stderr, " *ERROR: Could not open input file [%s]! Skipping...\n", fileName);
return -1;
}
// check file stream for errors
if (ferror(zStream))
{
fprintf(stderr, " *ERROR: Problem with stream of file [%s]! Skipping...\n", fileName);
fclose(zStream);
return -1;
}
// loop until end of file
while(true)
{
bzf = BZ2_bzReadOpen(&bzerr, zStream, Verbosity, 0, unused, nUnused);
if (bzf == NULL || bzerr != BZ_OK)
{
ret = testBZ2ErrorHandling(bzerr, bzf, streamNo);
fclose(zStream);
return ret;
}
streamNo++;
while (bzerr == BZ_OK)
{
nread = BZ2_bzRead(&bzerr, bzf, obuf, sizeof(obuf));
if (bzerr == BZ_DATA_ERROR_MAGIC)
{
ret = testBZ2ErrorHandling(bzerr, bzf, streamNo);
fclose(zStream);
return ret;
}
}
if (bzerr != BZ_STREAM_END)
{
ret = testBZ2ErrorHandling(bzerr, bzf, streamNo);
fclose(zStream);
return ret;
}
BZ2_bzReadGetUnused(&bzerr, bzf, (void**)(&unusedTmp), &nUnused);
if (bzerr != BZ_OK)
{
fprintf(stderr, " *ERROR: Unexpected error. Aborting!\n");
exit(3);
}
for (i = 0; i < nUnused; i++)
unused[i] = unusedTmp[i];
BZ2_bzReadClose(&bzerr, bzf);
if (bzerr != BZ_OK)
{
fprintf(stderr, " *ERROR: Unexpected error. Aborting!\n");
exit(3);
}
// check to see if we are at the end of the file
if (nUnused == 0)
{
int c = fgetc(zStream);
if (c == EOF)
break;
else
ungetc(c, zStream);
}
}
// check file stream for errors
if (ferror(zStream))
{
fprintf(stderr, " *ERROR: Problem with stream of file [%s]! Skipping...\n", fileName);
fclose(zStream);
return -1;
}
// close file
ret = fclose(zStream);
if (ret == EOF)
{
fprintf(stderr, " *ERROR: Problem closing file [%s]! Skipping...\n", fileName);
return -1;
}
return 0;
}
/*
*********************************************************
*/
int getFileMetaData(char *fileName)
{
int ret = 0;
// get the file meta data and store it in the global structure
ret = stat(fileName, &fileMetaData);
return ret;
}
/*
*********************************************************
*/
int writeFileMetaData(char *fileName)
{
int ret = 0;
struct utimbuf uTimBuf;
// store file times in structure
uTimBuf.actime = fileMetaData.st_atime;
uTimBuf.modtime = fileMetaData.st_mtime;
// update file with stored file permissions
ret = chmod(fileName, fileMetaData.st_mode);
if (ret != 0)
return ret;
// update file with stored file access and modification times
ret = utime(fileName, &uTimBuf);
if (ret != 0)
return ret;
// update file with stored file ownership (if access allows)
#ifndef WIN32
chown(fileName, fileMetaData.st_uid, fileMetaData.st_gid);
#endif
return 0;
}
/*
*********************************************************
*/
void banner()
{
fprintf(stderr, "Parallel BZIP2 v0.9.4 - by: Jeff Gilchrist [http://compression.ca]\n");
fprintf(stderr, "[Aug. 30, 2005] (uses libbzip2 by Julian Seward)\n\n");
fprintf(stderr, "** This is a BETA version - Use at your own risk! **\n");
return;
}
/*
*********************************************************
*/
void usage(char* progname)
{
banner();
fprintf(stderr, "\nInvalid command line! Aborting...\n\n");
fprintf(stderr, "Usage: %s [-1 .. -9] [-b#cdfkp#qrtV] <filename> <filename2> <filenameN>\n", progname);
fprintf(stderr, " -b# : where # is the file block size in 100k (default 9 = 900k)\n");
fprintf(stderr, " -c : output to standard out (stdout)\n");
fprintf(stderr, " -d : decompress file\n");
fprintf(stderr, " -f : force, overwrite existing output file\n");
fprintf(stderr, " -k : keep input file, don't delete\n");
fprintf(stderr, " -p# : where # is the number of processors (default");
#ifdef _SC_NPROCESSORS_ONLN
fprintf(stderr, ": autodetect)\n");
#else
fprintf(stderr, " 2)\n");
#endif
fprintf(stderr, " -q : quiet mode, suppress non-error messages\n");
fprintf(stderr, " -r : read entire input file into RAM and split between processors\n");
fprintf(stderr, " -t : test compressed file integrity\n");
fprintf(stderr, " -V : display version info for pbzip2 then exit\n");
fprintf(stderr, " -1 .. -9 : set BWT block size to 100k .. 900k (default 900k)\n\n");
fprintf(stderr, "Example: pbzip2 -b15qk myfile.tar\n");
fprintf(stderr, "Example: pbzip2 -p4 -r -5 myfile.tar second*.txt\n");
fprintf(stderr, "Example: pbzip2 -d myfile.tar.bz2\n\n");
exit(-1);
}
/*
*********************************************************
*/
int main(int argc, char* argv[])
{
queue *fifo;
pthread_t con, output;
char **FileList = NULL;
char *InFilename = NULL;
char bz2Header[] = {"BZh91AY&SY"}; // using 900k block size
char OutFilename[255];
char cmdLineTemp[255];
char tmpBuff[50];
struct timeval tvStartTime;
struct timeval tvStopTime;
#ifndef WIN32
struct timezone tz;
#else
SYSTEMTIME systemtime;
LARGE_INTEGER filetime;
#endif
struct stat statbuf;
double timeCalc = 0.0;
double timeStart = 0.0;
double timeStop = 0.0;
off_t fileSize = 0;
size_t size;
int cmdLineTempCount = 0;
int readEntireFile = 0;
int numCPU = 2;
int hInfile = -1;
int hOutfile = -1;
int numBlocks = 0;
int blockSize = 9*100000;
int decompress = 0;
int testFile = 0;
int keep = 0;
int force = 0;
int ret = 0;
int i, j, k;
int fileLoop;
int errLevel = 0;
// get current time for benchmark reference
#ifndef WIN32
gettimeofday(&tvStartTime, &tz);
#else
GetSystemTime(&systemtime);
SystemTimeToFileTime(&systemtime, (FILETIME *)&filetime);
tvStartTime.tv_sec = filetime.QuadPart / 10000000;
tvStartTime.tv_usec = (filetime.QuadPart - (LONGLONG)tvStartTime.tv_sec * 10000000) / 10;
#endif
// check to make sure proper command line is given
if (argc < 2)
{
usage(argv[0]);
}
FileListCount = 0;
FileList = new char *[argc];
if (FileList == NULL)
{
fprintf(stderr, " *ERROR: Not enough memory! Aborting...\n");
return 1;
}
// Autodetect the number of CPUs on a box, if available
#ifdef _SC_NPROCESSORS_ONLN
numCPU = sysconf(_SC_NPROCESSORS_ONLN);
#endif
// parse command line switches
for (i=1; i < argc; i++)
{
if (argv[i][0] == '-')
{
#ifdef PBZIP_DEBUG
fprintf(stderr, "argv[%d]: %s Len: %d\n", i, argv[i], strlen(argv[i]));
#endif
// check for multiple switches grouped together
for (j=1; argv[i][j] != '\0'; j++)
{
switch (argv[i][j])
{
case 'p': k = j+1; cmdLineTempCount = 0; strcpy(cmdLineTemp, "2");
while (argv[i][k] != '\0' && k<sizeof(cmdLineTemp))
{
// no more numbers, finish
if ((argv[i][k] < '0') || (argv[i][k] > '9'))
break;
k++;
cmdLineTempCount++;
}
if (cmdLineTempCount == 0)
usage(argv[0]);
strncpy(cmdLineTemp, argv[i]+j+1, cmdLineTempCount);
numCPU = atoi(cmdLineTemp);
if (numCPU > 4096)
{
fprintf(stderr," *ERROR: Maximal number of supported processors is 4096! Aborting...\n");
return 1;
}
else if (numCPU < 1)
{
fprintf(stderr," *ERROR: Minimum number of supported processors is 1! Aborting...\n");
return 1;
}
j += cmdLineTempCount;
#ifdef PBZIP_DEBUG
fprintf(stderr, "-p%d\n", numCPU);
#endif
break;
case 'b': cmdLineTempCount = 0; blockSize = 900000;
if (argv[i][j+1])
{
if ( argv[i][j+1] < '1' || argv[i][j+1] > '9' )
{
fprintf(stderr," *ERROR: Number 1-9 expected for a block size definition! Aborting...\n");
return 1;
}
blockSize = (argv[i][j+1]-'0')*100000;
}
else
{
usage(argv[0]);
}
j++;
#ifdef PBZIP_DEBUG
fprintf(stderr, "-b%d\n", blockSize);
#endif
break;
case 'd': decompress = 1; break;
case 'c': OutputStdOut = 1; keep = 1; break;
case 'f': force = 1; break;
case 'k': keep = 1; break;
case 'q': QuietMode = 1; break;
case 'r': readEntireFile = 1; break;
case 't': testFile = 1; break;
case 'V': banner(); exit(0); break;
case '1': BWTblockSize = 1; break;
case '2': BWTblockSize = 2; break;
case '3': BWTblockSize = 3; break;
case '4': BWTblockSize = 4; break;
case '5': BWTblockSize = 5; break;
case '6': BWTblockSize = 6; break;
case '7': BWTblockSize = 7; break;
case '8': BWTblockSize = 8; break;
case '9': BWTblockSize = 9; break;
}
}
}
else
{
// add filename to list for processing FileListCount
FileList[FileListCount] = argv[i];
FileListCount++;
}
} /* for */
if (FileListCount == 0)
usage(argv[0]);
if (QuietMode != 1)
{
// display program banner
banner();
// do sanity check to make sure integers are the size we expect
#ifdef PBZIP_DEBUG
fprintf(stderr, "off_t size: %d uint size: %d\n", sizeof(off_t), sizeof(unsigned int));
#endif
if (sizeof(off_t) <= 4)
{
fprintf(stderr, "\n *WARNING: off_t variable size only %d bits!\n", sizeof(off_t)*8);
if (decompress == 1)
fprintf(stderr, " You will only able to uncompress files smaller than 2GB in size.\n\n");
else
fprintf(stderr, " You will only able to compress files smaller than 2GB in size.\n\n");
}
}
// setup signal handling
sigInFilename = NULL;
sigOutFilename = NULL;
signal(SIGINT, mySignalCatcher);
signal(SIGTERM, mySignalCatcher);
#ifndef WIN32
signal(SIGHUP, mySignalCatcher);
#endif
// display global settings
if (QuietMode != 1)
{
if (testFile != 1)
{
fprintf(stderr, "\n # CPUs: %d\n", numCPU);
if (decompress != 1)
{
fprintf(stderr, " BWT Block Size: %d00k\n", BWTblockSize);
if (blockSize < 100000)
fprintf(stderr, "File Block Size: %d bytes\n", blockSize);
else
fprintf(stderr, "File Block Size: %dk\n", blockSize/1000);
}
}
fprintf(stderr, "-------------------------------------------\n");
}
// initialize mutexes
OutMutex = new pthread_mutex_t;
// make sure memory was allocated properly
if (OutMutex == NULL)
{
fprintf(stderr, " *ERROR: Could not allocate memory (OutMutex)! Aborting...\n");
return 1;
}
pthread_mutex_init(OutMutex, NULL);
MemMutex = new pthread_mutex_t;
// make sure memory was allocated properly
if (MemMutex == NULL)
{
fprintf(stderr, " *ERROR: Could not allocate memory (MemMutex)! Aborting...\n");
return 1;
}
pthread_mutex_init(MemMutex, NULL);
// create queue
fifo = queueInit(numCPU);
if (fifo == NULL)
{
fprintf (stderr, " *ERROR: Queue Init failed. Aborting...\n");
return 1;
}
// process all files
for (fileLoop=0; fileLoop < FileListCount; fileLoop++)
{
allDone = 0;
// set input filename
InFilename = FileList[fileLoop];
// test file for errors if requested
if (testFile != 0)
{
if (QuietMode != 1)
{
fprintf(stderr, " File #: %d of %d\n", fileLoop+1, FileListCount);
fprintf(stderr, " Testing: %s\n", InFilename);
}
ret = testCompressedData(InFilename);
if (ret > 0)
return ret;
else if (ret == 0)
{
if (QuietMode != 1)
fprintf(stderr, " Test: OK\n");
}
else
errLevel = 2;
if (QuietMode != 1)
fprintf(stderr, "-------------------------------------------\n");
continue;
}
// set ouput filename
strncpy(OutFilename, FileList[fileLoop], 250);
if (decompress == 1)
{
// check if input file is a valid .bz2 compressed file
hInfile = open(InFilename, O_RDONLY | O_BINARY);
// check to see if file exists before processing
if (hInfile == -1)
{
fprintf(stderr, " *ERROR: File [%s] NOT found! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
memset(tmpBuff, 0, sizeof(tmpBuff));
size = read(hInfile, tmpBuff, strlen(bz2Header)+1);
close(hInfile);
if ((size == (size_t)(-1)) || (size < strlen(bz2Header)+1))
{
fprintf(stderr, " *ERROR: File [%s] is NOT a valid bzip2! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
else
{
// make sure start of file has valid bzip2 header
if (memstr(tmpBuff, 4, bz2Header, 3) == NULL)
{
fprintf(stderr, " *ERROR: File [%s] is NOT a valid bzip2! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
// skip 4th char which differs depending on BWT block size used
if (memstr(tmpBuff+4, size-4, bz2Header+4, strlen(bz2Header)-4) == NULL)
{
fprintf(stderr, " *ERROR: File [%s] is NOT a valid bzip2! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
// set block size for decompression
if ((tmpBuff[3] >= '1') && (tmpBuff[3] <= '9'))
BWTblockSizeChar = tmpBuff[3];
else
{
fprintf(stderr, " *ERROR: File [%s] is NOT a valid bzip2! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
}
// check if filename ends with .bz2
if (strncasecmp(&OutFilename[strlen(OutFilename)-4], ".bz2", 4) == 0)
{
// remove .bz2 extension
OutFilename[strlen(OutFilename)-4] = '\0';
}
else
{
// add .out extension so we don't overwrite original file
strcat(OutFilename, ".out");
}
}
else
{
// check input file to make sure its not already a .bz2 file
if (strncasecmp(&InFilename[strlen(InFilename)-4], ".bz2", 4) == 0)
{
fprintf(stderr, " *ERROR: Input file [%s] already has a .bz2 extension! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
strcat(OutFilename, ".bz2");
}
// setup signal handling filenames
sigInFilename = InFilename;
sigOutFilename = OutFilename;
// read file for compression
hInfile = open(InFilename, O_RDONLY | O_BINARY);
// check to see if file exists before processing
if (hInfile == -1)
{
fprintf(stderr, " *ERROR: File [%s] NOT found! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
// get some information about the file
fstat(hInfile, &statbuf);
// check to make input is not a directory
if (S_ISDIR(statbuf.st_mode))
{
fprintf(stderr, " *ERROR: File [%s] is a directory! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
// check to make sure input is a regular file
if (!S_ISREG(statbuf.st_mode))
{
fprintf(stderr, " *ERROR: File [%s] is not a regular file! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
// get size of file
fileSize = statbuf.st_size;
// don't process a 0 byte file
if (fileSize == 0)
{
fprintf(stderr, " *ERROR: File is of size 0 [%s]! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
// get file meta data to write to output file
if (getFileMetaData(InFilename) != 0)
{
fprintf(stderr, " *ERROR: Could not get file meta data from [%s]! Skipping...\n", InFilename);
fprintf(stderr, "-------------------------------------------\n");
continue;
}
// check to see if output file exists
if ((force != 1) && (OutputStdOut == 0))
{
hOutfile = open(OutFilename, O_RDONLY | O_BINARY);
// check to see if file exists before processing
if (hOutfile != -1)
{
fprintf(stderr, " *ERROR: Output file [%s] already exists! Use -f to overwrite...\n", OutFilename);
fprintf(stderr, "-------------------------------------------\n");
close(hOutfile);
continue;
}
}
if (readEntireFile == 1)
{
// determine block size to try and spread data equally over # CPUs
blockSize = fileSize / numCPU;
}
// display per file settings
if (QuietMode != 1)
{
fprintf(stderr, " File #: %d of %d\n", fileLoop+1, FileListCount);
fprintf(stderr, " Input Name: %s\n", InFilename);
if (OutputStdOut == 0)
fprintf(stderr, " Output Name: %s\n\n", OutFilename);
else
fprintf(stderr, " Output Name: <stdout>\n\n");
if (decompress == 1)
fprintf(stderr, " BWT Block Size: %c00k\n", BWTblockSizeChar);
fprintf(stderr, " Input Size: %llu bytes\n", (unsigned long long)fileSize);
}
if (decompress == 1)
{
numBlocks = 0;
}
else
{
// calculate the # of blocks of data
numBlocks = (fileSize + blockSize - 1) / blockSize;
}
#ifdef PBZIP_DEBUG
fprintf(stderr, "# Blocks: %d\n", numBlocks);
#endif
// set global variable
NumBlocks = numBlocks;
// create output buffer
OutputBuffer.resize(numBlocks);
// make sure memory was allocated properly
if (OutputBuffer.size() != numBlocks)
{
fprintf(stderr, " *ERROR: Could not allocate memory (OutputBuffer)! Aborting...\n");
return 1;
}
// set empty buffer
for (i=0; i < numBlocks; i++)
{
OutputBuffer[i].buf = NULL;
OutputBuffer[i].bufSize = 0;
}
if (decompress == 1)
{
if (QuietMode != 1)
fprintf(stderr, "Decompressing data...\n");
for (i=0; i < numCPU; i++)
{
ret = pthread_create(&con, NULL, consumer_decompress, fifo);
if (ret != 0)
{
fprintf(stderr, " *ERROR: Not enough resources to create consumer thread #%d (code = %d) Aborting...\n", i, ret);
return 1;
}
}
ret = pthread_create(&output, NULL, fileWriter, OutFilename);
if (ret != 0)
{
fprintf(stderr, " *ERROR: Not enough resources to create fileWriter thread (code = %d) Aborting...\n", ret);
return 1;
}
// start reading in data for decompression
producer_decompress(hInfile, fileSize, fifo);
}
else
{
if (QuietMode != 1)
fprintf(stderr, "Compressing data...\n");
for (i=0; i < numCPU; i++)
{
ret = pthread_create(&con, NULL, consumer, fifo);
if (ret != 0)
{
fprintf(stderr, " *ERROR: Not enough resources to create consumer thread #%d (code = %d) Aborting...\n", i, ret);
return 1;
}
}
ret = pthread_create(&output, NULL, fileWriter, OutFilename);
if (ret != 0)
{
fprintf(stderr, " *ERROR: Not enough resources to create fileWriter thread (code = %d) Aborting...\n", ret);
return 1;
}
// start reading in data for compression
producer(hInfile, fileSize, blockSize, fifo);
}
// wait until exit of thread
pthread_join(output, NULL);
if (OutputStdOut == 0)
{
statbuf.st_size = 0;
// check to see if output file is larger than 0 bytes
stat(OutFilename, &statbuf);
// get size of file
if (statbuf.st_size == 0)
{
fprintf(stderr, " *ERROR: Output file is size 0 bytes! Deleting...\n");
remove(OutFilename);
}
else
{
// write store file meta data to output file
if (writeFileMetaData(OutFilename) != 0)
fprintf(stderr, " *ERROR: Could not write file meta data to [%s]!\n", InFilename);
}
}
// finished processing file
sigInFilename = NULL;
sigOutFilename = NULL;
// remove input file unless requested not to by user
if (keep != 1)
{
if (OutputStdOut == 0)
{
// only remove input file if output file exists
if (stat(OutFilename, &statbuf) == 0)
remove(InFilename);
}
else
remove(InFilename);
}
// reclaim memory
OutputBuffer.clear();
fifo->empty = 1;
fifo->full = 0;
fifo->head = 0;
fifo->tail = 0;
if (QuietMode != 1)
fprintf(stderr, "-------------------------------------------\n");
} /* for */
// reclaim memory
queueDelete(fifo);
fifo = NULL;
if (OutMutex != NULL)
{
pthread_mutex_destroy(OutMutex);
delete OutMutex;
OutMutex = NULL;
}
if (MemMutex != NULL)
{
pthread_mutex_destroy(MemMutex);
delete MemMutex;
MemMutex = NULL;
}
// get current time for end of benchmark
#ifndef WIN32
gettimeofday(&tvStopTime, &tz);
#else
GetSystemTime(&systemtime);
SystemTimeToFileTime(&systemtime, (FILETIME *)&filetime);
tvStopTime.tv_sec = filetime.QuadPart / 10000000;
tvStopTime.tv_usec = (filetime.QuadPart - (LONGLONG)tvStopTime.tv_sec * 10000000) / 10;
#endif
#ifdef PBZIP_DEBUG
fprintf(stderr, "\n Start Time: %ld + %ld\n", tvStartTime.tv_sec, tvStartTime.tv_usec);
fprintf(stderr, " Stop Time : %ld + %ld\n", tvStopTime.tv_sec, tvStopTime.tv_usec);
#endif
// convert time structure to real numbers
timeStart = (double)tvStartTime.tv_sec + ((double)tvStartTime.tv_usec / 1000000);
timeStop = (double)tvStopTime.tv_sec + ((double)tvStopTime.tv_usec / 1000000);
timeCalc = timeStop - timeStart;
if (QuietMode != 1)
fprintf(stderr, "\n Wall Clock: %f seconds\n", timeCalc);
return errLevel;
}
|
/*******************************************************************************
* Copyright 2003-2012 LASMEA UMR 6602 CNRS/U.B.P
* Copyright 2011-2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
*
* Distributed under the Boost Software License, Version 1.0.
* See accompanying file LICENSE.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt
******************************************************************************/
#ifndef NT2_TOOLBOX_INTEGRATION_OUTPUT_HPP_INCLUDED
#define NT2_TOOLBOX_INTEGRATION_OUTPUT_HPP_INCLUDED
#include <cstddef>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
namespace nt2 { namespace integration
{
template<typename T, typename R> struct output
{
T integrals;
R errors;
std::size_t eval_count;
bool successful;
};
} }
BOOST_FUSION_ADAPT_TPL_STRUCT
(
(T)(R),
(nt2::integration::output)(T)(R),
(T , integrals)
(R , errors)
(std::size_t, eval_count)
(bool , successful)
);
#endif
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/ash/user_accounts_delegate_chromeos.h"
#include <algorithm>
#include <iterator>
#include "base/logging.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/ui/inline_login_dialog.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "components/signin/core/browser/mutable_profile_oauth2_token_service.h"
#include "components/signin/core/browser/profile_oauth2_token_service.h"
#include "components/signin/core/browser/signin_manager.h"
#include "components/user_manager/user.h"
#include "google_apis/gaia/gaia_auth_util.h"
namespace chromeos {
UserAccountsDelegateChromeOS::UserAccountsDelegateChromeOS(
Profile* user_profile)
: user_profile_(user_profile) {
ProfileOAuth2TokenServiceFactory::GetForProfile(user_profile_)
->AddObserver(this);
}
UserAccountsDelegateChromeOS::~UserAccountsDelegateChromeOS() {
ProfileOAuth2TokenServiceFactory::GetForProfile(user_profile_)
->RemoveObserver(this);
}
std::string UserAccountsDelegateChromeOS::GetPrimaryAccountId() {
return SigninManagerFactory::GetForProfile(user_profile_)
->GetAuthenticatedAccountId();
}
std::vector<std::string>
UserAccountsDelegateChromeOS::GetSecondaryAccountIds() {
ProfileOAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(user_profile_);
std::vector<std::string> accounts = token_service->GetAccounts();
// Filter primary account.
std::vector<std::string>::iterator it =
std::remove(accounts.begin(), accounts.end(), GetPrimaryAccountId());
LOG_IF(WARNING, std::distance(it, accounts.end()) != 1)
<< "Found " << std::distance(it, accounts.end())
<< " primary accounts in the account list.";
accounts.erase(it, accounts.end());
return accounts;
}
std::string UserAccountsDelegateChromeOS::GetAccountDisplayName(
const std::string& account_id) {
user_manager::User* user =
ProfileHelper::Get()->GetUserByProfile(user_profile_);
if (gaia::AreEmailsSame(user->email(), account_id) &&
!user->display_email().empty())
return user->display_email();
return account_id;
}
void UserAccountsDelegateChromeOS::DeleteAccount(
const std::string& account_id) {
MutableProfileOAuth2TokenService* oauth2_token_service =
ProfileOAuth2TokenServiceFactory::GetPlatformSpecificForProfile(
user_profile_);
oauth2_token_service->RevokeCredentials(account_id);
}
void UserAccountsDelegateChromeOS::LaunchAddAccountDialog() {
ui::InlineLoginDialog::Show(user_profile_);
}
void UserAccountsDelegateChromeOS::OnRefreshTokenAvailable(
const std::string& account_id) {
NotifyAccountListChanged();
}
void UserAccountsDelegateChromeOS::OnRefreshTokenRevoked(
const std::string& account_id) {
NotifyAccountListChanged();
}
} // namespace chromeos
|
// the rules were based off of this link https://en.wikipedia.org/wiki/Uno_(card_game) all house rules are planned to make it in the final version
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iterator>
#include <ctime>
//#include <bits/stdc++.h>
#include <sstream>
using namespace std;
class Card {
public:
char type;
char color;
Card(char t, char c) :
type(t),
color(c)
{}
char getType() {
return type;
}
char getColor() {
return color;
}
char getBoth() {
return type, color;
}
void changeColor(char c) {
color = c;
}
};
class Player {
public:
Player(vector<Card> c) :
cards(c)
{}
vector<Card> getCards() {
return cards;
}
void dealCard(int index) {
cards.erase(cards.begin() + index);
}
void drawCard(Card c) {
cards.push_back(c);
}
vector<Card> cards;
};
vector<Card> deck{Card('0', 'R'), Card('1', 'R'), Card('2', 'R'), Card('3', 'R'), Card('4', 'R'), Card('5', 'R'), Card('6', 'R'), Card('7', 'R'), Card('8', 'R'), Card('9', 'R'), Card('/', 'R'), Card('%', 'R'), Card('&', 'R'), Card('0', 'Y'), Card('1', 'Y'), Card('2', 'Y'), Card('3', 'Y'), Card('4', 'Y'), Card('5', 'Y'), Card('6', 'Y'), Card('7', 'Y'), Card('8', 'Y'), Card('9', 'Y'), Card('/', 'Y'), Card('%', 'Y'), Card('&', 'Y'), Card('0', 'G'), Card('1', 'G'), Card('2', 'G'), Card('3', 'G'), Card('4', 'G'), Card('5', 'G'), Card('6', 'G'), Card('7', 'G'), Card('8', 'G'), Card('9', 'G'), Card('/', 'G'), Card('%', 'G'), Card('&', 'G'), Card('0', 'B'), Card('1', 'B'), Card('2', 'B'), Card('3', 'B'), Card('4', 'B'), Card('5', 'B'), Card('6', 'B'), Card('7', 'B'), Card('8', 'B'), Card('9', 'B'), Card('/', 'B'), Card('%', 'B'), Card('&', 'B'), Card('1', 'R'), Card('2', 'R'), Card('3', 'R'), Card('4', 'R'), Card('5', 'R'), Card('6', 'R'), Card('7', 'R'), Card('8', 'R'), Card('9', 'R'), Card('/', 'R'), Card('%', 'R'), Card('&', 'R'), Card('1', 'Y'), Card('2', 'Y'), Card('3', 'Y'), Card('4', 'Y'), Card('5', 'Y'), Card('6', 'Y'), Card('7', 'Y'), Card('8', 'Y'), Card('9', 'Y'), Card('/', 'Y'), Card('%', 'Y'), Card('&', 'Y'), Card('1', 'G'), Card('2', 'G'), Card('3', 'G'), Card('4', 'G'), Card('5', 'G'), Card('6', 'G'), Card('7', 'G'), Card('8', 'G'), Card('9', 'G'), Card('/', 'G'), Card('%', 'G'), Card('&', 'G'), Card('1', 'B'), Card('2', 'B'), Card('3', 'B'), Card('4', 'B'), Card('5', 'B'), Card('6', 'B'), Card('7', 'B'), Card('8', 'B'), Card('9', 'B'), Card('/', 'B'), Card('%', 'B'), Card('&', 'B'), Card('*', 'N'), Card('*', 'N'), Card('*', 'N'), Card('*', 'N'), Card('@', 'N'), Card('@', 'N'), Card('@', 'N'), Card('@', 'N')};
vector<Card> centerPile;
vector<Player> players;
bool playerHasWon = false;
bool valid;
bool playersTurn = true;
bool isReversed =false;
int turns = 0;
int cardsToDraw = 0;
string line;
string event;
int main() {
srand (time(NULL));
random_shuffle(deck.begin(), deck.end());
vector<Card> hand;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 7; j++) {
hand.push_back(deck.back());
deck.pop_back();
}
players.push_back(Player(hand));
hand.clear();
}
centerPile.push_back(deck.back());
deck.pop_back();
if (centerPile.at(0).getColor() == 'N') {
int r = rand() % 3;
if (r == 0)
centerPile.at(0).changeColor('Y');
else if (r == 1)
centerPile.at(0).changeColor('G');
else if (r == 2)
centerPile.at(0).changeColor('B');
else if (r == 3)
centerPile.at(0).changeColor('R');
}
string event;
string choice;
vector<string> tokens;
tokens.clear();
do {
playersTurn = true;
if (event == "+4") {
cardsToDraw += 4;
playersTurn = false;
}
else if (event == "+2") {
cardsToDraw += 2;
playersTurn = false;
}
else if (event == "cancel") {
playersTurn = false;
}
tokens.clear();
int jumpInCounter = players.size();
int tickFoward = 0;
while ((event == "none" || event =="cancel") && jumpInCounter > 0) {
jumpInCounter = players.size();
for (int i = turns; i < turns + players.size();i++) {
int canJumpIn = NULL;
for (int j = 0; j < players.at(i % players.size()).getCards().size();j++) {
if (players.at(i % players.size()).getCards().at(j).getType() == centerPile.back().getType() &&
players.at(i % players.size()).getCards().at(j).getColor() == centerPile.back().getColor()) {
canJumpIn = j;
}
}
if (canJumpIn == NULL) {
canJumpIn = -1;
jumpInCounter--;
}
if (canJumpIn > -1) {
cout << "your cards: ";
for (Card c: players.at(i % players.size()).getCards())
cout << c.getType() << c.getColor() << ", ";
cout << endl;
cout << "cards in the center pile: ";
for (Card c: centerPile) {
cout << c.getType();
cout << c.getColor() << ", ";
}
cout << "player " << i % players.size() << " can jump in with a " << players.at(i % players.size()).getCards().at(canJumpIn).getType() << players.at(i % players.size()).getCards().at(canJumpIn).getColor() << " card \nwould you like to jump in?(yes): ";
getline(cin, choice);
stringstream check1(choice);
string intmd;
while(getline(check1, intmd, ' ')) {
tokens.push_back(intmd);
}
if (tokens.at(0) == "yes") {
cout << "the card will be played \n";
centerPile.push_back(players.at(i % players.size()).getCards().at(canJumpIn));
players.at(i % players.size()).dealCard(canJumpIn);
tickFoward = i;
}
else {
cout << "you chose to let the oppurtunity pass \n";
jumpInCounter--;
}
tokens.clear();
}
}
}
turns += tickFoward;
while (event == "+4" || event == "+2") {
tokens.clear();
int prev = NULL;
if (isReversed) {
prev = 1;
}
else {
prev = -1;
}
int playerHasCard = NULL;
for (int i = 0; i < players.at(turns % players.size()).getCards().size();i++)
if (players.at(turns % players.size()).getCards().at(i).getType() == centerPile.back().getType())
playerHasCard = i;
if (playerHasCard == NULL)
playerHasCard = -1;
bool prevPlayerCouldvePlayedAnotherCard = NULL;
cout << "player " << (turns + prev) % players.size() << endl;
for (Card c:players.at((turns + prev) % players.size()).getCards())
if(c.getColor() == centerPile[centerPile.size() - 1].getColor() ||
c.getType() == centerPile[centerPile.size() - 1].getType() ||
c.getType() == '*')
prevPlayerCouldvePlayedAnotherCard = true;
if (prevPlayerCouldvePlayedAnotherCard == NULL)
prevPlayerCouldvePlayedAnotherCard = false;
cout << "your cards: ";
for (Card c: players.at(turns % players.size()).getCards())
cout << c.getType() << c.getColor() << ", ";
cout << endl;
cout << "cards in the center pile: ";
for (Card c: centerPile) {
cout << c.getType();
cout << c.getColor() << ", ";
}
cout << "player " << turns % players.size() << " will have to draw " << cardsToDraw << " cards \nwould you like to challenge this move?(yes) or would you like to deal your +4 card?(deal): ";
getline(cin, choice);
stringstream check1(choice);
string intmd;
while(getline(check1, intmd, ' ')) {
tokens.push_back(intmd);
}
if (tokens.at(0) == "yes" && event == "+4" && prevPlayerCouldvePlayedAnotherCard) {
cout << "your challenge was correct, previous player must now draw your cards to draw +2, and it is your turn. But, the card in the center does not get withdrawn\n";
playersTurn = false;
event = "none";
turns -= prev;
cardsToDraw += 2;
}
else if (tokens.at(0) == "yes" && event == "+4" && !prevPlayerCouldvePlayedAnotherCard) {
cout << "your challenge was incorrect, you must now draw your cards to draw +2, and it is not your turn\n";
cardsToDraw += 2;
event = "none";
}
else if (tokens.at(0) == "yes" && event != "+4") {
cout << "you can only do that to +4 cards, continuing...\n";
event = "none";
}
else if (tokens.at(0) == "deal" && playerHasCard > -1) {
cout << "you will deal the matching card you have\n";
centerPile.push_back(players.at(turns % players.size()).getCards().at(playerHasCard));
players.at(turns % players.size()).dealCard(playerHasCard);
if (event == "+4")
cardsToDraw += 4;
else if (event == "+2")
cardsToDraw += 2;
turns -= prev;
}
else if (tokens.at(0) == "deal" && playerHasCard == -1) {
cout << "you have no matching cards in your deck, continuing...\n";
event = "none";
}
else {
cout << "you have chosen to accept the move and do nothing of note\n";
event = "none";
}
}
tokens.clear();
for (int i = 0; i < cardsToDraw;i++) {
players.at(turns % players.size()).drawCard(deck.back());
deck.pop_back();
}
cout << "player " << turns % players.size() << " has picked up " << cardsToDraw << " cards \n";
cardsToDraw = 0;
event = "none";
choice = "";
valid = false;
while (!valid && playersTurn) {
cout << "player " << turns % players.size() << " turn: ";
getline(cin, choice);
vector<string> tokens;
stringstream check1(choice);
string intmd;
while(getline(check1, intmd, ' ')) {
tokens.push_back(intmd);
}
if (tokens.at(0) == "table") {
cout << "your cards: ";
for (Card c: players.at(turns % players.size()).getCards())
cout << c.getType() << c.getColor() << ", ";
cout << endl;
for (int i = 0; i < players.size();i++) {
cout << "player " << (i + 1) << " has " << players.at(i).getCards().size() << " cards \n";
}
cout << "cards in the center pile: ";
for (Card c: centerPile) {
cout << c.getType();
cout << c.getColor() << ", ";
}
cout << endl;
cout << "the deck has " << deck.size() << " cards in it \n";
}
else if (tokens.at(0) == "deal") {
try {
int toke = stoi(tokens.at(1));
if (players.at(turns % players.size()).getCards().at(toke).getType() == centerPile.back().getType() ||
players.at(turns % players.size()).getCards().at(toke).getColor() == centerPile.back().getColor() ||
players.at(turns % players.size()).getCards().at(toke).getColor() == 'N') {
valid = true;
switch (int(players.at(turns % players.size()).getCards().at(toke).getType())) {
case '/':
event = "cancel";
break;
case '%':
event = "reverse";
break;
case '&':
event = "+2";
break;
case '*':
players.at(turns % players.size()).cards.at(toke).changeColor(tokens.at(2)[0]);
break;
case '@':
players.at(turns % players.size()).cards.at(toke).changeColor(tokens.at(2)[0]);
event = "+4";
}
centerPile.push_back(players.at(turns % players.size()).getCards().at(toke));
players.at(turns % players.size()).dealCard(toke);
}
else {
valid = false;
}
}
catch (...) {
cout << "incorrect token(s) \n";
valid = false;
}
}
else if (tokens.at(0) == "draw") {
cout << deck.back().getType() << deck.back().getColor() << endl;
players.at(turns % players.size()).drawCard(deck.back());
deck.pop_back();
valid = false;
}
else {
cout << "try again \n";
valid = false;
}
if (players.at(turns % players.size()).getCards().size() == 0) {
playerHasWon = true;
}
}
if (deck.size() == 0) {
deck = centerPile;
random_shuffle(deck.begin(), deck.end());
centerPile.clear();
}
if (event == "reverse") {
if (players.size() == 2) {
event = "cancel";
}
else if (isReversed) {
isReversed = false;
}
else if (!isReversed) {
isReversed = true;
}
}
if (playerHasWon) {}
else if (isReversed) {
turns--;
}
else {
turns++;
}
} while (!playerHasWon);
cout << "player " << turns % players.size() << " Has won the game\n";
return 0;
}
|
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string input1;
getline(cin, input1);
int size = stoi(input1);
string input2;
getline(cin, input2);
stringstream s(input2);
string buffer;
unordered_set<int> us;
while (getline(s, buffer, ' ')) {
us.insert(stoi(buffer));
}
for (int i=1; i <= size; i++) {
if (us.find(i) == us.end()) {
// found non existent number
cout << i << '\n';
return 0;
}
}
return 1;
}
|
// (c) Copyright Juergen Hunold 2008
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE.txt or copy at
// https://www.bfgroup.xyz/b2/LICENSE.txt)
#define BOOST_TEST_MODULE QtCore
#include <QtCore>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE (defines)
{
BOOST_CHECK_EQUAL(BOOST_IS_DEFINED(QT_CORE_LIB), true);
}
BOOST_AUTO_TEST_CASE( qstring_test)
{
QString dummy;
BOOST_CHECK_EQUAL(dummy.isEmpty(), true);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.