text
stringlengths 5
1.04M
|
|---|
/**********************************************************************
* File: fpchop.cpp (Formerly fp_chop.c)
* Description: Code to chop fixed pitch text into character cells.
* Author: Ray Smith
*
* (C) Copyright 1993, Hewlett-Packard Ltd.
** 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 "blobbox.h"
#include "statistc.h"
#include "drawtord.h"
#include "tovars.h"
#include "topitch.h"
#include "fpchop.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#define EXTERN
EXTERN INT_VAR (textord_fp_chop_error, 2,
"Max allowed bending of chop cells");
EXTERN double_VAR (textord_fp_chop_snap, 0.5,
"Max distance of chop pt from vertex");
ELISTIZE(C_OUTLINE_FRAG)
//#undef ASSERT_HOST
//#define ASSERT_HOST(x) if (!(x)) AfxMessageBox(#x);
/**********************************************************************
* fixed_pitch_words
*
* Make a ROW from a fixed pitch TO_ROW.
**********************************************************************/
ROW *fixed_pitch_words( //find lines
TO_ROW *row, //row to do
FCOORD rotation //for drawing
) {
bool bol; //start of line
uint8_t blanks; //in front of word
uint8_t new_blanks; //blanks in empty cell
int16_t chop_coord; //chop boundary
int16_t prev_chop_coord; //start of cell
int16_t rep_left; //left edge of rep word
ROW *real_row; //output row
C_OUTLINE_LIST left_coutlines;
C_OUTLINE_LIST right_coutlines;
C_BLOB_LIST cblobs;
C_BLOB_IT cblob_it = &cblobs;
WERD_LIST words;
WERD_IT word_it = &words; //new words
//repeated blobs
WERD_IT rep_it = &row->rep_words;
WERD *word; //new word
int32_t xstarts[2]; //row ends
int32_t prev_x; //end of prev blob
//iterator
BLOBNBOX_IT box_it = row->blob_list ();
//boundaries
ICOORDELT_IT cell_it = &row->char_cells;
#ifndef GRAPHICS_DISABLED
if (textord_show_page_cuts && to_win != nullptr) {
plot_row_cells (to_win, ScrollView::RED, row, 0, &row->char_cells);
}
#endif
prev_x = -INT16_MAX;
bol = true;
blanks = 0;
if (rep_it.empty ())
rep_left = INT16_MAX;
else
rep_left = rep_it.data ()->bounding_box ().left ();
if (box_it.empty ())
return nullptr; //empty row
xstarts[0] = box_it.data ()->bounding_box ().left ();
if (rep_left < xstarts[0]) {
xstarts[0] = rep_left;
}
if (cell_it.empty () || row->char_cells.singleton ()) {
tprintf ("Row without enough char cells!\n");
tprintf ("Leftmost blob is at (%d,%d)\n",
box_it.data ()->bounding_box ().left (),
box_it.data ()->bounding_box ().bottom ());
return nullptr;
}
ASSERT_HOST (!cell_it.empty () && !row->char_cells.singleton ());
prev_chop_coord = cell_it.data ()->x ();
word = nullptr;
while (rep_left < cell_it.data ()->x ()) {
word = add_repeated_word (&rep_it, rep_left, prev_chop_coord,
blanks, row->fixed_pitch, &word_it);
}
cell_it.mark_cycle_pt ();
if (prev_chop_coord >= cell_it.data ()->x ())
cell_it.forward ();
for (; !cell_it.cycled_list (); cell_it.forward ()) {
chop_coord = cell_it.data ()->x ();
while (!box_it.empty ()
&& box_it.data ()->bounding_box ().left () <= chop_coord) {
if (box_it.data ()->bounding_box ().right () > prev_x)
prev_x = box_it.data ()->bounding_box ().right ();
split_to_blob (box_it.extract (), chop_coord,
textord_fp_chop_error + 0.5f,
&left_coutlines,
&right_coutlines);
box_it.forward ();
while (!box_it.empty() && box_it.data()->cblob() == nullptr) {
delete box_it.extract();
box_it.forward();
}
}
if (!right_coutlines.empty() && left_coutlines.empty())
split_to_blob (nullptr, chop_coord,
textord_fp_chop_error + 0.5f,
&left_coutlines,
&right_coutlines);
if (!left_coutlines.empty()) {
cblob_it.add_after_then_move(new C_BLOB(&left_coutlines));
} else {
if (rep_left < chop_coord) {
if (rep_left > prev_chop_coord)
new_blanks = (uint8_t) floor ((rep_left - prev_chop_coord)
/ row->fixed_pitch + 0.5);
else
new_blanks = 0;
}
else {
if (chop_coord > prev_chop_coord)
new_blanks = (uint8_t) floor ((chop_coord - prev_chop_coord)
/ row->fixed_pitch + 0.5);
else
new_blanks = 0;
}
if (!cblob_it.empty()) {
if (blanks < 1 && word != nullptr && !word->flag (W_REP_CHAR))
blanks = 1;
word = new WERD (&cblobs, blanks, nullptr);
cblob_it.set_to_list (&cblobs);
word->set_flag (W_DONT_CHOP, true);
word_it.add_after_then_move (word);
if (bol) {
word->set_flag (W_BOL, true);
bol = false;
}
blanks = new_blanks;
}
else
blanks += new_blanks;
while (rep_left < chop_coord) {
word = add_repeated_word (&rep_it, rep_left, prev_chop_coord,
blanks, row->fixed_pitch, &word_it);
}
}
if (prev_chop_coord < chop_coord)
prev_chop_coord = chop_coord;
}
if (!cblob_it.empty()) {
word = new WERD(&cblobs, blanks, nullptr);
word->set_flag (W_DONT_CHOP, true);
word_it.add_after_then_move (word);
if (bol)
word->set_flag (W_BOL, true);
}
ASSERT_HOST (word != nullptr);
while (!rep_it.empty ()) {
add_repeated_word (&rep_it, rep_left, prev_chop_coord,
blanks, row->fixed_pitch, &word_it);
}
//at end of line
word_it.data ()->set_flag (W_EOL, true);
if (prev_chop_coord > prev_x)
prev_x = prev_chop_coord;
xstarts[1] = prev_x + 1;
real_row = new ROW (row, (int16_t) row->kern_size, (int16_t) row->space_size);
word_it.set_to_list (real_row->word_list ());
//put words in row
word_it.add_list_after (&words);
real_row->recalc_bounding_box ();
return real_row;
}
/**********************************************************************
* add_repeated_word
*
* Add repeated word into the row at the given point.
**********************************************************************/
WERD *add_repeated_word( //move repeated word
WERD_IT *rep_it, //repeated words
int16_t &rep_left, //left edge of word
int16_t &prev_chop_coord, //previous word end
uint8_t &blanks, //no of blanks
float pitch, //char cell size
WERD_IT *word_it //list of words
) {
WERD *word; //word to move
int16_t new_blanks; //extra blanks
if (rep_left > prev_chop_coord) {
new_blanks = (uint8_t) floor ((rep_left - prev_chop_coord) / pitch + 0.5);
blanks += new_blanks;
}
word = rep_it->extract ();
prev_chop_coord = word->bounding_box ().right ();
word_it->add_after_then_move (word);
word->set_blanks (blanks);
rep_it->forward ();
if (rep_it->empty ())
rep_left = INT16_MAX;
else
rep_left = rep_it->data ()->bounding_box ().left ();
blanks = 0;
return word;
}
/**********************************************************************
* split_to_blob
*
* Split a BLOBNBOX across a vertical chop line and put the pieces
* into a left outline list and a right outline list.
**********************************************************************/
void split_to_blob( //split the blob
BLOBNBOX *blob, //blob to split
int16_t chop_coord, //place to chop
float pitch_error, //allowed deviation
C_OUTLINE_LIST *left_coutlines, //for cblobs
C_OUTLINE_LIST *right_coutlines) {
C_BLOB *real_cblob; //cblob to chop
if (blob != nullptr) {
real_cblob = blob->cblob();
} else {
real_cblob = nullptr;
}
if (!right_coutlines->empty() || real_cblob != nullptr)
fixed_chop_cblob(real_cblob,
chop_coord,
pitch_error,
left_coutlines,
right_coutlines);
delete blob;
}
/**********************************************************************
* fixed_chop_cblob
*
* Chop the given cblob (if any) and the existing right outlines to
* produce a list of outlines left of the chop point and more to the right.
**********************************************************************/
void fixed_chop_cblob( //split the blob
C_BLOB *blob, //blob to split
int16_t chop_coord, //place to chop
float pitch_error, //allowed deviation
C_OUTLINE_LIST *left_outlines, //left half of chop
C_OUTLINE_LIST *right_outlines //right half of chop
) {
C_OUTLINE *old_right; //already there
C_OUTLINE_LIST new_outlines; //new right ones
//output iterator
C_OUTLINE_IT left_it = left_outlines;
//in/out iterator
C_OUTLINE_IT right_it = right_outlines;
C_OUTLINE_IT new_it = &new_outlines;
C_OUTLINE_IT blob_it; //outlines in blob
if (!right_it.empty ()) {
while (!right_it.empty ()) {
old_right = right_it.extract ();
right_it.forward ();
fixed_split_coutline(old_right,
chop_coord,
pitch_error,
&left_it,
&new_it);
}
right_it.add_list_before (&new_outlines);
}
if (blob != nullptr) {
blob_it.set_to_list (blob->out_list ());
for (blob_it.mark_cycle_pt (); !blob_it.cycled_list ();
blob_it.forward ())
fixed_split_coutline (blob_it.extract (), chop_coord, pitch_error,
&left_it, &right_it);
delete blob;
}
}
/**********************************************************************
* fixed_split_outline
*
* Chop the given outline (if necessary) placing the fragments which
* fall either side of the chop line into the appropriate list.
**********************************************************************/
void fixed_split_coutline( //chop the outline
C_OUTLINE *srcline, //source outline
int16_t chop_coord, //place to chop
float pitch_error, //allowed deviation
C_OUTLINE_IT *left_it, //left half of chop
C_OUTLINE_IT *right_it //right half of chop
) {
C_OUTLINE *child; //child outline
TBOX srcbox; //box of outline
C_OUTLINE_LIST left_ch; //left children
C_OUTLINE_LIST right_ch; //right children
C_OUTLINE_FRAG_LIST left_frags;//chopped fragments
C_OUTLINE_FRAG_LIST right_frags;;
C_OUTLINE_IT left_ch_it = &left_ch;
//for whole children
C_OUTLINE_IT right_ch_it = &right_ch;
//for holes
C_OUTLINE_IT child_it = srcline->child ();
srcbox = srcline->bounding_box();
if (srcbox.left() + srcbox.right() <= chop_coord * 2
&& srcbox.right() < chop_coord + pitch_error) {
// Whole outline is in the left side or not far over the chop_coord,
// so put the whole thing on the left.
left_it->add_after_then_move(srcline);
} else if (srcbox.left() + srcbox.right() > chop_coord * 2
&& srcbox.left () > chop_coord - pitch_error) {
// Whole outline is in the right side or not far over the chop_coord,
// so put the whole thing on the right.
right_it->add_before_stay_put(srcline);
} else {
// Needs real chopping.
if (fixed_chop_coutline(srcline, chop_coord, pitch_error,
&left_frags, &right_frags)) {
for (child_it.mark_cycle_pt(); !child_it.cycled_list();
child_it.forward()) {
child = child_it.extract();
srcbox = child->bounding_box();
if (srcbox.right() < chop_coord) {
// Whole child is on the left.
left_ch_it.add_after_then_move(child);
} else if (srcbox.left() > chop_coord) {
// Whole child is on the right.
right_ch_it.add_after_then_move (child);
} else {
// No pitch_error is allowed when chopping children to prevent
// impossible outlines from being created.
if (fixed_chop_coutline(child, chop_coord, 0.0f,
&left_frags, &right_frags)) {
delete child;
} else {
if (srcbox.left() + srcbox.right() <= chop_coord * 2)
left_ch_it.add_after_then_move(child);
else
right_ch_it.add_after_then_move(child);
}
}
}
close_chopped_cfragments(&left_frags, &left_ch, pitch_error, left_it);
close_chopped_cfragments(&right_frags, &right_ch, pitch_error, right_it);
ASSERT_HOST(left_ch.empty() && right_ch.empty());
// No children left.
delete srcline; // Smashed up.
} else {
// Chop failed. Just use middle coord.
if (srcbox.left() + srcbox.right() <= chop_coord * 2)
left_it->add_after_then_move(srcline); // Stick whole in left.
else
right_it->add_before_stay_put(srcline);
}
}
}
/**********************************************************************
* fixed_chop_coutline
*
* Chop the given coutline (if necessary) placing the fragments which
* fall either side of the chop line into the appropriate list.
* If the coutline lies too heavily to one side to chop, false is returned.
**********************************************************************/
bool fixed_chop_coutline( //chop the outline
C_OUTLINE* srcline, //source outline
int16_t chop_coord, //place to chop
float pitch_error, //allowed deviation
C_OUTLINE_FRAG_LIST* left_frags, //left half of chop
C_OUTLINE_FRAG_LIST* right_frags //right half of chop
) {
bool first_frag; //fragment
int16_t left_edge; //of outline
int16_t startindex; //in first fragment
int32_t length; //of outline
int16_t stepindex; //into outline
int16_t head_index; //start of fragment
ICOORD head_pos; //start of fragment
int16_t tail_index; //end of fragment
ICOORD tail_pos; //end of fragment
ICOORD pos; //current point
int16_t first_index = 0; //first tail
ICOORD first_pos; //first tail
length = srcline->pathlength ();
pos = srcline->start_pos ();
left_edge = pos.x ();
tail_index = 0;
tail_pos = pos;
for (stepindex = 0; stepindex < length; stepindex++) {
if (pos.x () < left_edge) {
left_edge = pos.x ();
tail_index = stepindex;
tail_pos = pos;
}
pos += srcline->step (stepindex);
}
if (left_edge >= chop_coord - pitch_error)
return false; //not worth it
startindex = tail_index;
first_frag = true;
head_index = tail_index;
head_pos = tail_pos;
do {
do {
tail_pos += srcline->step (tail_index);
tail_index++;
if (tail_index == length)
tail_index = 0;
}
while (tail_pos.x () != chop_coord && tail_index != startindex);
if (tail_index == startindex) {
if (first_frag)
return false; //doesn't cross line
else
break;
}
ASSERT_HOST (head_index != tail_index);
if (!first_frag) {
save_chop_cfragment(head_index,
head_pos,
tail_index,
tail_pos,
srcline,
left_frags);
}
else {
first_index = tail_index;
first_pos = tail_pos;
first_frag = false;
}
while (srcline->step (tail_index).x () == 0) {
tail_pos += srcline->step (tail_index);
tail_index++;
if (tail_index == length)
tail_index = 0;
}
head_index = tail_index;
head_pos = tail_pos;
while (srcline->step (tail_index).x () > 0) {
do {
tail_pos += srcline->step (tail_index);
tail_index++;
if (tail_index == length)
tail_index = 0;
}
while (tail_pos.x () != chop_coord);
ASSERT_HOST (head_index != tail_index);
save_chop_cfragment(head_index,
head_pos,
tail_index,
tail_pos,
srcline,
right_frags);
while (srcline->step (tail_index).x () == 0) {
tail_pos += srcline->step (tail_index);
tail_index++;
if (tail_index == length)
tail_index = 0;
}
head_index = tail_index;
head_pos = tail_pos;
}
}
while (tail_index != startindex);
save_chop_cfragment(head_index,
head_pos,
first_index,
first_pos,
srcline,
left_frags);
return true; //did some chopping
}
/**********************************************************************
* save_chop_cfragment
*
* Store the given fragment in the given fragment list.
**********************************************************************/
void save_chop_cfragment( //chop the outline
int16_t head_index, //head of fragment
ICOORD head_pos, //head of fragment
int16_t tail_index, //tail of fragment
ICOORD tail_pos, //tail of fragment
C_OUTLINE *srcline, //source of edgesteps
C_OUTLINE_FRAG_LIST *frags //fragment list
) {
int16_t jump; //gap across end
int16_t stepcount; //total steps
C_OUTLINE_FRAG *head; //head of fragment
C_OUTLINE_FRAG *tail; //tail of fragment
int16_t tail_y; //ycoord of tail
ASSERT_HOST (tail_pos.x () == head_pos.x ());
ASSERT_HOST (tail_index != head_index);
stepcount = tail_index - head_index;
if (stepcount < 0)
stepcount += srcline->pathlength ();
jump = tail_pos.y () - head_pos.y ();
if (jump < 0)
jump = -jump;
if (jump == stepcount)
return; //its a nop
tail_y = tail_pos.y ();
head = new C_OUTLINE_FRAG (head_pos, tail_pos, srcline,
head_index, tail_index);
tail = new C_OUTLINE_FRAG (head, tail_y);
head->other_end = tail;
add_frag_to_list(head, frags);
add_frag_to_list(tail, frags);
}
/**********************************************************************
* C_OUTLINE_FRAG::C_OUTLINE_FRAG
*
* Constructors for C_OUTLINE_FRAG.
**********************************************************************/
C_OUTLINE_FRAG::C_OUTLINE_FRAG( //record fragment
ICOORD start_pt, //start coord
ICOORD end_pt, //end coord
C_OUTLINE *outline, //source of steps
int16_t start_index,
int16_t end_index) {
start = start_pt;
end = end_pt;
ycoord = start_pt.y ();
stepcount = end_index - start_index;
if (stepcount < 0)
stepcount += outline->pathlength ();
ASSERT_HOST (stepcount > 0);
steps = new DIR128[stepcount];
if (end_index > start_index) {
for (int i = start_index; i < end_index; ++i)
steps[i - start_index] = outline->step_dir(i);
}
else {
int len = outline->pathlength();
int i = start_index;
for (; i < len; ++i)
steps[i - start_index] = outline->step_dir(i);
if (end_index > 0)
for (; i < end_index + len; ++i)
steps[i - start_index] = outline->step_dir(i - len);
}
other_end = nullptr;
delete close();
}
C_OUTLINE_FRAG::C_OUTLINE_FRAG( //record fragment
C_OUTLINE_FRAG *head, //other end
int16_t tail_y) {
ycoord = tail_y;
other_end = head;
start = head->start;
end = head->end;
steps = nullptr;
stepcount = 0;
}
/**********************************************************************
* add_frag_to_list
*
* Insert the fragment in the list at the appropriate place to keep
* them in ascending ycoord order.
**********************************************************************/
void add_frag_to_list( //ordered add
C_OUTLINE_FRAG *frag, //fragment to add
C_OUTLINE_FRAG_LIST *frags //fragment list
) {
//output list
C_OUTLINE_FRAG_IT frag_it = frags;
if (!frags->empty ()) {
for (frag_it.mark_cycle_pt (); !frag_it.cycled_list ();
frag_it.forward ()) {
if (frag_it.data ()->ycoord > frag->ycoord
|| (frag_it.data ()->ycoord == frag->ycoord
&& frag->other_end->ycoord < frag->ycoord)) {
frag_it.add_before_then_move (frag);
return;
}
}
}
frag_it.add_to_end (frag);
}
/**********************************************************************
* close_chopped_cfragments
*
* Clear the given list of fragments joining them up into outlines.
* Each outline made soaks up any of the child outlines which it encloses.
**********************************************************************/
void close_chopped_cfragments( //chop the outline
C_OUTLINE_FRAG_LIST *frags, //list to clear
C_OUTLINE_LIST *children, //potential children
float pitch_error, //allowed shrinkage
C_OUTLINE_IT *dest_it //output list
) {
//iterator
C_OUTLINE_FRAG_IT frag_it = frags;
C_OUTLINE_FRAG *bottom_frag; //bottom of cut
C_OUTLINE_FRAG *top_frag; //top of cut
C_OUTLINE *outline; //new outline
C_OUTLINE *child; //current child
C_OUTLINE_IT child_it = children;
C_OUTLINE_IT olchild_it; //children of outline
while (!frag_it.empty()) {
frag_it.move_to_first();
// get bottom one
bottom_frag = frag_it.extract();
frag_it.forward();
top_frag = frag_it.data(); // look at next
if ((bottom_frag->steps == nullptr && top_frag->steps == nullptr)
|| (bottom_frag->steps != nullptr && top_frag->steps != nullptr)) {
if (frag_it.data_relative(1)->ycoord == top_frag->ycoord)
frag_it.forward();
}
top_frag = frag_it.extract();
if (top_frag->other_end != bottom_frag) {
outline = join_chopped_fragments(bottom_frag, top_frag);
ASSERT_HOST(outline == nullptr);
} else {
outline = join_chopped_fragments(bottom_frag, top_frag);
if (outline != nullptr) {
olchild_it.set_to_list(outline->child());
for (child_it.mark_cycle_pt(); !child_it.cycled_list();
child_it.forward()) {
child = child_it.data();
if (*child < *outline)
olchild_it.add_to_end(child_it.extract());
}
if (outline->bounding_box().width() > pitch_error)
dest_it->add_after_then_move(outline);
else
delete outline; // Make it disappear.
}
}
}
while (!child_it.empty ()) {
dest_it->add_after_then_move (child_it.extract ());
child_it.forward ();
}
}
/**********************************************************************
* join_chopped_fragments
*
* Join the two lists of POLYPTs such that neither OUTLINE_FRAG
* operand keeps responsibility for the fragment.
**********************************************************************/
C_OUTLINE *join_chopped_fragments( //join pieces
C_OUTLINE_FRAG *bottom, //bottom of cut
C_OUTLINE_FRAG *top //top of cut
) {
C_OUTLINE *outline; //closed loop
if (bottom->other_end == top) {
if (bottom->steps == nullptr)
outline = top->close (); //turn to outline
else
outline = bottom->close ();
delete top;
delete bottom;
return outline;
}
if (bottom->steps == nullptr) {
ASSERT_HOST (top->steps != nullptr);
join_segments (bottom->other_end, top);
}
else {
ASSERT_HOST (top->steps == nullptr);
join_segments (top->other_end, bottom);
}
top->other_end->other_end = bottom->other_end;
bottom->other_end->other_end = top->other_end;
delete bottom;
delete top;
return nullptr;
}
/**********************************************************************
* join_segments
*
* Join the two edgestep fragments such that the second comes after
* the first and the gap between them is closed.
**********************************************************************/
void join_segments( //join pieces
C_OUTLINE_FRAG *bottom, //bottom of cut
C_OUTLINE_FRAG *top //top of cut
) {
DIR128 *steps; //new steps
int32_t stepcount; //no of steps
int16_t fake_count; //fake steps
DIR128 fake_step; //step entry
ASSERT_HOST (bottom->end.x () == top->start.x ());
fake_count = top->start.y () - bottom->end.y ();
if (fake_count < 0) {
fake_count = -fake_count;
fake_step = 32;
}
else
fake_step = 96;
stepcount = bottom->stepcount + fake_count + top->stepcount;
steps = new DIR128[stepcount];
memmove (steps, bottom->steps, bottom->stepcount);
memset (steps + bottom->stepcount, fake_step.get_dir(), fake_count);
memmove (steps + bottom->stepcount + fake_count, top->steps,
top->stepcount);
delete [] bottom->steps;
bottom->steps = steps;
bottom->stepcount = stepcount;
bottom->end = top->end;
bottom->other_end->end = top->end;
}
/**********************************************************************
* C_OUTLINE_FRAG::close
*
* Join the ends of this fragment and turn it into an outline.
**********************************************************************/
C_OUTLINE *C_OUTLINE_FRAG::close() { //join pieces
DIR128 *new_steps; //new steps
int32_t new_stepcount; //no of steps
int16_t fake_count; //fake steps
DIR128 fake_step; //step entry
ASSERT_HOST (start.x () == end.x ());
fake_count = start.y () - end.y ();
if (fake_count < 0) {
fake_count = -fake_count;
fake_step = 32;
}
else
fake_step = 96;
new_stepcount = stepcount + fake_count;
if (new_stepcount > C_OUTLINE::kMaxOutlineLength)
return nullptr; // Can't join them
new_steps = new DIR128[new_stepcount];
memmove(new_steps, steps, stepcount);
memset (new_steps + stepcount, fake_step.get_dir(), fake_count);
auto* result = new C_OUTLINE (start, new_steps, new_stepcount);
delete [] new_steps;
return result;
}
/**********************************************************************
* C_OUTLINE_FRAG::operator=
*
* Copy this fragment.
**********************************************************************/
//join pieces
C_OUTLINE_FRAG & C_OUTLINE_FRAG::operator= (
const C_OUTLINE_FRAG & src //fragment to copy
) {
delete [] steps;
stepcount = src.stepcount;
steps = new DIR128[stepcount];
memmove (steps, src.steps, stepcount);
start = src.start;
end = src.end;
ycoord = src.ycoord;
return *this;
}
|
// Generated from /POI/java/org/apache/poi/hpsf/CodePageString.java
#include <org/apache/poi/hpsf/CodePageString.hpp>
#include <java/io/OutputStream.hpp>
#include <java/lang/Class.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/lang/StringBuilder.hpp>
#include <org/apache/poi/hpsf/Property.hpp>
#include <org/apache/poi/hpsf/TypedPropertyValue.hpp>
#include <org/apache/poi/util/CodePageUtil.hpp>
#include <org/apache/poi/util/LittleEndian.hpp>
#include <org/apache/poi/util/LittleEndianByteArrayInputStream.hpp>
#include <org/apache/poi/util/LittleEndianConsts.hpp>
#include <org/apache/poi/util/POILogFactory.hpp>
#include <org/apache/poi/util/POILogger.hpp>
#include <Array.hpp>
#include <ObjectArray.hpp>
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
poi::hpsf::CodePageString::CodePageString(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::hpsf::CodePageString::CodePageString()
: CodePageString(*static_cast< ::default_init_tag* >(0))
{
ctor();
}
poi::util::POILogger*& poi::hpsf::CodePageString::LOG()
{
clinit();
return LOG_;
}
poi::util::POILogger* poi::hpsf::CodePageString::LOG_;
void poi::hpsf::CodePageString::ctor()
{
super::ctor();
}
void poi::hpsf::CodePageString::read(::poi::util::LittleEndianByteArrayInputStream* lei)
{
auto offset = npc(lei)->getReadIndex();
auto size = npc(lei)->readInt();
_value = new ::int8_tArray(size);
if(size == 0) {
return;
}
npc(lei)->readFully(_value);
if((*_value)[size - int32_t(1)] != 0) {
auto msg = ::java::lang::StringBuilder().append(u"CodePageString started at offset #"_j)->append(offset)
->append(u" is not NULL-terminated"_j)->toString();
npc(LOG_)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(msg)}));
}
TypedPropertyValue::skipPadding(lei);
}
java::lang::String* poi::hpsf::CodePageString::getJavaValue(int32_t codepage) /* throws(UnsupportedEncodingException) */
{
auto cp = (codepage == -int32_t(1)) ? Property::DEFAULT_CODEPAGE : codepage;
auto result = ::poi::util::CodePageUtil::getStringFromCodePage(_value, cp);
auto const terminator = npc(result)->indexOf(static_cast< int32_t >(char16_t(0x0000)));
if(terminator == -int32_t(1)) {
auto msg = ::java::lang::StringBuilder().append(u"String terminator (\\0) for CodePageString property value not found."_j)->append(u"Continue without trimming and hope for the best."_j)->toString();
npc(LOG_)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(msg)}));
return result;
}
if(terminator != npc(result)->length() - int32_t(1)) {
auto msg = ::java::lang::StringBuilder().append(u"String terminator (\\0) for CodePageString property value occured before the end of string. "_j)->append(u"Trimming and hope for the best."_j)->toString();
npc(LOG_)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(msg)}));
}
return npc(result)->substring(0, terminator);
}
int32_t poi::hpsf::CodePageString::getSize()
{
return ::poi::util::LittleEndianConsts::INT_SIZE + npc(_value)->length;
}
void poi::hpsf::CodePageString::setJavaValue(::java::lang::String* string, int32_t codepage) /* throws(UnsupportedEncodingException) */
{
auto cp = (codepage == -int32_t(1)) ? Property::DEFAULT_CODEPAGE : codepage;
_value = ::poi::util::CodePageUtil::getBytesInCodePage(::java::lang::StringBuilder().append(string)->append(u"\0"_j)->toString(), cp);
}
int32_t poi::hpsf::CodePageString::write(::java::io::OutputStream* out) /* throws(IOException) */
{
::poi::util::LittleEndian::putUInt(npc(_value)->length, out);
npc(out)->write(_value);
return ::poi::util::LittleEndianConsts::INT_SIZE + npc(_value)->length;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::hpsf::CodePageString::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.hpsf.CodePageString", 34);
return c;
}
void poi::hpsf::CodePageString::clinit()
{
super::clinit();
static bool in_cl_init = false;
struct clinit_ {
clinit_() {
in_cl_init = true;
LOG_ = ::poi::util::POILogFactory::getLogger(static_cast< ::java::lang::Class* >(CodePageString::class_()));
}
};
if(!in_cl_init) {
static clinit_ clinit_instance;
}
}
java::lang::Class* poi::hpsf::CodePageString::getClass0()
{
return class_();
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Keyco developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "primitives/transaction.h"
#include "core_io.h"
#include "init.h"
#include "keystore.h"
#include "main.h"
#include "net.h"
#include "rpcserver.h"
#include "script/script.h"
#include "script/sign.h"
#include "script/standard.h"
#include "uint256.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else {
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"If verbose is non-zero, returns an Object with information about 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n"
"\nResult (if verbose is not set or set to 0):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"keycoaddress\" (string) keyco address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
);
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
string strHex = EncodeHexTx(tx);
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
#ifdef ENABLE_WALLET
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent ( minconf maxconf [\"address\",...] )\n"
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. \"addresses\" (string) A json array of keyco addresses to filter\n"
" [\n"
" \"address\" (string) keyco address\n"
" ,...\n"
" ]\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the keyco address\n"
" \"account\" : \"account\", (string) The associated account, or \"\" for the default account\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction amount in btc\n"
" \"confirmations\" : n (numeric) The number of confirmations\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n"
+ HelpExampleCli("listunspent", "")
+ HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
+ HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
);
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2) {
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs) {
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Keyco address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs) {
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size()) {
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
CAmount nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash()) {
CTxDestination address;
if (ExtractDestination(pk, address)) {
const CScriptID& hash = boost::get<CScriptID>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
entry.push_back(Pair("spendable", out.fSpendable));
results.push_back(entry);
}
return results;
}
#endif
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...}\n"
"\nCreate a transaction spending the given inputs and sending to the given addresses.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n"
" {\n"
" \"address\": x.xxx (numeric, required) The key is the keyco address, the value is the btc amount\n"
" ,...\n"
" }\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
);
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CMutableTransaction rawTx;
BOOST_FOREACH(const Value& input, inputs) {
const Object& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(txid, nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo) {
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Keyco address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
return EncodeHexTx(rawTx);
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hex\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) keyco address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decoderawtransaction", "\"hexstring\"")
+ HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
);
RPCTypeCheck(params, list_of(str_type));
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value decodescript(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) keyco address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decodescript", "\"hexstring\"")
+ HelpExampleRpc("decodescript", "\"hexstring\"")
);
RPCTypeCheck(params, list_of(str_type));
Object r;
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
return r;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\": \"value\", (string) The raw transaction with signature(s) (hex-encoded string)\n"
" \"complete\": n (numeric) if transaction has a complete set of signature (0 if not)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"")
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (const std::exception &) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type) {
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys) {
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type) {
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs) {
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
CCoinsModifier coins = view.ModifyCoins(txid);
if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
if ((unsigned int)nOut >= coins->vout.size())
coins->vout.resize(nOut+1);
coins->vout[nOut].scriptPubKey = scriptPubKey;
coins->vout[nOut].nValue = 0; // we don't know the actual output value
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type));
Value v = find_value(prevOut, "redeemScript");
if (!(v == Value::null)) {
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type) {
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
fComplete = false;
continue;
}
const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CMutableTransaction& txv, txVariants) {
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i)))
fComplete = false;
}
Object result;
result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n"
+ HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
RPCTypeCheck(params, list_of(str_type)(bool_type));
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
CCoinsViewCache &view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
CValidationState state;
if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) {
if(state.IsInvalid())
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
else
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
}
RelayTransaction(tx);
return hashTx.GetHex();
}
|
/***************************************************************************
*
* Copyright (c) 2003 - 2011 Petri Purho
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
***************************************************************************/
#include "../point_inside.h"
#include "../../debug.h"
#ifdef CENG_TESTER_ENABLED
namespace ceng {
namespace math {
namespace test {
int IsPointInsidePolygonTest()
{
typedef ceng::math::CVector2< float > Vec2;
{
std::vector< Vec2 > vertices( 4 );
vertices[ 0 ] = Vec2( -2.0f, -2.0f );
vertices[ 1 ] = Vec2( 2.0f, -2.0f );
vertices[ 2 ] = Vec2( 2.0f, 2.0f );
vertices[ 3 ] = Vec2( -2.0f, 2.0f );
Vec2 check_me = Vec2( 0.0f, 0.0f );
test_assert( IsPointInsidePolygon( check_me, vertices ) == true );
check_me = Vec2( -1.999f, 0.0f );
test_assert( IsPointInsidePolygon( check_me, vertices ) == true );
check_me = Vec2( 1.999f, 0.0f );
test_assert( IsPointInsidePolygon( check_me, vertices ) == true );
check_me = Vec2( 1.999f, -1.999f );
test_assert( IsPointInsidePolygon( check_me, vertices ) == true );
check_me = Vec2( 1.999f, -2.001f );
test_assert( IsPointInsidePolygon( check_me, vertices ) == false );
}
{
std::vector< Vec2 > vertices( 5 );
vertices[ 0 ] = Vec2( -2.0f, -2.0f );
vertices[ 1 ] = Vec2( 0.0f, 0.0f );
vertices[ 2 ] = Vec2( 2.0f, -2.0f );
vertices[ 3 ] = Vec2( 2.0f, 2.0f );
vertices[ 4 ] = Vec2( -2.0f, 2.0f );
Vec2 check_me = Vec2( 0.0f, 0.01f );
test_assert( IsPointInsidePolygon( check_me, vertices ) == true );
check_me = Vec2( 0.0f, -0.01f );
test_assert( IsPointInsidePolygon( check_me, vertices ) == false );
check_me = Vec2( -1.9999f, -1.999f );
test_assert( IsPointInsidePolygon( check_me, vertices ) == true );
check_me = Vec2( -1.9999f, -2.0001f );
test_assert( IsPointInsidePolygon( check_me, vertices ) == false );
}
return 0;
}
TEST_REGISTER( IsPointInsidePolygonTest );
} // end of namespace test
} // end of namespace math
} // end of namespace ceng
#endif
|
// Copyright (c) 2011-2017 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 <qt/addresstablemodel.h>
#include <qt/guiutil.h>
#include <qt/walletmodel.h>
#include <base58.h>
#include <wallet/wallet.h>
#include <QFont>
#include <QDebug>
const QString AddressTableModel::Send = "S";
const QString AddressTableModel::Receive = "R";
struct AddressTableEntry
{
enum Type {
Sending,
Receiving,
Hidden /* QSortFilterProxyModel will filter these out */
};
Type type;
QString label;
QString address;
AddressTableEntry() {}
AddressTableEntry(Type _type, const QString &_label, const QString &_address):
type(_type), label(_label), address(_address) {}
};
struct AddressTableEntryLessThan
{
bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const
{
return a.address < b.address;
}
bool operator()(const AddressTableEntry &a, const QString &b) const
{
return a.address < b;
}
bool operator()(const QString &a, const AddressTableEntry &b) const
{
return a < b.address;
}
};
/* Determine address type from address purpose */
static AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine)
{
AddressTableEntry::Type addressType = AddressTableEntry::Hidden;
// "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all.
if (strPurpose == "send")
addressType = AddressTableEntry::Sending;
else if (strPurpose == "receive")
addressType = AddressTableEntry::Receiving;
else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess
addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);
return addressType;
}
// Private implementation
class AddressTablePriv
{
public:
CWallet *wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTableModel *parent;
AddressTablePriv(CWallet *_wallet, AddressTableModel *_parent):
wallet(_wallet), parent(_parent) {}
void refreshAddressTable()
{
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
for (const std::pair<CTxDestination, CAddressBookData>& item : wallet->mapAddressBook)
{
const CTxDestination& address = item.first;
bool fMine = IsMine(*wallet, address);
AddressTableEntry::Type addressType = translateTransactionType(
QString::fromStdString(item.second.purpose), fMine);
const std::string& strName = item.second.name;
cachedAddressTable.append(AddressTableEntry(addressType,
QString::fromStdString(strName),
QString::fromStdString(EncodeDestination(address))));
}
}
// qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
// Even though the map is already sorted this re-sorting step is needed because the originating map
// is sorted by binary address, not by base58() address.
qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
}
void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
int upperIndex = (upper - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);
switch(status)
{
case CT_NEW:
if(inModel)
{
qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));
parent->endInsertRows();
break;
case CT_UPDATED:
if(!inModel)
{
qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = label;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if(!inModel)
{
qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedAddressTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedAddressTable.size();
}
AddressTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedAddressTable.size())
{
return &cachedAddressTable[idx];
}
else
{
return 0;
}
}
};
AddressTableModel::AddressTableModel(CWallet *_wallet, WalletModel *parent) :
QAbstractTableModel(parent),walletModel(parent),wallet(_wallet),priv(0)
{
columns << tr("Label") << tr("Address");
priv = new AddressTablePriv(wallet, this);
priv->refreshAddressTable();
}
AddressTableModel::~AddressTableModel()
{
delete priv;
}
int AddressTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int AddressTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant AddressTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
switch(index.column())
{
case Label:
if(rec->label.isEmpty() && role == Qt::DisplayRole)
{
return tr("(no label)");
}
else
{
return rec->label;
}
case Address:
return rec->address;
}
}
else if (role == Qt::FontRole)
{
QFont font;
if(index.column() == Address)
{
font = GUIUtil::fixedPitchFont();
}
return font;
}
else if (role == TypeRole)
{
switch(rec->type)
{
case AddressTableEntry::Sending:
return Send;
case AddressTableEntry::Receiving:
return Receive;
default: break;
}
}
return QVariant();
}
bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(!index.isValid())
return false;
AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive");
editStatus = OK;
if(role == Qt::EditRole)
{
LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
CTxDestination curAddress = DecodeDestination(rec->address.toStdString());
if(index.column() == Label)
{
// Do nothing, if old label == new label
if(rec->label == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
} else if(index.column() == Address) {
CTxDestination newAddress = DecodeDestination(value.toString().toStdString());
// Refuse to set invalid address, set error status and return false
if(boost::get<CNoDestination>(&newAddress))
{
editStatus = INVALID_ADDRESS;
return false;
}
// Do nothing, if old address == new address
else if(newAddress == curAddress)
{
editStatus = NO_CHANGES;
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if(wallet->mapAddressBook.count(newAddress))
{
editStatus = DUPLICATE_ADDRESS;
return false;
}
// Double-check that we're not overwriting a receiving address
else if(rec->type == AddressTableEntry::Sending)
{
// Remove old entry
wallet->DelAddressBook(curAddress);
// Add new entry with new address
wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
}
}
return true;
}
return false;
}
QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return 0;
AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer());
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
// Can edit address and label for sending addresses,
// and only label for receiving addresses.
if(rec->type == AddressTableEntry::Sending ||
(rec->type == AddressTableEntry::Receiving && index.column()==Label))
{
retval |= Qt::ItemIsEditable;
}
return retval;
}
QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
AddressTableEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
else
{
return QModelIndex();
}
}
void AddressTableModel::updateEntry(const QString &address,
const QString &label, bool isMine, const QString &purpose, int status)
{
// Update address book model from Bitcoin core
priv->updateEntry(address, label, isMine, purpose, status);
}
QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address, const OutputType address_type)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
editStatus = OK;
if(type == Send)
{
if(!walletModel->validateAddress(address))
{
editStatus = INVALID_ADDRESS;
return QString();
}
// Check for duplicate addresses
{
LOCK(wallet->cs_wallet);
if(wallet->mapAddressBook.count(DecodeDestination(strAddress)))
{
editStatus = DUPLICATE_ADDRESS;
return QString();
}
}
}
else if(type == Receive)
{
// Generate a new address to associate with given label
CPubKey newKey;
if(!wallet->GetKeyFromPool(newKey))
{
WalletModel::UnlockContext ctx(walletModel->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet failed or was cancelled
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
if(!wallet->GetKeyFromPool(newKey))
{
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
}
strAddress = EncodeDestination(GetDestinationForKey(newKey, address_type));
}
else
{
return QString();
}
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBook(DecodeDestination(strAddress), strLabel,
(type == Send ? "send" : "receive"));
}
return QString::fromStdString(strAddress);
}
bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent)
{
Q_UNUSED(parent);
AddressTableEntry *rec = priv->index(row);
if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving)
{
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelAddressBook(DecodeDestination(rec->address.toStdString()));
}
return true;
}
/* Look up label for address in address book, if not found return empty string.
*/
QString AddressTableModel::labelForAddress(const QString &address) const
{
{
LOCK(wallet->cs_wallet);
CTxDestination destination = DecodeDestination(address.toStdString());
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(destination);
if (mi != wallet->mapAddressBook.end())
{
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
int AddressTableModel::lookupAddress(const QString &address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if(lst.isEmpty())
{
return -1;
}
else
{
return lst.at(0).row();
}
}
void AddressTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
|
#include "Suggest.h"
#include <Columns/ColumnString.h>
#include <Common/typeid_cast.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int UNKNOWN_PACKET_FROM_SERVER;
extern const int DEADLOCK_AVOIDED;
}
void Suggest::load(const ConnectionParameters & connection_parameters, size_t suggestion_limit)
{
loading_thread = std::thread([connection_parameters, suggestion_limit, this]
{
for (size_t retry = 0; retry < 10; ++retry)
{
try
{
Connection connection(
connection_parameters.host,
connection_parameters.port,
connection_parameters.default_database,
connection_parameters.user,
connection_parameters.password,
"client",
connection_parameters.compression,
connection_parameters.security);
loadImpl(connection, connection_parameters.timeouts, suggestion_limit);
}
catch (const Exception & e)
{
/// Retry when the server said "Client should retry".
if (e.code() == ErrorCodes::DEADLOCK_AVOIDED)
continue;
std::cerr << "Cannot load data for command line suggestions: " << getCurrentExceptionMessage(false, true) << "\n";
}
catch (...)
{
std::cerr << "Cannot load data for command line suggestions: " << getCurrentExceptionMessage(false, true) << "\n";
}
break;
}
/// Note that keyword suggestions are available even if we cannot load data from server.
std::sort(words.begin(), words.end());
words_no_case = words;
std::sort(words_no_case.begin(), words_no_case.end(), [](const std::string & str1, const std::string & str2)
{
return std::lexicographical_compare(begin(str1), end(str1), begin(str2), end(str2), [](const char char1, const char char2)
{
return std::tolower(char1) < std::tolower(char2);
});
});
ready = true;
});
}
Suggest::Suggest()
{
/// Keywords may be not up to date with ClickHouse parser.
words = {"CREATE", "DATABASE", "IF", "NOT", "EXISTS", "TEMPORARY", "TABLE", "ON", "CLUSTER", "DEFAULT",
"MATERIALIZED", "ALIAS", "ENGINE", "AS", "VIEW", "POPULATE", "SETTINGS", "ATTACH", "DETACH", "DROP",
"RENAME", "TO", "ALTER", "ADD", "MODIFY", "CLEAR", "COLUMN", "AFTER", "COPY", "PROJECT",
"PRIMARY", "KEY", "CHECK", "PARTITION", "PART", "FREEZE", "FETCH", "FROM", "SHOW", "INTO",
"OUTFILE", "FORMAT", "TABLES", "DATABASES", "LIKE", "PROCESSLIST", "CASE", "WHEN", "THEN", "ELSE",
"END", "DESCRIBE", "DESC", "USE", "SET", "OPTIMIZE", "FINAL", "DEDUPLICATE", "INSERT", "VALUES",
"SELECT", "DISTINCT", "SAMPLE", "ARRAY", "JOIN", "GLOBAL", "LOCAL", "ANY", "ALL", "INNER",
"LEFT", "RIGHT", "FULL", "OUTER", "CROSS", "USING", "PREWHERE", "WHERE", "GROUP", "BY",
"WITH", "TOTALS", "HAVING", "ORDER", "COLLATE", "LIMIT", "UNION", "AND", "OR", "ASC",
"IN", "KILL", "QUERY", "SYNC", "ASYNC", "TEST", "BETWEEN", "TRUNCATE"};
}
void Suggest::loadImpl(Connection & connection, const ConnectionTimeouts & timeouts, size_t suggestion_limit)
{
std::stringstream query;
query << "SELECT DISTINCT arrayJoin(extractAll(name, '[\\\\w_]{2,}')) AS res FROM ("
"SELECT name FROM system.functions"
" UNION ALL "
"SELECT name FROM system.table_engines"
" UNION ALL "
"SELECT name FROM system.formats"
" UNION ALL "
"SELECT name FROM system.table_functions"
" UNION ALL "
"SELECT name FROM system.data_type_families"
" UNION ALL "
"SELECT name FROM system.merge_tree_settings"
" UNION ALL "
"SELECT name FROM system.settings"
" UNION ALL "
"SELECT cluster FROM system.clusters"
" UNION ALL "
"SELECT concat(func.name, comb.name) FROM system.functions AS func CROSS JOIN system.aggregate_function_combinators AS comb WHERE is_aggregate";
/// The user may disable loading of databases, tables, columns by setting suggestion_limit to zero.
if (suggestion_limit > 0)
{
String limit_str = toString(suggestion_limit);
query <<
" UNION ALL "
"SELECT name FROM system.databases LIMIT " << limit_str
<< " UNION ALL "
"SELECT DISTINCT name FROM system.tables LIMIT " << limit_str
<< " UNION ALL "
"SELECT DISTINCT name FROM system.columns LIMIT " << limit_str;
}
query << ") WHERE notEmpty(res)";
fetch(connection, timeouts, query.str());
}
void Suggest::fetch(Connection & connection, const ConnectionTimeouts & timeouts, const std::string & query)
{
connection.sendQuery(timeouts, query);
while (true)
{
Packet packet = connection.receivePacket();
switch (packet.type)
{
case Protocol::Server::Data:
fillWordsFromBlock(packet.block);
continue;
case Protocol::Server::Progress:
continue;
case Protocol::Server::ProfileInfo:
continue;
case Protocol::Server::Totals:
continue;
case Protocol::Server::Extremes:
continue;
case Protocol::Server::Log:
continue;
case Protocol::Server::Exception:
packet.exception->rethrow();
return;
case Protocol::Server::EndOfStream:
return;
default:
throw Exception("Unknown packet from server", ErrorCodes::UNKNOWN_PACKET_FROM_SERVER);
}
}
}
void Suggest::fillWordsFromBlock(const Block & block)
{
if (!block)
return;
if (block.columns() != 1)
throw Exception("Wrong number of columns received for query to read words for suggestion", ErrorCodes::LOGICAL_ERROR);
const ColumnString & column = typeid_cast<const ColumnString &>(*block.getByPosition(0).column);
size_t rows = block.rows();
for (size_t i = 0; i < rows; ++i)
words.emplace_back(column.getDataAt(i).toString());
}
}
|
#include <simplechain/contract_object.h>
#include <simplechain/contract_entry.h>
namespace simplechain {
ContractEntryPrintable contract_object::to_printable(const contract_object& obj) {
ContractEntryPrintable printable;
printable.id = obj.contract_address;
printable.owner_address = obj.owner_address;
printable.name = obj.contract_name;
printable.description = obj.contract_desc;
printable.type_of_contract = obj.type_of_contract;
printable.code_printable = obj.code;
printable.registered_block = obj.registered_block;
if (obj.inherit_from != "")
{
printable.inherit_from = obj.inherit_from;
}
for (auto& addr : obj.derived)
{
printable.derived.push_back(addr);
}
printable.createtime = obj.create_time;
return printable;
}
}
namespace fc {
void to_variant(const simplechain::contract_object& var, variant& vo) {
fc::mutable_variant_object obj("registered_block", var.registered_block);
obj("owner_address", var.owner_address);
// TODO: code to varient
obj("create_time", var.create_time);
obj("contract_address", var.contract_address);
obj("contract_name", var.contract_name);
obj("contract_desc", var.contract_desc);
obj("type_of_contract", var.type_of_contract);
obj("native_contract_key", var.native_contract_key);
obj("derived", var.derived);
obj("inherit_from", var.inherit_from);
if (var.type_of_contract == simplechain::contract_type::normal_contract) {
obj("abi", var.code.abi);
obj("offline_abi", var.code.offline_abi);
obj("storage_properties", var.code.storage_properties);
}
vo = std::move(obj);
}
void from_variant(const fc::variant& var, simplechain::contract_object& vo) {
const auto& varobj = var.as<fc::mutable_variant_object>();
vo.registered_block = varobj["registered_block"].as_uint64();
vo.owner_address = varobj["owner_address"].as_string();
if (varobj.find("code") != varobj.end())
fc::from_variant(varobj["code"], vo.code);
else if (varobj.find("code_printable") != varobj.end())
fc::from_variant(varobj["code_printable"], vo.code);
// fc::from_variant(varobj["create_time"], vo.create_time);
if (varobj.find("contract_address") != varobj.end())
vo.contract_address = varobj["contract_address"].as_string();
else if(varobj.find("id") != varobj.end())
vo.contract_address = varobj["id"].as_string();
if(varobj.find("contract_name") != varobj.end())
vo.contract_name = varobj["contract_name"].as_string();
if(varobj.find("contract_desc") != varobj.end())
vo.contract_desc = varobj["contract_desc"].as_string();
if(varobj.find("type_of_contract") != varobj.end())
fc::from_variant(varobj["type_of_contract"], vo.type_of_contract);
if(varobj.find("native_contract_key") != varobj.end())
vo.native_contract_key = varobj["native_contract_key"].as_string();
if(varobj.find("derived") != varobj.end())
vo.derived = varobj["derived"].as <std::vector<std::string>>();
if(varobj.find("inherit_from") != varobj.end())
vo.inherit_from = varobj["inherit_from"].as_string();
}
}
|
// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("KaixinCoin");
// Client version number
#define CLIENT_VERSION_SUFFIX ""
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID ""
# define GIT_COMMIT_DATE "Ari 23,2014 23:00"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) ""
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
* products derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
* works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
* specific prior written permission from Alliance for Sustainable Energy, LLC.
*
* 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, THE UNITED STATES GOVERNMENT, OR ANY 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.
**********************************************************************************************************************/
#ifndef OPENSTUDIO_MATERIALSCONTROLLER_HPP
#define OPENSTUDIO_MATERIALSCONTROLLER_HPP
#include "ModelSubTabController.hpp"
namespace openstudio {
class MaterialsController : public ModelSubTabController
{
Q_OBJECT
public:
MaterialsController(bool isIP, const model::Model & model);
virtual ~MaterialsController();
protected:
virtual void onAddObject(const openstudio::IddObjectType& iddObjectType) override;
virtual void onCopyObject(const openstudio::model::ModelObject& modelObject) override;
virtual void onRemoveObject(openstudio::model::ModelObject) override;
virtual void onReplaceObject(openstudio::model::ModelObject modelObject, const OSItemId& replacementItemId) override;
virtual void onPurgeObjects(const openstudio::IddObjectType& iddObjectType) override;
virtual void onDrop(const OSItemId& itemId) override;
virtual void onInspectItem(OSItem* item) override;
};
} // openstudio
#endif // OPENSTUDIO_MATERIALSCONTROLLER_HPP
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <climits>
#include <AzCore/Casting/numeric_cast.h>
#include <AzCore/Debug/Profiler.h>
#include <AzCore/IO/Streamer/FileRequest.h>
#include <AzCore/IO/Streamer/StreamerContext.h>
#include <AzCore/IO/Streamer/StorageDrive_Windows.h>
#include <AzCore/std/typetraits/decay.h>
#include <AzCore/std/typetraits/is_unsigned.h>
#include <AzCore/StringFunc/StringFunc.h>
#include <AzCore/std/string/conversions.h>
namespace AZ::IO
{
#if AZ_STREAMER_ADD_EXTRA_PROFILING_INFO
static constexpr char FileSwitchesName[] = "File switches";
static constexpr char SeeksName[] = "Seeks";
static constexpr char DirectReadsName[] = "Direct reads (no internal alloc)";
#endif // AZ_STREAMER_ADD_EXTRA_PROFILING_INFO
const AZStd::chrono::microseconds StorageDriveWin::s_averageSeekTime =
AZStd::chrono::milliseconds(9) + // Common average seek time for desktop hdd drives.
AZStd::chrono::milliseconds(3); // Rotational latency for a 7200RPM disk
//
// ConstructionOptions
//
StorageDriveWin::ConstructionOptions::ConstructionOptions()
: m_hasSeekPenalty(true)
, m_enableUnbufferedReads(true)
, m_enableSharing(false)
, m_minimalReporting(false)
{}
//
// FileReadInformation
//
void StorageDriveWin::FileReadInformation::AllocateAlignedBuffer(size_t size, size_t sectorSize)
{
AZ_Assert(m_sectorAlignedOutput == nullptr, "Assign a sector aligned buffer when one is already assigned.");
m_sectorAlignedOutput = azmalloc(size, sectorSize, AZ::SystemAllocator);
}
void StorageDriveWin::FileReadInformation::Clear()
{
if (m_sectorAlignedOutput)
{
azfree(m_sectorAlignedOutput, AZ::SystemAllocator);
}
*this = FileReadInformation{};
}
//
// StorageDriveWin
//
StorageDriveWin::StorageDriveWin(const AZStd::vector<AZStd::string_view>& drivePaths, u32 maxFileHandles, u32 maxMetaDataCacheEntries,
size_t physicalSectorSize, size_t logicalSectorSize, u32 ioChannelCount, s32 overCommit, ConstructionOptions options)
: m_maxFileHandles(maxFileHandles)
, m_physicalSectorSize(physicalSectorSize)
, m_logicalSectorSize(logicalSectorSize)
, m_ioChannelCount(ioChannelCount)
, m_overCommit(overCommit)
, m_constructionOptions(options)
{
AZ_Assert(!drivePaths.empty(), "StorageDrive_win requires at least one drive path to work.");
// Get drive paths
m_drivePaths.reserve(drivePaths.size());
for (AZStd::string_view drivePath : drivePaths)
{
AZStd::string path(drivePath);
// Erase the slash as it's one less character to compare and avoids issues with forward and
// backward slashes.
const char lastChar = path.back();
if (lastChar == AZ_CORRECT_FILESYSTEM_SEPARATOR || lastChar == AZ_WRONG_FILESYSTEM_SEPARATOR)
{
path.pop_back();
}
m_drivePaths.push_back(AZStd::move(path));
}
// Create name for statistics. The name will include all drive mappings on this physical device
// for instance "Storage drive (F,G,H)". Colons and slashes are removed.
m_name = "Storage drive (";
m_name += m_drivePaths[0].substr(0, m_drivePaths[0].length()-1);
for (size_t i = 1; i < m_drivePaths.size(); ++i)
{
m_name += ',';
// Add the path, but don't include the slash as that might cause formating issues with some profilers.
m_name += m_drivePaths[i].substr(0, m_drivePaths[i].length()-1);
}
m_name += ')';
if (!m_constructionOptions.m_minimalReporting)
{
AZ_Printf("Streamer", "%s created.\n", m_name.c_str());
}
if (m_physicalSectorSize == 0)
{
m_physicalSectorSize = 16_kib;
AZ_Error("StorageDriveWin", false,
"Received physical sector size of 0 for %s. Picking a sector size of %zu instead.\n", m_name.c_str(), m_physicalSectorSize);
}
if (m_logicalSectorSize == 0)
{
m_logicalSectorSize = 4_kib;
AZ_Error("StorageDriveWin", false,
"Received logical sector size of 0 for %s. Picking a sector size of %zu instead.\n", m_name.c_str(), m_logicalSectorSize);
}
AZ_Error("StorageDriveWin", IStreamerTypes::IsPowerOf2(m_physicalSectorSize) && IStreamerTypes::IsPowerOf2(m_logicalSectorSize),
"StorageDriveWin requires power-of-2 sector sizes. Received physical: %zu and logical: %zu",
m_physicalSectorSize, m_logicalSectorSize);
// Cap the IO channels to the maximum
if (m_ioChannelCount == 0)
{
m_ioChannelCount = aznumeric_cast<u32>(AZ::Platform::StreamerContextThreadSync::MaxIoEvents);
AZ_Warning("StorageDriveWin", false,
"Received io channel count of 0 for %s. Picking a count of %zu instead.\n",
m_name.c_str(), AZ::Platform::StreamerContextThreadSync::MaxIoEvents);
}
else
{
m_ioChannelCount = AZ::GetMin(m_ioChannelCount, aznumeric_cast<u32>(AZ::Platform::StreamerContextThreadSync::MaxIoEvents));
}
// Make sure that the overCommit isn't so small that no slots are ever reported.
if (aznumeric_cast<s32>(m_ioChannelCount) + m_overCommit <= 0)
{
AZ_Error("StorageDriveWin", false,
"Received overcommit (%i) for %s that subtracts more than the number of IO channels (%u). Setting combined count to 1.\n",
m_overCommit, m_name.c_str(), m_ioChannelCount);
m_overCommit = 1 - aznumeric_cast<s32>(m_ioChannelCount);
}
// Add initial dummy values to the stats to avoid division by zero later on and avoid needing branches.
m_readSizeAverage.PushEntry(1);
m_readTimeAverage.PushEntry(AZStd::chrono::microseconds(1));
AZ_Assert(IStreamerTypes::IsPowerOf2(maxMetaDataCacheEntries),
"StorageDriveWin requires a power-of-2 for maxMetaDataCacheEntries. Received %zu", maxMetaDataCacheEntries);
m_metaDataCache_paths.resize(maxMetaDataCacheEntries);
m_metaDataCache_fileSize.resize(maxMetaDataCacheEntries);
}
StorageDriveWin::~StorageDriveWin()
{
for (HANDLE file : m_fileCache_handles)
{
if (file != INVALID_HANDLE_VALUE)
{
::CloseHandle(file);
}
}
if (!m_constructionOptions.m_minimalReporting)
{
AZ_Printf("Streamer", "%s destroyed.\n", m_name.c_str());
}
}
void StorageDriveWin::PrepareRequest(FileRequest* request)
{
AZ_PROFILE_FUNCTION(AzCore);
AZ_Assert(request, "PrepareRequest was provided a null request.");
if (AZStd::holds_alternative<Requests::ReadRequestData>(request->GetCommand()))
{
auto& readRequest = AZStd::get<Requests::ReadRequestData>(request->GetCommand());
if (IsServicedByThisDrive(readRequest.m_path.GetAbsolutePath()))
{
FileRequest* read = m_context->GetNewInternalRequest();
read->CreateRead(request, readRequest.m_output, readRequest.m_outputSize, readRequest.m_path,
readRequest.m_offset, readRequest.m_size);
m_context->PushPreparedRequest(read);
return;
}
}
StreamStackEntry::PrepareRequest(request);
}
void StorageDriveWin::QueueRequest(FileRequest* request)
{
AZ_PROFILE_FUNCTION(AzCore);
AZ_Assert(request, "QueueRequest was provided a null request.");
AZStd::visit([this, request](auto&& args)
{
using Command = AZStd::decay_t<decltype(args)>;
if constexpr (AZStd::is_same_v<Command, Requests::ReadData>)
{
if (IsServicedByThisDrive(args.m_path.GetAbsolutePath()))
{
m_pendingReadRequests.push_back(request);
return;
}
}
else if constexpr (AZStd::is_same_v<Command, Requests::FileExistsCheckData> ||
AZStd::is_same_v<Command, Requests::FileMetaDataRetrievalData>)
{
if (IsServicedByThisDrive(args.m_path.GetAbsolutePath()))
{
m_pendingRequests.push_back(request);
return;
}
}
else if constexpr (AZStd::is_same_v<Command, Requests::CancelData>)
{
if (CancelRequest(request, args.m_target))
{
// Only forward if this isn't part of the request chain, otherwise the storage device should
// be the last step as it doesn't forward any (sub)requests.
return;
}
}
else if constexpr (AZStd::is_same_v<Command, Requests::FlushData>)
{
FlushCache(args.m_path);
}
else if constexpr (AZStd::is_same_v<Command, Requests::FlushAllData>)
{
FlushEntireCache();
}
else if constexpr (AZStd::is_same_v<Command, Requests::ReportData>)
{
Report(args);
}
StreamStackEntry::QueueRequest(request);
}, request->GetCommand());
}
bool StorageDriveWin::ExecuteRequests()
{
bool hasFinalizedReads = FinalizeReads();
bool hasWorked = false;
if (!m_pendingReadRequests.empty())
{
FileRequest* request = m_pendingReadRequests.front();
if (ReadRequest(request))
{
m_pendingReadRequests.pop_front();
hasWorked = true;
}
}
else if (!m_pendingRequests.empty())
{
FileRequest* request = m_pendingRequests.front();
hasWorked = AZStd::visit(
[this, request](auto&& args)
{
using Command = AZStd::decay_t<decltype(args)>;
if constexpr (AZStd::is_same_v<Command, Requests::FileExistsCheckData>)
{
FileExistsRequest(request);
m_pendingRequests.pop_front();
return true;
}
else if constexpr (AZStd::is_same_v<Command, Requests::FileMetaDataRetrievalData>)
{
FileMetaDataRetrievalRequest(request);
m_pendingRequests.pop_front();
return true;
}
else
{
AZ_Assert(false, "A request was added to StorageDriveWin's pending queue that isn't supported.");
return false;
}
},
request->GetCommand());
}
return StreamStackEntry::ExecuteRequests() || hasFinalizedReads || hasWorked;
}
void StorageDriveWin::UpdateStatus(Status& status) const
{
StreamStackEntry::UpdateStatus(status);
status.m_numAvailableSlots = AZStd::min(status.m_numAvailableSlots, CalculateNumAvailableSlots());
status.m_isIdle = status.m_isIdle && m_pendingReadRequests.empty() && m_pendingRequests.empty() && (m_activeReads_Count == 0);
}
void StorageDriveWin::UpdateCompletionEstimates(AZStd::chrono::system_clock::time_point now, AZStd::vector<FileRequest*>& internalPending,
StreamerContext::PreparedQueue::iterator pendingBegin, StreamerContext::PreparedQueue::iterator pendingEnd)
{
StreamStackEntry::UpdateCompletionEstimates(now, internalPending, pendingBegin, pendingEnd);
const RequestPath* activeFile = nullptr;
if (m_activeCacheSlot != InvalidFileCacheIndex)
{
activeFile = &m_fileCache_paths[m_activeCacheSlot];
}
u64 activeOffset = m_activeOffset;
// Determine the time of the first available slot
AZStd::chrono::system_clock::time_point earliestSlot = AZStd::chrono::system_clock::time_point::max();
for (size_t i = 0; i < m_readSlots_readInfo.size(); ++i)
{
if (m_readSlots_active[i])
{
FileReadInformation& read = m_readSlots_readInfo[i];
u64 totalBytesRead = m_readSizeAverage.GetTotal();
double totalReadTimeUSec = aznumeric_caster(m_readTimeAverage.GetTotal().count());
auto readCommand = AZStd::get_if<Requests::ReadData>(&read.m_request->GetCommand());
AZ_Assert(readCommand, "Request currently reading doesn't contain a read command.");
auto endTime = read.m_startTime + AZStd::chrono::microseconds(aznumeric_cast<u64>((readCommand->m_size * totalReadTimeUSec) / totalBytesRead));
earliestSlot = AZStd::min(earliestSlot, endTime);
read.m_request->SetEstimatedCompletion(endTime);
}
}
if (earliestSlot != AZStd::chrono::system_clock::time_point::max())
{
now = earliestSlot;
}
// Estimate requests in this stack entry.
for (FileRequest* request : m_pendingReadRequests)
{
EstimateCompletionTimeForRequest(request, now, activeFile, activeOffset);
}
for (FileRequest* request : m_pendingRequests)
{
EstimateCompletionTimeForRequest(request, now, activeFile, activeOffset);
}
// Estimate internally pending requests. Because this call will go from the top of the stack to the bottom,
// but estimation is calculated from the bottom to the top, this list should be processed in reverse order.
for (auto requestIt = internalPending.rbegin(); requestIt != internalPending.rend(); ++requestIt)
{
EstimateCompletionTimeForRequestChecked(*requestIt, now, activeFile, activeOffset);
}
// Estimate pending requests that have not been queued yet.
for (auto requestIt = pendingBegin; requestIt != pendingEnd; ++requestIt)
{
EstimateCompletionTimeForRequestChecked(*requestIt, now, activeFile, activeOffset);
}
}
void StorageDriveWin::EstimateCompletionTimeForRequest(FileRequest* request, AZStd::chrono::system_clock::time_point& startTime,
const RequestPath*& activeFile, u64& activeOffset) const
{
u64 readSize = 0;
u64 offset = 0;
const RequestPath* targetFile = nullptr;
AZStd::visit([&](auto&& args)
{
using Command = AZStd::decay_t<decltype(args)>;
if constexpr (AZStd::is_same_v<Command, Requests::ReadData>)
{
targetFile = &args.m_path;
readSize = args.m_size;
offset = args.m_offset;
}
else if constexpr (AZStd::is_same_v<Command, Requests::CompressedReadData>)
{
targetFile = &args.m_compressionInfo.m_archiveFilename;
readSize = args.m_compressionInfo.m_compressedSize;
offset = args.m_compressionInfo.m_offset;
}
else if constexpr (AZStd::is_same_v<Command, Requests::FileExistsCheckData>)
{
readSize = 0;
AZStd::chrono::microseconds getFileExistsTimeAverage = m_getFileExistsTimeAverage.CalculateAverage();
startTime += getFileExistsTimeAverage;
}
else if constexpr (AZStd::is_same_v<Command, Requests::FileMetaDataRetrievalData>)
{
readSize = 0;
AZStd::chrono::microseconds getFileExistsTimeAverage = m_getFileMetaDataRetrievalTimeAverage.CalculateAverage();
startTime += getFileExistsTimeAverage;
}
}, request->GetCommand());
if (readSize > 0)
{
if (activeFile && activeFile != targetFile)
{
if (FindInFileHandleCache(*targetFile) == InvalidFileCacheIndex)
{
AZStd::chrono::microseconds fileOpenCloseTimeAverage = m_fileOpenCloseTimeAverage.CalculateAverage();
startTime += fileOpenCloseTimeAverage;
}
activeOffset = std::numeric_limits<u64>::max();
}
if (activeOffset != offset && m_constructionOptions.m_hasSeekPenalty)
{
startTime += s_averageSeekTime;
}
u64 totalBytesRead = m_readSizeAverage.GetTotal();
double totalReadTimeUSec = aznumeric_caster(m_readTimeAverage.GetTotal().count());
startTime += AZStd::chrono::microseconds(aznumeric_cast<u64>((readSize * totalReadTimeUSec) / totalBytesRead));
activeOffset = offset + readSize;
}
request->SetEstimatedCompletion(startTime);
}
void StorageDriveWin::EstimateCompletionTimeForRequestChecked(FileRequest* request,
AZStd::chrono::system_clock::time_point startTime, const RequestPath*& activeFile, u64& activeOffset) const
{
AZStd::visit([&, this](auto&& args)
{
using Command = AZStd::decay_t<decltype(args)>;
if constexpr (AZStd::is_same_v<Command, Requests::ReadData> ||
AZStd::is_same_v<Command, Requests::FileExistsCheckData>)
{
if (IsServicedByThisDrive(args.m_path.GetAbsolutePath()))
{
EstimateCompletionTimeForRequest(request, startTime, activeFile, activeOffset);
}
}
else if constexpr (AZStd::is_same_v<Command, Requests::CompressedReadData>)
{
if (IsServicedByThisDrive(args.m_compressionInfo.m_archiveFilename.GetAbsolutePath()))
{
EstimateCompletionTimeForRequest(request, startTime, activeFile, activeOffset);
}
}
}, request->GetCommand());
}
s32 StorageDriveWin::CalculateNumAvailableSlots() const
{
return (m_overCommit + aznumeric_cast<s32>(m_ioChannelCount)) - aznumeric_cast<s32>(m_pendingReadRequests.size()) -
aznumeric_cast<s32>(m_pendingRequests.size()) - m_activeReads_Count;
}
auto StorageDriveWin::OpenFile(HANDLE& fileHandle, size_t& cacheSlot, FileRequest* request, const Requests::ReadData& data) -> OpenFileResult
{
HANDLE file = INVALID_HANDLE_VALUE;
// If the file is already opened for use, use that file handle and update it's last touched time.
size_t cacheIndex = FindInFileHandleCache(data.m_path);
if (cacheIndex != InvalidFileCacheIndex)
{
file = m_fileCache_handles[cacheIndex];
AZ_Assert(file != INVALID_HANDLE_VALUE, "Found the file '%s' in cache, but file handle is invalid.\n",
data.m_path.GetRelativePath());
}
else
{
// If the file is not already found in the cache, attempt to claim an available cache entry.
cacheIndex = FindAvailableFileHandleCacheIndex();
if (cacheIndex == InvalidFileCacheIndex)
{
// No files ready to be evicted.
return OpenFileResult::CacheFull;
}
// Adding explicit scope here for profiling file Open & Close
{
AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::ReadRequest OpenFile %s", m_name.c_str());
TIMED_AVERAGE_WINDOW_SCOPE(m_fileOpenCloseTimeAverage);
// All reads are overlapped (asynchronous).
// Depending on configuration, reads can also be unbuffered.
// Unbuffered means Windows does not use its own file cache for these files.
DWORD createFlags = m_constructionOptions.m_enableUnbufferedReads ? (FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING) : FILE_FLAG_OVERLAPPED;
DWORD shareMode = (m_constructionOptions.m_enableSharing || data.m_sharedRead) ? FILE_SHARE_READ: 0;
AZStd::wstring filenameW;
AZStd::to_wstring(filenameW, data.m_path.GetAbsolutePath());
file = ::CreateFileW(
filenameW.c_str(), // file name
FILE_GENERIC_READ, // desired access
shareMode, // share mode
nullptr, // security attributes
OPEN_EXISTING, // creation disposition
createFlags, // flags and attributes
nullptr); // template file
if (file == INVALID_HANDLE_VALUE)
{
// Failed to open the file, so let the next entry in the stack try.
StreamStackEntry::QueueRequest(request);
return OpenFileResult::RequestForwarded;
}
// Remove any alertable IO completion notifications that could be queued by the IO Manager.
if (!::SetFileCompletionNotificationModes(file, FILE_SKIP_SET_EVENT_ON_HANDLE | FILE_SKIP_COMPLETION_PORT_ON_SUCCESS))
{
AZ_Warning("StorageDriveWin", false, "Failed to remove alertable IO completion notifications. (Error: %u)\n", ::GetLastError());
}
if (m_fileCache_handles[cacheIndex] != INVALID_HANDLE_VALUE)
{
::CloseHandle(m_fileCache_handles[cacheIndex]);
}
}
// Fill the cache entry with data about the new file.
m_fileCache_handles[cacheIndex] = file;
m_fileCache_activeReads[cacheIndex] = 0;
m_fileCache_paths[cacheIndex] = data.m_path;
}
AZ_Assert(file != INVALID_HANDLE_VALUE, "While searching for file '%s' in StorageDeviceWin::OpenFile failed to detect a problem.",
data.m_path.GetRelativePath());
// Set the current request and update timestamp, regardless of cache hit or miss.
m_fileCache_lastTimeUsed[cacheIndex] = AZStd::chrono::system_clock::now();
fileHandle = file;
cacheSlot = cacheIndex;
return OpenFileResult::FileOpened;
}
bool StorageDriveWin::ReadRequest(FileRequest* request)
{
AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::ReadRequest %s", m_name.c_str());
if (!m_cachesInitialized)
{
m_fileCache_lastTimeUsed.resize(m_maxFileHandles, AZStd::chrono::system_clock::time_point::min());
m_fileCache_paths.resize(m_maxFileHandles);
m_fileCache_handles.resize(m_maxFileHandles, INVALID_HANDLE_VALUE);
m_fileCache_activeReads.resize(m_maxFileHandles, 0);
m_readSlots_readInfo.resize(m_ioChannelCount);
m_readSlots_statusInfo.resize(m_ioChannelCount);
m_readSlots_active.resize(m_ioChannelCount);
m_cachesInitialized = true;
}
if (m_activeReads_Count >= m_ioChannelCount)
{
return false;
}
size_t readSlot = FindAvailableReadSlot();
AZ_Assert(readSlot != InvalidReadSlotIndex, "Active read slot count indicates there's a read slot available, but no read slot was found.");
return ReadRequest(request, readSlot);
}
bool StorageDriveWin::ReadRequest(FileRequest* request, size_t readSlot)
{
AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::ReadRequest %s", m_name.c_str());
if (!m_context->GetStreamerThreadSynchronizer().AreEventHandlesAvailable())
{
// There are no more events handles available so delay executing this request until events become available.
return false;
}
auto data = AZStd::get_if<Requests::ReadData>(&request->GetCommand());
AZ_Assert(data, "Read request in StorageDriveWin doesn't contain read data.");
HANDLE file = INVALID_HANDLE_VALUE;
size_t fileCacheSlot = InvalidFileCacheIndex;
switch (OpenFile(file, fileCacheSlot, request, *data))
{
case OpenFileResult::FileOpened:
break;
case OpenFileResult::RequestForwarded:
return true;
case OpenFileResult::CacheFull:
return false;
default:
AZ_Assert(false, "Unsupported OpenFileRequest returned.");
}
DWORD readSize = aznumeric_cast<DWORD>(data->m_size);
u64 readOffs = data->m_offset;
void* output = data->m_output;
FileReadInformation& readInfo = m_readSlots_readInfo[readSlot];
readInfo.m_request = request;
if (m_constructionOptions.m_enableUnbufferedReads)
{
// Check alignment of the file read information: size, offset, and address.
// If any are unaligned to the sector sizes, make adjustments and allocate an aligned buffer.
const bool alignedAddr = IStreamerTypes::IsAlignedTo(data->m_output, aznumeric_caster(m_physicalSectorSize));
const bool alignedOffs = IStreamerTypes::IsAlignedTo(data->m_offset, aznumeric_caster(m_logicalSectorSize));
// Adjust the offset if it's misaligned.
// Align the offset down to next lowest sector.
// Change the size to compensate.
//
// Before:
// +---------------+---------------+
// | XXXXXXXXXXXX|XXXXXXX |
// +---------------+---------------+
// ^--- offset
// <--- size --------->
//
// After:
// +---------------+---------------+
// |###XXXXXXXXXXXX|XXXXXXX |
// +---------------+---------------+
// ^--- offset
// <--- size ------------->
// <--> copyBackOffset
//
// Store the size of the adjustment in copyBackOffset, which will be used
// later to copy only the X's and not the #'s (from diagram above).
if (!alignedOffs)
{
readOffs = AZ_SIZE_ALIGN_DOWN(readOffs, m_logicalSectorSize);
u64 offsetCorrection = data->m_offset - readOffs;
readInfo.m_copyBackOffset = offsetCorrection;
readSize = aznumeric_cast<DWORD>(data->m_size + offsetCorrection);
}
bool alignedSize = IStreamerTypes::IsAlignedTo(readSize, aznumeric_caster(m_logicalSectorSize));
if (!alignedSize)
{
DWORD alignedReadSize = aznumeric_caster(AZ_SIZE_ALIGN_UP(readSize, m_logicalSectorSize));
if (alignedReadSize <= data->m_outputSize)
{
alignedSize = true;
readSize = alignedReadSize;
}
}
// Adjust the size again if the end is misaligned.
// Aligns the new read size up to be a multiple of the the sector size.
//
// Before:
// +---------------+---------------+
// |XXXXXXXXXXXXXXX|XXXXXXX |
// +---------------+---------------+
// ^--- offset
// <--- size ------------->
//
// After:
// +---------------+---------------+
// |XXXXXXXXXXXXXXX|XXXXXXX########|
// +---------------+---------------+
// ^--- offset
// <--- size ---------------------->
//
// Once everything is aligned, allocate the temporary buffer.
// Again, when read completes from OS, only copy back the X's and not
// the #'s (from diagram above).
const bool isAligned = (alignedAddr && alignedSize && alignedOffs);
if (!isAligned)
{
readSize = aznumeric_cast<DWORD>(AZ_SIZE_ALIGN_UP(readSize, m_logicalSectorSize));
readInfo.AllocateAlignedBuffer(readSize, m_physicalSectorSize);
output = readInfo.m_sectorAlignedOutput;
}
#if AZ_STREAMER_ADD_EXTRA_PROFILING_INFO
m_directReadsPercentageStat.PushSample(isAligned ? 1.0 : 0.0);
Statistic::PlotImmediate(m_name, DirectReadsName, m_directReadsPercentageStat.GetMostRecentSample());
#endif // AZ_STREAMER_ADD_EXTRA_PROFILING_INFO
}
FileReadStatus& readStatus = m_readSlots_statusInfo[readSlot];
LPOVERLAPPED overlapped = &readStatus.m_overlapped;
overlapped->Offset = aznumeric_caster(readOffs);
overlapped->OffsetHigh = aznumeric_caster(readOffs >> (sizeof(overlapped->Offset) << 3));
overlapped->hEvent = m_context->GetStreamerThreadSynchronizer().CreateEventHandle();
readStatus.m_fileHandleIndex = fileCacheSlot;
bool result = false;
{
AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::ReadRequest ::ReadFile");
result = ::ReadFile(file, output, readSize, nullptr, overlapped);
}
if (!result)
{
DWORD error = ::GetLastError();
if (error != ERROR_IO_PENDING)
{
AZ_Warning("StorageDriveWin", false, "::ReadFile failed with error: %u\n", error);
m_context->GetStreamerThreadSynchronizer().DestroyEventHandle(overlapped->hEvent);
// Finish the request since this drive opened the file handle but the read failed.
request->SetStatus(IStreamerTypes::RequestStatus::Failed);
m_context->MarkRequestAsCompleted(request);
readInfo.Clear();
return true;
}
}
else
{
// If this scope is reached, it means that ::ReadFile processed the read synchronously. This can happen if
// the OS already had the file in the cache. The OVERLAPPED struct will still be filled out so we proceed as
// if the read was fully asynchronous.
}
auto now = AZStd::chrono::system_clock::now();
if (m_activeReads_Count++ == 0)
{
m_activeReads_startTime = now;
}
readInfo.m_startTime = now;
m_readSlots_active[readSlot] = true;
#if AZ_STREAMER_ADD_EXTRA_PROFILING_INFO
if (m_activeCacheSlot == fileCacheSlot)
{
m_fileSwitchPercentageStat.PushSample(0.0);
m_seekPercentageStat.PushSample(m_activeOffset == data->m_offset ? 0.0 : 1.0);
}
else
{
m_fileSwitchPercentageStat.PushSample(1.0);
m_seekPercentageStat.PushSample(0.0);
}
Statistic::PlotImmediate(m_name, FileSwitchesName, m_fileSwitchPercentageStat.GetMostRecentSample());
Statistic::PlotImmediate(m_name, SeeksName, m_seekPercentageStat.GetMostRecentSample());
#endif // AZ_STREAMER_ADD_EXTRA_PROFILING_INFO
m_fileCache_activeReads[fileCacheSlot]++;
m_activeCacheSlot = fileCacheSlot;
m_activeOffset = readOffs + readSize;
return true;
}
bool StorageDriveWin::CancelRequest(FileRequest* cancelRequest, FileRequestPtr& target)
{
bool ownsRequestChain = false;
for (auto it = m_pendingReadRequests.begin(); it != m_pendingReadRequests.end();)
{
if ((*it)->WorksOn(target))
{
(*it)->SetStatus(IStreamerTypes::RequestStatus::Canceled);
m_context->MarkRequestAsCompleted(*it);
it = m_pendingReadRequests.erase(it);
ownsRequestChain = true;
}
else
{
++it;
}
}
// Pending requests have been accounted for, now address any active reads and issue a Cancel call to the OS.
size_t fileCacheIndex = InvalidFileCacheIndex;
for (size_t readSlot = 0; readSlot < m_readSlots_active.size(); ++readSlot)
{
if (m_readSlots_active[readSlot] && m_readSlots_readInfo[readSlot].m_request->WorksOn(target))
{
if (fileCacheIndex == InvalidFileCacheIndex)
{
fileCacheIndex = m_readSlots_statusInfo[readSlot].m_fileHandleIndex;
}
AZ_Assert(fileCacheIndex == m_readSlots_statusInfo[readSlot].m_fileHandleIndex,
"Active file reads for a target read request have mismatched file cache indexes.");
ownsRequestChain = true;
if (!::CancelIoEx(m_fileCache_handles[fileCacheIndex], &m_readSlots_statusInfo[readSlot].m_overlapped))
{
DWORD error = ::GetLastError();
if (error != ERROR_NOT_FOUND)
{
AZ_Error("StorageDriveWin", false, "::CancelIoEx failed with error: %u\n", error);
}
}
}
}
if (ownsRequestChain)
{
cancelRequest->SetStatus(IStreamerTypes::RequestStatus::Completed);
m_context->MarkRequestAsCompleted(cancelRequest);
}
return ownsRequestChain;
}
void StorageDriveWin::FileExistsRequest(FileRequest* request)
{
auto& fileExists = AZStd::get<Requests::FileExistsCheckData>(request->GetCommand());
AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::FileExistsRequest %s : %s",
m_name.c_str(), fileExists.m_path.GetRelativePath());
TIMED_AVERAGE_WINDOW_SCOPE(m_getFileExistsTimeAverage);
AZ_Assert(IsServicedByThisDrive(fileExists.m_path.GetAbsolutePath()),
"FileExistsRequest was queued on a StorageDriveWin that doesn't service files on the given path '%s'.",
fileExists.m_path.GetRelativePath());
size_t cacheIndex = FindInFileHandleCache(fileExists.m_path);
if (cacheIndex != InvalidFileCacheIndex)
{
fileExists.m_found = true;
request->SetStatus(IStreamerTypes::RequestStatus::Completed);
m_context->MarkRequestAsCompleted(request);
return;
}
cacheIndex = FindInMetaDataCache(fileExists.m_path);
if (cacheIndex != InvalidMetaDataCacheIndex)
{
fileExists.m_found = true;
request->SetStatus(IStreamerTypes::RequestStatus::Completed);
m_context->MarkRequestAsCompleted(request);
return;
}
WIN32_FILE_ATTRIBUTE_DATA attributes;
AZStd::wstring filenameW;
AZStd::to_wstring(filenameW, fileExists.m_path.GetAbsolutePath());
if (::GetFileAttributesExW(filenameW.c_str(), GetFileExInfoStandard, &attributes))
{
if ((attributes.dwFileAttributes != INVALID_FILE_ATTRIBUTES) &&
((attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0))
{
LARGE_INTEGER fileSize;
fileSize.LowPart = attributes.nFileSizeLow;
fileSize.HighPart = attributes.nFileSizeHigh;
cacheIndex = GetNextMetaDataCacheSlot();
m_metaDataCache_paths[cacheIndex] = fileExists.m_path;
m_metaDataCache_fileSize[cacheIndex] = aznumeric_caster(fileSize.QuadPart);
fileExists.m_found = true;
request->SetStatus(IStreamerTypes::RequestStatus::Completed);
m_context->MarkRequestAsCompleted(request);
}
return;
}
StreamStackEntry::QueueRequest(request);
}
void StorageDriveWin::FileMetaDataRetrievalRequest(FileRequest* request)
{
auto& command = AZStd::get<Requests::FileMetaDataRetrievalData>(request->GetCommand());
AZ_PROFILE_SCOPE(AzCore, "StorageDriveWin::FileMetaDataRetrievalRequest %s : %s",
m_name.c_str(), command.m_path.GetRelativePath());
TIMED_AVERAGE_WINDOW_SCOPE(m_getFileMetaDataRetrievalTimeAverage);
size_t cacheIndex = FindInMetaDataCache(command.m_path);
if (cacheIndex != InvalidMetaDataCacheIndex)
{
command.m_fileSize = m_metaDataCache_fileSize[cacheIndex];
command.m_found = true;
request->SetStatus(IStreamerTypes::RequestStatus::Completed);
m_context->MarkRequestAsCompleted(request);
return;
}
LARGE_INTEGER fileSize{};
cacheIndex = FindInFileHandleCache(command.m_path);
if (cacheIndex != InvalidFileCacheIndex)
{
AZ_Assert(m_fileCache_handles[cacheIndex] != INVALID_HANDLE_VALUE,
"File path '%s' doesn't have an associated file handle.", m_fileCache_paths[cacheIndex].GetRelativePath());
if (::GetFileSizeEx(m_fileCache_handles[cacheIndex], &fileSize) == FALSE)
{
StreamStackEntry::QueueRequest(request);
return;
}
}
else
{
WIN32_FILE_ATTRIBUTE_DATA attributes;
AZStd::wstring filenameW;
AZStd::to_wstring(filenameW, command.m_path.GetAbsolutePath());
if (::GetFileAttributesExW(filenameW.c_str(), GetFileExInfoStandard, &attributes) &&
(attributes.dwFileAttributes != INVALID_FILE_ATTRIBUTES) && ((attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0))
{
fileSize.LowPart = attributes.nFileSizeLow;
fileSize.HighPart = attributes.nFileSizeHigh;
}
else
{
StreamStackEntry::QueueRequest(request);
return;
}
}
command.m_fileSize = aznumeric_caster(fileSize.QuadPart);
command.m_found = true;
cacheIndex = GetNextMetaDataCacheSlot();
m_metaDataCache_paths[cacheIndex] = command.m_path;
m_metaDataCache_fileSize[cacheIndex] = aznumeric_caster(fileSize.QuadPart);
request->SetStatus(IStreamerTypes::RequestStatus::Completed);
m_context->MarkRequestAsCompleted(request);
}
void StorageDriveWin::FlushCache(const RequestPath& filePath)
{
if (m_cachesInitialized)
{
size_t cacheIndex = FindInFileHandleCache(filePath);
if (cacheIndex != InvalidFileCacheIndex)
{
if (m_fileCache_handles[cacheIndex] != INVALID_HANDLE_VALUE)
{
AZ_Assert(m_fileCache_activeReads[cacheIndex] == 0, "Flushing '%s' but it has %u active reads\n",
filePath.GetRelativePath(), m_fileCache_activeReads[cacheIndex]);
::CloseHandle(m_fileCache_handles[cacheIndex]);
m_fileCache_handles[cacheIndex] = INVALID_HANDLE_VALUE;
}
m_fileCache_activeReads[cacheIndex] = 0;
m_fileCache_lastTimeUsed[cacheIndex] = AZStd::chrono::system_clock::time_point();
m_fileCache_paths[cacheIndex].Clear();
}
cacheIndex = FindInMetaDataCache(filePath);
if (cacheIndex != InvalidMetaDataCacheIndex)
{
m_metaDataCache_paths[cacheIndex].Clear();
m_metaDataCache_fileSize[cacheIndex] = 0;
}
}
}
void StorageDriveWin::FlushEntireCache()
{
if (m_cachesInitialized)
{
// Clear file handle cache
for (size_t cacheIndex = 0; cacheIndex < m_maxFileHandles; ++cacheIndex)
{
if (m_fileCache_handles[cacheIndex] != INVALID_HANDLE_VALUE)
{
AZ_Assert(m_fileCache_activeReads[cacheIndex] == 0, "Flushing '%s' but it has %u active reads\n",
m_fileCache_paths[cacheIndex].GetRelativePath(), m_fileCache_activeReads[cacheIndex]);
::CloseHandle(m_fileCache_handles[cacheIndex]);
m_fileCache_handles[cacheIndex] = INVALID_HANDLE_VALUE;
}
m_fileCache_activeReads[cacheIndex] = 0;
m_fileCache_lastTimeUsed[cacheIndex] = AZStd::chrono::system_clock::time_point();
m_fileCache_paths[cacheIndex].Clear();
}
// Clear meta data cache
auto metaDataCacheSize = m_metaDataCache_paths.size();
m_metaDataCache_paths.clear();
m_metaDataCache_fileSize.clear();
m_metaDataCache_front = 0;
m_metaDataCache_paths.resize(metaDataCacheSize);
m_metaDataCache_fileSize.resize(metaDataCacheSize);
}
}
bool StorageDriveWin::FinalizeReads()
{
AZ_PROFILE_FUNCTION(AzCore);
bool hasWorked = false;
for (size_t readSlot = 0; readSlot < m_readSlots_active.size(); ++readSlot)
{
if (m_readSlots_active[readSlot])
{
FileReadStatus& status = m_readSlots_statusInfo[readSlot];
if (HasOverlappedIoCompleted(&status.m_overlapped))
{
DWORD bytesTransferred = 0;
BOOL result = ::GetOverlappedResult(m_fileCache_handles[status.m_fileHandleIndex],
&status.m_overlapped, &bytesTransferred, FALSE);
DWORD error = ::GetLastError();
if (result || error == ERROR_OPERATION_ABORTED)
{
hasWorked = true;
constexpr bool encounteredError = false;
FinalizeSingleRequest(status, readSlot, bytesTransferred, error == ERROR_OPERATION_ABORTED, encounteredError);
}
else if (error != ERROR_IO_PENDING && error != ERROR_IO_INCOMPLETE)
{
AZ_Error("StorageDriveWin", false, "Async file read operation completed with extended error code %u\n", error);
hasWorked = true;
constexpr bool encounteredError = true;
FinalizeSingleRequest(status, readSlot, bytesTransferred, false, encounteredError);
}
}
}
}
return hasWorked;
}
void StorageDriveWin::FinalizeSingleRequest(FileReadStatus& status, size_t readSlot, DWORD numBytesTransferred,
bool isCanceled, bool encounteredError)
{
m_activeReads_ByteCount += numBytesTransferred;
if (--m_activeReads_Count == 0)
{
// Update read stats now that the operation is done.
m_readSizeAverage.PushEntry(m_activeReads_ByteCount);
m_readTimeAverage.PushEntry(AZStd::chrono::duration_cast<AZStd::chrono::microseconds>(
AZStd::chrono::system_clock::now() - m_activeReads_startTime));
m_activeReads_ByteCount = 0;
}
FileReadInformation& fileReadInfo = m_readSlots_readInfo[readSlot];
auto readCommand = AZStd::get_if<Requests::ReadData>(&fileReadInfo.m_request->GetCommand());
AZ_Assert(readCommand != nullptr, "Request stored with the overlapped I/O call did not contain a read request.");
if (fileReadInfo.m_sectorAlignedOutput && !encounteredError)
{
auto offsetAddress = reinterpret_cast<u8*>(fileReadInfo.m_sectorAlignedOutput) + fileReadInfo.m_copyBackOffset;
::memcpy(readCommand->m_output, offsetAddress, readCommand->m_size);
}
// The request could be reading more due to alignment requirements. It should however never read less that the amount of
// requested data.
bool isSuccess = !encounteredError && (readCommand->m_size <= numBytesTransferred);
fileReadInfo.m_request->SetStatus(
isCanceled
? IStreamerTypes::RequestStatus::Canceled
: isSuccess
? IStreamerTypes::RequestStatus::Completed
: IStreamerTypes::RequestStatus::Failed
);
m_context->MarkRequestAsCompleted(fileReadInfo.m_request);
m_fileCache_activeReads[status.m_fileHandleIndex]--;
m_readSlots_active[readSlot] = false;
m_context->GetStreamerThreadSynchronizer().DestroyEventHandle(status.m_overlapped.hEvent);
fileReadInfo.Clear();
// There's now a slot available to queue the next request, if there is one.
if (!m_pendingReadRequests.empty())
{
FileRequest* request = m_pendingReadRequests.front();
if (ReadRequest(request, readSlot))
{
m_pendingReadRequests.pop_front();
}
}
}
size_t StorageDriveWin::FindInFileHandleCache(const RequestPath& filePath) const
{
size_t numFiles = m_fileCache_paths.size();
for (size_t i = 0; i < numFiles; ++i)
{
if (m_fileCache_paths[i] == filePath)
{
return i;
}
}
return InvalidFileCacheIndex;
}
size_t StorageDriveWin::FindAvailableFileHandleCacheIndex() const
{
AZ_Assert(m_cachesInitialized, "Using file cache before it has been (lazily) initialized\n");
// This needs to look for files with no active reads, and the oldest file among those.
size_t cacheIndex = InvalidFileCacheIndex;
AZStd::chrono::system_clock::time_point oldest = AZStd::chrono::system_clock::time_point::max();
for (size_t index = 0; index < m_maxFileHandles; ++index)
{
if (m_fileCache_activeReads[index] == 0 && m_fileCache_lastTimeUsed[index] < oldest)
{
oldest = m_fileCache_lastTimeUsed[index];
cacheIndex = index;
}
}
return cacheIndex;
}
size_t StorageDriveWin::FindAvailableReadSlot()
{
for (size_t i = 0; i < m_readSlots_active.size(); ++i)
{
if (!m_readSlots_active[i])
{
return i;
}
}
return InvalidReadSlotIndex;
}
size_t StorageDriveWin::FindInMetaDataCache(const RequestPath& filePath) const
{
size_t numFiles = m_metaDataCache_paths.size();
for (size_t i = 0; i < numFiles; ++i)
{
if (m_metaDataCache_paths[i] == filePath)
{
return i;
}
}
return InvalidMetaDataCacheIndex;
}
size_t StorageDriveWin::GetNextMetaDataCacheSlot()
{
m_metaDataCache_front = (m_metaDataCache_front + 1) & (m_metaDataCache_paths.size() - 1);
return m_metaDataCache_front;
}
bool StorageDriveWin::IsServicedByThisDrive(const char* filePath) const
{
// This approach doesn't allow paths to be resolved to the correct drive when junctions are used or when a drive
// is mapped as folder of another drive. To do this correctly "GetVolumePathName" should be used, but this takes
// about 1 to 1.5 ms per request, so this introduces unacceptably large overhead particularly when the user has
// multiple disks.
for (const AZStd::string& drivePath : m_drivePaths)
{
if (azstrnicmp(filePath, drivePath.c_str(), drivePath.length()) == 0)
{
return true;
}
}
return false;
}
void StorageDriveWin::CollectStatistics(AZStd::vector<Statistic>& statistics) const
{
if (m_cachesInitialized)
{
constexpr double bytesToMB = aznumeric_cast<double>(1_mib);
using DoubleSeconds = AZStd::chrono::duration<double>;
double totalBytesReadMB = m_readSizeAverage.GetTotal() / bytesToMB;
double totalReadTimeSec = AZStd::chrono::duration_cast<DoubleSeconds>(m_readTimeAverage.GetTotal()).count();
statistics.push_back(Statistic::CreateFloat(m_name, "Read Speed (avg. mbps)", totalBytesReadMB / totalReadTimeSec));
statistics.push_back(Statistic::CreateInteger(m_name, "File Open & Close (avg. us)", m_fileOpenCloseTimeAverage.CalculateAverage().count()));
statistics.push_back(Statistic::CreateInteger(m_name, "Get file exists (avg. us)", m_getFileExistsTimeAverage.CalculateAverage().count()));
statistics.push_back(Statistic::CreateInteger(m_name, "Get file meta data (avg. us)", m_getFileMetaDataRetrievalTimeAverage.CalculateAverage().count()));
statistics.push_back(Statistic::CreateInteger(m_name, "Available slots", CalculateNumAvailableSlots()));
#if AZ_STREAMER_ADD_EXTRA_PROFILING_INFO
statistics.push_back(Statistic::CreatePercentage(m_name, FileSwitchesName, m_fileSwitchPercentageStat.GetAverage()));
statistics.push_back(Statistic::CreatePercentage(m_name, SeeksName, m_seekPercentageStat.GetAverage()));
statistics.push_back(Statistic::CreatePercentage(m_name, DirectReadsName, m_directReadsPercentageStat.GetAverage()));
#endif
}
StreamStackEntry::CollectStatistics(statistics);
}
void StorageDriveWin::Report(const Requests::ReportData& data) const
{
switch (data.m_reportType)
{
case Requests::ReportType::FileLocks:
if (m_cachesInitialized)
{
for (u32 i = 0; i < m_maxFileHandles; ++i)
{
if (m_fileCache_handles[i] != INVALID_HANDLE_VALUE)
{
AZ_Printf("Streamer", "File lock in %s : '%s'.\n", m_name.c_str(), m_fileCache_paths[i].GetRelativePath());
}
}
}
else
{
AZ_Printf("Streamer", "File lock in %s : No files have been streamed.\n", m_name.c_str());
}
break;
default:
break;
}
}
} // namespace AZ::IO
|
// $Id$
//
// Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include "Dict.h"
namespace RDKit {
void Dict::getVal(const std::string &what, std::string &res) const {
//
// We're going to try and be somewhat crafty about this getVal stuff to make
// these
// containers a little bit more generic. The normal behavior here is that
// the
// value being queried must be directly castable to type T. We'll robustify
// a
// little bit by trying that and, if the cast fails, attempting a couple of
// other casts, which will then be lexically cast to type T.
//
for (const auto &i : _data) {
if (i.key == what) {
rdvalue_tostring(i.val, res);
return;
}
}
throw KeyErrorException(what);
}
template <>
std::string Dict::getVal<std::string>(const std::string &what) const {
for (auto &data : _data) {
if (data.key == what) {
std::string res;
rdvalue_tostring(data.val, res);
return res;
}
}
throw KeyErrorException(what);
}
bool Dict::getValIfPresent(const std::string &what, std::string &res) const {
//
// We're going to try and be somewhat crafty about this getVal stuff to make
// these
// containers a little bit more generic. The normal behavior here is that
// the
// value being queried must be directly castable to type T. We'll robustify
// a
// little bit by trying that and, if the cast fails, attempting a couple of
// other casts, which will then be lexically cast to type T.
//
for (const auto &i : _data) {
if (i.key == what) {
rdvalue_tostring(i.val, res);
return true;
}
}
return false;
}
} // namespace RDKit
|
// Copyright information and license terms for this software can be
// found in the file LICENSE that is included with the distribution
#include "NtType.h"
const char* NtType::StructureId("epics:nt/NTType:1.0");
NtType::NtType(const boost::python::dict& pyDict, const std::string& structureId)
: PvObject(pyDict, structureId)
{
}
NtType::NtType(const NtType& ntType)
: PvObject(ntType.pvStructurePtr)
{
}
NtType::NtType(const epics::pvData::PVStructurePtr& pvStructurePtr)
: PvObject(pvStructurePtr)
{
}
NtType::~NtType()
{
}
|
//----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2019, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY 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.
//
//----------------------------------------------------------------------------
//
// Representation of an HEVC_video_descriptor
//
//----------------------------------------------------------------------------
#include "tsHEVCVideoDescriptor.h"
#include "tsDescriptor.h"
#include "tsTablesDisplay.h"
#include "tsTablesFactory.h"
#include "tsxmlElement.h"
TSDUCK_SOURCE;
#define MY_XML_NAME u"HEVC_video_descriptor"
#define MY_DID ts::DID_HEVC_VIDEO
#define MY_STD ts::STD_MPEG
TS_XML_DESCRIPTOR_FACTORY(ts::HEVCVideoDescriptor, MY_XML_NAME);
TS_ID_DESCRIPTOR_FACTORY(ts::HEVCVideoDescriptor, ts::EDID::Standard(MY_DID));
TS_ID_DESCRIPTOR_DISPLAY(ts::HEVCVideoDescriptor::DisplayDescriptor, ts::EDID::Standard(MY_DID));
//----------------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------------
ts::HEVCVideoDescriptor::HEVCVideoDescriptor() :
AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0),
profile_space(0),
tier(false),
profile_idc(0),
profile_compatibility_indication(0),
progressive_source(false),
interlaced_source(false),
non_packed_constraint(false),
frame_only_constraint(false),
reserved_zero_44bits(0),
level_idc(0),
HEVC_still_present(false),
HEVC_24hr_picture_present(false),
temporal_id_min(),
temporal_id_max()
{
_is_valid = true;
}
ts::HEVCVideoDescriptor::HEVCVideoDescriptor(DuckContext& duck, const Descriptor& desc) :
HEVCVideoDescriptor()
{
deserialize(duck, desc);
}
//----------------------------------------------------------------------------
// Serialization
//----------------------------------------------------------------------------
void ts::HEVCVideoDescriptor::serialize(DuckContext& duck, Descriptor& desc) const
{
ByteBlockPtr bbp(serializeStart());
bbp->appendUInt8(((profile_space & 0x03) << 6) | (tier ? 0x20 : 0x00) | (profile_idc & 0x1F));
bbp->appendUInt32(profile_compatibility_indication);
bbp->appendUInt16((progressive_source ? 0x8000 : 0x0000) |
(interlaced_source ? 0x4000 : 0x0000) |
(non_packed_constraint ? 0x2000 : 0x0000) |
(frame_only_constraint ? 0x1000 : 0x0000) |
(uint16_t(reserved_zero_44bits >> 32) & 0x0FFF));
bbp->appendUInt32(uint32_t(reserved_zero_44bits));
bbp->appendUInt8(level_idc);
const bool temporal = temporal_id_min.set() && temporal_id_max.set();
bbp->appendUInt8((temporal ? 0x80 : 0x00) | (HEVC_still_present ? 0x40 : 0x00) | (HEVC_24hr_picture_present ? 0x20 : 0x00) | 0x1F);
if (temporal) {
bbp->appendUInt8(0xF8 | (temporal_id_min.value() & 0x07));
bbp->appendUInt8(0xF8 | (temporal_id_max.value() & 0x07));
}
serializeEnd(desc, bbp);
}
//----------------------------------------------------------------------------
// Deserialization
//----------------------------------------------------------------------------
void ts::HEVCVideoDescriptor::deserialize(DuckContext& duck, const Descriptor& desc)
{
_is_valid = desc.isValid() && desc.tag() == _tag && (desc.payloadSize() == 13 || desc.payloadSize() == 15);
if (_is_valid) {
const uint8_t* data = desc.payload();
profile_space = (data[0] >> 6) & 0x03;
tier = (data[0] & 0x20) != 0;
profile_idc = data[0] & 0x1F;
profile_compatibility_indication = GetUInt32(data + 1);
progressive_source = (data[5] & 0x80) != 0;
interlaced_source = (data[5] & 0x40) != 0;
non_packed_constraint = (data[5] & 0x20) != 0;
frame_only_constraint = (data[5] & 0x10) != 0;
reserved_zero_44bits = uint64_t(GetUInt16(data + 5) & 0x0FFF) | GetUInt32(data + 7);
level_idc = data[11];
const bool temporal = (data[12] & 0x80) != 0;
HEVC_still_present = (data[12] & 0x40) != 0;
HEVC_24hr_picture_present = (data[12] & 0x20) != 0;
temporal_id_min.reset();
temporal_id_max.reset();
if (temporal) {
_is_valid = desc.payloadSize() >= 15;
if (_is_valid) {
temporal_id_min = data[13] & 0x07;
temporal_id_max = data[14] & 0x07;
}
}
}
}
//----------------------------------------------------------------------------
// Static method to display a descriptor.
//----------------------------------------------------------------------------
void ts::HEVCVideoDescriptor::DisplayDescriptor(TablesDisplay& display, DID did, const uint8_t* data, size_t size, int indent, TID tid, PDS pds)
{
std::ostream& strm(display.duck().out());
const std::string margin(indent, ' ');
if (size >= 13) {
const int profile_space = (data[0] >> 6) & 0x03;
const bool tier = (data[0] & 0x20) != 0;
const int profile_idc = data[0] & 0x1F;
const uint32_t profile_compatibility_indication = GetUInt32(data + 1);
const bool progressive_source = (data[5] & 0x80) != 0;
const bool interlaced_source = (data[5] & 0x40) != 0;
const bool non_packed_constraint = (data[5] & 0x20) != 0;
const bool frame_only_constraint = (data[5] & 0x10) != 0;
const uint64_t reserved_zero_44bits = uint64_t(GetUInt16(data + 5) & 0x0FFF) | GetUInt32(data + 7);
const int level_idc = data[11];
const bool temporal = (data[12] & 0x80) != 0;
const bool HEVC_still_present = (data[12] & 0x40) != 0;
const bool HEVC_24hr_picture_present = (data[12] & 0x20) != 0;
data += 13; size -= 13;
strm << margin << "Profile space: " << profile_space
<< ", tier: " << UString::TrueFalse(tier)
<< ", profile IDC: " << profile_idc
<< std::endl
<< margin << "Profile compatibility: " << UString::Hexa(profile_compatibility_indication)
<< std::endl
<< margin << "Progressive source: " << UString::TrueFalse(progressive_source)
<< ", interlaced source: " << UString::TrueFalse(interlaced_source)
<< ", non packed: " << UString::TrueFalse(non_packed_constraint)
<< ", frame only: " << UString::TrueFalse(frame_only_constraint)
<< std::endl
<< margin << "Reserved-zero 44 bits: " << UString::Hexa(reserved_zero_44bits, 11)
<< std::endl
<< margin << "Level IDC: " << level_idc
<< ", still pictures: " << UString::TrueFalse(HEVC_still_present)
<< ", 24-hour pictures: " << UString::TrueFalse(HEVC_24hr_picture_present)
<< std::endl;
if (temporal && size >= 2) {
strm << margin << "Temporal id min: " << int(data[0] & 0x07) << ", max: " << int(data[1] & 0x07) << std::endl;
data += 2; size -= 2;
}
}
display.displayExtraData(data, size, indent);
}
//----------------------------------------------------------------------------
// XML serialization
//----------------------------------------------------------------------------
void ts::HEVCVideoDescriptor::buildXML(DuckContext& duck, xml::Element* root) const
{
root->setIntAttribute(u"profile_space", profile_space, true);
root->setBoolAttribute(u"tier_flag", tier);
root->setIntAttribute(u"profile_idc", profile_idc, true);
root->setIntAttribute(u"profile_compatibility_indication", profile_compatibility_indication, true);
root->setBoolAttribute(u"progressive_source_flag", progressive_source);
root->setBoolAttribute(u"interlaced_source_flag", interlaced_source);
root->setBoolAttribute(u"non_packed_constraint_flag", non_packed_constraint);
root->setBoolAttribute(u"frame_only_constraint_flag", frame_only_constraint);
root->setIntAttribute(u"reserved_zero_44bits", reserved_zero_44bits, true);
root->setIntAttribute(u"level_idc", level_idc, true);
root->setBoolAttribute(u"HEVC_still_present_flag", HEVC_still_present);
root->setBoolAttribute(u"HEVC_24hr_picture_present_flag", HEVC_24hr_picture_present);
root->setOptionalIntAttribute(u"temporal_id_min", temporal_id_min, true);
root->setOptionalIntAttribute(u"temporal_id_max", temporal_id_max, true);
}
//----------------------------------------------------------------------------
// XML deserialization
//----------------------------------------------------------------------------
void ts::HEVCVideoDescriptor::fromXML(DuckContext& duck, const xml::Element* element)
{
_is_valid =
checkXMLName(element) &&
element->getIntAttribute<uint8_t>(profile_space, u"profile_space", true, 0, 0x00, 0x03) &&
element->getBoolAttribute(tier, u"tier_flag", true) &&
element->getIntAttribute<uint8_t>(profile_idc, u"profile_idc", true, 0, 0x00, 0x1F) &&
element->getIntAttribute<uint32_t>(profile_compatibility_indication, u"profile_compatibility_indication", true) &&
element->getBoolAttribute(progressive_source, u"progressive_source_flag", true) &&
element->getBoolAttribute(interlaced_source, u"interlaced_source_flag", true) &&
element->getBoolAttribute(non_packed_constraint, u"non_packed_constraint_flag", true) &&
element->getBoolAttribute(frame_only_constraint, u"frame_only_constraint_flag", true) &&
element->getIntAttribute<uint64_t>(reserved_zero_44bits, u"reserved_zero_44bits", true, 0, 0, TS_UCONST64(0x00000FFFFFFFFFFF)) &&
element->getIntAttribute<uint8_t>(level_idc, u"level_idc", true) &&
element->getBoolAttribute(HEVC_still_present, u"HEVC_still_present_flag", true) &&
element->getBoolAttribute(HEVC_24hr_picture_present, u"HEVC_24hr_picture_present_flag", true) &&
element->getOptionalIntAttribute<uint8_t>(temporal_id_min, u"temporal_id_min", 0x00, 0x07) &&
element->getOptionalIntAttribute<uint8_t>(temporal_id_max, u"temporal_id_max", 0x00, 0x07);
if (_is_valid && temporal_id_min.set() + temporal_id_max.set() == 1) {
_is_valid = false;
element->report().error(u"line %d: in <%s>, attributes 'temporal_id_min' and 'temporal_id_max' must be both present or both omitted", {element->lineNumber(), _xml_name});
}
}
|
/*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ivision/model/CreateTagResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ivision;
using namespace AlibabaCloud::Ivision::Model;
CreateTagResult::CreateTagResult() :
ServiceResult()
{}
CreateTagResult::CreateTagResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
CreateTagResult::~CreateTagResult()
{}
void CreateTagResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto tagNode = value["Tag"];
if(!tagNode["ProjectId"].isNull())
tag_.projectId = tagNode["ProjectId"].asString();
if(!tagNode["TagId"].isNull())
tag_.tagId = tagNode["TagId"].asString();
if(!tagNode["TagName"].isNull())
tag_.tagName = tagNode["TagName"].asString();
if(!tagNode["Description"].isNull())
tag_.description = tagNode["Description"].asString();
if(!tagNode["Count"].isNull())
tag_.count = std::stoi(tagNode["Count"].asString());
if(!tagNode["CreationTime"].isNull())
tag_.creationTime = tagNode["CreationTime"].asString();
}
CreateTagResult::Tag CreateTagResult::getTag()const
{
return tag_;
}
|
//
// Created by Aidan on 8/27/2021.
//
// Howdy! This file contains unverified endpoints so they may need touching up.
// Sorry for the mess, I just don't have the time to verify everything by hand,
// especially with the volatile nature of a live service like Discord. If
// something doesn't work come swing by #🔚endpoints on the Discord++ server and
// someone'll help you out! If the endpoints work fine swing by that same
// channel with proof of credit for the @Endpoint Verifier role!
#ifndef OBJECT_BREAKOUTS
#error This header should only be included in plugin-objects.hh
#endif
#include "../field.hh"
class AuditLog {
public:
field<std::vector<AuditLogEntry>> audit_log_entries;
field<std::vector<Integration>> integrations;
field<std::vector<Channel>> threads;
field<std::vector<User>> users;
field<std::vector<Webhook>> webhooks;
NLOHMANN_DEFINE_FIELD_TYPE_INTRUSIVE(AuditLog, {}, {}, audit_log_entries,
integrations, threads, users,
webhooks);
};
class AuditLogEntry {
public:
nullable_field<Snowflake> target_id;
omittable_field<std::vector<AuditLogChange>> changes;
nullable_field<Snowflake> user_id;
field<Snowflake> id;
field<AuditLogEvent> action_type;
omittable_field<OptionalAuditEntryInfo> options;
omittable_field<std::string> reason;
NLOHMANN_DEFINE_FIELD_TYPE_INTRUSIVE(AuditLogEntry, {}, {}, target_id,
changes, user_id, id, action_type,
options, reason);
};
class OptionalAuditEntryInfo {
public:
omittable_field<Snowflake> channel_id;
omittable_field<std::string> count;
omittable_field<std::string> delete_member_days;
omittable_field<Snowflake> id;
omittable_field<std::string> members_removed;
omittable_field<Snowflake> message_id;
omittable_field<std::string> role_name;
field<std::string> type;
NLOHMANN_DEFINE_FIELD_TYPE_INTRUSIVE(OptionalAuditEntryInfo, {}, {},
channel_id, count, delete_member_days,
id, members_removed, message_id,
role_name, type);
};
class AuditLogChange {
public:
omittable_field<json> new_value;
omittable_field<json> old_value;
field<std::string> key;
NLOHMANN_DEFINE_FIELD_TYPE_INTRUSIVE(AuditLogChange, {}, {}, new_value,
old_value, key);
};
|
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "ListViewEngine.hpp"
#include <cassert>
#include <log/log.hpp>
namespace gui
{
ListViewEngine::ListViewEngine(std::shared_ptr<ListItemProvider> prov)
{
setProvider(std::move(prov));
}
ListViewEngine::~ListViewEngine()
{
clear();
}
void ListViewEngine::setElementsCount(unsigned int count)
{
if (elementsCount != count || elementsCount == 0) {
onElementsCountChanged(count);
}
}
void ListViewEngine::setBoundaries(Boundaries value)
{
boundaries = value;
}
void ListViewEngine::setOrientation(listview::Orientation value)
{
orientation = value;
if (orientation == listview::Orientation::TopBottom) {
body->setAlignment(Alignment::Vertical::Top);
}
else {
body->setAlignment(Alignment::Vertical::Bottom);
}
}
void ListViewEngine::setProvider(std::shared_ptr<ListItemProvider> prov)
{
if (prov != nullptr) {
provider = prov;
provider->list = this;
}
}
bool ListViewEngine::isEmpty() const noexcept
{
return elementsCount == 0;
}
void ListViewEngine::rebuildList(listview::RebuildType rebuildType, unsigned int dataOffset, bool forceRebuild)
{
if (pageLoaded || forceRebuild) {
setElementsCount(provider->requestRecordsCount());
setup(rebuildType, dataOffset);
// If deletion operation caused last page to be removed request previous one.
if ((startIndex != 0 && startIndex == elementsCount)) {
requestPreviousPage();
}
else {
provider->requestRecords(startIndex, calculateLimit());
}
}
else {
rebuildRequests.push_front({rebuildType, dataOffset});
}
}
void ListViewEngine::reSendLastRebuildRequest()
{
rebuildList(lastRebuildRequest.first, lastRebuildRequest.second, true);
}
void ListViewEngine::prepareFullRebuild()
{
setStartIndex();
storedFocusIndex = listview::nPos;
}
void ListViewEngine::prepareOnOffsetRebuild(unsigned int dataOffset)
{
if (dataOffset < elementsCount) {
startIndex = dataOffset;
storedFocusIndex = listview::nPos;
}
else {
LOG_ERROR("Requested rebuild on index greater than elements count");
}
}
void ListViewEngine::prepareInPlaceRebuild()
{
if (!body->empty()) {
storedFocusIndex = getFocusItemIndex();
}
}
void ListViewEngine::prepareOnPageElementRebuild(unsigned int dataOffset)
{
startIndex = (dataOffset / calculateMaxItemsOnPage()) * calculateMaxItemsOnPage();
storedFocusIndex = dataOffset % calculateMaxItemsOnPage();
}
void ListViewEngine::setup(listview::RebuildType rebuildType, unsigned int dataOffset)
{
switch (rebuildType) {
case listview::RebuildType::Full:
prepareFullRebuild();
break;
case listview::RebuildType::OnOffset:
prepareOnOffsetRebuild(dataOffset);
break;
case listview::RebuildType::InPlace:
prepareInPlaceRebuild();
break;
case listview::RebuildType::OnPageElement:
prepareOnPageElementRebuild(dataOffset);
break;
}
if (prepareRebuildCallback) {
prepareRebuildCallback();
setElementsCount(provider->requestRecordsCount());
}
lastRebuildRequest = {rebuildType, dataOffset};
body->setReverseOrder(false);
direction = listview::Direction::Bottom;
}
void ListViewEngine::onClose()
{
if (!body->empty()) {
storedFocusIndex = getFocusItemIndex();
}
clear();
}
unsigned int ListViewEngine::getFocusItemIndex()
{
auto index = body->getFocusItemIndex();
if (direction == listview::Direction::Top) {
int position = currentPageSize - 1 - index;
index = std::abs(position);
}
return index;
}
std::shared_ptr<ListItemProvider> ListViewEngine::getProvider()
{
return provider;
}
void ListViewEngine::reset()
{
clear();
setStartIndex();
body->setReverseOrder(false);
direction = listview::Direction::Bottom;
}
void ListViewEngine::clear()
{
body->setFocusItem(nullptr);
while (auto el = body->children.back()) {
if (el->type == ItemType::LIST_ITEM) {
if (!dynamic_cast<ListItem *>(el)->deleteByList) {
body->removeWidget(el);
}
else {
body->erase(el);
}
}
else
body->erase(el);
}
}
void ListViewEngine::refresh()
{
if (provider == nullptr) {
LOG_ERROR("ListView Data provider not exist");
return;
}
clear();
checkEmptyListCallbacks();
addItemsOnPage();
setFocus();
if (updateScrollCallback) {
updateScrollCallback(ListViewScrollUpdateData{startIndex,
currentPageSize,
elementsCount,
provider->getMinimalItemSpaceRequired(),
direction,
boundaries});
}
if (resizeScrollCallback) {
resizeScrollCallback();
}
pageLoaded = true;
// Check if there were queued rebuild Requests - if so rebuild list again.
if (!rebuildRequests.empty()) {
auto request = rebuildRequests.back();
rebuildRequests.pop_back();
rebuildList(request.first, request.second);
}
fillFirstPage();
}
void ListViewEngine::onProviderDataUpdate()
{
if (!renderFullList()) {
return;
}
refresh();
}
Order ListViewEngine::getOrderFromDirection() const noexcept
{
if (direction == listview::Direction::Bottom)
return Order::Next;
return Order::Previous;
}
Order ListViewEngine::getOppositeOrderFromDirection() const noexcept
{
if (direction == listview::Direction::Bottom)
return Order::Previous;
return Order::Next;
}
void ListViewEngine::setStartIndex()
{
if (orientation == listview::Orientation::TopBottom) {
startIndex = 0;
}
else {
startIndex = elementsCount;
}
}
void ListViewEngine::recalculateStartIndex()
{
if (direction == listview::Direction::Top) {
startIndex = startIndex < currentPageSize ? 0 : startIndex - currentPageSize;
}
}
void ListViewEngine::fillFirstPage()
{
// Check if first page is filled with items. If not reload page to be filled with items. Check for both
// Orientations.
if (orientation == listview::Orientation::TopBottom && direction == listview::Direction::Top &&
startIndex == 0) {
if (body->getPrimarySizeLeft() >= provider->getMinimalItemSpaceRequired()) {
focusOnLastItem = true;
if (checkFullRenderRequirementCallback) {
checkFullRenderRequirementCallback();
}
rebuildList();
}
}
if (orientation == listview::Orientation::BottomTop && direction == listview::Direction::Bottom &&
startIndex + currentPageSize == elementsCount) {
if (body->getPrimarySizeLeft() >= provider->getMinimalItemSpaceRequired()) {
focusOnLastItem = true;
if (checkFullRenderRequirementCallback) {
checkFullRenderRequirementCallback();
}
rebuildList();
}
}
}
void ListViewEngine::addItemsOnPage()
{
currentPageSize = 0;
ListItem *item = nullptr;
while ((item = provider->getItem(getOrderFromDirection())) != nullptr) {
body->addWidget(item);
if (!item->visible) {
// In case model is tracking internal indexes -> undo last get.
if (requestFullListRender) {
provider->getItem(getOppositeOrderFromDirection());
}
break;
}
currentPageSize++;
}
recalculateStartIndex();
}
bool ListViewEngine::renderFullList()
{
if (!requestFullListRender) {
return true;
}
if (elementsCount != 0 && !requestCompleteData) {
requestCompleteData = true;
provider->requestRecords(0, elementsCount);
return false;
}
if (requestCompleteData) {
unsigned int page = 0;
auto pageStartIndex = 0;
clear();
while (true) {
addItemsOnPage();
if (currentPageSize == 0) {
break;
}
if (currentPageSize + pageStartIndex == elementsCount) {
break;
}
page += 1;
pageStartIndex += currentPageSize;
clear();
}
clear();
requestCompleteData = false;
requestFullListRender = false;
if (lastRebuildRequest.first == listview::RebuildType::Full) {
if (orientation == listview::Orientation::TopBottom) {
if (setupScrollCallback) {
setupScrollCallback(ListViewScrollSetupData{startIndex, 0, (page + 1)});
}
}
else {
if (setupScrollCallback) {
setupScrollCallback(ListViewScrollSetupData{startIndex, page, (page + 1)});
}
}
}
reSendLastRebuildRequest();
return false;
}
return true;
} // namespace gui
void ListViewEngine::setFocus()
{
if (storedFocusIndex != listview::nPos) {
if (!body->setFocusOnElement(storedFocusIndex)) {
body->setFocusOnLastElement();
}
}
if (focusOnLastItem) {
body->setFocusOnLastElement();
focusOnLastItem = false;
}
}
void ListViewEngine::onElementsCountChanged(unsigned int count)
{
if (elementsCount == 0 || count == 0) {
shouldCallEmptyListCallbacks = true;
}
elementsCount = count;
if (checkFullRenderRequirementCallback) {
checkFullRenderRequirementCallback();
}
}
void ListViewEngine::checkEmptyListCallbacks()
{
if (shouldCallEmptyListCallbacks) {
if (isEmpty()) {
if (emptyListCallback) {
emptyListCallback();
}
}
else if (notEmptyListCallback) {
notEmptyListCallback();
}
shouldCallEmptyListCallbacks = false;
}
}
void ListViewEngine::recalculateOnBoxRequestedResize()
{
if (currentPageSize != body->getVisibleChildrenCount()) {
unsigned int diff = currentPageSize < body->getVisibleChildrenCount()
? 0
: currentPageSize - body->getVisibleChildrenCount();
currentPageSize = body->getVisibleChildrenCount();
if (direction == listview::Direction::Top) {
startIndex += diff;
}
else {
startIndex = startIndex < diff ? 0 : startIndex - diff;
}
if (checkFullRenderRequirementCallback) {
checkFullRenderRequirementCallback();
}
rebuildList();
}
}
unsigned int ListViewEngine::calculateMaxItemsOnPage()
{
assert(provider->getMinimalItemSpaceRequired() != 0);
auto count = body->getPrimarySize() / provider->getMinimalItemSpaceRequired();
return count;
}
unsigned int ListViewEngine::calculateLimit(listview::Direction value)
{
auto minLimit =
(2 * currentPageSize > calculateMaxItemsOnPage() ? 2 * currentPageSize : calculateMaxItemsOnPage());
if (value == listview::Direction::Bottom) {
return (minLimit + startIndex <= elementsCount ? minLimit : elementsCount - startIndex);
}
else {
return minLimit < startIndex ? minLimit : startIndex;
}
}
bool ListViewEngine::requestNextPage()
{
if (startIndex + currentPageSize >= elementsCount && boundaries == Boundaries::Continuous) {
startIndex = 0;
}
else if (startIndex + currentPageSize >= elementsCount && boundaries == Boundaries::Fixed) {
return false;
}
else {
startIndex = startIndex <= elementsCount - currentPageSize ? startIndex + currentPageSize
: elementsCount - (elementsCount - startIndex);
}
direction = listview::Direction::Bottom;
body->setReverseOrder(false);
pageLoaded = false;
storedFocusIndex = listview::nPos;
provider->requestRecords(startIndex, calculateLimit());
return true;
}
bool ListViewEngine::requestPreviousPage()
{
auto topFetchIndex = 0;
auto limit = 0;
if (startIndex == 0 && boundaries == Boundaries::Continuous) {
startIndex = elementsCount;
if (elementsCount > currentPageSize && fetchType == listview::FetchType::Fixed) {
auto calculateFixedFill =
elementsCount % currentPageSize != 0 ? elementsCount % currentPageSize : currentPageSize;
topFetchIndex = elementsCount - calculateFixedFill;
}
else {
topFetchIndex = elementsCount - calculateLimit(listview::Direction::Top);
}
limit = calculateLimit(listview::Direction::Top);
}
else if (startIndex == 0 && boundaries == Boundaries::Fixed) {
return false;
}
else {
limit = calculateLimit(listview::Direction::Top);
topFetchIndex = startIndex < calculateLimit(listview::Direction::Top)
? 0
: startIndex - calculateLimit(listview::Direction::Top);
}
direction = listview::Direction::Top;
body->setReverseOrder(true);
pageLoaded = false;
storedFocusIndex = listview::nPos;
provider->requestRecords(topFetchIndex, limit);
return true;
}
} /* namespace gui */
|
#include "power.hpp"
#include "stm32h7xx_hal.h"
#include "32blit.h"
#include "32blit_battery.hpp"
#include "i2c.h"
#include "i2c-bq24295.h"
namespace power {
// power state we're changing to
enum class Target {
IDLE,
SLEEP,
OFF
};
static uint32_t last_input_time = 0, sleep_fade_start = 0;
float sleep_fade = 1.0f;
const int sleep_inactivity_time = 120000; // ms before sleeping
const int fade_out_time = 1000, auto_sleep_fade_out_time = 3000, fade_in_time = 500;
static Target target = Target::IDLE;
void update() {
if(target == Target::IDLE) {
// inactivity timeout
if(HAL_GetTick() - last_input_time > sleep_inactivity_time) {
target = Target::SLEEP;
sleep_fade_start = HAL_GetTick();
}
} else if(target == Target::OFF && sleep_fade == 0.0f) {
// fade to off complete
// TODO: disable almost everything (need HOME button interrupt, battery status, etc.)
// we're not charging, enter shipping mode to save battery
// (and shut down entirely if not connected to USB)
auto charge_status = battery::get_charge_status();
if(charge_status == battery::BatteryChargeStatus::NotCharging || charge_status == battery::BatteryChargeStatus::ChargingComplete)
bq24295_enable_shipping_mode(&hi2c4);
}
if(target != Target::IDLE) {
// fade out (slower for auto-sleep)
auto fade_time = target == Target::SLEEP ? auto_sleep_fade_out_time : fade_out_time;
sleep_fade = std::max(0.0f, 1.0f - float(HAL_GetTick() - sleep_fade_start) / fade_time);
blit_update_volume();
} else if(sleep_fade < 1.0f) {
// fade in
sleep_fade = std::min(1.0f, float(HAL_GetTick() - sleep_fade_start) / fade_in_time);
blit_update_volume();
}
}
void update_active() {
// fading out or done fading, fade back in
if(target == Target::SLEEP) {
target = Target::IDLE;
sleep_fade_start = HAL_GetTick() - sleep_fade * fade_in_time;
}
last_input_time = HAL_GetTick();
}
void power_off() {
target = Target::OFF;
sleep_fade_start = HAL_GetTick();
}
bool is_off() {
return target == Target::OFF && sleep_fade == 0.0f;
}
}
|
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2020.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#include <OpenMS/DATASTRUCTURES/Adduct.h>
#include <OpenMS/DATASTRUCTURES/Compomer.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <iostream>
using namespace std;
namespace OpenMS
{
/// Default Constructor
Compomer::Compomer() :
cmp_(2),
net_charge_(0),
mass_(0),
pos_charges_(0),
neg_charges_(0),
log_p_(0),
rt_shift_(0),
id_(0)
{
}
/// Constructor with net-charge and mass
Compomer::Compomer(Int net_charge, double mass, double log_p) :
cmp_(2),
net_charge_(net_charge),
mass_(mass),
pos_charges_(0),
neg_charges_(0),
log_p_(log_p),
rt_shift_(0),
id_(0)
{
}
/// Copy C'tor
Compomer::Compomer(const Compomer& p) :
cmp_(p.cmp_),
net_charge_(p.net_charge_),
mass_(p.mass_),
pos_charges_(p.pos_charges_),
neg_charges_(p.neg_charges_),
log_p_(p.log_p_),
rt_shift_(p.rt_shift_),
id_(p.id_)
{
}
/// Assignment Operator
Compomer& Compomer::operator=(const Compomer& source)
{
if (&source == this)
return *this;
cmp_ = source.cmp_;
net_charge_ = source.net_charge_;
mass_ = source.mass_;
pos_charges_ = source.pos_charges_;
neg_charges_ = source.neg_charges_;
log_p_ = source.log_p_;
rt_shift_ = source.rt_shift_;
id_ = source.id_;
return *this;
}
/// Add a.amount of Adduct @param a to Compomer's @param side and update its properties
void Compomer::add(const Adduct& a, UInt side)
{
if (side >= BOTH)
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::add() does not support this value for 'side'!", String(side));
if (a.getAmount() < 0)
{
std::cerr << "Compomer::add() was given adduct with negative amount! Are you sure this is what you want?!\n";
}
//if (a.getCharge() < 0)
//{
// std::cerr << "Compomer::add() was given adduct with negative charge! Are you sure this is what you want?!\n";
//}
if (cmp_[side].count(a.getFormula()) == 0)
{
cmp_[side][a.getFormula()] = a;
}
else
{
cmp_[side][a.getFormula()] += a; //update adducts amount
}
int mult[] = {-1, 1};
net_charge_ += a.getAmount() * a.getCharge() * mult[side];
mass_ += a.getAmount() * a.getSingleMass() * mult[side];
pos_charges_ += std::max(a.getAmount() * a.getCharge() * mult[side], 0);
neg_charges_ -= std::min(a.getAmount() * a.getCharge() * mult[side], 0);
log_p_ += std::fabs((float)a.getAmount()) * a.getLogProb();
rt_shift_ += a.getAmount() * a.getRTShift() * mult[side];
}
/**
* indicates if these two compomers can coexist for one feature
* @param cmp The other Compomer we compare to
* @param side_this Indicates which "side"(negative or positive adducts) we are looking at. Negative adducts belong to the left side of the ChargePair.
* @param side_other See above.
*/
bool Compomer::isConflicting(const Compomer& cmp, UInt side_this, UInt side_other) const
{
if (side_this >= BOTH)
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::isConflicting() does not support this value for 'side_this'!", String(side_this));
if (side_other >= BOTH)
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::isConflicting() does not support this value for 'side_other'!", String(side_other));
bool conflict_found = false;
// size is equal - we need to check more thorough...
if (cmp_[side_this].size() == cmp.getComponent()[side_other].size())
{
for (CompomerSide::const_iterator it = cmp_[side_this].begin(); it != cmp_[side_this].end(); ++it)
{
// is it there at all?! if yes: has it the same amount?!
CompomerSide::const_iterator it2 = cmp.getComponent()[side_other].find(it->first);
if (it2 == cmp.getComponent()[side_other].end() || it2->second.getAmount() != it->second.getAmount())
{
conflict_found = true;
break;
}
}
}
else
conflict_found = true;
//
// if (conflict_found) std::cout << "found conflict!! between \n" << (*this) << "and\n" << cmp << " at sides i:" << (left_this?"left":"right") << " and j:" << (left_other?"left":"right") << "\n"
// << "with implicits i:" << implicit_this.getAmount() << " && j: " << implicit_other.getAmount() << "\n";
return conflict_found;
}
/// set an Id which allows unique identification of a compomer
void Compomer::setID(const Size& id)
{
id_ = id;
}
/// return Id which allows unique identification of this compomer
const Size& Compomer::getID() const
{
return id_;
}
const Compomer::CompomerComponents& Compomer::getComponent() const
{
return cmp_;
}
/// net charge of compomer (i.e. difference between left and right side of compomer)
const Int& Compomer::getNetCharge() const
{
return net_charge_;
}
/// mass of all contained adducts
const double& Compomer::getMass() const
{
return mass_;
}
/// summed positive charges of contained adducts
const Int& Compomer::getPositiveCharges() const
{
return pos_charges_;
}
/// summed negative charges of contained adducts
const Int& Compomer::getNegativeCharges() const
{
return neg_charges_;
}
/// return log probability
const double& Compomer::getLogP() const
{
return log_p_;
}
/// return RT shift induced by this compomer
const double& Compomer::getRTShift() const
{
return rt_shift_;
}
String Compomer::getAdductsAsString() const
{
return "(" + getAdductsAsString(LEFT) + ") --> (" + getAdductsAsString(RIGHT) + ")";
}
String Compomer::getAdductsAsString(UInt side) const
{
if (side >= BOTH)
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::getAdductsAsString() does not support this value for 'side'!", String(side));
String r;
CompomerSide::const_iterator it = cmp_[side].begin();
for (; it != cmp_[side].end(); ++it)
{
Int f = it->second.getAmount();
if (it->first.has('+'))
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "An Adduct contains implicit charge. This is not allowed!", it->first);
EmpiricalFormula ef(it->first);
ef = ef * f;
r += ef.toString();
}
return r;
}
bool Compomer::isSingleAdduct(Adduct& a, const UInt side) const
{
if (side >= BOTH)
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::isSimpleAdduct() does not support this value for 'side'!", String(side));
if (cmp_[side].size() != 1)
return false;
if (cmp_[side].count(a.getFormula()) == 0)
return false;
return true;
}
Compomer Compomer::removeAdduct(const Adduct& a) const
{
Compomer tmp = removeAdduct(a, LEFT);
tmp = tmp.removeAdduct(a, RIGHT);
return tmp;
}
Compomer Compomer::removeAdduct(const Adduct& a, const UInt side) const
{
if (side >= BOTH)
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::removeAdduct() does not support this value for 'side'!", String(side));
Compomer tmp(*this);
if (tmp.cmp_[side].count(a.getFormula()) > 0)
{
{ // how many instances does this side contain?
Int amount = tmp.cmp_[side][a.getFormula()].getAmount();
int mult[] = {-1, 1};
//const Adduct &to_remove = tmp.cmp_[side][a.getFormula()];
tmp.net_charge_ -= amount * a.getCharge() * mult[side];
tmp.mass_ -= amount * a.getSingleMass() * mult[side];
tmp.pos_charges_ -= std::max(amount * a.getCharge() * mult[side], 0);
tmp.neg_charges_ -= -std::min(amount * a.getCharge() * mult[side], 0);
tmp.log_p_ -= std::fabs((float)amount) * a.getLogProb();
tmp.rt_shift_ -= amount * a.getRTShift() * mult[side];
}
// remove entry from map
tmp.cmp_[side].erase(a.getFormula());
}
return tmp;
}
StringList Compomer::getLabels(const UInt side) const
{
if (side >= BOTH)
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::getLabels() does not support this value for 'side'!", String(side));
StringList tmp;
for (CompomerSide::const_iterator it = this->cmp_[side].begin(); it != this->cmp_[side].end(); ++it)
{
if (it->second.getLabel() != "")
{
tmp.push_back(it->second.getLabel());
}
}
return tmp;
}
/// Adds @p add_side to this compomer.
void Compomer::add(const CompomerSide& add_side, UInt side)
{
for (CompomerSide::const_iterator it = add_side.begin(); it != add_side.end(); ++it)
{
this->add(it->second, side);
}
}
/// Sort compomer by (in order of importance): net-charge, mass, probability
OPENMS_DLLAPI bool operator<(const Compomer& c1, const Compomer& c2)
{
// how to sort Compomers:
// first by net_charge
if (c1.net_charge_ < c2.net_charge_)
return true;
else if (c1.net_charge_ > c2.net_charge_)
return false;
else
{
// then my mass
if (c1.mass_ < c2.mass_)
return true;
else if (c1.mass_ > c2.mass_)
return false;
else
{
// then by log probability (most probable compomers first!)
return c1.log_p_ > c2.log_p_;
}
}
}
/// Print the contents of a Compomer to a stream.
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Compomer& cmp)
{
os << "Compomer: ";
os << "Da " << cmp.mass_ << "; q_net " << cmp.net_charge_ << "; logP " << cmp.log_p_ << "[[ ";
os << cmp.getAdductsAsString();
os << " ]]\n";
return os;
}
bool operator==(const Compomer& a, const Compomer& b)
{
return a.cmp_ == b.cmp_
&& a.net_charge_ == b.net_charge_
&& a.mass_ == b.mass_
&& a.pos_charges_ == b.pos_charges_
&& a.neg_charges_ == b.neg_charges_
&& a.log_p_ == b.log_p_
&& a.id_ == b.id_;
}
}
|
/*
Copyright 2017 Nanoleaf Ltd.
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 "AuroraPlugin.h"
#include "LayoutProcessingUtils.h"
#include "ColorUtils.h"
#include "DataManager.h"
#include "PluginFeatures.h"
#include "Logger.h"
#include <stdio.h>
#include <limits.h>
#include "AveragingFilter.h"
#ifdef __cplusplus
extern "C" {
#endif
void initPlugin();
void getPluginFrame(Frame_t* frames, int* nFrames, int* sleepTime);
void pluginCleanup();
#ifdef __cplusplus
}
#endif
LayoutData* layoutData;
FrameSlice_t* frameSlices = NULL;
int nFrameSlices = 0;
AveragingFilter af;
static int currentAuroraRotation = 0;
RGB_t * colorPalette = NULL;
int nColors = 0;
RGB_t barColor;
int colorIndex = 1;
RGB_t baseColor;
int findMaxExpanse(){
int maxDegrees = 0;
//grab the layout data, this function returns a pointer to a statically allocated buffer. Safe to call as many time as required.
//Dont delete this pointer. The memory is managed automatically.
layoutData = getLayoutData();
int maxExpanse = INT_MIN;
int d;
//cycle through 0-360 degrees at multiples of 30 degrees
for (d = 0; d < 360/30; d++){
//for every rotation, find the expanse, and hunt for the maximum
int maxX = INT_MIN, minX = INT_MAX;
for (int i = 0; i < layoutData->nPanels; i++){
if (maxX < layoutData->panels[i].shape->getCentroid().x){
maxX = (int)layoutData->panels[i].shape->getCentroid().x;
}
if (minX > layoutData->panels[i].shape->getCentroid().x){
minX = (int)layoutData->panels[i].shape->getCentroid().x;
}
}
if (maxExpanse < (maxX - minX)){
maxExpanse = (maxX - minX);
maxDegrees = d*30;
}
int angleToRotateBy = 30;
rotateAuroraPanels(layoutData, &angleToRotateBy);
printf ("Max expanse : %d\n", maxExpanse);
printf ("d %d\n", d);
}
//turn the layout back to the maDegrees
int angleToRotateBack = maxDegrees - d;
rotateAuroraPanels(layoutData, &angleToRotateBack);
return maxDegrees;
}
/**
* @description: Initialize the plugin. Called once, when the plugin is loaded.
* This function can be used to enable rhythm or advanced features,
* e.g., to enable energy feature, simply call enableEnergy()
* It can also be used to load the LayoutData and the colorPalette from the DataManager.
* Any allocation, if done here, should be deallocated in the plugin cleanup function
*
*/
void initPlugin(){
//do allocation here
//rotate the layout so that right to left have the maximum number of frame slices
currentAuroraRotation = findMaxExpanse();
printf ("max expanse found at angle %d", currentAuroraRotation);
//quantizes the layout into frameslices. See SDK documentation for more information
getFrameSlicesFromLayoutForTriangle(layoutData, &frameSlices, &nFrameSlices, currentAuroraRotation);
getColorPalette(&colorPalette, &nColors);
if (nColors == 0){
barColor = {255, 255, 255};
baseColor = {0, 0, 0};
}
else if (nColors == 1){
barColor = colorPalette[0];
baseColor = {0, 0, 0};
}
else if (nColors >= 2){
baseColor = colorPalette[0];
barColor = colorPalette[1];
}
enableEnergy();
}
/**
* @description: this the 'main' function that gives a frame to the Aurora to display onto the panels
* To obtain updated values of enabled features, simply call get<feature_name>, e.g.,
* getEnergy(), getIsBeat().
*
* If the plugin is a sound visualization plugin, the sleepTime variable will be NULL and is not required to be
* filled in
* This function, if is an effects plugin, can specify the interval it is to be called at through the sleepTime variable
* if its a sound visualization plugin, this function is called at an interval of 50ms or more.
*
* @param frames: a pre-allocated buffer of the Frame_t structure to fill up with RGB values to show on panels.
* Maximum size of this buffer is equal to the number of panels
* @param nFrames: fill with the number of frames in frames
* @param sleepTime: specify interval after which this function is called again, NULL if sound visualization plugin
*/
void getPluginFrame(Frame_t* frames, int* nFrames, int* sleepTime){
// static int rotationCounter = 0;
// if (rotationCounter == 100){
// int angle = 30; //the angle to rotate the layout by
// rotateAuroraPanels(layoutData, &angle);
// currentAuroraRotation += angle; //update the currentAuroraRotation by the new angle
// //call getFrameSlicesFromLayoutForTriangle to get the new frameSlices as per the new layout
// //always call freeFrameSlices before calling getFrameSlicesFromLayoutForTriangle. (safe to call with NULL pointer
// //getFrameSlicesFromLayoutForTriangle allocates memory, and hence is important to ensure that the memory allocated from a previous call is properly deallocated
// //to ensure no memory leaks occur
// freeFrameSlices(frameSlices);
// getFrameSlicesFromLayoutForTriangle(layoutData, &frameSlices, &nFrameSlices, currentAuroraRotation);
// rotationCounter = 0;
// currentAuroraRotation = currentAuroraRotation % 360;
// }
//// rotationCounter++;
#define SKIP_COUNT 1
// a tiny block of code that allows the developer to skips calls of this function.
//if this plugin wishes to run only every 150ms for instance, the skip count would be set to 2
static int cnt = 0;
if (cnt < SKIP_COUNT){
cnt++;
return;
}
cnt = 0;
if (nColors >= 2) {
static int barColorTimer = 0;
static const int barColorTimerThresh = 30*1000/100;
if (barColorTimer >= barColorTimerThresh){
if (colorIndex >= nColors){
colorIndex = 1;
}
barColor = colorPalette[colorIndex++];
barColorTimer = 0;
}
barColorTimer++;
}
static const int32_t maxBarLength = 100;
static int32_t barMarker = 0;
static const int barMarkerInertialRelaxationStep = 45.0;
int frameIndex = 0;
uint16_t energy = getEnergy();
af.feedFilter(energy);
double avgEnergy = af.getAverage();
static double maxEnergy = energy;
if (avgEnergy > maxEnergy){
maxEnergy = maxEnergy / 0.8;
}
else{
maxEnergy = maxEnergy * 0.8;
}
if (maxEnergy < 512){ maxEnergy = 512;}
int32_t barLength = (energy * maxBarLength) / (2*maxEnergy);
RGB_t netColor;
if (barLength > barMarker){
barMarker = barLength;
}
//map the length of the soundbar to the Aurora Layout. In this case,
//calculate the number of frames that are affected from the total number of frame slices
int nFramesAffected = (barMarker*nFrameSlices)/maxBarLength;
if (nFramesAffected > nFrameSlices){
nFramesAffected = nFrameSlices;
}
int x_start = 450;
int x = x_start;
int x_step = (nFramesAffected == 0) ? 0 : x_start/nFramesAffected;
for (int i = 0; i < nFramesAffected; i++){
x = x - x_step;
int x_t = (x > 255) ? 255 : x;
//the net color is a mix between a weighted base color and bar color.
//As the frameSlices moves towards the end of the bar, the effect of the bar color decreases
//and the base color becomes stronger and stronger.
//In other words the bar color fades into the base color
netColor = (((barColor*x_t)/255) + ((baseColor*(255-x_t)))/255);
netColor = limitRGB(netColor, 255, 0);
for (unsigned int j = 0; j < frameSlices[i].panelIds.size(); j++){
frames[frameIndex].panelId = frameSlices[i].panelIds[j];
frames[frameIndex].r = netColor.R;
frames[frameIndex].g = netColor.G;
frames[frameIndex].b = netColor.B;
frames[frameIndex].transTime = 1;
frameIndex++;
}
}
for (int i = nFramesAffected; i < nFrameSlices; i++){
for (unsigned int j = 0; j < frameSlices[i].panelIds.size(); j++){
frames[frameIndex].panelId = frameSlices[i].panelIds[j];
frames[frameIndex].r = baseColor.R;
frames[frameIndex].g = baseColor.G;
frames[frameIndex].b = baseColor.B;
frames[frameIndex].transTime = 1;
frameIndex++;
}
}
if (barMarker > 0){
//the soundbar relaxes to 0 slowly, instead of jumping to the level of the sound immediately.
//gives a more 'organic' effect.
barMarker -= barMarkerInertialRelaxationStep;
if (barMarker < 0){
barMarker = 0;
}
}
*nFrames = frameIndex;
}
/**
* @description: called once when the plugin is being closed.
* Do all deallocation for memory allocated in initplugin here
*/
void pluginCleanup(){
//do deallocation here
freeFrameSlices(frameSlices);
}
|
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Kokkos is licensed under 3-clause BSD terms of use:
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
#define KOKKOS_IMPL_COMPILING_LIBRARY true
#include<Kokkos_Core.hpp>
namespace Kokkos {
namespace Impl {
KOKKOS_IMPL_VIEWCOPY_ETI_INST(double********,LayoutStride,LayoutRight, Serial,int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(double********,LayoutStride,LayoutLeft, Serial,int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(double********,LayoutStride,LayoutStride,Serial,int)
KOKKOS_IMPL_VIEWFILL_ETI_INST(double********,LayoutStride,Serial,int)
}
}
|
#pragma once
#include <algorithm>
#include <math.h>
#include "grid.hpp"
#include "data_column.hpp"
inline void minmod(dataColumn &c, double dxi) {
/*
* Obtain the left and right hand states from linear extrapolation
* and apply the minmod limiter.
*/
int var;
int i;
double a;
double b;
double dxi_inv = 1.0/dxi;
double dxi_half = 0.5*dxi;
double m[c.nx_tot-1+c.gz];
for (var = 0; var < c.nvar; var++) {
for (i = c.beg; i < c.end-1; i++) {
a = (c.V[var][i+1] - c.V[var][i])*dxi_inv;
b = (c.V[var][i+2] - c.V[var][i+1])*dxi_inv;
if (a*b < 0.0) {
m[i] = 0.0;
}
else if (fabs(a) < fabs(b)) {
m[i] = a;
}
else{
m[i] = b;
}
}
for (i = c.beg; i < c.end-1; i++) {
c.VL[var][i] = c.V[var][i+1] + m[i]*dxi_half;
c.VR[var][i] = c.V[var][i+2] - m[i+1]*dxi_half;
}
}
return;
}
|
#include <hxcpp.h>
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_StringTools
#include <StringTools.h>
#endif
#ifndef INCLUDED_haxe_Exception
#include <haxe/Exception.h>
#endif
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
#ifndef INCLUDED_haxe_ds_StringMap
#include <haxe/ds/StringMap.h>
#endif
#ifndef INCLUDED_lime_graphics_Image
#include <lime/graphics/Image.h>
#endif
#ifndef INCLUDED_lime_media_AudioBuffer
#include <lime/media/AudioBuffer.h>
#endif
#ifndef INCLUDED_lime_utils_AssetCache
#include <lime/utils/AssetCache.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_77dd7e775494cb08_14_new,"lime.utils.AssetCache","new",0x205507da,"lime.utils.AssetCache.new","lime/utils/AssetCache.hx",14,0xcfac28d4)
HX_LOCAL_STACK_FRAME(_hx_pos_77dd7e775494cb08_38_exists,"lime.utils.AssetCache","exists",0x81df4ea2,"lime.utils.AssetCache.exists","lime/utils/AssetCache.hx",38,0xcfac28d4)
HX_LOCAL_STACK_FRAME(_hx_pos_77dd7e775494cb08_59_set,"lime.utils.AssetCache","set",0x2058d31c,"lime.utils.AssetCache.set","lime/utils/AssetCache.hx",59,0xcfac28d4)
HX_LOCAL_STACK_FRAME(_hx_pos_77dd7e775494cb08_81_clear,"lime.utils.AssetCache","clear",0x54b4fb87,"lime.utils.AssetCache.clear","lime/utils/AssetCache.hx",81,0xcfac28d4)
namespace lime{
namespace utils{
void AssetCache_obj::__construct(){
HX_GC_STACKFRAME(&_hx_pos_77dd7e775494cb08_14_new)
HXLINE( 17) this->enabled = true;
HXLINE( 24) this->audio = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 25) this->font = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 26) this->image = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 33) this->version = 382134;
}
Dynamic AssetCache_obj::__CreateEmpty() { return new AssetCache_obj; }
void *AssetCache_obj::_hx_vtable = 0;
Dynamic AssetCache_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< AssetCache_obj > _hx_result = new AssetCache_obj();
_hx_result->__construct();
return _hx_result;
}
bool AssetCache_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x218de06a;
}
bool AssetCache_obj::exists(::String id,::String type){
HX_STACKFRAME(&_hx_pos_77dd7e775494cb08_38_exists)
HXLINE( 39) bool _hx_tmp;
HXDLIN( 39) if ((type != HX_("IMAGE",3b,57,57,3b))) {
HXLINE( 39) _hx_tmp = ::hx::IsNull( type );
}
else {
HXLINE( 39) _hx_tmp = true;
}
HXDLIN( 39) if (_hx_tmp) {
HXLINE( 41) if (this->image->exists(id)) {
HXLINE( 41) return true;
}
}
HXLINE( 44) bool _hx_tmp1;
HXDLIN( 44) if ((type != HX_("FONT",cf,25,81,2e))) {
HXLINE( 44) _hx_tmp1 = ::hx::IsNull( type );
}
else {
HXLINE( 44) _hx_tmp1 = true;
}
HXDLIN( 44) if (_hx_tmp1) {
HXLINE( 46) if (this->font->exists(id)) {
HXLINE( 46) return true;
}
}
HXLINE( 49) bool _hx_tmp2;
HXDLIN( 49) bool _hx_tmp3;
HXDLIN( 49) if ((type != HX_("SOUND",af,c4,ba,fe))) {
HXLINE( 49) _hx_tmp3 = (type == HX_("MUSIC",85,08,49,8e));
}
else {
HXLINE( 49) _hx_tmp3 = true;
}
HXDLIN( 49) if (!(_hx_tmp3)) {
HXLINE( 49) _hx_tmp2 = ::hx::IsNull( type );
}
else {
HXLINE( 49) _hx_tmp2 = true;
}
HXDLIN( 49) if (_hx_tmp2) {
HXLINE( 51) if (this->audio->exists(id)) {
HXLINE( 51) return true;
}
}
HXLINE( 54) return false;
}
HX_DEFINE_DYNAMIC_FUNC2(AssetCache_obj,exists,return )
void AssetCache_obj::set(::String id,::String type, ::Dynamic asset){
HX_STACKFRAME(&_hx_pos_77dd7e775494cb08_59_set)
HXDLIN( 59) ::String _hx_switch_0 = type;
if ( (_hx_switch_0==HX_("FONT",cf,25,81,2e)) ){
HXLINE( 62) this->font->set(id,asset);
HXDLIN( 62) goto _hx_goto_2;
}
if ( (_hx_switch_0==HX_("IMAGE",3b,57,57,3b)) ){
HXLINE( 65) if (!(::Std_obj::isOfType(asset,::hx::ClassOf< ::lime::graphics::Image >()))) {
HXLINE( 65) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(((HX_("Cannot cache non-Image asset: ",d6,62,c2,3a) + ::Std_obj::string(asset)) + HX_(" as Image",ad,d1,70,d4))));
}
HXLINE( 67) this->image->set(id,( ( ::lime::graphics::Image)(asset) ));
HXLINE( 64) goto _hx_goto_2;
}
if ( (_hx_switch_0==HX_("MUSIC",85,08,49,8e)) || (_hx_switch_0==HX_("SOUND",af,c4,ba,fe)) ){
HXLINE( 70) if (!(::Std_obj::isOfType(asset,::hx::ClassOf< ::lime::media::AudioBuffer >()))) {
HXLINE( 70) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(((HX_("Cannot cache non-AudioBuffer asset: ",b1,96,a5,01) + ::Std_obj::string(asset)) + HX_(" as AudioBuffer",48,2a,fe,73))));
}
HXLINE( 72) this->audio->set(id,( ( ::lime::media::AudioBuffer)(asset) ));
HXLINE( 69) goto _hx_goto_2;
}
/* default */{
HXLINE( 75) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown((type + HX_(" assets are not cachable",f3,2d,ee,fa))));
}
_hx_goto_2:;
}
HX_DEFINE_DYNAMIC_FUNC3(AssetCache_obj,set,(void))
void AssetCache_obj::clear(::String prefix){
HX_GC_STACKFRAME(&_hx_pos_77dd7e775494cb08_81_clear)
HXDLIN( 81) if (::hx::IsNull( prefix )) {
HXLINE( 83) this->audio = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 84) this->font = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 85) this->image = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
}
else {
HXLINE( 89) ::Dynamic keys = this->audio->keys();
HXLINE( 91) {
HXLINE( 91) ::Dynamic key = keys;
HXDLIN( 91) while(( (bool)(key->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){
HXLINE( 91) ::String key1 = ( (::String)(key->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) );
HXLINE( 93) if (::StringTools_obj::startsWith(key1,prefix)) {
HXLINE( 95) this->audio->remove(key1);
}
}
}
HXLINE( 99) ::Dynamic keys1 = this->font->keys();
HXLINE( 101) {
HXLINE( 101) ::Dynamic key1 = keys1;
HXDLIN( 101) while(( (bool)(key1->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){
HXLINE( 101) ::String key = ( (::String)(key1->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) );
HXLINE( 103) if (::StringTools_obj::startsWith(key,prefix)) {
HXLINE( 105) this->font->remove(key);
}
}
}
HXLINE( 109) ::Dynamic keys2 = this->image->keys();
HXLINE( 111) {
HXLINE( 111) ::Dynamic key2 = keys2;
HXDLIN( 111) while(( (bool)(key2->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){
HXLINE( 111) ::String key = ( (::String)(key2->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) );
HXLINE( 113) if (::StringTools_obj::startsWith(key,prefix)) {
HXLINE( 115) this->image->remove(key);
}
}
}
}
}
HX_DEFINE_DYNAMIC_FUNC1(AssetCache_obj,clear,(void))
::hx::ObjectPtr< AssetCache_obj > AssetCache_obj::__new() {
::hx::ObjectPtr< AssetCache_obj > __this = new AssetCache_obj();
__this->__construct();
return __this;
}
::hx::ObjectPtr< AssetCache_obj > AssetCache_obj::__alloc(::hx::Ctx *_hx_ctx) {
AssetCache_obj *__this = (AssetCache_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(AssetCache_obj), true, "lime.utils.AssetCache"));
*(void **)__this = AssetCache_obj::_hx_vtable;
__this->__construct();
return __this;
}
AssetCache_obj::AssetCache_obj()
{
}
void AssetCache_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(AssetCache);
HX_MARK_MEMBER_NAME(audio,"audio");
HX_MARK_MEMBER_NAME(enabled,"enabled");
HX_MARK_MEMBER_NAME(image,"image");
HX_MARK_MEMBER_NAME(font,"font");
HX_MARK_MEMBER_NAME(version,"version");
HX_MARK_END_CLASS();
}
void AssetCache_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(audio,"audio");
HX_VISIT_MEMBER_NAME(enabled,"enabled");
HX_VISIT_MEMBER_NAME(image,"image");
HX_VISIT_MEMBER_NAME(font,"font");
HX_VISIT_MEMBER_NAME(version,"version");
}
::hx::Val AssetCache_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"set") ) { return ::hx::Val( set_dyn() ); }
break;
case 4:
if (HX_FIELD_EQ(inName,"font") ) { return ::hx::Val( font ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"audio") ) { return ::hx::Val( audio ); }
if (HX_FIELD_EQ(inName,"image") ) { return ::hx::Val( image ); }
if (HX_FIELD_EQ(inName,"clear") ) { return ::hx::Val( clear_dyn() ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"exists") ) { return ::hx::Val( exists_dyn() ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"enabled") ) { return ::hx::Val( enabled ); }
if (HX_FIELD_EQ(inName,"version") ) { return ::hx::Val( version ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val AssetCache_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"font") ) { font=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
break;
case 5:
if (HX_FIELD_EQ(inName,"audio") ) { audio=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
if (HX_FIELD_EQ(inName,"image") ) { image=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"enabled") ) { enabled=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"version") ) { version=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void AssetCache_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("audio",d6,78,80,27));
outFields->push(HX_("enabled",81,04,31,7e));
outFields->push(HX_("image",5b,1f,69,bd));
outFields->push(HX_("font",cf,5d,c0,43));
outFields->push(HX_("version",18,e7,f1,7c));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo AssetCache_obj_sMemberStorageInfo[] = {
{::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(AssetCache_obj,audio),HX_("audio",d6,78,80,27)},
{::hx::fsBool,(int)offsetof(AssetCache_obj,enabled),HX_("enabled",81,04,31,7e)},
{::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(AssetCache_obj,image),HX_("image",5b,1f,69,bd)},
{::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(AssetCache_obj,font),HX_("font",cf,5d,c0,43)},
{::hx::fsInt,(int)offsetof(AssetCache_obj,version),HX_("version",18,e7,f1,7c)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *AssetCache_obj_sStaticStorageInfo = 0;
#endif
static ::String AssetCache_obj_sMemberFields[] = {
HX_("audio",d6,78,80,27),
HX_("enabled",81,04,31,7e),
HX_("image",5b,1f,69,bd),
HX_("font",cf,5d,c0,43),
HX_("version",18,e7,f1,7c),
HX_("exists",dc,1d,e0,bf),
HX_("set",a2,9b,57,00),
HX_("clear",8d,71,5b,48),
::String(null()) };
::hx::Class AssetCache_obj::__mClass;
void AssetCache_obj::__register()
{
AssetCache_obj _hx_dummy;
AssetCache_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("lime.utils.AssetCache",e8,d2,51,4a);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(AssetCache_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< AssetCache_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = AssetCache_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = AssetCache_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace utils
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "hw/cpu/commands/keyboard/cex9e.hpp"
namespace hw::cpu::commands::keyboard {
CEX9E::CEX9E( const std::shared_ptr< HardwareMediator >& mediator )
: Command{ mediator } {}
void CEX9E::execute( uint16_t value ) const {
// Check if the mediator is present
if( !mediator_ ) return;
// Check if CPU is OK
auto cpu = mediator_->getCPU();
if( !cpu ) return;
// TODO
//if () cpu->skip();
}
} // namespace hw::cpu::commands::keyboard
|
#include "stdafx.h"
#include "Msg.h"
#include "ConvEng.h"
#include "TextFile.h"
#ifdef RTF_SUPPORT
#include "RtfParser.h"
#endif
BOOL ConvertTextFile(
PBYTE pbySource,
DWORD dwFileSize,
PBYTE pbyTarget,
DWORD dwTargetSize,
BOOL fAnsiToUnicode,
PINT pnTargetFileSize)
{
BOOL fRet = FALSE;
if (!fAnsiToUnicode && *((PWORD)pbySource) != 0xFEFF) {
MsgNotUnicodeTextSourceFile();
return FALSE;
}
if (fAnsiToUnicode && *((PWORD)pbySource) == 0xFEFF) {
MsgNotAnsiTextSourceFile();
return FALSE;
}
if (fAnsiToUnicode) {
PWCH pwchTarget = (PWCH)pbyTarget;
// Put Unicode text file flag
*pwchTarget = 0xFEFF;
*pnTargetFileSize = 1;
// Null file
if (!dwFileSize) {
fRet = TRUE;
goto Exit;
}
// Convert
*pnTargetFileSize += AnsiStrToUnicodeStr(pbySource, dwFileSize,
pwchTarget+1, dwTargetSize-2);
*pnTargetFileSize *= sizeof(WCHAR);
} else {
// Check and skip Uncode text file flag
if (dwFileSize < 2) {
goto Exit;
}
PWCH pwchData = (PWCH)pbySource;
if (*pwchData != 0xFEFF) {
goto Exit;
}
pwchData++;
// Null file w/ Unicode flag only
if (dwFileSize == 2) {
fRet = TRUE;
goto Exit;
}
// Convert
*pnTargetFileSize = UnicodeStrToAnsiStr(pwchData,
dwFileSize/sizeof(WCHAR) - 1, (PCHAR)pbyTarget, dwTargetSize);
}
if (*pnTargetFileSize) {
fRet = TRUE;
}
Exit:
return fRet;
}
BOOL ConvertHtmlFile(
PBYTE pbySource,
DWORD dwFileSize,
PBYTE pbyTarget,
DWORD dwTargetSize,
BOOL fAnsiToUnicode,
PINT pnTargetFileSize)
{
BOOL fRet = FALSE;
if (!ConvertTextFile(pbySource, dwFileSize, pbyTarget,
// Reserve the last space to explicitly assign zero to the last
// character in the buffer
dwTargetSize - (fAnsiToUnicode ? sizeof(WCHAR):sizeof(char)),
fAnsiToUnicode, pnTargetFileSize)) {
return FALSE;
}
// Change charset
if (fAnsiToUnicode) {
const WCHAR* const wszUnicodeCharset = L"charset=unicode";
WCHAR *pwch1, *pwch2;
int nLengthIncrease;
*((PWCH)(pbyTarget+*pnTargetFileSize)) = 0;
pwch1 = wcsstr((PWCH)pbyTarget, L"charset=");
if (!pwch1) {
// Some Html file may haven't code page flag,
// We skip charset replace step for this kind of files
fRet = TRUE;
goto Exit;
}
pwch2 = wcschr(pwch1, L'\"');
if (!pwch2 || (pwch2 - pwch1 >= 20)) {
goto Exit;
}
nLengthIncrease = (int)(wcslen(wszUnicodeCharset) - (pwch2 - pwch1));
if (*pnTargetFileSize + nLengthIncrease*sizeof(WCHAR) > dwTargetSize) {
goto Exit;
}
MoveMemory(pwch2 + nLengthIncrease, pwch2,
pbyTarget + *pnTargetFileSize - (PBYTE)pwch2);
CopyMemory(pwch1, wszUnicodeCharset, wcslen(wszUnicodeCharset)*sizeof(WCHAR));
*pnTargetFileSize += nLengthIncrease*sizeof(WCHAR);
fRet = TRUE;
} else {
const CHAR* const szGBCharset = "charset=gb18030";
CHAR *pch1, *pch2;
int nLengthIncrease;
*((PCHAR)(pbyTarget+*pnTargetFileSize)) = 0;
pch1 = strstr((PCHAR)pbyTarget, "charset=");
if (!pch1) {
// Some Html file may haven't code page flag,
// We skip charset replace step for this kind of files
fRet = TRUE;
goto Exit;
}
pch2 = strchr(pch1, '\"');
if (!pch2 || (pch2 - pch1 >= 20)) {
goto Exit;
}
nLengthIncrease = (int)(strlen(szGBCharset) - (pch2 - pch1));
if (*pnTargetFileSize + nLengthIncrease > (int)dwTargetSize) {
goto Exit;
}
MoveMemory(pch2 + nLengthIncrease, pch2,
(PCHAR)pbyTarget + *pnTargetFileSize - pch2);
CopyMemory(pch1, szGBCharset, strlen(szGBCharset)*sizeof(char));
*pnTargetFileSize += nLengthIncrease*sizeof(char);
fRet = TRUE;
}
Exit:
return fRet;
}
#ifdef XML_SUPPORT
BOOL ConvertXmlFile(
PBYTE pbySource,
DWORD dwFileSize,
PBYTE pbyTarget,
DWORD dwTargetSize,
BOOL fAnsiToUnicode,
PINT pnTargetFileSize)
{
BOOL fRet = FALSE;
if (!ConvertTextFile(pbySource, dwFileSize, pbyTarget,
// Reserve the last space to explicitly assign zero to the last
// character in the buffer
dwTargetSize - (fAnsiToUnicode ? sizeof(WCHAR):sizeof(char)),
fAnsiToUnicode, pnTargetFileSize)) {
return FALSE;
}
// Change charset
if (fAnsiToUnicode) {
const WCHAR* const wszUnicodeCharset = L"UTF-16";
WCHAR *pwchEnd, *pwch1, *pwch2;
int nLengthIncrease;
*((PWCH)(pbyTarget+*pnTargetFileSize)) = 0;
pwch1 = wcsstr((PWCH)pbyTarget, L"<?xml");
if (!pwch1) {
goto Exit;
}
pwchEnd = wcsstr(pwch1, L"?>");
if (!pwchEnd) {
goto Exit;
}
// temp set to null-terminal
*pwchEnd = 0;
pwch1 = wcsstr(pwch1, L"encoding=");
if (!pwch1) {
// Some Html file may haven't code page flag,
// We skip charset replace step for this kind of files
fRet = TRUE;
*pwchEnd = '?';
goto Exit;
}
pwch1 += wcslen(L"encoding=");
WCHAR wch = *pwch1;
pwch1++;
if (wch != '\"' && wch != '\'') {
*pwchEnd = '?';
goto Exit;
}
pwch2 = wcschr(pwch1, wch);
if (!pwch2 || (pwch2 - pwch1 >= 20)) {
*pwchEnd = '?';
goto Exit;
}
// restore *pwch2
*pwchEnd = '?';
nLengthIncrease = (int)(wcslen(wszUnicodeCharset) - (pwch2 - pwch1));
if (*pnTargetFileSize + nLengthIncrease*sizeof(WCHAR) > dwTargetSize) {
goto Exit;
}
MoveMemory(pwch2 + nLengthIncrease, pwch2,
pbyTarget + *pnTargetFileSize - (PBYTE)pwch2);
CopyMemory(pwch1, wszUnicodeCharset, wcslen(wszUnicodeCharset)*sizeof(WCHAR));
*pnTargetFileSize += nLengthIncrease*sizeof(WCHAR);
fRet = TRUE;
} else {
const char* const szGBCharset = "GB18030";
char *pchEnd, *pch1, *pch2;
int nLengthIncrease;
*((PCH)(pbyTarget+*pnTargetFileSize)) = 0;
pch1 = strstr((char*)pbyTarget, "<?xml");
if (!pch1) {
goto Exit;
}
pchEnd = strstr(pch1, "?>");
if (!pchEnd) {
goto Exit;
}
// temp set to null-terminal
*pchEnd = 0;
pch1 = strstr(pch1, "encoding=");
if (!pch1) {
// Some Html file may haven't code page flag,
// We skip charset replace step for this kind of files
fRet = TRUE;
*pchEnd = '?';
goto Exit;
}
pch1 += strlen("encoding=");
CHAR ch = *pch1;
pch1++;
if (ch != '\"' && ch != '\'') {
*pchEnd = '?';
goto Exit;
}
pch2 = strchr(pch1, ch);
if (!pch2 || (pch2 - pch1 >= 20)) {
*pchEnd = '?';
goto Exit;
}
// restore *pwch2
*pchEnd = '?';
nLengthIncrease = (int)(strlen(szGBCharset) - (pch2 - pch1));
if (*pnTargetFileSize + nLengthIncrease > (int)dwTargetSize) {
goto Exit;
}
MoveMemory(pch2 + nLengthIncrease, pch2,
pbyTarget + *pnTargetFileSize - (PBYTE)pch2);
CopyMemory(pch1, szGBCharset, strlen(szGBCharset));
*pnTargetFileSize += nLengthIncrease;
fRet = TRUE;
}
Exit:
return fRet;
}
#endif
#ifdef RTF_SUPPORT
BOOL ConvertRtfFile(
PBYTE pBuf, // Read buf
DWORD dwSize, // File size
PBYTE pWrite, // Write buf
DWORD dwWriteSize,
BOOL fAnsiToUnicode,
PINT pnTargetFileSize)
{
CRtfParser* pcParser;
DWORD dwVersion;
DWORD dwCodepage;
BOOL fRet = FALSE;
pcParser = new CRtfParser(pBuf, dwSize, pWrite, dwSize*3);
if (!pcParser) {
MsgOverflow();
goto gotoExit;
}
if (!pcParser->fRTFFile()) {
MsgNotRtfSourceFile();
goto gotoExit;
}
if (ecOK != pcParser->GetVersion(&dwVersion) ||
dwVersion != 1) {
MsgNotRtfSourceFile();
goto gotoExit;
}
if (ecOK != pcParser->GetCodepage(&dwCodepage) ||
dwCodepage != 936) {
MsgNotRtfSourceFile();
goto gotoExit;
}
// Explain WordID by corresponding word text
if (ecOK != pcParser->Do()) {
MsgNotRtfSourceFile();
goto gotoExit;
}
pcParser->GetResult((PDWORD)pnTargetFileSize);
fRet = TRUE;
gotoExit:
if (pcParser) {
delete pcParser;
}
return fRet;
}
#endif
|
// Copyright 2014 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/register-configuration.h"
#include "src/globals.h"
#include "src/macro-assembler.h"
namespace v8 {
namespace internal {
namespace {
#define REGISTER_COUNT(R) 1 +
static const int kMaxAllocatableGeneralRegisterCount =
ALLOCATABLE_GENERAL_REGISTERS(REGISTER_COUNT)0;
static const int kMaxAllocatableDoubleRegisterCount =
ALLOCATABLE_DOUBLE_REGISTERS(REGISTER_COUNT)0;
static const int kAllocatableGeneralCodes[] = {
#define REGISTER_CODE(R) kRegCode_##R,
ALLOCATABLE_GENERAL_REGISTERS(REGISTER_CODE)};
#undef REGISTER_CODE
#define REGISTER_CODE(R) kDoubleCode_##R,
static const int kAllocatableDoubleCodes[] = {
ALLOCATABLE_DOUBLE_REGISTERS(REGISTER_CODE)};
#if V8_TARGET_ARCH_ARM
static const int kAllocatableNoVFP32DoubleCodes[] = {
ALLOCATABLE_NO_VFP32_DOUBLE_REGISTERS(REGISTER_CODE)};
#endif // V8_TARGET_ARCH_ARM
#undef REGISTER_CODE
static const char* const kGeneralRegisterNames[] = {
#define REGISTER_NAME(R) #R,
GENERAL_REGISTERS(REGISTER_NAME)
#undef REGISTER_NAME
};
static const char* const kFloatRegisterNames[] = {
#define REGISTER_NAME(R) #R,
FLOAT_REGISTERS(REGISTER_NAME)
#undef REGISTER_NAME
};
static const char* const kDoubleRegisterNames[] = {
#define REGISTER_NAME(R) #R,
DOUBLE_REGISTERS(REGISTER_NAME)
#undef REGISTER_NAME
};
static const char* const kSimd128RegisterNames[] = {
#define REGISTER_NAME(R) #R,
SIMD128_REGISTERS(REGISTER_NAME)
#undef REGISTER_NAME
};
STATIC_ASSERT(RegisterConfiguration::kMaxGeneralRegisters >=
Register::kNumRegisters);
STATIC_ASSERT(RegisterConfiguration::kMaxFPRegisters >=
FloatRegister::kNumRegisters);
STATIC_ASSERT(RegisterConfiguration::kMaxFPRegisters >=
DoubleRegister::kNumRegisters);
STATIC_ASSERT(RegisterConfiguration::kMaxFPRegisters >=
Simd128Register::kNumRegisters);
static int get_num_allocatable_double_registers() {
return
#if V8_TARGET_ARCH_IA32
kMaxAllocatableDoubleRegisterCount;
#elif V8_TARGET_ARCH_X64
kMaxAllocatableDoubleRegisterCount;
#elif V8_TARGET_ARCH_ARM
CpuFeatures::IsSupported(VFP32DREGS)
? kMaxAllocatableDoubleRegisterCount
: (ALLOCATABLE_NO_VFP32_DOUBLE_REGISTERS(REGISTER_COUNT) 0);
#elif V8_TARGET_ARCH_ARM64
kMaxAllocatableDoubleRegisterCount;
#elif V8_TARGET_ARCH_MIPS
kMaxAllocatableDoubleRegisterCount;
#elif V8_TARGET_ARCH_MIPS64
kMaxAllocatableDoubleRegisterCount;
#elif V8_TARGET_ARCH_PPC
kMaxAllocatableDoubleRegisterCount;
#elif V8_TARGET_ARCH_S390
kMaxAllocatableDoubleRegisterCount;
#else
#error Unsupported target architecture.
#endif
}
static const int* get_allocatable_double_codes() {
return
#if V8_TARGET_ARCH_ARM
CpuFeatures::IsSupported(VFP32DREGS) ? kAllocatableDoubleCodes
: kAllocatableNoVFP32DoubleCodes;
#else
kAllocatableDoubleCodes;
#endif
}
class ArchDefaultRegisterConfiguration : public RegisterConfiguration {
public:
ArchDefaultRegisterConfiguration()
: RegisterConfiguration(
Register::kNumRegisters, DoubleRegister::kNumRegisters,
kMaxAllocatableGeneralRegisterCount,
get_num_allocatable_double_registers(), kAllocatableGeneralCodes,
get_allocatable_double_codes(),
kSimpleFPAliasing ? AliasingKind::OVERLAP : AliasingKind::COMBINE,
kGeneralRegisterNames, kFloatRegisterNames, kDoubleRegisterNames,
kSimd128RegisterNames) {}
};
struct RegisterConfigurationInitializer {
static void Construct(void* config) {
new (config) ArchDefaultRegisterConfiguration();
}
};
static base::LazyInstance<ArchDefaultRegisterConfiguration,
RegisterConfigurationInitializer>::type
kDefaultRegisterConfiguration = LAZY_INSTANCE_INITIALIZER;
// Allocatable registers with the masking register removed.
class ArchDefaultPoisoningRegisterConfiguration : public RegisterConfiguration {
public:
ArchDefaultPoisoningRegisterConfiguration()
: RegisterConfiguration(
Register::kNumRegisters, DoubleRegister::kNumRegisters,
kMaxAllocatableGeneralRegisterCount - 1,
get_num_allocatable_double_registers(),
InitializeGeneralRegisterCodes(), get_allocatable_double_codes(),
kSimpleFPAliasing ? AliasingKind::OVERLAP : AliasingKind::COMBINE,
kGeneralRegisterNames, kFloatRegisterNames, kDoubleRegisterNames,
kSimd128RegisterNames) {}
private:
static const int* InitializeGeneralRegisterCodes() {
int filtered_index = 0;
for (int i = 0; i < kMaxAllocatableGeneralRegisterCount; ++i) {
if (kAllocatableGeneralCodes[i] != kSpeculationPoisonRegister.code()) {
allocatable_general_codes_[filtered_index] =
kAllocatableGeneralCodes[i];
filtered_index++;
}
}
DCHECK_EQ(filtered_index, kMaxAllocatableGeneralRegisterCount - 1);
return allocatable_general_codes_;
}
static int
allocatable_general_codes_[kMaxAllocatableGeneralRegisterCount - 1];
};
int ArchDefaultPoisoningRegisterConfiguration::allocatable_general_codes_
[kMaxAllocatableGeneralRegisterCount - 1];
struct PoisoningRegisterConfigurationInitializer {
static void Construct(void* config) {
new (config) ArchDefaultPoisoningRegisterConfiguration();
}
};
static base::LazyInstance<ArchDefaultPoisoningRegisterConfiguration,
PoisoningRegisterConfigurationInitializer>::type
kDefaultPoisoningRegisterConfiguration = LAZY_INSTANCE_INITIALIZER;
// RestrictedRegisterConfiguration uses the subset of allocatable general
// registers the architecture support, which results into generating assembly
// to use less registers. Currently, it's only used by RecordWrite code stub.
class RestrictedRegisterConfiguration : public RegisterConfiguration {
public:
RestrictedRegisterConfiguration(
int num_allocatable_general_registers,
std::unique_ptr<int[]> allocatable_general_register_codes,
std::unique_ptr<char const* []> allocatable_general_register_names)
: RegisterConfiguration(
Register::kNumRegisters, DoubleRegister::kNumRegisters,
num_allocatable_general_registers,
get_num_allocatable_double_registers(),
allocatable_general_register_codes.get(),
get_allocatable_double_codes(),
kSimpleFPAliasing ? AliasingKind::OVERLAP : AliasingKind::COMBINE,
allocatable_general_register_names.get(), kFloatRegisterNames,
kDoubleRegisterNames, kSimd128RegisterNames),
allocatable_general_register_codes_(
std::move(allocatable_general_register_codes)),
allocatable_general_register_names_(
std::move(allocatable_general_register_names)) {
for (int i = 0; i < num_allocatable_general_registers; ++i) {
DCHECK(
IsAllocatableGeneralRegister(allocatable_general_register_codes_[i]));
}
}
bool IsAllocatableGeneralRegister(int code) {
for (int i = 0; i < kMaxAllocatableGeneralRegisterCount; ++i) {
if (code == kAllocatableGeneralCodes[i]) {
return true;
}
}
return false;
}
private:
std::unique_ptr<int[]> allocatable_general_register_codes_;
std::unique_ptr<char const* []> allocatable_general_register_names_;
};
} // namespace
const RegisterConfiguration* RegisterConfiguration::Default() {
return &kDefaultRegisterConfiguration.Get();
}
const RegisterConfiguration* RegisterConfiguration::Poisoning() {
return &kDefaultPoisoningRegisterConfiguration.Get();
}
const RegisterConfiguration* RegisterConfiguration::RestrictGeneralRegisters(
RegList registers) {
int num = NumRegs(registers);
std::unique_ptr<int[]> codes{new int[num]};
std::unique_ptr<char const* []> names { new char const*[num] };
int counter = 0;
for (int i = 0; i < Default()->num_allocatable_general_registers(); ++i) {
auto reg = Register::from_code(Default()->GetAllocatableGeneralCode(i));
if (reg.bit() & registers) {
DCHECK(counter < num);
codes[counter] = reg.code();
names[counter] = Default()->GetGeneralRegisterName(i);
counter++;
}
}
return new RestrictedRegisterConfiguration(num, std::move(codes),
std::move(names));
}
RegisterConfiguration::RegisterConfiguration(
int num_general_registers, int num_double_registers,
int num_allocatable_general_registers, int num_allocatable_double_registers,
const int* allocatable_general_codes, const int* allocatable_double_codes,
AliasingKind fp_aliasing_kind, const char* const* general_register_names,
const char* const* float_register_names,
const char* const* double_register_names,
const char* const* simd128_register_names)
: num_general_registers_(num_general_registers),
num_float_registers_(0),
num_double_registers_(num_double_registers),
num_simd128_registers_(0),
num_allocatable_general_registers_(num_allocatable_general_registers),
num_allocatable_float_registers_(0),
num_allocatable_double_registers_(num_allocatable_double_registers),
num_allocatable_simd128_registers_(0),
allocatable_general_codes_mask_(0),
allocatable_float_codes_mask_(0),
allocatable_double_codes_mask_(0),
allocatable_simd128_codes_mask_(0),
allocatable_general_codes_(allocatable_general_codes),
allocatable_double_codes_(allocatable_double_codes),
fp_aliasing_kind_(fp_aliasing_kind),
general_register_names_(general_register_names),
float_register_names_(float_register_names),
double_register_names_(double_register_names),
simd128_register_names_(simd128_register_names) {
DCHECK_LE(num_general_registers_,
RegisterConfiguration::kMaxGeneralRegisters);
DCHECK_LE(num_double_registers_, RegisterConfiguration::kMaxFPRegisters);
for (int i = 0; i < num_allocatable_general_registers_; ++i) {
allocatable_general_codes_mask_ |= (1 << allocatable_general_codes_[i]);
}
for (int i = 0; i < num_allocatable_double_registers_; ++i) {
allocatable_double_codes_mask_ |= (1 << allocatable_double_codes_[i]);
}
if (fp_aliasing_kind_ == COMBINE) {
num_float_registers_ = num_double_registers_ * 2 <= kMaxFPRegisters
? num_double_registers_ * 2
: kMaxFPRegisters;
num_allocatable_float_registers_ = 0;
for (int i = 0; i < num_allocatable_double_registers_; i++) {
int base_code = allocatable_double_codes_[i] * 2;
if (base_code >= kMaxFPRegisters) continue;
allocatable_float_codes_[num_allocatable_float_registers_++] = base_code;
allocatable_float_codes_[num_allocatable_float_registers_++] =
base_code + 1;
allocatable_float_codes_mask_ |= (0x3 << base_code);
}
num_simd128_registers_ = num_double_registers_ / 2;
num_allocatable_simd128_registers_ = 0;
int last_simd128_code = allocatable_double_codes_[0] / 2;
for (int i = 1; i < num_allocatable_double_registers_; i++) {
int next_simd128_code = allocatable_double_codes_[i] / 2;
// This scheme assumes allocatable_double_codes_ are strictly increasing.
DCHECK_GE(next_simd128_code, last_simd128_code);
if (last_simd128_code == next_simd128_code) {
allocatable_simd128_codes_[num_allocatable_simd128_registers_++] =
next_simd128_code;
allocatable_simd128_codes_mask_ |= (0x1 << next_simd128_code);
}
last_simd128_code = next_simd128_code;
}
} else {
DCHECK(fp_aliasing_kind_ == OVERLAP);
num_float_registers_ = num_simd128_registers_ = num_double_registers_;
num_allocatable_float_registers_ = num_allocatable_simd128_registers_ =
num_allocatable_double_registers_;
for (int i = 0; i < num_allocatable_float_registers_; ++i) {
allocatable_float_codes_[i] = allocatable_simd128_codes_[i] =
allocatable_double_codes_[i];
}
allocatable_float_codes_mask_ = allocatable_simd128_codes_mask_ =
allocatable_double_codes_mask_;
}
}
// Assert that kFloat32, kFloat64, and kSimd128 are consecutive values.
STATIC_ASSERT(static_cast<int>(MachineRepresentation::kSimd128) ==
static_cast<int>(MachineRepresentation::kFloat64) + 1);
STATIC_ASSERT(static_cast<int>(MachineRepresentation::kFloat64) ==
static_cast<int>(MachineRepresentation::kFloat32) + 1);
int RegisterConfiguration::GetAliases(MachineRepresentation rep, int index,
MachineRepresentation other_rep,
int* alias_base_index) const {
DCHECK(fp_aliasing_kind_ == COMBINE);
DCHECK(IsFloatingPoint(rep) && IsFloatingPoint(other_rep));
if (rep == other_rep) {
*alias_base_index = index;
return 1;
}
int rep_int = static_cast<int>(rep);
int other_rep_int = static_cast<int>(other_rep);
if (rep_int > other_rep_int) {
int shift = rep_int - other_rep_int;
int base_index = index << shift;
if (base_index >= kMaxFPRegisters) {
// Alias indices would be out of FP register range.
return 0;
}
*alias_base_index = base_index;
return 1 << shift;
}
int shift = other_rep_int - rep_int;
*alias_base_index = index >> shift;
return 1;
}
bool RegisterConfiguration::AreAliases(MachineRepresentation rep, int index,
MachineRepresentation other_rep,
int other_index) const {
DCHECK(fp_aliasing_kind_ == COMBINE);
DCHECK(IsFloatingPoint(rep) && IsFloatingPoint(other_rep));
if (rep == other_rep) {
return index == other_index;
}
int rep_int = static_cast<int>(rep);
int other_rep_int = static_cast<int>(other_rep);
if (rep_int > other_rep_int) {
int shift = rep_int - other_rep_int;
return index == other_index >> shift;
}
int shift = other_rep_int - rep_int;
return index >> shift == other_index;
}
} // namespace internal
} // namespace v8
|
/* -----------------------------------------------------------------------------
* This file is a part of the NVCM Tests project: https://github.com/nvitya/nvcmtests
* Copyright (c) 2018 Viktor Nagy, nvitya
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software. Permission is granted to anyone to use this
* software for any purpose, including commercial applications, and to alter
* it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
* --------------------------------------------------------------------------- */
/*
* file: main.cpp (USB special test)
* brief: Special USB Device (multi-board)
* version: 1.00
* date: 2020-03-11
* authors: nvitya
* notes:
* The "definition" of this special USB device is originated from Niklas Gürtler:
* https://github.com/Erlkoenig90/f1usb
* https://www.mikrocontroller.net/articles/USB-Tutorial_mit_STM32
* This implementation is compatible with the f1usb-master from Niklas Gürtler.
*
* The device does not provide a standard interface, it can be controller with libusb.
* The project for testing it: https://github.com/nvitya/nvcmtests/usbclient_spec
* Or using the one from Niklas Gürtler: https://github.com/Erlkoenig90/usbclient
*/
#include <usb_cdc_echo.h>
#include "platform.h"
#include "hwpins.h"
#include "hwclkctrl.h"
#include "hwuart.h"
#include "cppinit.h"
#include "clockcnt.h"
#include "hwusbctrl.h"
#include "traces.h"
THwUart conuart; // console uart
#if defined(BOARD_ARDUINO_DUE)
TGpioPin led1pin(1, 27, false); // D13
void setup_board()
{
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
// UART - On the Arduino programmer interface
hwpinctrl.PinSetup(0, 8, PINCFG_INPUT | PINCFG_AF_0); // UART_RXD
hwpinctrl.PinSetup(0, 9, PINCFG_OUTPUT | PINCFG_AF_0); // UART_TXD
conuart.Init(0); // UART
}
#endif
#if defined(BOARD_MIBO64_ATSAM4S)
TGpioPin led1pin(PORTNUM_A, 1, false);
void setup_board()
{
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
hwpinctrl.PinSetup(PORTNUM_A, 9, PINCFG_INPUT | PINCFG_AF_0); // UART0_RX
hwpinctrl.PinSetup(PORTNUM_A, 10, PINCFG_OUTPUT | PINCFG_AF_0); // UART0_TX
conuart.Init(0);
}
#endif
#if defined(BOARD_NUCLEO_F446) || defined(BOARD_NUCLEO_F746)
TGpioPin led1pin(1, 0, false);
TGpioPin led2pin(1, 7, false);
TGpioPin led3pin(1, 14, false);
#define LED_COUNT 3
void setup_board()
{
// nucleo board leds
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
led2pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
led3pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
// USART3: Stlink USB / Serial converter
hwpinctrl.PinSetup(3, 8, PINCFG_OUTPUT | PINCFG_AF_7); // USART3_TX: PD.8
hwpinctrl.PinSetup(3, 9, PINCFG_INPUT | PINCFG_AF_7); // USART3_RX: PD.9
conuart.Init(3); // USART3
// USB_OTG_FS PINS
hwpinctrl.PinSetup(PORTNUM_A, 11, PINCFG_INPUT | PINCFG_AF_10 | PINCFG_SPEED_FAST); // USB_OTG_FS DM
hwpinctrl.PinSetup(PORTNUM_A, 12, PINCFG_INPUT | PINCFG_AF_10 | PINCFG_SPEED_FAST); // USB_OTG_FS DP
}
#endif
#if defined(BOARD_DISCOVERY_F072)
TGpioPin led1pin(PORTNUM_C, 6, false);
TGpioPin led2pin(PORTNUM_C, 8, false);
TGpioPin led3pin(PORTNUM_C, 9, false);
TGpioPin led4pin(PORTNUM_C, 7, false);
#define LED_COUNT 4
void setup_board()
{
// direction leds
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
led2pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
led3pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
led4pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
}
#endif
#if defined(BOARD_MIN_F103)
TGpioPin led1pin(2, 13, false); // PC13
void setup_board()
{
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
// USART1
hwpinctrl.PinSetup(PORTNUM_A, 9, PINCFG_OUTPUT | PINCFG_AF_0); // USART1_TX
hwpinctrl.PinSetup(PORTNUM_A, 10, PINCFG_INPUT | PINCFG_AF_0); // USART1_RX
conuart.Init(1);
}
#endif
#if defined(BOARD_MIBO48_STM32F303)
TGpioPin led1pin(PORTNUM_C, 13, false); // PC13
void setup_board()
{
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
// USB PINS
hwpinctrl.PinSetup(PORTNUM_A, 11, PINCFG_INPUT | PINCFG_AF_14 | PINCFG_SPEED_FAST); // USB DM
hwpinctrl.PinSetup(PORTNUM_A, 12, PINCFG_INPUT | PINCFG_AF_14 | PINCFG_SPEED_FAST); // USB DP
// USART1
hwpinctrl.PinSetup(PORTNUM_A, 9, PINCFG_OUTPUT | PINCFG_AF_7); // USART1_TX
hwpinctrl.PinSetup(PORTNUM_A, 10, PINCFG_INPUT | PINCFG_AF_7); // USART1_RX
conuart.Init(1);
}
#endif
#if defined(BOARD_MIBO48_STM32G473)
TGpioPin led1pin(PORTNUM_C, 13, false); // PC13
void setup_board()
{
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
// USB PINS
hwpinctrl.PinSetup(PORTNUM_A, 11, PINCFG_INPUT | PINCFG_AF_14 | PINCFG_SPEED_FAST); // USB DM
hwpinctrl.PinSetup(PORTNUM_A, 12, PINCFG_INPUT | PINCFG_AF_14 | PINCFG_SPEED_FAST); // USB DP
// USART1
hwpinctrl.PinSetup(PORTNUM_A, 9, PINCFG_OUTPUT | PINCFG_AF_7); // USART1_TX
hwpinctrl.PinSetup(PORTNUM_A, 10, PINCFG_INPUT | PINCFG_AF_7); // USART1_RX
conuart.Init(1);
}
#endif
#if defined(BOARD_MIBO64_STM32F405)
TGpioPin led1pin(PORTNUM_C, 13, false); // PC13
void setup_board()
{
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
// USB PINS
hwpinctrl.PinSetup(PORTNUM_A, 11, PINCFG_INPUT | PINCFG_AF_10 | PINCFG_SPEED_FAST); // USB DM
hwpinctrl.PinSetup(PORTNUM_A, 12, PINCFG_INPUT | PINCFG_AF_10 | PINCFG_SPEED_FAST); // USB DP
// USART1
hwpinctrl.PinSetup(PORTNUM_A, 9, PINCFG_OUTPUT | PINCFG_AF_7); // USART1_TX
hwpinctrl.PinSetup(PORTNUM_A, 10, PINCFG_INPUT | PINCFG_AF_7); // USART1_RX
conuart.Init(1);
}
#endif
#if defined(BOARD_MIBO64_STM32F070)
TGpioPin led1pin(PORTNUM_C, 13, false); // PC13
void setup_board()
{
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
// USB PINS
//hwpinctrl.PinSetup(PORTNUM_A, 11, PINCFG_INPUT | PINCFG_AF_0 | PINCFG_SPEED_FAST); // USB DM
//hwpinctrl.PinSetup(PORTNUM_A, 12, PINCFG_INPUT | PINCFG_AF_0 | PINCFG_SPEED_FAST); // USB DP
// USART1
hwpinctrl.PinSetup(PORTNUM_A, 9, PINCFG_OUTPUT | PINCFG_AF_1); // USART1_TX
hwpinctrl.PinSetup(PORTNUM_A, 10, PINCFG_INPUT | PINCFG_AF_1); // USART1_RX
conuart.Init(1);
}
#endif
#if defined(BOARD_XPLAINED_SAME70)
TGpioPin led1pin(2, 8, false); // C8
void setup_board()
{
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
// USART1 - EDBG
hwpinctrl.PinSetup(0, 21, PINCFG_INPUT | PINCFG_AF_0); // USART1_RXD
MATRIX->CCFG_SYSIO |= (1 << 4); // select PB4 instead of TDI !!!!!!!!!
hwpinctrl.PinSetup(1, 4, PINCFG_OUTPUT | PINCFG_AF_3); // USART1_TXD
conuart.Init(0x101); // USART1
// dedicated HS USB pins, no pin setup required
}
#endif
#if defined(BOARD_MIBO64_ATSAME5X)
TGpioPin led1pin(PORTNUM_A, 1, false);
void setup_board()
{
led1pin.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
// SERCOM0
hwpinctrl.PinSetup(PORTNUM_A, 4, PINCFG_OUTPUT | PINCFG_AF_3); // PAD[0] = TX
hwpinctrl.PinSetup(PORTNUM_A, 5, PINCFG_INPUT | PINCFG_AF_3); // PAD[1] = RX
conuart.Init(0);
// SERCOM2
//hwpinctrl.PinSetup(PORTNUM_A, 12, PINCFG_AF_2); // PAD[0] = TX
//hwpinctrl.PinSetup(PORTNUM_A, 13, PINCFG_AF_2); // PAD[1] = RX
//conuart.Init(2);
// USB PINS
hwpinctrl.PinSetup(PORTNUM_A, 24, PINCFG_AF_7); // USB DM
hwpinctrl.PinSetup(PORTNUM_A, 25, PINCFG_AF_7); // USB DP
}
#endif
// ---------------------------------------------------------------------------------------
#ifndef LED_COUNT
#define LED_COUNT 1
#endif
// the C libraries require "_start" so we keep it as the entry point
extern "C" __attribute__((noreturn)) void _start(void)
{
// the processor jumps here right after the reset
// the MCU runs slower, using the internal RC oscillator
// all variables are unstable, they will be overridden later
mcu_disable_interrupts();
mcu_preinit_code(); // inline code for preparing the MCU, RAM regions. Without this even the stack does not work on some MCUs.
// Set the interrupt vector table offset, so that the interrupts and exceptions work
mcu_init_vector_table();
unsigned clockspeed = MCU_CLOCK_SPEED / 1;
#ifdef MCU_INPUT_FREQ
if (!hwclkctrl.InitCpuClock(MCU_INPUT_FREQ, clockspeed))
#else
if (!hwclkctrl.InitCpuClockIntRC(MCU_INTRC_SPEED, clockspeed))
#endif
{
while (1)
{
// the external oscillator did not start.
}
}
// now the MCU runs faster, start the memory, and C/C++ initialization:
cppinit();
// ...from now on all the variables work, static classes are initialized.
// provide info to the system about the clock speed:
hwclkctrl.SetClockInfo(clockspeed);
mcu_enable_fpu(); // enable coprocessor if present
//mcu_enable_icache(); // enable instruction cache if present
clockcnt_init();
// go on with the hardware initializations
setup_board();
traces_init();
tracebuf.waitsend = true; // start with blocking mode
TRACE("\r\n--------------------------\r\n");
TRACE("NVCM USB SPEC TEST\r\n");
TRACE("Board: \"%s\"\r\n", BOARD_NAME);
TRACE("SystemCoreClock: %u\r\n", SystemCoreClock);
TRACE_FLUSH();
usb_device_init();
TRACE("\r\nStarting main cycle...\r\n");
tracebuf.waitsend = false; // go to buffered mode
//tracebuf.waitsend = true; // better for basic debugging
mcu_enable_interrupts();
unsigned hbclocks = SystemCoreClock;
unsigned t0, t1;
t0 = CLOCKCNT;
// Infinite loop
while (1)
{
t1 = CLOCKCNT;
tracebuf.Run(); // send out buffered characters
usb_device_run();
if (t1-t0 > hbclocks)
{
// heartbeat task
//led1pin.Toggle();
t0 = t1;
}
}
}
// ----------------------------------------------------------------------------
|
#include "catch.hpp"
#include <MatrixMerchant/AMatrix>
#include <amatrix.h>
#include <complex>
#include <fstream>
#include <sstream>
#include <streambuf>
TEST_CASE("AMatrix: Array real General as MatrixXd",
"[AMatrix][Reader][Array][Real][General][Double]")
{
using Matrix = AMatrix::Matrix<double, AMatrix::dynamic, AMatrix::dynamic>;
using Reader = MatrixMerchant::Reader;
Matrix matrix(0, 0);
Reader::ReadFromFile(matrix, "./data/array_real_general_3_4.mtx");
REQUIRE(matrix.size1() == 3);
REQUIRE(matrix.size2() == 4);
REQUIRE(matrix(0, 0) == -1.7874030527951525);
REQUIRE(matrix(1, 0) == 2.8017662727841071);
REQUIRE(matrix(2, 0) == -7.3458785314655870);
REQUIRE(matrix(0, 1) == -2.4010370783465085);
REQUIRE(matrix(1, 1) == 9.1842295135688801);
REQUIRE(matrix(2, 1) == 4.4479713459839871);
REQUIRE(matrix(0, 2) == 9.0628790375549286);
REQUIRE(matrix(1, 2) == -3.7799237041860287);
REQUIRE(matrix(2, 2) == 5.5080306442042399);
REQUIRE(matrix(0, 3) == -7.3354743327476690);
REQUIRE(matrix(1, 3) == -3.3000793596121447);
REQUIRE(matrix(2, 3) == 5.7081113423916179);
}
TEST_CASE("AMatrix: Array real General as MatrixXf",
"[AMatrix][Reader][Array][Real][General][Float]")
{
using Matrix = AMatrix::Matrix<float, AMatrix::dynamic, AMatrix::dynamic>;
using Reader = MatrixMerchant::Reader;
Matrix matrix(0, 0);
Reader::ReadFromFile(matrix, "./data/array_real_general_3_4.mtx");
REQUIRE( matrix.size1() == 3 );
REQUIRE( matrix.size2() == 4 );
REQUIRE( matrix(0, 0) == -1.7874030527951525f );
REQUIRE( matrix(1, 0) == 2.8017662727841071f );
REQUIRE( matrix(2, 0) == -7.3458785314655870f );
REQUIRE( matrix(0, 1) == -2.4010370783465085f );
REQUIRE( matrix(1, 1) == 9.1842295135688801f );
REQUIRE( matrix(2, 1) == 4.4479713459839871f );
REQUIRE( matrix(0, 2) == 9.0628790375549286f );
REQUIRE( matrix(1, 2) == -3.7799237041860287f );
REQUIRE( matrix(2, 2) == 5.5080306442042399f );
REQUIRE( matrix(0, 3) == -7.3354743327476690f );
REQUIRE( matrix(1, 3) == -3.3000793596121447f );
REQUIRE( matrix(2, 3) == 5.7081113423916179f );
}
TEST_CASE("AMatrix: Array real General as MatrixXi",
"[AMatrix][Reader][Array][Real][General][Integer]")
{
using Matrix = AMatrix::Matrix<int, AMatrix::dynamic, AMatrix::dynamic>;
using Reader = MatrixMerchant::Reader;
Matrix matrix(0, 0);
Reader::ReadFromFile(matrix, "./data/array_integer_general_3_4.mtx");
REQUIRE( matrix.size1() == 3 );
REQUIRE( matrix.size2() == 4 );
REQUIRE( matrix(0, 0) == -9 );
REQUIRE( matrix(1, 0) == -5 );
REQUIRE( matrix(2, 0) == -8 );
REQUIRE( matrix(0, 1) == -1 );
REQUIRE( matrix(1, 1) == 5 );
REQUIRE( matrix(2, 1) == 1 );
REQUIRE( matrix(0, 2) == -6 );
REQUIRE( matrix(1, 2) == 7 );
REQUIRE( matrix(2, 2) == -8 );
REQUIRE( matrix(0, 3) == 9 );
REQUIRE( matrix(1, 3) == 3 );
REQUIRE( matrix(2, 3) == 3 );
}
TEST_CASE("AMatrix: Array complex General as MatrixXcd",
"[AMatrix][Reader][Array][Complex][General]")
{
using Scalar = double;
using Complex = std::complex<Scalar>;
using Matrix = AMatrix::Matrix<Complex, AMatrix::dynamic, AMatrix::dynamic>;
using Reader = MatrixMerchant::Reader;
Matrix matrix(0, 0);
Reader::ReadFromFile(matrix, "./data/array_complex_general_3_4.mtx");
REQUIRE(matrix.size1() == 3);
REQUIRE(matrix.size2() == 4);
REQUIRE(matrix(0, 0).real() == 6.3475699384495456);
REQUIRE(matrix(0, 0).imag() == 7.2543707383778369);
REQUIRE(matrix(1, 0).real() == -8.6063311685072641);
REQUIRE(matrix(1, 0).imag() == 2.5072858827017797);
REQUIRE(matrix(2, 0).real() == -8.0315916320117786);
REQUIRE(matrix(2, 0).imag() == -1.8991193467271117);
REQUIRE(matrix(0, 1).real() == 8.2479279251527657);
REQUIRE(matrix(0, 1).imag() == 0.9826791458003789);
REQUIRE(matrix(1, 1).real() == -7.7922395613298150);
REQUIRE(matrix(1, 1).imag() == -1.4988090472583906);
REQUIRE(matrix(2, 1).real() == -4.7440298331251043);
REQUIRE(matrix(2, 1).imag() == 2.7754100562267894);
REQUIRE(matrix(0, 2).real() == 4.2339856131784046);
REQUIRE(matrix(0, 2).imag() == 7.5881483892900476);
REQUIRE(matrix(1, 2).real() == -0.6683207826546286);
REQUIRE(matrix(1, 2).imag() == 0.90539482502031063);
REQUIRE(matrix(2, 2).real() == 7.0539735089809170);
REQUIRE(matrix(2, 2).imag() == 3.3949272347743857);
REQUIRE(matrix(0, 3).real() == 0.50032872310356353);
REQUIRE(matrix(0, 3).imag() == -5.6527470259273542);
REQUIRE(matrix(1, 3).real() == 8.2913524063734627);
REQUIRE(matrix(1, 3).imag() == -7.3097830459045490);
REQUIRE(matrix(2, 3).real() == -9.8304020948925732);
REQUIRE(matrix(2, 3).imag() == 4.5726971397846796);
}
|
#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/requires.hpp>
#include <agency/detail/invoke.hpp>
#include <agency/detail/type_traits.hpp>
#include <agency/execution/executor/detail/utility/invoke_functors.hpp>
#include <agency/execution/executor/properties/bulk.hpp>
#include <agency/execution/executor/properties/twoway.hpp>
#include <agency/execution/executor/require.hpp>
#include <type_traits>
namespace agency
{
namespace detail
{
template<class E, class Function, class ResultFactory, class... SharedFactories,
__AGENCY_REQUIRES(is_executor<E>::value),
__AGENCY_REQUIRES(executor_execution_depth<E>::value == sizeof...(SharedFactories)),
__AGENCY_REQUIRES(!std::is_void<result_of_t<Function(executor_index_t<E>, result_of_t<SharedFactories()>&...)>>::value)
>
__AGENCY_ANNOTATION
executor_future_t<E,result_of_t<ResultFactory()>>
bulk_twoway_execute_with_collected_result(const E& exec, Function f, executor_shape_t<E> shape, ResultFactory result_factory, SharedFactories... shared_factories)
{
// get a reference to avoid copies in agency::require
executor_ref<E> exec_ref{exec};
// wrap f in a functor that will collect f's result and call bulk_twoway_execute()
return agency::require(exec_ref, bulk, twoway).bulk_twoway_execute(invoke_and_collect_result<Function>{f}, shape, result_factory, shared_factories...);
}
} // end detail
} // end agency
|
#pragma once
#include <vector>
#include <memory>
#include "core.hpp"
class Scene;
class Object;
class Camera;
class Renderer
{
private:
unsigned int m_width, m_height;
float m_ar;
RNG m_rng;
Vector sample(float x, float y, const Scene& scene, const std::vector<std::shared_ptr<Object>> &emissiveObjects, const Camera& camera, unsigned int s1, unsigned int s2);
public:
unsigned int MC_SAMPLES, LIGHT_SAMPLES;
Renderer(unsigned int width, unsigned int height): m_width(width), m_height(height)
{
m_ar = (float)width / height;
MC_SAMPLES = 16;
LIGHT_SAMPLES = 8;
}
void reset(unsigned int width, unsigned int height)
{
m_width = width;
m_height = height;
m_ar = (float)width / height;
}
unsigned int getWidth() { return m_width; }
unsigned int getHeight() { return m_height; }
void setWidth(unsigned int width)
{
m_width = width;
m_ar = (float)width/m_height;
}
void setHeight(unsigned int height)
{
m_height = height;
m_ar = (float)m_width/height;
}
Vector traceRay(Ray &ray, const Scene &scene, const std::vector<std::shared_ptr<Object>> &areaLights, RNG &rng, unsigned int s1, unsigned int s2);
void render(const Scene& scene, const Camera& camera, char* &pixels);
};
|
#pragma once
#include "error.hpp"
#include "uuid.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <optional>
#include <string>
#include <vector>
class Model {
public:
Uuid id;
};
|
/*
* Copyright (c) 2020, NVIDIA 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.
*/
#pragma once
#include <type_traits>
namespace cugraph {
namespace internals {
class Callback {
public:
virtual ~Callback() {}
};
class GraphBasedDimRedCallback : public Callback {
public:
template <typename T>
void setup(int n, int n_components)
{
this->n = n;
this->n_components = n_components;
this->isFloat = std::is_same<T, float>::value;
}
virtual void on_preprocess_end(void *positions) = 0;
virtual void on_epoch_end(void *positions) = 0;
virtual void on_train_end(void *positions) = 0;
protected:
int n;
int n_components;
bool isFloat;
};
} // namespace internals
} // namespace cugraph
|
// RUN: %clang_cc1 -verify -fopenmp %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp -std=c++98 %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp -std=c++11 %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp-simd %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp-simd -std=c++98 %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp-simd -std=c++11 %s -Wuninitialized
void foo() {
}
#if __cplusplus >= 201103L
// expected-note@+2 4 {{declared here}}
#endif
bool foobool(int argc) {
return argc;
}
struct S1; // expected-note {{declared here}}
template <class T, typename S, int N, int ST> // expected-note {{declared here}}
T tmain(T argc, S **argv) { //expected-note 2 {{declared here}}
#pragma omp for simd safelen // expected-error {{expected '(' after 'safelen'}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp for simd safelen ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp for simd safelen () // expected-error {{expected expression}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
// expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}}
// expected-error@+2 2 {{integral constant expression}}
// expected-note@+1 2 {{read of non-const variable 'argc' is not allowed in a constant expression}}
#pragma omp for simd safelen (argc
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
// expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}}
#pragma omp for simd safelen (ST // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp for simd safelen (1)) // expected-warning {{extra tokens at the end of '#pragma omp for simd' are ignored}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp for simd safelen ((ST > 0) ? 1 + ST : 2)
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
// expected-error@+6 2 {{directive '#pragma omp for simd' cannot contain more than one 'safelen' clause}}
// expected-error@+5 {{argument to 'safelen' clause must be a strictly positive integer value}}
// expected-error@+4 2 {{integral constant expression}}
#if __cplusplus >= 201103L
// expected-note@+2 2 {{non-constexpr function 'foobool' cannot be used in a constant expression}}
#endif
#pragma omp for simd safelen (foobool(argc)), safelen (true), safelen (-5)
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp for simd safelen (S) // expected-error {{'S' does not refer to a value}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#if __cplusplus <= 199711L
// expected-error@+4 2 {{integral constant expression}}
#else
// expected-error@+2 2 {{integral constant expression must have integral or unscoped enumeration type, not 'char *'}}
#endif
#pragma omp for simd safelen (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp for simd safelen (4)
for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
#pragma omp for simd safelen (N) // expected-error {{argument to 'safelen' clause must be a strictly positive integer value}}
for (T i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST];
return argc;
}
int main(int argc, char **argv) {
#pragma omp for simd safelen // expected-error {{expected '(' after 'safelen'}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp for simd safelen ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp for simd safelen () // expected-error {{expected expression}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp for simd safelen (4 // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp for simd safelen (2+2)) // expected-warning {{extra tokens at the end of '#pragma omp for simd' are ignored}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
// expected-error@+4 {{integral constant expression}}
#if __cplusplus >= 201103L
// expected-note@+2 {{non-constexpr function 'foobool' cannot be used in a constant expression}}
#endif
#pragma omp for simd safelen (foobool(1) > 0 ? 1 : 2)
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
// expected-error@+6 {{integral constant expression}}
#if __cplusplus >= 201103L
// expected-note@+4 {{non-constexpr function 'foobool' cannot be used in a constant expression}}
#endif
// expected-error@+2 2 {{directive '#pragma omp for simd' cannot contain more than one 'safelen' clause}}
// expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}}
#pragma omp for simd safelen (foobool(argc)), safelen (true), safelen (-5)
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#pragma omp for simd safelen (S1) // expected-error {{'S1' does not refer to a value}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
#if __cplusplus <= 199711L
// expected-error@+4 {{integral constant expression}}
#else
// expected-error@+2 {{integral constant expression must have integral or unscoped enumeration type, not 'char *'}}
#endif
#pragma omp for simd safelen (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4];
// expected-error@+3 {{statement after '#pragma omp for simd' must be a for loop}}
// expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, -1, -2>' requested here}}
#pragma omp for simd safelen(safelen(tmain<int, char, -1, -2>(argc, argv) // expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}}
foo();
// expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, 12, 4>' requested here}}
return tmain<int, char, 12, 4>(argc, argv);
}
|
//
// Copyright 2019 The ANGLE 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.
//
// RewriteRowMajorMatrices: Rewrite row-major matrices as column-major.
//
#include "compiler/translator/tree_ops/RewriteRowMajorMatrices.h"
#include "compiler/translator/Compiler.h"
#include "compiler/translator/ImmutableStringBuilder.h"
#include "compiler/translator/StaticType.h"
#include "compiler/translator/SymbolTable.h"
#include "compiler/translator/tree_util/IntermNode_util.h"
#include "compiler/translator/tree_util/IntermTraverse.h"
#include "compiler/translator/tree_util/ReplaceVariable.h"
namespace sh
{
namespace
{
// Only structs with matrices are tracked. If layout(row_major) is applied to a struct that doesn't
// have matrices, it's silently dropped. This is also used to avoid creating duplicates for inner
// structs that don't have matrices.
struct StructConversionData
{
// The converted struct with every matrix transposed.
TStructure *convertedStruct = nullptr;
// The copy-from and copy-to functions copying from a struct to its converted version and back.
TFunction *copyFromOriginal = nullptr;
TFunction *copyToOriginal = nullptr;
};
bool DoesFieldContainRowMajorMatrix(const TField *field, bool isBlockRowMajor)
{
TLayoutMatrixPacking matrixPacking = field->type()->getLayoutQualifier().matrixPacking;
// The field is row major if either explicitly specified as such, or if it inherits it from the
// block layout qualifier.
if (matrixPacking == EmpColumnMajor || (matrixPacking == EmpUnspecified && !isBlockRowMajor))
{
return false;
}
// The field is qualified with row_major, but if it's not a matrix or a struct containing
// matrices, that's a useless qualifier.
const TType *type = field->type();
return type->isMatrix() || type->isStructureContainingMatrices();
}
TField *DuplicateField(const TField *field)
{
return new TField(new TType(*field->type()), field->name(), field->line(), field->symbolType());
}
void SetColumnMajor(TType *type)
{
TLayoutQualifier layoutQualifier = type->getLayoutQualifier();
layoutQualifier.matrixPacking = EmpColumnMajor;
type->setLayoutQualifier(layoutQualifier);
}
TType *TransposeMatrixType(const TType *type)
{
TType *newType = new TType(*type);
SetColumnMajor(newType);
newType->setPrimarySize(static_cast<unsigned char>(type->getRows()));
newType->setSecondarySize(static_cast<unsigned char>(type->getCols()));
return newType;
}
void CopyArraySizes(const TType *from, TType *to)
{
if (from->isArray())
{
to->makeArrays(from->getArraySizes());
}
}
// Determine if the node is an index node (array index or struct field selection). For the purposes
// of this transformation, swizzle nodes are considered index nodes too.
bool IsIndexNode(TIntermNode *node, TIntermNode *child)
{
if (node->getAsSwizzleNode())
{
return true;
}
TIntermBinary *binaryNode = node->getAsBinaryNode();
if (binaryNode == nullptr || child != binaryNode->getLeft())
{
return false;
}
TOperator op = binaryNode->getOp();
return op == EOpIndexDirect || op == EOpIndexDirectInterfaceBlock ||
op == EOpIndexDirectStruct || op == EOpIndexIndirect;
}
TIntermSymbol *CopyToTempVariable(TSymbolTable *symbolTable,
TIntermTyped *node,
TIntermSequence *prependStatements)
{
TVariable *temp = CreateTempVariable(symbolTable, &node->getType());
TIntermDeclaration *tempDecl = CreateTempInitDeclarationNode(temp, node);
prependStatements->push_back(tempDecl);
return new TIntermSymbol(temp);
}
TIntermAggregate *CreateStructCopyCall(const TFunction *copyFunc, TIntermTyped *expression)
{
return TIntermAggregate::CreateFunctionCall(*copyFunc, new TIntermSequence({expression}));
}
TIntermTyped *CreateTransposeCall(TSymbolTable *symbolTable, TIntermTyped *expression)
{
return CreateBuiltInFunctionCallNode("transpose", new TIntermSequence({expression}),
*symbolTable, 300);
}
TOperator GetIndex(TSymbolTable *symbolTable,
TIntermNode *node,
TIntermSequence *indices,
TIntermSequence *prependStatements)
{
// Swizzle nodes are converted EOpIndexDirect for simplicity, with one index per swizzle
// channel.
TIntermSwizzle *asSwizzle = node->getAsSwizzleNode();
if (asSwizzle)
{
for (int channel : asSwizzle->getSwizzleOffsets())
{
indices->push_back(CreateIndexNode(channel));
}
return EOpIndexDirect;
}
TIntermBinary *binaryNode = node->getAsBinaryNode();
ASSERT(binaryNode);
TOperator op = binaryNode->getOp();
ASSERT(op == EOpIndexDirect || op == EOpIndexDirectInterfaceBlock ||
op == EOpIndexDirectStruct || op == EOpIndexIndirect);
TIntermTyped *rhs = binaryNode->getRight()->deepCopy();
if (rhs->getAsConstantUnion() == nullptr)
{
rhs = CopyToTempVariable(symbolTable, rhs, prependStatements);
}
indices->push_back(rhs);
return op;
}
TIntermTyped *ReplicateIndexNode(TSymbolTable *symbolTable,
TIntermNode *node,
TIntermTyped *lhs,
TIntermSequence *indices)
{
TIntermSwizzle *asSwizzle = node->getAsSwizzleNode();
if (asSwizzle)
{
return new TIntermSwizzle(lhs, asSwizzle->getSwizzleOffsets());
}
TIntermBinary *binaryNode = node->getAsBinaryNode();
ASSERT(binaryNode);
ASSERT(indices->size() == 1);
TIntermTyped *rhs = indices->front()->getAsTyped();
return new TIntermBinary(binaryNode->getOp(), lhs, rhs);
}
TOperator GetIndexOp(TIntermNode *node)
{
return node->getAsConstantUnion() ? EOpIndexDirect : EOpIndexIndirect;
}
bool IsConvertedField(TIntermTyped *indexNode,
const angle::HashMap<const TField *, bool> &convertedFields)
{
TIntermBinary *asBinary = indexNode->getAsBinaryNode();
if (asBinary == nullptr)
{
return false;
}
if (asBinary->getOp() != EOpIndexDirectInterfaceBlock)
{
return false;
}
const TInterfaceBlock *interfaceBlock = asBinary->getLeft()->getType().getInterfaceBlock();
ASSERT(interfaceBlock);
TIntermConstantUnion *fieldIndexNode = asBinary->getRight()->getAsConstantUnion();
ASSERT(fieldIndexNode);
ASSERT(fieldIndexNode->getConstantValue() != nullptr);
int fieldIndex = fieldIndexNode->getConstantValue()->getIConst();
const TField *field = interfaceBlock->fields()[fieldIndex];
return convertedFields.count(field) > 0 && convertedFields.at(field);
}
// A helper class to transform expressions of array type. Iterates over every element of the
// array.
class TransformArrayHelper
{
public:
TransformArrayHelper(TIntermTyped *baseExpression)
: mBaseExpression(baseExpression),
mBaseExpressionType(baseExpression->getType()),
mArrayIndices(mBaseExpressionType.getArraySizes().size(), 0)
{}
TIntermTyped *getNextElement(TIntermTyped *valueExpression, TIntermTyped **valueElementOut)
{
const TSpan<const unsigned int> &arraySizes = mBaseExpressionType.getArraySizes();
// If the last index overflows, element enumeration is done.
if (mArrayIndices.back() >= arraySizes.back())
{
return nullptr;
}
TIntermTyped *element = getCurrentElement(mBaseExpression);
if (valueExpression)
{
*valueElementOut = getCurrentElement(valueExpression);
}
incrementIndices(arraySizes);
return element;
}
void accumulateForRead(TSymbolTable *symbolTable,
TIntermTyped *transformedElement,
TIntermSequence *prependStatements)
{
TIntermTyped *temp = CopyToTempVariable(symbolTable, transformedElement, prependStatements);
mReadTransformConstructorArgs.push_back(temp);
}
TIntermTyped *constructReadTransformExpression()
{
const TSpan<const unsigned int> &baseTypeArraySizes = mBaseExpressionType.getArraySizes();
TVector<unsigned int> arraySizes(baseTypeArraySizes.begin(), baseTypeArraySizes.end());
TIntermTyped *firstElement = mReadTransformConstructorArgs.front()->getAsTyped();
const TType &baseType = firstElement->getType();
// If N dimensions, acc[0] == size[0] and acc[i] == size[i] * acc[i-1].
// The last value is unused, and is not present.
TVector<unsigned int> accumulatedArraySizes(arraySizes.size() - 1);
if (accumulatedArraySizes.size() > 0)
{
accumulatedArraySizes[0] = arraySizes[0];
}
for (size_t index = 1; index + 1 < arraySizes.size(); ++index)
{
accumulatedArraySizes[index] = accumulatedArraySizes[index - 1] * arraySizes[index];
}
return constructReadTransformExpressionHelper(arraySizes, accumulatedArraySizes, baseType,
0);
}
private:
TIntermTyped *getCurrentElement(TIntermTyped *expression)
{
TIntermTyped *element = expression->deepCopy();
for (auto it = mArrayIndices.rbegin(); it != mArrayIndices.rend(); ++it)
{
unsigned int index = *it;
element = new TIntermBinary(EOpIndexDirect, element, CreateIndexNode(index));
}
return element;
}
void incrementIndices(const TSpan<const unsigned int> &arraySizes)
{
// Assume mArrayIndices is an N digit number, where digit i is in the range
// [0, arraySizes[i]). This function increments this number. Last digit is the most
// significant digit.
for (size_t digitIndex = 0; digitIndex < arraySizes.size(); ++digitIndex)
{
++mArrayIndices[digitIndex];
if (mArrayIndices[digitIndex] < arraySizes[digitIndex])
{
break;
}
if (digitIndex + 1 != arraySizes.size())
{
// This digit has now overflown and is reset to 0, carry will be added to the next
// digit. The most significant digit will keep the overflow though, to make it
// clear we have exhausted the range.
mArrayIndices[digitIndex] = 0;
}
}
}
TIntermTyped *constructReadTransformExpressionHelper(
const TVector<unsigned int> &arraySizes,
const TVector<unsigned int> &accumulatedArraySizes,
const TType &baseType,
size_t elementsOffset)
{
ASSERT(!arraySizes.empty());
TType *transformedType = new TType(baseType);
transformedType->makeArrays(arraySizes);
// If one dimensional, create the constructor with the given elements.
if (arraySizes.size() == 1)
{
ASSERT(accumulatedArraySizes.size() == 0);
auto sliceStart = mReadTransformConstructorArgs.begin() + elementsOffset;
TIntermSequence slice(sliceStart, sliceStart + arraySizes[0]);
return TIntermAggregate::CreateConstructor(*transformedType, &slice);
}
// If not, create constructors for every column recursively.
TVector<unsigned int> subArraySizes(arraySizes.begin(), arraySizes.end() - 1);
TVector<unsigned int> subArrayAccumulatedSizes(accumulatedArraySizes.begin(),
accumulatedArraySizes.end() - 1);
TIntermSequence constructorArgs;
unsigned int colStride = accumulatedArraySizes.back();
for (size_t col = 0; col < arraySizes.back(); ++col)
{
size_t colElementsOffset = elementsOffset + col * colStride;
constructorArgs.push_back(constructReadTransformExpressionHelper(
subArraySizes, subArrayAccumulatedSizes, baseType, colElementsOffset));
}
return TIntermAggregate::CreateConstructor(*transformedType, &constructorArgs);
}
TIntermTyped *mBaseExpression;
const TType &mBaseExpressionType;
TVector<unsigned int> mArrayIndices;
TIntermSequence mReadTransformConstructorArgs;
};
// Traverser that:
//
// 1. Converts |layout(row_major) matCxR M| to |layout(column_major) matRxC Mt|.
// 2. Converts |layout(row_major) S s| to |layout(column_major) St st|, where S is a struct that
// contains matrices, and St is a new struct with the transformation in 1 applied to matrix
// members (recursively).
// 3. When read from, the following transformations are applied:
//
// M -> transpose(Mt)
// M[c] -> gvecN(Mt[0][c], Mt[1][c], ..., Mt[N-1][c])
// M[c][r] -> Mt[r][c]
// M[c].yz -> gvec2(Mt[1][c], Mt[2][c])
// MArr -> MType[D1]..[DN](transpose(MtArr[0]...[0]), ...)
// s -> copy_St_to_S(st)
// sArr -> SType[D1]...[DN](copy_St_to_S(stArr[0]..[0]), ...)
// (matrix reads through struct are transformed similarly to M)
//
// 4. When written to, the following transformations are applied:
//
// M = exp -> Mt = transpose(exp)
// M[c] = exp -> temp = exp
// Mt[0][c] = temp[0]
// Mt[1][c] = temp[1]
// ...
// Mt[N-1][c] = temp[N-1]
// M[c][r] = exp -> Mt[r][c] = exp
// M[c].yz = exp -> temp = exp
// Mt[1][c] = temp[0]
// Mt[2][c] = temp[1]
// MArr = exp -> temp = exp
// Mt = MtType[D1]..[DN](temp([0]...[0]), ...)
// s = exp -> st = copy_S_to_St(exp)
// sArr = exp -> temp = exp
// St = StType[D1]...[DN](copy_S_to_St(temp[0]..[0]), ...)
// (matrix writes through struct are transformed similarly to M)
//
// 5. If any of the above is passed to an `inout` parameter, both transformations are applied:
//
// f(M[c]) -> temp = gvecN(Mt[0][c], Mt[1][c], ..., Mt[N-1][c])
// f(temp)
// Mt[0][c] = temp[0]
// Mt[1][c] = temp[1]
// ...
// Mt[N-1][c] = temp[N-1]
//
// f(s) -> temp = copy_St_to_S(st)
// f(temp)
// st = copy_S_to_St(temp)
//
// If passed to an `out` parameter, the `temp` parameter is simply not initialized.
//
// 6. If the expression leading to the matrix or struct has array subscripts, temp values are
// created for them to avoid duplicating side effects.
//
class RewriteRowMajorMatricesTraverser : public TIntermTraverser
{
public:
RewriteRowMajorMatricesTraverser(TCompiler *compiler, TSymbolTable *symbolTable)
: TIntermTraverser(true, true, true, symbolTable),
mCompiler(compiler),
mStructMapOut(&mOuterPass.structMap),
mInterfaceBlockMap(&mOuterPass.interfaceBlockMap),
mInterfaceBlockFieldConvertedIn(mOuterPass.interfaceBlockFieldConverted),
mCopyFunctionDefinitionsOut(&mOuterPass.copyFunctionDefinitions),
mOuterTraverser(nullptr),
mInnerPassRoot(nullptr),
mIsProcessingInnerPassSubtree(false)
{}
bool visitDeclaration(Visit visit, TIntermDeclaration *node) override
{
// No need to process declarations in inner passes.
if (mInnerPassRoot != nullptr)
{
return true;
}
if (visit != PreVisit)
{
return true;
}
const TIntermSequence &sequence = *(node->getSequence());
TIntermTyped *variable = sequence.front()->getAsTyped();
const TType &type = variable->getType();
// If it's a struct declaration that has matrices, remember it. If a row-major instance
// of it is created, it will have to be converted.
if (type.isStructSpecifier() && type.isStructureContainingMatrices())
{
const TStructure *structure = type.getStruct();
ASSERT(structure);
ASSERT(mOuterPass.structMap.count(structure) == 0);
StructConversionData structData;
mOuterPass.structMap[structure] = structData;
return false;
}
// If it's an interface block, it may have to be converted if it contains any row-major
// fields.
if (type.isInterfaceBlock() && type.getInterfaceBlock()->containsMatrices())
{
const TInterfaceBlock *block = type.getInterfaceBlock();
ASSERT(block);
bool isBlockRowMajor = type.getLayoutQualifier().matrixPacking == EmpRowMajor;
const TFieldList &fields = block->fields();
bool anyRowMajor = isBlockRowMajor;
for (const TField *field : fields)
{
if (DoesFieldContainRowMajorMatrix(field, isBlockRowMajor))
{
anyRowMajor = true;
break;
}
}
if (anyRowMajor)
{
convertInterfaceBlock(node);
}
return false;
}
return true;
}
void visitSymbol(TIntermSymbol *symbol) override
{
// If in inner pass, only process if the symbol is under that root.
if (mInnerPassRoot != nullptr && !mIsProcessingInnerPassSubtree)
{
return;
}
const TVariable *variable = &symbol->variable();
bool needsRewrite = mInterfaceBlockMap->count(variable) != 0;
// If it's a field of a nameless interface block, it may still need conversion.
if (!needsRewrite)
{
// Nameless interface block field symbols have the interface block pointer set, but are
// not interface blocks.
if (symbol->getType().getInterfaceBlock() && !variable->getType().isInterfaceBlock())
{
needsRewrite = convertNamelessInterfaceBlockField(symbol);
}
}
if (needsRewrite)
{
transformExpression(symbol);
}
}
bool visitBinary(Visit visit, TIntermBinary *node) override
{
if (node == mInnerPassRoot)
{
// We only want to process the right-hand side of an assignment in inner passes. When
// visit is InVisit, the left-hand side is already processed, and the right-hand side is
// next. Set a flag to mark this duration.
mIsProcessingInnerPassSubtree = visit == InVisit;
}
return true;
}
TIntermSequence *getStructCopyFunctions() { return &mOuterPass.copyFunctionDefinitions; }
private:
typedef angle::HashMap<const TStructure *, StructConversionData> StructMap;
typedef angle::HashMap<const TVariable *, TVariable *> InterfaceBlockMap;
typedef angle::HashMap<const TField *, bool> InterfaceBlockFieldConverted;
RewriteRowMajorMatricesTraverser(
TSymbolTable *symbolTable,
RewriteRowMajorMatricesTraverser *outerTraverser,
InterfaceBlockMap *interfaceBlockMap,
const InterfaceBlockFieldConverted &interfaceBlockFieldConverted,
StructMap *structMap,
TIntermSequence *copyFunctionDefinitions,
TIntermBinary *innerPassRoot)
: TIntermTraverser(true, true, true, symbolTable),
mStructMapOut(structMap),
mInterfaceBlockMap(interfaceBlockMap),
mInterfaceBlockFieldConvertedIn(interfaceBlockFieldConverted),
mCopyFunctionDefinitionsOut(copyFunctionDefinitions),
mOuterTraverser(outerTraverser),
mInnerPassRoot(innerPassRoot),
mIsProcessingInnerPassSubtree(false)
{}
void convertInterfaceBlock(TIntermDeclaration *node)
{
ASSERT(mInnerPassRoot == nullptr);
const TIntermSequence &sequence = *(node->getSequence());
TIntermTyped *variableNode = sequence.front()->getAsTyped();
const TType &type = variableNode->getType();
const TInterfaceBlock *block = type.getInterfaceBlock();
ASSERT(block);
bool isBlockRowMajor = type.getLayoutQualifier().matrixPacking == EmpRowMajor;
// Recreate the struct with its row-major fields converted to column-major equivalents.
TIntermSequence newDeclarations;
TFieldList *newFields = new TFieldList;
for (const TField *field : block->fields())
{
TField *newField = nullptr;
if (DoesFieldContainRowMajorMatrix(field, isBlockRowMajor))
{
newField = convertField(field, &newDeclarations);
// Remember that this field was converted.
mOuterPass.interfaceBlockFieldConverted[field] = true;
}
else
{
newField = DuplicateField(field);
}
newFields->push_back(newField);
}
// Create a new interface block with these fields.
TLayoutQualifier blockLayoutQualifier = type.getLayoutQualifier();
blockLayoutQualifier.matrixPacking = EmpColumnMajor;
TInterfaceBlock *newInterfaceBlock =
new TInterfaceBlock(mSymbolTable, block->name(), newFields, blockLayoutQualifier,
block->symbolType(), block->extension());
// Create a new declaration with the new type. Declarations are separated at this point,
// so there should be only one variable here.
ASSERT(sequence.size() == 1);
TType *newInterfaceBlockType =
new TType(newInterfaceBlock, type.getQualifier(), blockLayoutQualifier);
TIntermDeclaration *newDeclaration = new TIntermDeclaration;
const TVariable *variable = &variableNode->getAsSymbolNode()->variable();
const TType *newType = newInterfaceBlockType;
if (type.isArray())
{
TType *newArrayType = new TType(*newType);
CopyArraySizes(&type, newArrayType);
newType = newArrayType;
}
// If the interface block variable itself is temp, use an empty name.
bool variableIsTemp = variable->symbolType() == SymbolType::Empty;
const ImmutableString &variableName =
variableIsTemp ? kEmptyImmutableString : variable->name();
TVariable *newVariable = new TVariable(mSymbolTable, variableName, newType,
variable->symbolType(), variable->extension());
newDeclaration->appendDeclarator(new TIntermSymbol(newVariable));
mOuterPass.interfaceBlockMap[variable] = newVariable;
newDeclarations.push_back(newDeclaration);
// Replace the interface block definition with the new one, prepending any new struct
// definitions.
mMultiReplacements.emplace_back(getParentNode()->getAsBlock(), node, newDeclarations);
}
bool convertNamelessInterfaceBlockField(TIntermSymbol *symbol)
{
const TVariable *variable = &symbol->variable();
const TInterfaceBlock *interfaceBlock = symbol->getType().getInterfaceBlock();
// Find the variable corresponding to this interface block. If the interface block
// is not rewritten, or this refers to a field that is not rewritten, there's
// nothing to do.
for (auto iter : *mInterfaceBlockMap)
{
// Skip other rewritten nameless interface block fields.
if (!iter.first->getType().isInterfaceBlock())
{
continue;
}
// Skip if this is not a field of this rewritten interface block.
if (iter.first->getType().getInterfaceBlock() != interfaceBlock)
{
continue;
}
const ImmutableString symbolName = symbol->getName();
// Find which field it is
const TVector<TField *> fields = interfaceBlock->fields();
for (size_t fieldIndex = 0; fieldIndex < fields.size(); ++fieldIndex)
{
const TField *field = fields[fieldIndex];
if (field->name() != symbolName)
{
continue;
}
// If this field doesn't need a rewrite, there's nothing to do.
if (mInterfaceBlockFieldConvertedIn.count(field) == 0 ||
!mInterfaceBlockFieldConvertedIn.at(field))
{
break;
}
// Create a new variable that references the replaced interface block.
TType *newType = new TType(variable->getType());
newType->setInterfaceBlock(iter.second->getType().getInterfaceBlock());
TVariable *newVariable =
new TVariable(mSymbolTable, variable->name(), newType, variable->symbolType(),
variable->extension());
(*mInterfaceBlockMap)[variable] = newVariable;
return true;
}
break;
}
return false;
}
void convertStruct(const TStructure *structure, TIntermSequence *newDeclarations)
{
ASSERT(mInnerPassRoot == nullptr);
ASSERT(mOuterPass.structMap.count(structure) != 0);
StructConversionData *structData = &mOuterPass.structMap[structure];
if (structData->convertedStruct)
{
return;
}
TFieldList *newFields = new TFieldList;
for (const TField *field : structure->fields())
{
newFields->push_back(convertField(field, newDeclarations));
}
// Create unique names for the converted structs. We can't leave them nameless and have
// a name autogenerated similar to temp variables, as nameless structs exist. A fake
// variable is created for the sole purpose of generating a temp name.
TVariable *newStructTypeName =
new TVariable(mSymbolTable, kEmptyImmutableString, StaticType::GetBasic<EbtUInt>(),
SymbolType::Empty);
TStructure *newStruct = new TStructure(mSymbolTable, newStructTypeName->name(), newFields,
SymbolType::AngleInternal);
TType *newType = new TType(newStruct, true);
TVariable *newStructVar =
new TVariable(mSymbolTable, kEmptyImmutableString, newType, SymbolType::Empty);
TIntermDeclaration *structDecl = new TIntermDeclaration;
structDecl->appendDeclarator(new TIntermSymbol(newStructVar));
newDeclarations->push_back(structDecl);
structData->convertedStruct = newStruct;
}
TField *convertField(const TField *field, TIntermSequence *newDeclarations)
{
ASSERT(mInnerPassRoot == nullptr);
TField *newField = nullptr;
const TType *fieldType = field->type();
TType *newType = nullptr;
if (fieldType->isStructureContainingMatrices())
{
// If the field is a struct instance, convert the struct and replace the field
// with an instance of the new struct.
const TStructure *fieldTypeStruct = fieldType->getStruct();
convertStruct(fieldTypeStruct, newDeclarations);
StructConversionData &structData = mOuterPass.structMap[fieldTypeStruct];
newType = new TType(structData.convertedStruct, false);
SetColumnMajor(newType);
CopyArraySizes(fieldType, newType);
}
else if (fieldType->isMatrix())
{
// If the field is a matrix, transpose the matrix and replace the field with
// that, removing the matrix packing qualifier.
newType = TransposeMatrixType(fieldType);
}
if (newType)
{
newField = new TField(newType, field->name(), field->line(), field->symbolType());
}
else
{
newField = DuplicateField(field);
}
return newField;
}
void determineAccess(TIntermNode *expression,
TIntermNode *accessor,
bool *isReadOut,
bool *isWriteOut)
{
// If passing to a function, look at whether the parameter is in, out or inout.
TIntermAggregate *functionCall = accessor->getAsAggregate();
if (functionCall)
{
TIntermSequence *arguments = functionCall->getSequence();
for (size_t argIndex = 0; argIndex < arguments->size(); ++argIndex)
{
if ((*arguments)[argIndex] == expression)
{
TQualifier qualifier = EvqIn;
// If the aggregate is not a function call, it's a constructor, and so every
// argument is an input.
const TFunction *function = functionCall->getFunction();
if (function)
{
const TVariable *param = function->getParam(argIndex);
qualifier = param->getType().getQualifier();
}
*isReadOut = qualifier != EvqOut;
*isWriteOut = qualifier == EvqOut || qualifier == EvqInOut;
break;
}
}
return;
}
TIntermBinary *assignment = accessor->getAsBinaryNode();
if (assignment && IsAssignment(assignment->getOp()))
{
// If expression is on the right of assignment, it's being read from.
*isReadOut = assignment->getRight() == expression;
// If it's on the left of assignment, it's being written to.
*isWriteOut = assignment->getLeft() == expression;
return;
}
// Any other usage is a read.
*isReadOut = true;
*isWriteOut = false;
}
void transformExpression(TIntermSymbol *symbol)
{
// Walk up the parent chain while the nodes are EOpIndex* (whether array indexing or struct
// field selection) or swizzle and construct the replacement expression. This traversal can
// lead to one of the following possibilities:
//
// - a.b[N].etc.s (struct, or struct array): copy function should be declared and used,
// - a.b[N].etc.M (matrix or matrix array): transpose() should be used,
// - a.b[N].etc.M[c] (a column): each element in column needs to be handled separately,
// - a.b[N].etc.M[c].yz (multiple elements): similar to whole column, but a subset of
// elements,
// - a.b[N].etc.M[c][r] (an element): single element to handle.
// - a.b[N].etc.x (not struct or matrix): not modified
//
// primaryIndex will contain c, if any. secondaryIndices will contain {0, ..., R-1}
// (if no [r] or swizzle), {r} (if [r]), or {1, 2} (corresponding to .yz) if any.
//
// In all cases, the base symbol is replaced. |baseExpression| will contain everything up
// to (and not including) the last index/swizzle operations, i.e. a.b[N].etc.s/M/x. Any
// non constant array subscript is assigned to a temp variable to avoid duplicating side
// effects.
//
// ---
//
// NOTE that due to the use of insertStatementsInParentBlock, cases like this will be
// mistranslated, and this bug is likely present in most transformations that use this
// feature:
//
// if (x == 1 && a.b[x = 2].etc.M = value)
//
// which will translate to:
//
// temp = (x = 2)
// if (x == 1 && a.b[temp].etc.M = transpose(value))
//
// See http://anglebug.com/3829.
//
TIntermTyped *baseExpression =
new TIntermSymbol(mInterfaceBlockMap->at(&symbol->variable()));
const TStructure *structure = nullptr;
TIntermNode *primaryIndex = nullptr;
TIntermSequence secondaryIndices;
// In some cases, it is necessary to prepend or append statements. Those are captured in
// |prependStatements| and |appendStatements|.
TIntermSequence prependStatements;
TIntermSequence appendStatements;
// If the expression is neither a struct or matrix, no modification is necessary.
// If it's a struct that doesn't have matrices, again there's no transformation necessary.
// If it's an interface block matrix field that didn't need to be transposed, no
// transpformation is necessary.
//
// In all these cases, |baseExpression| contains all of the original expression.
//
// If the starting symbol itself is a field of a nameless interface block, it needs
// conversion if we reach here.
bool requiresTransformation = !symbol->getType().isInterfaceBlock();
uint32_t accessorIndex = 0;
TIntermTyped *previousAncestor = symbol;
while (IsIndexNode(getAncestorNode(accessorIndex), previousAncestor))
{
TIntermTyped *ancestor = getAncestorNode(accessorIndex)->getAsTyped();
ASSERT(ancestor);
const TType &previousAncestorType = previousAncestor->getType();
TIntermSequence indices;
TOperator op = GetIndex(mSymbolTable, ancestor, &indices, &prependStatements);
bool opIsIndex = op == EOpIndexDirect || op == EOpIndexIndirect;
bool isArrayIndex = opIsIndex && previousAncestorType.isArray();
bool isMatrixIndex = opIsIndex && previousAncestorType.isMatrix();
// If it's a direct index in a matrix, it's the primary index.
bool isMatrixPrimarySubscript = isMatrixIndex && !isArrayIndex;
ASSERT(!isMatrixPrimarySubscript ||
(primaryIndex == nullptr && secondaryIndices.empty()));
// If primary index is seen and the ancestor is still an index, it must be a direct
// index as the secondary one. Note that if primaryIndex is set, there can only ever be
// one more parent of interest, and that's subscripting the second dimension.
bool isMatrixSecondarySubscript = primaryIndex != nullptr;
ASSERT(!isMatrixSecondarySubscript || (opIsIndex && !isArrayIndex));
if (requiresTransformation && isMatrixPrimarySubscript)
{
ASSERT(indices.size() == 1);
primaryIndex = indices.front();
// Default the secondary indices to include every row. If there's a secondary
// subscript provided, it will override this.
int rows = previousAncestorType.getRows();
for (int r = 0; r < rows; ++r)
{
secondaryIndices.push_back(CreateIndexNode(r));
}
}
else if (isMatrixSecondarySubscript)
{
ASSERT(requiresTransformation);
secondaryIndices = indices;
// Indices after this point are not interesting. There can't actually be any other
// index nodes other than desktop GLSL's swizzles on scalars, like M[1][2].yyy.
++accessorIndex;
break;
}
else
{
// Replicate the expression otherwise.
baseExpression =
ReplicateIndexNode(mSymbolTable, ancestor, baseExpression, &indices);
const TType &ancestorType = ancestor->getType();
structure = ancestorType.getStruct();
requiresTransformation =
requiresTransformation ||
IsConvertedField(ancestor, mInterfaceBlockFieldConvertedIn);
// If we reach a point where the expression is neither a matrix-containing struct
// nor a matrix, there's no transformation required. This can happen if we decend
// through a struct marked with row-major but arrive at a member that doesn't
// include a matrix.
if (!ancestorType.isMatrix() && !ancestorType.isStructureContainingMatrices())
{
requiresTransformation = false;
}
}
previousAncestor = ancestor;
++accessorIndex;
}
TIntermNode *originalExpression =
accessorIndex == 0 ? symbol : getAncestorNode(accessorIndex - 1);
TIntermNode *accessor = getAncestorNode(accessorIndex);
// if accessor is EOpArrayLength, we don't need to perform any transformations either.
// Note that this only applies to unsized arrays, as the RemoveArrayLengthMethod()
// transformation would have removed this operation otherwise.
TIntermUnary *accessorAsUnary = accessor->getAsUnaryNode();
if (requiresTransformation && accessorAsUnary && accessorAsUnary->getOp() == EOpArrayLength)
{
ASSERT(accessorAsUnary->getOperand() == originalExpression);
ASSERT(accessorAsUnary->getOperand()->getType().isUnsizedArray());
requiresTransformation = false;
// We need to replace the whole expression including the EOpArrayLength, to avoid
// confusing the replacement code as the original and new expressions don't have the
// same type (one is the transpose of the other). This doesn't affect the .length()
// operation, so this replacement is ok, though it's not worth special-casing this in
// the node replacement algorithm.
//
// Note: the |if (!requiresTransformation)| immediately below will be entered after
// this.
originalExpression = accessor;
accessor = getAncestorNode(accessorIndex + 1);
baseExpression = new TIntermUnary(EOpArrayLength, baseExpression, nullptr);
}
if (!requiresTransformation)
{
ASSERT(primaryIndex == nullptr);
queueReplacementWithParent(accessor, originalExpression, baseExpression,
OriginalNode::IS_DROPPED);
RewriteRowMajorMatricesTraverser *traverser = mOuterTraverser ? mOuterTraverser : this;
traverser->insertStatementsInParentBlock(prependStatements, appendStatements);
return;
}
ASSERT(structure == nullptr || primaryIndex == nullptr);
ASSERT(structure != nullptr || baseExpression->getType().isMatrix());
// At the end, we can determine if the expression is being read from or written to (or both,
// if sent as an inout parameter to a function). For the sake of the transformation, the
// left-hand side of operations like += can be treated as "written to", without necessarily
// "read from".
bool isRead = false;
bool isWrite = false;
determineAccess(originalExpression, accessor, &isRead, &isWrite);
ASSERT(isRead || isWrite);
TIntermTyped *readExpression = nullptr;
if (isRead)
{
readExpression = transformReadExpression(
baseExpression, primaryIndex, &secondaryIndices, structure, &prependStatements);
// If both read from and written to (i.e. passed to inout parameter), store the
// expression in a temp variable and pass that to the function.
if (isWrite)
{
readExpression =
CopyToTempVariable(mSymbolTable, readExpression, &prependStatements);
}
// Replace the original expression with the transformed one. Read transformations
// always generate a single expression that can be used in place of the original (as
// oppposed to write transformations that can generate multiple statements).
queueReplacementWithParent(accessor, originalExpression, readExpression,
OriginalNode::IS_DROPPED);
}
TIntermSequence postTransformPrependStatements;
TIntermSequence *writeStatements = &appendStatements;
TOperator assignmentOperator = EOpAssign;
if (isWrite)
{
TIntermTyped *valueExpression = readExpression;
if (!valueExpression)
{
// If there's already a read expression, this was an inout parameter and
// |valueExpression| will contain the temp variable that was passed to the function
// instead.
//
// If not, then the modification is either through being passed as an out parameter
// to a function, or an assignment. In the former case, create a temp variable to
// be passed to the function. In the latter case, create a temp variable that holds
// the right hand side expression.
//
// In either case, use that temp value as the value to assign to |baseExpression|.
TVariable *temp =
CreateTempVariable(mSymbolTable, &originalExpression->getAsTyped()->getType());
TIntermDeclaration *tempDecl = nullptr;
valueExpression = new TIntermSymbol(temp);
TIntermBinary *assignment = accessor->getAsBinaryNode();
if (assignment)
{
assignmentOperator = assignment->getOp();
ASSERT(IsAssignment(assignmentOperator));
// We are converting the assignment to the left-hand side of an expression in
// the form M=exp. A subexpression of exp itself could require a
// transformation. This complicates things as there would be two replacements:
//
// - Replace M=exp with temp (because the return value of the assignment could
// be used)
// - Replace exp with exp2, where parent is M=exp
//
// The second replacement however is ineffective as the whole of M=exp is
// already transformed. What's worse, M=exp is transformed without taking exp's
// transformations into account. To address this issue, this same traverser is
// called on the right-hand side expression, with a special flag such that it
// only processes that expression.
//
RewriteRowMajorMatricesTraverser *outerTraverser =
mOuterTraverser ? mOuterTraverser : this;
RewriteRowMajorMatricesTraverser rhsTraverser(
mSymbolTable, outerTraverser, mInterfaceBlockMap,
mInterfaceBlockFieldConvertedIn, mStructMapOut, mCopyFunctionDefinitionsOut,
assignment);
getRootNode()->traverse(&rhsTraverser);
bool valid = rhsTraverser.updateTree(mCompiler, getRootNode());
ASSERT(valid);
tempDecl = CreateTempInitDeclarationNode(temp, assignment->getRight());
// Replace the whole assignment expression with the right-hand side as a read
// expression, in case the result of the assignment is used. For example, this
// transforms:
//
// if ((M += exp) == X)
// {
// // use M
// }
//
// to:
//
// temp = exp;
// M += transform(temp);
// if (transform(M) == X)
// {
// // use M
// }
//
// Note that in this case the assignment to M must be prepended in the parent
// block. In contrast, when sent to a function, the assignment to M should be
// done after the current function call is done.
//
// If the read from M itself (to replace assigmnet) needs to generate extra
// statements, they should be appended after the statements that write to M.
// These statements are stored in postTransformPrependStatements and appended to
// prependStatements in the end.
//
writeStatements = &prependStatements;
TIntermTyped *assignmentResultExpression = transformReadExpression(
baseExpression->deepCopy(), primaryIndex, &secondaryIndices, structure,
&postTransformPrependStatements);
// Replace the whole assignment, instead of just the right hand side.
TIntermNode *accessorParent = getAncestorNode(accessorIndex + 1);
queueReplacementWithParent(accessorParent, accessor, assignmentResultExpression,
OriginalNode::IS_DROPPED);
}
else
{
tempDecl = CreateTempDeclarationNode(temp);
// Replace the write expression (a function call argument) with the temp
// variable.
queueReplacementWithParent(accessor, originalExpression, valueExpression,
OriginalNode::IS_DROPPED);
}
prependStatements.push_back(tempDecl);
}
if (isRead)
{
baseExpression = baseExpression->deepCopy();
}
transformWriteExpression(baseExpression, primaryIndex, &secondaryIndices, structure,
valueExpression, assignmentOperator, writeStatements);
}
prependStatements.insert(prependStatements.end(), postTransformPrependStatements.begin(),
postTransformPrependStatements.end());
RewriteRowMajorMatricesTraverser *traverser = mOuterTraverser ? mOuterTraverser : this;
traverser->insertStatementsInParentBlock(prependStatements, appendStatements);
}
TIntermTyped *transformReadExpression(TIntermTyped *baseExpression,
TIntermNode *primaryIndex,
TIntermSequence *secondaryIndices,
const TStructure *structure,
TIntermSequence *prependStatements)
{
const TType &baseExpressionType = baseExpression->getType();
if (structure)
{
ASSERT(primaryIndex == nullptr && secondaryIndices->empty());
ASSERT(mStructMapOut->count(structure) != 0);
ASSERT((*mStructMapOut)[structure].convertedStruct != nullptr);
// Declare copy-from-converted-to-original-struct function (if not already).
declareStructCopyToOriginal(structure);
const TFunction *copyToOriginal = (*mStructMapOut)[structure].copyToOriginal;
if (baseExpressionType.isArray())
{
// If base expression is an array, transform every element.
TransformArrayHelper transformHelper(baseExpression);
TIntermTyped *element = nullptr;
while ((element = transformHelper.getNextElement(nullptr, nullptr)) != nullptr)
{
TIntermTyped *transformedElement =
CreateStructCopyCall(copyToOriginal, element);
transformHelper.accumulateForRead(mSymbolTable, transformedElement,
prependStatements);
}
return transformHelper.constructReadTransformExpression();
}
else
{
// If not reading an array, the result is simply a call to this function with the
// base expression.
return CreateStructCopyCall(copyToOriginal, baseExpression);
}
}
// If not indexed, the result is transpose(exp)
if (primaryIndex == nullptr)
{
ASSERT(secondaryIndices->empty());
if (baseExpressionType.isArray())
{
// If array, transpose every element.
TransformArrayHelper transformHelper(baseExpression);
TIntermTyped *element = nullptr;
while ((element = transformHelper.getNextElement(nullptr, nullptr)) != nullptr)
{
TIntermTyped *transformedElement = CreateTransposeCall(mSymbolTable, element);
transformHelper.accumulateForRead(mSymbolTable, transformedElement,
prependStatements);
}
return transformHelper.constructReadTransformExpression();
}
else
{
return CreateTransposeCall(mSymbolTable, baseExpression);
}
}
// If indexed the result is a vector (or just one element) where the primary and secondary
// indices are swapped.
ASSERT(!secondaryIndices->empty());
TOperator primaryIndexOp = GetIndexOp(primaryIndex);
TIntermTyped *primaryIndexAsTyped = primaryIndex->getAsTyped();
TIntermSequence transposedColumn;
for (TIntermNode *secondaryIndex : *secondaryIndices)
{
TOperator secondaryIndexOp = GetIndexOp(secondaryIndex);
TIntermTyped *secondaryIndexAsTyped = secondaryIndex->getAsTyped();
TIntermBinary *colIndexed = new TIntermBinary(
secondaryIndexOp, baseExpression->deepCopy(), secondaryIndexAsTyped->deepCopy());
TIntermBinary *colRowIndexed =
new TIntermBinary(primaryIndexOp, colIndexed, primaryIndexAsTyped->deepCopy());
transposedColumn.push_back(colRowIndexed);
}
if (secondaryIndices->size() == 1)
{
// If only one element, return that directly.
return transposedColumn.front()->getAsTyped();
}
// Otherwise create a constructor with the appropriate dimension.
TType *vecType = new TType(baseExpressionType.getBasicType(), secondaryIndices->size());
return TIntermAggregate::CreateConstructor(*vecType, &transposedColumn);
}
void transformWriteExpression(TIntermTyped *baseExpression,
TIntermNode *primaryIndex,
TIntermSequence *secondaryIndices,
const TStructure *structure,
TIntermTyped *valueExpression,
TOperator assignmentOperator,
TIntermSequence *writeStatements)
{
const TType &baseExpressionType = baseExpression->getType();
if (structure)
{
ASSERT(primaryIndex == nullptr && secondaryIndices->empty());
ASSERT(mStructMapOut->count(structure) != 0);
ASSERT((*mStructMapOut)[structure].convertedStruct != nullptr);
// Declare copy-to-converted-from-original-struct function (if not already).
declareStructCopyFromOriginal(structure);
// The result is call to this function with the value expression assigned to base
// expression.
const TFunction *copyFromOriginal = (*mStructMapOut)[structure].copyFromOriginal;
if (baseExpressionType.isArray())
{
// If array, assign every element.
TransformArrayHelper transformHelper(baseExpression);
TIntermTyped *element = nullptr;
TIntermTyped *valueElement = nullptr;
while ((element = transformHelper.getNextElement(valueExpression, &valueElement)) !=
nullptr)
{
TIntermTyped *functionCall =
CreateStructCopyCall(copyFromOriginal, valueElement);
writeStatements->push_back(new TIntermBinary(EOpAssign, element, functionCall));
}
}
else
{
TIntermTyped *functionCall =
CreateStructCopyCall(copyFromOriginal, valueExpression->deepCopy());
writeStatements->push_back(
new TIntermBinary(EOpAssign, baseExpression, functionCall));
}
return;
}
// If not indexed, the result is transpose(exp)
if (primaryIndex == nullptr)
{
ASSERT(secondaryIndices->empty());
if (baseExpressionType.isArray())
{
// If array, assign every element.
TransformArrayHelper transformHelper(baseExpression);
TIntermTyped *element = nullptr;
TIntermTyped *valueElement = nullptr;
while ((element = transformHelper.getNextElement(valueExpression, &valueElement)) !=
nullptr)
{
TIntermTyped *valueTransposed = CreateTransposeCall(mSymbolTable, valueElement);
writeStatements->push_back(
new TIntermBinary(EOpAssign, element, valueTransposed));
}
}
else
{
TIntermTyped *valueTransposed =
CreateTransposeCall(mSymbolTable, valueExpression->deepCopy());
writeStatements->push_back(
new TIntermBinary(assignmentOperator, baseExpression, valueTransposed));
}
return;
}
// If indexed, create one assignment per secondary index. If the right-hand side is a
// scalar, it's used with every assignment. If it's a vector, the assignment is
// per-component. The right-hand side cannot be a matrix as that would imply left-hand
// side being a matrix too, which is covered above where |primaryIndex == nullptr|.
ASSERT(!secondaryIndices->empty());
bool isValueExpressionScalar = valueExpression->getType().getNominalSize() == 1;
ASSERT(isValueExpressionScalar || valueExpression->getType().getNominalSize() ==
static_cast<int>(secondaryIndices->size()));
TOperator primaryIndexOp = GetIndexOp(primaryIndex);
TIntermTyped *primaryIndexAsTyped = primaryIndex->getAsTyped();
for (TIntermNode *secondaryIndex : *secondaryIndices)
{
TOperator secondaryIndexOp = GetIndexOp(secondaryIndex);
TIntermTyped *secondaryIndexAsTyped = secondaryIndex->getAsTyped();
TIntermBinary *colIndexed = new TIntermBinary(
secondaryIndexOp, baseExpression->deepCopy(), secondaryIndexAsTyped->deepCopy());
TIntermBinary *colRowIndexed =
new TIntermBinary(primaryIndexOp, colIndexed, primaryIndexAsTyped->deepCopy());
TIntermTyped *valueExpressionIndexed = valueExpression->deepCopy();
if (!isValueExpressionScalar)
{
valueExpressionIndexed = new TIntermBinary(secondaryIndexOp, valueExpressionIndexed,
secondaryIndexAsTyped->deepCopy());
}
writeStatements->push_back(
new TIntermBinary(assignmentOperator, colRowIndexed, valueExpressionIndexed));
}
}
const TFunction *getCopyStructFieldFunction(const TType *fromFieldType,
const TType *toFieldType,
bool isCopyToOriginal)
{
ASSERT(fromFieldType->getStruct());
ASSERT(toFieldType->getStruct());
// If copying from or to the original struct, the "to" field struct could require
// conversion to or from the "from" field struct. |isCopyToOriginal| tells us if we
// should expect to find toField or fromField in mStructMapOut, if true or false
// respectively.
const TFunction *fieldCopyFunction = nullptr;
if (isCopyToOriginal)
{
const TStructure *toFieldStruct = toFieldType->getStruct();
auto iter = mStructMapOut->find(toFieldStruct);
if (iter != mStructMapOut->end())
{
declareStructCopyToOriginal(toFieldStruct);
fieldCopyFunction = iter->second.copyToOriginal;
}
}
else
{
const TStructure *fromFieldStruct = fromFieldType->getStruct();
auto iter = mStructMapOut->find(fromFieldStruct);
if (iter != mStructMapOut->end())
{
declareStructCopyFromOriginal(fromFieldStruct);
fieldCopyFunction = iter->second.copyFromOriginal;
}
}
return fieldCopyFunction;
}
void addFieldCopy(TIntermBlock *body,
TIntermTyped *to,
TIntermTyped *from,
bool isCopyToOriginal)
{
const TType &fromType = from->getType();
const TType &toType = to->getType();
TIntermTyped *rhs = from;
if (fromType.getStruct())
{
const TFunction *fieldCopyFunction =
getCopyStructFieldFunction(&fromType, &toType, isCopyToOriginal);
if (fieldCopyFunction)
{
rhs = CreateStructCopyCall(fieldCopyFunction, from);
}
}
else if (fromType.isMatrix())
{
rhs = CreateTransposeCall(mSymbolTable, from);
}
body->appendStatement(new TIntermBinary(EOpAssign, to, rhs));
}
TFunction *declareStructCopy(const TStructure *from,
const TStructure *to,
bool isCopyToOriginal)
{
TType *fromType = new TType(from, true);
TType *toType = new TType(to, true);
// Create the parameter and return value variables.
TVariable *fromVar = new TVariable(mSymbolTable, ImmutableString("from"), fromType,
SymbolType::AngleInternal);
TVariable *toVar =
new TVariable(mSymbolTable, ImmutableString("to"), toType, SymbolType::AngleInternal);
TIntermSymbol *fromSymbol = new TIntermSymbol(fromVar);
TIntermSymbol *toSymbol = new TIntermSymbol(toVar);
// Create the function body as statements are generated.
TIntermBlock *body = new TIntermBlock;
// Declare the result variable.
TIntermDeclaration *toDecl = new TIntermDeclaration();
toDecl->appendDeclarator(toSymbol);
body->appendStatement(toDecl);
// Iterate over fields of the struct and copy one by one, transposing the matrices. If a
// struct is encountered that requires a transformation, this function is recursively
// called. As a result, it is important that the copy functions are placed in the code in
// order.
const TFieldList &fromFields = from->fields();
const TFieldList &toFields = to->fields();
ASSERT(fromFields.size() == toFields.size());
for (size_t fieldIndex = 0; fieldIndex < fromFields.size(); ++fieldIndex)
{
TIntermTyped *fieldIndexNode = CreateIndexNode(static_cast<int>(fieldIndex));
TIntermTyped *fromField =
new TIntermBinary(EOpIndexDirectStruct, fromSymbol->deepCopy(), fieldIndexNode);
TIntermTyped *toField = new TIntermBinary(EOpIndexDirectStruct, toSymbol->deepCopy(),
fieldIndexNode->deepCopy());
const TType *fromFieldType = fromFields[fieldIndex]->type();
bool isStructOrMatrix = fromFieldType->getStruct() || fromFieldType->isMatrix();
if (fromFieldType->isArray() && isStructOrMatrix)
{
// If struct or matrix array, we need to copy element by element.
TransformArrayHelper transformHelper(toField);
TIntermTyped *toElement = nullptr;
TIntermTyped *fromElement = nullptr;
while ((toElement = transformHelper.getNextElement(fromField, &fromElement)) !=
nullptr)
{
addFieldCopy(body, toElement, fromElement, isCopyToOriginal);
}
}
else
{
addFieldCopy(body, toField, fromField, isCopyToOriginal);
}
}
// Add return statement.
body->appendStatement(new TIntermBranch(EOpReturn, toSymbol->deepCopy()));
// Declare the function
TFunction *copyFunction = new TFunction(mSymbolTable, kEmptyImmutableString,
SymbolType::AngleInternal, toType, true);
copyFunction->addParameter(fromVar);
TIntermFunctionDefinition *functionDef =
CreateInternalFunctionDefinitionNode(*copyFunction, body);
mCopyFunctionDefinitionsOut->push_back(functionDef);
return copyFunction;
}
void declareStructCopyFromOriginal(const TStructure *structure)
{
StructConversionData *structData = &(*mStructMapOut)[structure];
if (structData->copyFromOriginal)
{
return;
}
structData->copyFromOriginal =
declareStructCopy(structure, structData->convertedStruct, false);
}
void declareStructCopyToOriginal(const TStructure *structure)
{
StructConversionData *structData = &(*mStructMapOut)[structure];
if (structData->copyToOriginal)
{
return;
}
structData->copyToOriginal =
declareStructCopy(structData->convertedStruct, structure, true);
}
TCompiler *mCompiler;
// This traverser can call itself to transform a subexpression before moving on. However, it
// needs to accumulate conversion functions in inner passes. The fields below marked with Out
// or In are inherited from the outer pass (for inner passes), or point to storage fields in
// mOuterPass (for the outer pass). The latter should not be used by the inner passes as they
// would be empty, so they are placed inside a struct to make them explicit.
struct
{
StructMap structMap;
InterfaceBlockMap interfaceBlockMap;
InterfaceBlockFieldConverted interfaceBlockFieldConverted;
TIntermSequence copyFunctionDefinitions;
} mOuterPass;
// A map from structures with matrices to their converted version.
StructMap *mStructMapOut;
// A map from interface block instances with row-major matrices to their converted variable. If
// an interface block is nameless, its fields are placed in this map instead. When a variable
// in this map is encountered, it signals the start of an expression that my need conversion,
// which is either "interfaceBlock.field..." or "field..." if nameless.
InterfaceBlockMap *mInterfaceBlockMap;
// A map from interface block fields to whether they need to be converted. If a field was
// already column-major, it shouldn't be transposed.
const InterfaceBlockFieldConverted &mInterfaceBlockFieldConvertedIn;
TIntermSequence *mCopyFunctionDefinitionsOut;
// If set, it's an inner pass and this will point to the outer pass traverser. All statement
// insertions are stored in the outer traverser and applied at once in the end. This prevents
// the inner passes from adding statements which invalidates the outer traverser's statement
// position tracking.
RewriteRowMajorMatricesTraverser *mOuterTraverser;
// If set, it's an inner pass that should only process the right-hand side of this particular
// node.
TIntermBinary *mInnerPassRoot;
bool mIsProcessingInnerPassSubtree;
};
} // anonymous namespace
bool RewriteRowMajorMatrices(TCompiler *compiler, TIntermBlock *root, TSymbolTable *symbolTable)
{
RewriteRowMajorMatricesTraverser traverser(compiler, symbolTable);
root->traverse(&traverser);
if (!traverser.updateTree(compiler, root))
{
return false;
}
size_t firstFunctionIndex = FindFirstFunctionDefinitionIndex(root);
root->insertChildNodes(firstFunctionIndex, *traverser.getStructCopyFunctions());
return compiler->validateAST(root);
}
} // namespace sh
|
#include "splashscreen.h"
#include "clientversion.h"
#include "util.h"
#include <QPainter>
#include <QApplication>
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) :
QSplashScreen(pixmap, f)
{
// set reference point, paddings
int paddingRight = 50;
int paddingTop = 50;
int titleVersionVSpace = 17;
int titleCopyrightVSpace = 40;
float fontFactor = 1.0;
// define text to place
QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down
QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
QString copyrightText = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Solidar developers"));
QString testnetAddText = QString(tr("[testnet]")); // define text to place as single text object
QString font = "Arial";
// load the bitmap for writing some text over it
QPixmap newPixmap;
if(GetBoolArg("-testnet")) {
newPixmap = QPixmap(":/images/splash_testnet");
}
else {
newPixmap = QPixmap(":/images/splash");
}
QPainter pixPaint(&newPixmap);
pixPaint.setPen(QColor(100,100,100));
// check font size and drawing with
pixPaint.setFont(QFont(font, 33*fontFactor));
QFontMetrics fm = pixPaint.fontMetrics();
int titleTextWidth = fm.width(titleText);
if(titleTextWidth > 160) {
// strange font rendering, Arial probably not found
fontFactor = 0.75;
}
pixPaint.setFont(QFont(font, 33*fontFactor));
fm = pixPaint.fontMetrics();
titleTextWidth = fm.width(titleText);
pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText);
pixPaint.setFont(QFont(font, 15*fontFactor));
// if the version string is to long, reduce size
fm = pixPaint.fontMetrics();
int versionTextWidth = fm.width(versionText);
if(versionTextWidth > titleTextWidth+paddingRight-10) {
pixPaint.setFont(QFont(font, 10*fontFactor));
titleVersionVSpace -= 5;
}
pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);
// draw copyright stuff
pixPaint.setFont(QFont(font, 10*fontFactor));
pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText);
// draw testnet string if -testnet is on
if(QApplication::applicationName().contains(QString("-testnet"))) {
// draw copyright stuff
QFont boldFont = QFont(font, 10*fontFactor);
boldFont.setWeight(QFont::Bold);
pixPaint.setFont(boldFont);
fm = pixPaint.fontMetrics();
int testnetAddTextWidth = fm.width(testnetAddText);
pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);
}
pixPaint.end();
this->setPixmap(newPixmap);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "ildasmpch.h"
#include <crtdbg.h>
#include <utilcode.h>
#include "specstrings.h"
#include "debugmacros.h"
#include "corpriv.h"
#include "ceeload.h"
#include "dynamicarray.h"
#include <metamodelpub.h>
#include "formattype.h"
#define DECLARE_DATA
#include "dasmenum.hpp"
#include "dis.h"
#include "resource.h"
#include "dasm_sz.h"
//#define MAX_FILENAME_LENGTH 2048 //moved to dis.h
#include <corsym.h>
#include <ndpversion.h>
// Disable the "initialization of static local vars is no thread safe" error
#ifdef _MSC_VER
#pragma warning(disable : 4640)
#endif
#if defined(_DEBUG) && defined(FEATURE_PREJIT)
#include <corcompile.h>
#endif
#ifdef TARGET_UNIX
#include "resourcestring.h"
#define NATIVE_STRING_RESOURCE_NAME dasm_rc
DECLARE_NATIVE_STRING_RESOURCE_TABLE(NATIVE_STRING_RESOURCE_NAME);
#endif
struct MIDescriptor
{
mdToken tkClass; // defining class token
mdToken tkDecl; // implemented method token
mdToken tkBody; // implementing method token
mdToken tkBodyParent; // parent of the implementing method
};
ISymUnmanagedReader* g_pSymReader = NULL;
IMDInternalImport* g_pImport = NULL;
IMetaDataImport2* g_pPubImport;
extern IMetaDataAssemblyImport* g_pAssemblyImport;
PELoader * g_pPELoader;
void * g_pMetaData;
unsigned g_cbMetaData;
IMAGE_COR20_HEADER * g_CORHeader;
DynamicArray<__int32> *g_pPtrTags = NULL; //to keep track of all "ldptr"
DynamicArray<DWORD> *g_pPtrSize= NULL; //to keep track of all "ldptr"
int g_iPtrCount = 0;
mdToken * g_cl_list = NULL;
mdToken * g_cl_enclosing = NULL;
BYTE* g_enum_td_type = NULL; // enum (TD) underlying types
BYTE* g_enum_tr_type = NULL; // enum (TR) underlying types
IMDInternalImport** g_asmref_import = NULL; // IMDInternalImports for external assemblies
DynamicArray<MIDescriptor> *g_pmi_list = NULL;
DWORD g_NumMI;
DWORD g_NumClasses;
DWORD g_NumTypeRefs;
DWORD g_NumAsmRefs;
DWORD g_NumModules;
BOOL g_fDumpIL = TRUE;
BOOL g_fDumpHeader = FALSE;
BOOL g_fDumpAsmCode = TRUE;
extern BOOL g_fDumpTokens; // declared in formatType.cpp
BOOL g_fDumpStats = FALSE;
BOOL g_fTDC = TRUE;
BOOL g_fShowCA = TRUE;
BOOL g_fCAVerbal = FALSE;
BOOL g_fShowRefs = FALSE;
BOOL g_fDumpToPerfWriter = FALSE;
HANDLE g_PerfDataFilePtr = NULL;
BOOL g_fDumpClassList = FALSE;
BOOL g_fDumpTypeList = FALSE;
BOOL g_fDumpSummary = FALSE;
BOOL g_fDecompile = FALSE; // still in progress
BOOL g_fShowBytes = FALSE;
BOOL g_fShowSource = FALSE;
BOOL g_fPrettyPrint = FALSE;
BOOL g_fInsertSourceLines = FALSE;
BOOL g_fThisIsInstanceMethod;
BOOL g_fTryInCode = TRUE;
BOOL g_fLimitedVisibility = FALSE;
#if defined(_DEBUG) && defined(FEATURE_PREJIT)
BOOL g_fNGenNativeMetadata = FALSE;
#endif
BOOL g_fHidePub = TRUE;
BOOL g_fHidePriv = TRUE;
BOOL g_fHideFam = TRUE;
BOOL g_fHideAsm = TRUE;
BOOL g_fHideFAA = TRUE;
BOOL g_fHideFOA = TRUE;
BOOL g_fHidePrivScope = TRUE;
BOOL g_fProject = FALSE; // if .winmd file, transform to .NET view
extern BOOL g_fQuoteAllNames; // declared in formatType.cpp, init to FALSE
BOOL g_fForwardDecl=FALSE;
char g_szAsmCodeIndent[MAX_MEMBER_LENGTH];
char g_szNamespace[MAX_MEMBER_LENGTH];
DWORD g_Mode = MODE_DUMP_ALL;
char g_pszClassToDump[MAX_CLASSNAME_LENGTH];
char g_pszMethodToDump[MAX_MEMBER_LENGTH];
char g_pszSigToDump[MAX_SIGNATURE_LENGTH];
BOOL g_fCustomInstructionEncodingSystem = FALSE;
COR_FIELD_OFFSET *g_rFieldOffset = NULL;
ULONG g_cFieldsMax, g_cFieldOffsets;
char* g_pszExeFile;
char g_szInputFile[MAX_FILENAME_LENGTH]; // in UTF-8
WCHAR g_wszFullInputFile[MAX_PATH + 1]; // in UTF-16
char g_szOutputFile[MAX_FILENAME_LENGTH]; // in UTF-8
char* g_pszObjFileName;
FILE* g_pFile = NULL;
mdToken g_tkClassToDump = 0;
mdToken g_tkMethodToDump = 0;
unsigned g_uConsoleCP = CP_ACP;
unsigned g_uCodePage = g_uConsoleCP;
char* g_rchCA = NULL; // dyn.allocated array of CA dumped/not flags
unsigned g_uNCA = 0; // num. of CAs
struct ResourceNode;
extern DynamicArray<LocalComTypeDescr*> *g_pLocalComType;
extern ULONG g_LocalComTypeNum;
// MetaInfo integration:
#include "../tools/metainfo/mdinfo.h"
BOOL g_fDumpMetaInfo = FALSE;
ULONG g_ulMetaInfoFilter = MDInfo::dumpDefault;
// Validator module type.
DWORD g_ValModuleType = ValidatorModuleTypeInvalid;
IMetaDataDispenserEx *g_pDisp = NULL;
void DisplayFile(__in __nullterminated WCHAR* szFile,
BOOL isFile,
ULONG DumpFilter,
__in_opt __nullterminated WCHAR* szObjFile,
strPassBackFn pDisplayString);
extern mdMethodDef g_tkEntryPoint; // integration with MetaInfo
DWORD DumpResourceToFile(__in __nullterminated WCHAR* wzFileName); // see DRES.CPP
struct VTableRef
{
mdMethodDef tkTok;
WORD wEntry;
WORD wSlot;
};
DynamicArray<VTableRef> *g_prVTableRef = NULL;
ULONG g_nVTableRef = 0;
struct EATableRef
{
mdMethodDef tkTok;
char* pszName;
};
DynamicArray<EATableRef> *g_prEATableRef=NULL;
ULONG g_nEATableRef = 0;
ULONG g_nEATableBase = 0;
extern HINSTANCE g_hResources;
void DumpCustomAttributeProps(mdToken tkCA, mdToken tkType, mdToken tkOwner, BYTE*pBlob, ULONG ulLen, void *GUICookie, bool bWithOwner);
WCHAR* RstrW(unsigned id)
{
static WCHAR buffer[1024];
DWORD cchBuff = (DWORD)COUNTOF(buffer);
WCHAR* buff = (WCHAR*)buffer;
memset(buffer,0,sizeof(buffer));
switch(id)
{
case IDS_E_DASMOK:
case IDS_E_PARTDASM:
case IDS_E_PARAMSEQNO:
case IDS_E_MEMBRENUM:
case IDS_E_ODDMEMBER:
case IDS_E_ENUMINIT:
case IDS_E_NODATA:
case IDS_E_VTFUTABLE:
case IDS_E_BOGUSRVA:
case IDS_E_EATJTABLE:
case IDS_E_EATJSIZE:
case IDS_E_RESFLAGS:
case IDS_E_MIHENTRY:
case IDS_E_CODEMGRTBL:
case IDS_E_COMIMAGE:
case IDS_E_MDDETAILS:
case IDS_E_MISTART:
case IDS_E_MIEND:
case IDS_E_ONLYITEMS:
case IDS_E_DECOMPRESS:
case IDS_E_COMPRESSED:
case IDS_E_INSTRDECOD:
case IDS_E_INSTRTYPE:
case IDS_E_SECTHEADER:
case IDS_E_MDAIMPORT:
case IDS_E_MDAFROMMDI:
case IDS_E_MDIIMPORT:
case IDS_E_NOMANIFEST:
case IDS_W_CREATEDW32RES:
case IDS_E_CORRUPTW32RES:
case IDS_E_CANTACCESSW32RES:
case IDS_E_CANTOPENW32RES:
case IDS_ERRORREOPENINGFILE:
wcscpy_s(buffer,COUNTOF(buffer),W("// "));
buff +=3;
cchBuff -= 3;
break;
case IDS_E_AUTOCA:
case IDS_E_METHBEG:
case IDS_E_DASMNATIVE:
case IDS_E_METHODRT:
case IDS_E_CODESIZE:
case IDS_W_CREATEDMRES:
case IDS_E_READINGMRES:
wcscpy_s(buffer,COUNTOF(buffer),W("%s// "));
buff +=5;
cchBuff -= 5;
break;
case IDS_E_NORVA:
wcscpy_s(buffer,COUNTOF(buffer),W("/* "));
buff += 3;
cchBuff -= 3;
break;
default:
break;
}
#ifdef TARGET_UNIX
LoadNativeStringResource(NATIVE_STRING_RESOURCE_TABLE(NATIVE_STRING_RESOURCE_NAME),id, buff, cchBuff, NULL);
#else
_ASSERTE(g_hResources != NULL);
WszLoadString(g_hResources,id,buff,cchBuff);
#endif
if(id == IDS_E_NORVA)
wcscat_s(buff,cchBuff,W(" */"));
return buffer;
}
char* RstrA(unsigned n, unsigned codepage)
{
static char buff[2048];
WCHAR* wz = RstrW(n);
// Unicode -> UTF-8
memset(buff,0,sizeof(buff));
if(!WszWideCharToMultiByte(codepage,0,(LPCWSTR)wz,-1,buff,sizeof(buff),NULL,NULL))
buff[0] = 0;
return buff;
}
char* RstrUTF(unsigned n)
{
return RstrA(n,CP_UTF8);
}
char* RstrANSI(unsigned n)
{
return RstrA(n,g_uConsoleCP);
}
#if 0
void PrintEncodingSystem()
{
long i;
printf("Custom opcode encoding system employed\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
for (i = 0; i < 256; i++)
{
long value = g_pInstructionDecodingTable->m_SingleByteOpcodes[i];
printf("0x%02x --> ", i);
printf("%s\n", OpcodeInfo[value].pszName);
}
}
#endif
// buffers for formatType functions
extern CQuickBytes * g_szBuf_KEYWORD;
extern CQuickBytes * g_szBuf_COMMENT;
extern CQuickBytes * g_szBuf_ERRORMSG;
extern CQuickBytes * g_szBuf_ANCHORPT;
extern CQuickBytes * g_szBuf_JUMPPT;
extern CQuickBytes * g_szBuf_UnquotedProperName;
extern CQuickBytes * g_szBuf_ProperName;
BOOL Init()
{
g_szBuf_KEYWORD = new CQuickBytes();
g_szBuf_COMMENT = new CQuickBytes();
g_szBuf_ERRORMSG = new CQuickBytes();
g_szBuf_ANCHORPT = new CQuickBytes();
g_szBuf_JUMPPT = new CQuickBytes();
g_szBuf_UnquotedProperName = new CQuickBytes();
g_szBuf_ProperName = new CQuickBytes();
return TRUE;
} // Init
extern LPCSTR *rAsmRefName; // decl. in formatType.cpp -- for AsmRef aliases
extern ULONG ulNumAsmRefs; // decl. in formatType.cpp -- for AsmRef aliases
void Cleanup()
{
if (g_pAssemblyImport != NULL)
{
g_pAssemblyImport->Release();
g_pAssemblyImport = NULL;
}
if (g_pPubImport != NULL)
{
g_pPubImport->Release();
g_pPubImport = NULL;
}
if (g_pImport != NULL)
{
g_pImport->Release();
g_pImport = NULL;
TokenSigDelete();
}
if (g_pDisp != NULL)
{
g_pDisp->Release();
g_pDisp = NULL;
}
if (g_pSymReader != NULL)
{
g_pSymReader->Release();
g_pSymReader = NULL;
}
if (g_pPELoader != NULL)
{
g_pPELoader->close();
SDELETE(g_pPELoader);
}
g_iPtrCount = 0;
g_NumClasses = 0;
g_NumTypeRefs = 0;
g_NumModules = 0;
g_tkEntryPoint = 0;
g_szAsmCodeIndent[0] = 0;
g_szNamespace[0]=0;
g_pszClassToDump[0]=0;
g_pszMethodToDump[0]=0;
g_pszSigToDump[0] = 0;
g_NumDups = 0;
g_NumRefs = 0;
g_NumMI = 0;
g_LocalComTypeNum = 0;
g_nEATableRef = 0;
g_fCustomInstructionEncodingSystem = FALSE;
if (rAsmRefName != NULL)
{
for (int i = 0; (unsigned)i < ulNumAsmRefs; i++)
{
if (rAsmRefName[i] != NULL) VDELETE(rAsmRefName[i]);
}
VDELETE(rAsmRefName);
ulNumAsmRefs = 0;
}
if (g_rchCA != NULL)
VDELETE(g_rchCA);
if (g_cl_list != NULL) VDELETE(g_cl_list);
if (g_cl_enclosing != NULL) VDELETE(g_cl_enclosing);
if (g_pmi_list != NULL) SDELETE(g_pmi_list);
if (g_dups != NULL) SDELETE(g_dups);
if (g_enum_td_type != NULL) VDELETE(g_enum_td_type);
if (g_enum_tr_type != NULL) VDELETE(g_enum_tr_type);
if (g_asmref_import != NULL)
{
for (DWORD i = 0; i < g_NumAsmRefs; i++)
{
if (g_asmref_import[i] != NULL)
g_asmref_import[i]->Release();
}
VDELETE(g_asmref_import);
g_NumAsmRefs = 0;
}
} // Cleanup
void Uninit()
{
if (g_pPtrTags != NULL)
{
SDELETE(g_pPtrTags);
}
if (g_pPtrSize != NULL)
{
SDELETE(g_pPtrSize);
}
if (g_pmi_list != NULL)
{
SDELETE(g_pmi_list);
}
if (g_dups != NULL) SDELETE(g_dups);
if (g_refs != NULL) SDELETE(g_refs);
if (g_pLocalComType != NULL)
{
SDELETE(g_pLocalComType);
}
if (g_prVTableRef != NULL)
{
SDELETE(g_prVTableRef);
}
if (g_prEATableRef != NULL)
{
SDELETE(g_prEATableRef);
}
if (g_szBuf_KEYWORD != NULL)
{
SDELETE(g_szBuf_KEYWORD);
}
if (g_szBuf_COMMENT != NULL)
{
SDELETE(g_szBuf_COMMENT);
}
if (g_szBuf_ERRORMSG != NULL)
{
SDELETE(g_szBuf_ERRORMSG);
}
if (g_szBuf_ANCHORPT != NULL)
{
SDELETE(g_szBuf_ANCHORPT);
}
if (g_szBuf_JUMPPT != NULL)
{
SDELETE(g_szBuf_JUMPPT);
}
if (g_szBuf_UnquotedProperName != NULL)
{
SDELETE(g_szBuf_UnquotedProperName);
}
if (g_szBuf_ProperName != NULL)
{
SDELETE(g_szBuf_ProperName);
}
} // Uninit
HRESULT IsClassRefInScope(mdTypeRef classref)
{
HRESULT hr = S_OK;
const char *pszNameSpace;
const char *pszClassName;
mdTypeDef classdef;
mdToken tkRes;
IfFailRet(g_pImport->GetNameOfTypeRef(classref, &pszNameSpace, &pszClassName));
MAKE_NAME_IF_NONE(pszClassName,classref);
IfFailRet(g_pImport->GetResolutionScopeOfTypeRef(classref, &tkRes));
hr = g_pImport->FindTypeDef(pszNameSpace, pszClassName,
(TypeFromToken(tkRes) == mdtTypeRef) ? tkRes : mdTokenNil, &classdef);
return hr;
}
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
BOOL EnumClasses()
{
HRESULT hr;
HENUMInternal hEnum;
ULONG i = 0,j;
//char szString[1024];
HENUMInternal hBody;
HENUMInternal hDecl;
if(g_cl_list) VDELETE(g_cl_list);
if(g_cl_enclosing) VDELETE(g_cl_enclosing);
if (g_pmi_list) SDELETE(g_pmi_list);
if (g_dups) SDELETE(g_dups);
if (g_enum_td_type) VDELETE(g_enum_td_type);
if (g_enum_tr_type) VDELETE(g_enum_tr_type);
if (g_asmref_import)
{
for (DWORD nIndex = 0; nIndex < g_NumAsmRefs; nIndex++)
{
if (g_asmref_import[nIndex] != NULL)
g_asmref_import[nIndex]->Release();
}
VDELETE(g_asmref_import);
g_NumAsmRefs = 0;
}
//--------------------------------------------------------------
if (FAILED(g_pImport->EnumAllInit(mdtTypeRef,&hEnum)))
{
printError(g_pFile, "MetaData error: cannot enumerate all TypeRefs");
return FALSE;
}
g_NumTypeRefs = g_pImport->EnumGetCount(&hEnum);
g_pImport->EnumClose(&hEnum);
if(g_NumTypeRefs)
{
g_enum_tr_type = new BYTE[g_NumTypeRefs+1];
if(g_enum_tr_type == NULL) return FALSE;
memset(g_enum_tr_type,0xFF,g_NumTypeRefs+1);
}
//--------------------------------------------------------------
if (FAILED(g_pImport->EnumAllInit(mdtAssemblyRef, &hEnum)))
{
printError(g_pFile, "MetaData error: cannot enumerate all AssemblyRefs");
return FALSE;
}
g_NumAsmRefs = g_pImport->EnumGetCount(&hEnum);
g_pImport->EnumClose(&hEnum);
if(g_NumAsmRefs)
{
g_asmref_import = new IMDInternalImport*[g_NumAsmRefs+1];
if(g_asmref_import == NULL) return FALSE;
memset(g_asmref_import,0,(g_NumAsmRefs+1)*sizeof(IMDInternalImport*));
}
//--------------------------------------------------------------
hr = g_pImport->EnumTypeDefInit(
&hEnum);
if (FAILED(hr))
{
printError(g_pFile,RstrUTF(IDS_E_CLSENUM));
return FALSE;
}
g_NumClasses = g_pImport->EnumGetCount(&hEnum);
g_tkClassToDump = 0;
g_NumMI = 0;
g_NumDups = 0;
if(g_NumClasses == 0) return TRUE;
g_enum_td_type = new BYTE[g_NumClasses+1];
if(g_enum_td_type == NULL) return FALSE;
memset(g_enum_td_type,0xFF,g_NumClasses+1);
g_cl_list = new mdToken[g_NumClasses];
if(g_cl_list == NULL) return FALSE;
g_cl_enclosing = new mdToken[g_NumClasses];
if(g_cl_enclosing == NULL)
{
VDELETE(g_cl_list);
return FALSE;
}
g_pmi_list = new DynamicArray<MIDescriptor>;
if(g_pmi_list == NULL)
{
VDELETE(g_cl_enclosing);
VDELETE(g_cl_list);
return FALSE;
}
g_dups = new DynamicArray<mdToken>;
if(g_dups == NULL)
{
SDELETE(g_pmi_list);
VDELETE(g_cl_enclosing);
VDELETE(g_cl_list);
return FALSE;
}
// fill the list of typedef tokens
while(g_pImport->EnumNext(&hEnum, &g_cl_list[i]))
{
mdToken tkEnclosing;
if (g_Mode == MODE_DUMP_CLASS || g_Mode == MODE_DUMP_CLASS_METHOD || g_Mode == MODE_DUMP_CLASS_METHOD_SIG)
{
CQuickBytes out;
// we want plain class name without token values
BOOL fDumpTokens = g_fDumpTokens;
g_fDumpTokens = FALSE;
PAL_CPP_TRY
{
if (strcmp(PrettyPrintClass(&out, g_cl_list[i], g_pImport), g_pszClassToDump) == 0)
{
g_tkClassToDump = g_cl_list[i];
}
}
PAL_CPP_CATCH_ALL
{ }
PAL_CPP_ENDTRY;
g_fDumpTokens = fDumpTokens;
}
g_cl_enclosing[i] = mdTypeDefNil;
hr = g_pImport->GetNestedClassProps(g_cl_list[i],&tkEnclosing);
if (SUCCEEDED(hr) && RidFromToken(tkEnclosing)) // No need to check token validity here, it's done later
g_cl_enclosing[i] = tkEnclosing;
if (SUCCEEDED(g_pImport->EnumMethodImplInit(g_cl_list[i],&hBody,&hDecl)))
{
if ((j = g_pImport->EnumMethodImplGetCount(&hBody,&hDecl)))
{
mdToken tkBody,tkDecl,tkBodyParent;
for (ULONG k = 0; k < j; k++)
{
if (g_pImport->EnumMethodImplNext(&hBody,&hDecl,&tkBody,&tkDecl) == S_OK)
{
if (SUCCEEDED(g_pImport->GetParentToken(tkBody,&tkBodyParent)))
{
(*g_pmi_list)[g_NumMI].tkClass = g_cl_list[i];
(*g_pmi_list)[g_NumMI].tkBody = tkBody;
(*g_pmi_list)[g_NumMI].tkDecl = tkDecl;
(*g_pmi_list)[g_NumMI].tkBodyParent = tkBodyParent;
g_NumMI++;
}
}
}
}
g_pImport->EnumMethodImplClose(&hBody,&hDecl);
}
i++;
}
g_pImport->EnumClose(&hEnum);
// check nesting consistency (circular nesting, invalid enclosers)
for(i = 0; i < g_NumClasses; i++)
{
mdToken tkThis = g_cl_list[i];
mdToken tkEncloser = g_cl_enclosing[i];
mdToken tkPrevLevel = tkThis;
while(tkEncloser != mdTypeDefNil)
{
if(tkThis == tkEncloser)
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_SELFNSTD),tkThis);
printError(g_pFile,szString);
g_cl_enclosing[i] = mdTypeDefNil;
break;
}
else
{
for(j = 0; (j < g_NumClasses)&&(tkEncloser != g_cl_list[j]); j++);
if(j == g_NumClasses)
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_NOENCLOS),
tkPrevLevel,tkEncloser);
printError(g_pFile,szString);
g_cl_enclosing[i] = mdTypeDefNil;
break;
}
else
{
tkPrevLevel = tkEncloser;
tkEncloser = g_cl_enclosing[j];
}
}
} // end while(tkEncloser != mdTypeDefNil)
} // end for(i = 0; i < g_NumClasses; i++)
// register all class dups
const char *pszClassName;
const char *pszNamespace;
const char *pszClassName1;
const char *pszNamespace1;
if (FAILED(g_pImport->GetNameOfTypeDef(
g_cl_list[0],
&pszClassName,
&pszNamespace)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), g_cl_list[0]);
printLine(g_pFile, sz);
return FALSE;
}
if((g_cl_enclosing[0]==mdTypeDefNil)
&&(0==strcmp(pszClassName,"<Module>"))
&&(*pszNamespace == 0))
{
(*g_dups)[g_NumDups++] = g_cl_list[0];
}
for(i = 1; i < g_NumClasses; i++)
{
if (FAILED(g_pImport->GetNameOfTypeDef(
g_cl_list[i],
&pszClassName,
&pszNamespace)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), g_cl_list[i]);
printLine(g_pFile, sz);
return FALSE;
}
for(j = 0; j < i; j++)
{
if (FAILED(g_pImport->GetNameOfTypeDef(
g_cl_list[j],
&pszClassName1,
&pszNamespace1)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), g_cl_list[j]);
printLine(g_pFile, sz);
return FALSE;
}
if((g_cl_enclosing[i]==g_cl_enclosing[j])
&&(0==strcmp(pszClassName,pszClassName1))
&&(0==strcmp(pszNamespace,pszNamespace1)))
{
(*g_dups)[g_NumDups++] = g_cl_list[i];
break;
}
}
} // end for(i = 1; i < g_NumClasses; i++)
//register all field and method dups
for(i = 0; i <= g_NumClasses; i++)
{
HENUMInternal hEnumMember;
mdToken *pMemberList = NULL;
DWORD NumMembers,k;
// methods
if (i != 0)
{
hr = g_pImport->EnumInit(mdtMethodDef, g_cl_list[i-1], &hEnumMember);
}
else
{
hr = g_pImport->EnumGlobalFunctionsInit(&hEnumMember);
}
if (FAILED(hr))
{
printLine(g_pFile,RstrUTF(IDS_E_MEMBRENUM));
return FALSE;
}
NumMembers = g_pImport->EnumGetCount(&hEnumMember);
pMemberList = new mdToken[NumMembers];
for (j = 0; g_pImport->EnumNext(&hEnumMember, &pMemberList[j]); j++);
_ASSERTE(j == NumMembers);
g_pImport->EnumClose(&hEnumMember);
for (j = 1; j < NumMembers; j++)
{
const char *pszName;
ULONG cSig;
PCCOR_SIGNATURE pSig;
if (FAILED(g_pImport->GetNameOfMethodDef(pMemberList[j], &pszName)) ||
FAILED(g_pImport->GetSigOfMethodDef(pMemberList[j], &cSig, &pSig)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), pMemberList[j]);
printLine(g_pFile, sz);
return FALSE;
}
for (k = 0; k < j; k++)
{
const char *szName1;
if (FAILED(g_pImport->GetNameOfMethodDef(pMemberList[k], &szName1)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), pMemberList[k]);
printLine(g_pFile, sz);
return FALSE;
}
if (strcmp(pszName, szName1) == 0)
{
ULONG cSig1;
PCCOR_SIGNATURE pSig1;
if (FAILED(g_pImport->GetSigOfMethodDef(pMemberList[k], &cSig1, &pSig1)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), pMemberList[k]);
printLine(g_pFile, sz);
return FALSE;
}
if((cSig == cSig1)&&(0==memcmp(pSig,pSig1,cSig)))
{
(*g_dups)[g_NumDups++] = pMemberList[j];
break;
}
}
}
}
VDELETE(pMemberList);
// fields
if (i != 0)
{
hr = g_pImport->EnumInit(mdtFieldDef, g_cl_list[i-1], &hEnumMember);
}
else
{
hr = g_pImport->EnumGlobalFieldsInit(&hEnumMember);
}
if (FAILED(hr))
{
printLine(g_pFile,RstrUTF(IDS_E_MEMBRENUM));
return FALSE;
}
NumMembers = g_pImport->EnumGetCount(&hEnumMember);
pMemberList = new mdToken[NumMembers];
for (j = 0; g_pImport->EnumNext(&hEnumMember, &pMemberList[j]); j++);
_ASSERTE(j == NumMembers);
g_pImport->EnumClose(&hEnumMember);
for (j = 1; j < NumMembers; j++)
{
const char *pszName;
ULONG cSig;
PCCOR_SIGNATURE pSig;
if (FAILED(g_pImport->GetNameOfFieldDef(pMemberList[j], &pszName)) ||
FAILED(g_pImport->GetSigOfFieldDef(pMemberList[j], &cSig, &pSig)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), pMemberList[j]);
printLine(g_pFile, sz);
return FALSE;
}
for (k = 0; k < j; k++)
{
const char *szName1;
if (FAILED(g_pImport->GetNameOfFieldDef(pMemberList[k], &szName1)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), pMemberList[k]);
printLine(g_pFile, sz);
return FALSE;
}
if (strcmp(pszName, szName1) == 0)
{
ULONG cSig1;
PCCOR_SIGNATURE pSig1;
if (FAILED(g_pImport->GetSigOfFieldDef(pMemberList[k], &cSig1, &pSig1)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), pMemberList[k]);
printLine(g_pFile, sz);
return FALSE;
}
if((cSig == cSig1)&&(0==memcmp(pSig,pSig1,cSig)))
{
(*g_dups)[g_NumDups++] = pMemberList[j];
break;
}
}
}
}
VDELETE(pMemberList);
} // end for(i = 0; i <= g_NumClasses; i++)
return TRUE;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
#ifndef _DEBUG
bool HasSuppressingAttribute()
{
const void* pData;
ULONG cbData;
return ((S_OK == g_pImport->GetCustomAttributeByName(TokenFromRid(mdtModule,1),
(LPCUTF8)"System.Runtime.CompilerServices.SuppressIldasmAttribute",
&pData,
&cbData))
|| (S_OK == g_pImport->GetCustomAttributeByName(TokenFromRid(mdtAssembly,1),
(LPCUTF8)"System.Runtime.CompilerServices.SuppressIldasmAttribute",
&pData,
&cbData)));
}
#endif
void DumpMscorlib(void* GUICookie)
{
// In the CoreCLR with reference assemblies and redirection it is more difficult to determine if
// a particular Assembly is the System assembly, like mscorlib.dll is for the Desktop CLR.
// In the CoreCLR runtimes, the System assembly can be System.Private.CoreLib.dll, System.Runtime.dll
// or netstandard.dll and in the future a different Assembly name could be used.
// We now determine the identity of the System assembly by querying if the Assembly defines the
// well known type System.Object as that type must be defined by the System assembly
// If this type is defined then we will output the ".mscorlib" directive to indicate that this
// assembly is the System assembly.
//
mdTypeDef tkObjectTypeDef = mdTypeDefNil;
// Lookup the type System.Object and see it it has a type definition in this assembly
if (SUCCEEDED(g_pPubImport->FindTypeDefByName(W("System.Object"), mdTypeDefNil, &tkObjectTypeDef)))
{
if (tkObjectTypeDef != mdTypeDefNil)
{
// We do have a type definition for System.Object in this assembly
//
DWORD dwClassAttrs = 0;
mdToken tkExtends = mdTypeDefNil;
// Retrieve the type def properties as well, so that we can check a few more things about
// the System.Object type
//
if (SUCCEEDED(g_pPubImport->GetTypeDefProps(tkObjectTypeDef, NULL, NULL, 0, &dwClassAttrs, &tkExtends)))
{
bool bExtends = g_pPubImport->IsValidToken(tkExtends);
bool isClass = ((dwClassAttrs & tdClassSemanticsMask) == tdClass);
// We also check the type properties to make sure that we have a class and not a Value type definition
// and that this type definition isn't extending another type.
//
if (isClass & !bExtends)
{
// We will mark this assembly with the System assembly directive: .mscorlib
//
printLine(GUICookie, "");
sprintf_s(szString, SZSTRING_SIZE, "%s%s ", g_szAsmCodeIndent, KEYWORD(".mscorlib"));
printLine(GUICookie, szString);
printLine(GUICookie, "");
}
}
}
}
}
void DumpTypelist(void* GUICookie)
{
if(g_NumClasses > 1)
{
DWORD i;
CQuickBytes out;
printLine(GUICookie,"");
sprintf_s(szString,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".typelist"));
printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"%s%s",g_szAsmCodeIndent,SCOPE());
printLine(GUICookie,szString);
strcat_s(g_szAsmCodeIndent,MAX_MEMBER_LENGTH," ");
for(i = 0; i < g_NumClasses; i++)
{
out.Shrink(0);
sprintf_s(szString,SZSTRING_SIZE, "%s%s",g_szAsmCodeIndent, PrettyPrintClass(&out, g_cl_list[i], g_pImport));
printLine(GUICookie,szString);
}
g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-2] = 0;
sprintf_s(szString,SZSTRING_SIZE,"%s%s",g_szAsmCodeIndent,UNSCOPE());
printLine(GUICookie,szString);
printLine(GUICookie,"");
}
}
#define ELEMENT_TYPE_TYPEDEF (ELEMENT_TYPE_MAX+1)
BOOL EnumTypedefs()
{
HENUMInternal hEnum;
ULONG i,l;
mdToken tk;
if (g_typedefs) SDELETE(g_typedefs);
g_typedefs = new DynamicArray<TypeDefDescr>;
g_NumTypedefs = 0;
if (FAILED(g_pImport->EnumAllInit(mdtTypeSpec, &hEnum)))
{
return FALSE;
}
for (i = 0; g_pImport->EnumNext(&hEnum, &tk); i++)
{
ULONG cSig;
PCCOR_SIGNATURE sig;
if (FAILED(g_pImport->GetSigFromToken(tk, &cSig, &sig)))
{
return FALSE;
}
if (*sig == ELEMENT_TYPE_TYPEDEF)
{
TypeDefDescr* pTDD = &((*g_typedefs)[g_NumTypedefs]);
pTDD->szName = (char*)sig+1;
l = 2+(ULONG)strlen((char*)sig+1);
pTDD->tkTypeSpec = GET_UNALIGNED_VAL32(sig + l);
pTDD->tkSelf = tk;
if (TypeFromToken(pTDD->tkTypeSpec) == mdtTypeSpec)
{
if (FAILED(g_pImport->GetSigFromToken(pTDD->tkTypeSpec,&(pTDD->cb), &(pTDD->psig))))
{
return FALSE;
}
}
else if (TypeFromToken(pTDD->tkTypeSpec) == mdtCustomAttribute)
{
l += sizeof(mdToken);
pTDD->psig = sig + l;
pTDD->cb = cSig - l;
}
else
{
pTDD->psig = NULL;
pTDD->cb = 0;
}
g_NumTypedefs++;
}
}
g_pImport->EnumClose(&hEnum);
return TRUE;
}
void DumpTypedefs(void* GUICookie)
{
DWORD i;
char* szptr;
CQuickBytes out;
printLine(GUICookie,"");
for(i = 0; i < g_NumTypedefs; i++)
{
TypeDefDescr* pTDD = &((*g_typedefs)[i]);
szptr = &szString[0];
szString[0] = 0;
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,ANCHORPT(KEYWORD(".typedef"),pTDD->tkSelf));
if(g_fDumpTokens)
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X*/ "),pTDD->tkSelf);
{
ULONG n = g_NumTypedefs;
DWORD tk = pTDD->tkTypeSpec;
switch (TypeFromToken(tk))
{
default:
break;
case mdtCustomAttribute:
printLine(GUICookie,szString);
strcat_s(g_szAsmCodeIndent,MAX_MEMBER_LENGTH," ");
{
mdToken tkType;
mdToken tkOwner;
BYTE* pBlob=NULL;
ULONG uLen=0;
tkType = GET_UNALIGNED_VAL32(pTDD->psig);
tkOwner = GET_UNALIGNED_VAL32(pTDD->psig + sizeof(mdToken));
if(pTDD->cb > 2*sizeof(mdToken))
{
pBlob = (BYTE*)pTDD->psig + 2*sizeof(mdToken);
uLen = pTDD->cb - 2*sizeof(mdToken);
}
DumpCustomAttributeProps(0,tkType,tkOwner,pBlob,uLen,GUICookie,
(RidFromToken(tkOwner)!=0));
}
sprintf_s(szString,SZSTRING_SIZE,"%s %s %s", g_szAsmCodeIndent,KEYWORD("as"),
ProperName((*g_typedefs)[i].szName));
printLine(GUICookie,szString);
g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-8]=0;
continue;
case mdtMethodDef:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("method "));
break;
case mdtFieldDef:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("field "));
break;
case mdtMemberRef:
{
PCCOR_SIGNATURE typePtr;
const char *pszMemberName;
ULONG cComSig;
if (FAILED(g_pImport->GetNameAndSigOfMemberRef(
tk,
&typePtr,
&cComSig,
&pszMemberName)))
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"ERROR ");
break;
}
unsigned callConv = CorSigUncompressData(typePtr);
if (isCallConv(callConv, IMAGE_CEE_CS_CALLCONV_FIELD))
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("field "));
else
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("method "));
break;
}
}
g_NumTypedefs = 0;
PrettyPrintToken(szString, tk, g_pImport,g_pFile,0);
g_NumTypedefs = n;
szptr = &szString[strlen(szString)];
}
szptr+= sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," %s %s", KEYWORD("as"), ProperName((*g_typedefs)[i].szName));
printLine(GUICookie,szString);
}
}
BOOL PrintClassList()
{
DWORD i;
BOOL fSuccess = FALSE;
//char szString[1024];
char* szptr;
if(g_NumClasses)
{
printLine(g_pFile,COMMENT("// Classes defined in this module:"));
printLine(g_pFile,COMMENT("//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"));
for (i = 0; i < g_NumClasses; i++)
{
const char *pszClassName;
const char *pszNamespace;
DWORD dwClassAttrs;
mdTypeRef crExtends;
if (FAILED(g_pImport->GetNameOfTypeDef(
g_cl_list[i],
&pszClassName,
&pszNamespace)))
{
printLine(g_pFile, COMMENT("// Invalid TypeDef record"));
return FALSE;
}
MAKE_NAME_IF_NONE(pszClassName,g_cl_list[i]);
// if this is the "<Module>" class (there is a misnomer) then skip it!
if (FAILED(g_pImport->GetTypeDefProps(
g_cl_list[i],
&dwClassAttrs,
&crExtends)))
{
printLine(g_pFile, COMMENT("// Invalid TypeDef record"));
return FALSE;
}
szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"// ");
if (IsTdInterface(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"Interface ");
//else if (IsTdValueType(dwClassAttrs)) szptr+=sprintf(szptr,"Value Class");
//else if (IsTdUnmanagedValueType(dwClassAttrs)) szptr+=sprintf(szptr,"NotInGCHeap Value Class");
else szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"Class ");
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%-30s ", pszClassName);
if (IsTdPublic(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(public) ");
if (IsTdAbstract(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(abstract) ");
if (IsTdAutoLayout(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(auto) ");
if (IsTdSequentialLayout(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(sequential) ");
if (IsTdExplicitLayout(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(explicit) ");
if (IsTdAnsiClass(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(ansi) ");
if (IsTdUnicodeClass(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(unicode) ");
if (IsTdAutoClass(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(autochar) ");
if (IsTdImport(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(import) ");
if (IsTdWindowsRuntime(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(windowsruntime) ");
//if (IsTdEnum(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(enum) ");
if (IsTdSealed(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(sealed) ");
if (IsTdNestedPublic(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(nested public) ");
if (IsTdNestedPrivate(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(nested private) ");
if (IsTdNestedFamily(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(nested family) ");
if (IsTdNestedAssembly(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(nested assembly) ");
if (IsTdNestedFamANDAssem(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(nested famANDassem) ");
if (IsTdNestedFamORAssem(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(nested famORassem) ");
printLine(g_pFile,COMMENT(szString));
}
printLine(g_pFile,COMMENT("//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"));
printLine(g_pFile,"");
}
else
printLine(g_pFile,COMMENT("// No classes defined in this module"));
fSuccess = TRUE;
return fSuccess;
}
BOOL ValidateToken(mdToken tk, ULONG type = (ULONG) ~0)
{
BOOL bRtn;
//char szString[1024];
bRtn = g_pImport->IsValidToken(tk);
if (!bRtn)
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_INVALIDTK), tk);
printError(g_pFile,szString);
}
else if (type != (ULONG) ~0 && TypeFromToken(tk) != type)
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_UNEXPTYPE),
TypeFromToken(type), TypeFromToken(tk));
printError(g_pFile,szString);
bRtn = FALSE;
}
return bRtn;
}
BOOL DumpModule(mdModuleRef mdMod)
{
const char *pszModName;
//char szString[1024];
if (FAILED(g_pImport->GetModuleRefProps(mdMod,&pszModName)))
{
pszModName = "Invalid ModuleRef record";
}
MAKE_NAME_IF_NONE(pszModName,mdMod);
sprintf_s(szString,SZSTRING_SIZE,"%s%s \"%s\"",g_szAsmCodeIndent,KEYWORD(".import"),pszModName); // what about GUID and MVID?
printLine(g_pFile,szString);
return TRUE;
}
char* DumpPinvokeMap(DWORD dwMappingFlags, const char *szImportName,
mdModuleRef mrImportDLL, __inout __nullterminated char* szString, void* GUICookie)
{
const char *szImportDLLName;
char* szptr = &szString[strlen(szString)];
if (FAILED(g_pImport->GetModuleRefProps(mrImportDLL,&szImportDLLName)))
{
szImportDLLName = "Invalid ModuleRef record";
}
if(strlen(szImportDLLName) != 0)
{
szptr = DumpQString(GUICookie,
(char*)szImportDLLName,
g_szAsmCodeIndent,
80);
}
//if(strlen(szImportDLLName)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"\"%s\"",szImportDLLName);
//if(szImportName && strlen(szImportName)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," as \"%s\"",szImportName);
if(szImportName && strlen(szImportName))
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD(" as "));
szptr = DumpQString(GUICookie,
(char*)szImportName,
g_szAsmCodeIndent,
80);
}
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD((char*)0));
if(IsPmNoMangle(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," nomangle");
if(IsPmCharSetAnsi(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," ansi");
if(IsPmCharSetUnicode(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," unicode");
if(IsPmCharSetAuto(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," autochar");
if(IsPmSupportsLastError(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," lasterr");
if(IsPmCallConvWinapi(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," winapi");
if(IsPmCallConvCdecl(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," cdecl");
if(IsPmCallConvThiscall(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," thiscall");
if(IsPmCallConvFastcall(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," fastcall");
if(IsPmCallConvStdcall(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," stdcall");
if(IsPmBestFitEnabled(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," bestfit:on");
if(IsPmBestFitDisabled(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," bestfit:off");
if(IsPmThrowOnUnmappableCharEnabled(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," charmaperror:on");
if(IsPmThrowOnUnmappableCharDisabled(dwMappingFlags)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," charmaperror:off");
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD((char*)-1));
return szptr;
}
void DumpByteArray(__inout __nullterminated char* szString, const BYTE* pBlob, ULONG ulLen, void* GUICookie)
{
ULONG32 ulStrOffset = 0;
ULONG32 j = 0;
ULONG32 k = 0;
ULONG32 m = 0;
char sz[256];
bool printsz = FALSE;
char* szptr = NULL;
BYTE byt = 0;
ulStrOffset = (ULONG32) strlen(szString);
szptr = &szString[ulStrOffset];
if(!pBlob) ulLen = 0;
for(j = 0, k=0, m=0; j < ulLen; j++,k++,m++)
{
if(k == 16)
{
if(printsz)
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT(" // %s"),sz);
}
printLine(GUICookie,szString);
strcpy_s(szString,SZSTRING_SIZE,g_szAsmCodeIndent);
for(k=(ULONG32) strlen(szString); k < ulStrOffset; k++) szString[k] = ' ';
szString[k] = 0;
szptr = &szString[ulStrOffset];
k = 0;
m = 0;
printsz = FALSE;
}
bool bBreak = FALSE;
PAL_CPP_TRY {
byt = pBlob[j];
}
PAL_CPP_CATCH_ALL
{
strcat_s(szString, SZSTRING_SIZE,ERRORMSG("INVALID DATA ADDRESS"));
bBreak = TRUE;
}
PAL_CPP_ENDTRY;
if (bBreak)
break;
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%2.2X ",byt);
if(isprint(byt))
{
if(g_fDumpRTF)
{
if((byt == '\\')||(byt=='{')||(byt=='}')) sz[m++]='\\';
sz[m] = byt;
}
else if(g_fDumpHTML)
{
if(byt == '<') { sz[m] = 0; strcat_s(sz,256-m,LTN()); m+=(ULONG32)(strlen(LTN())); }
else if(byt == '>') { sz[m] = 0; strcat_s(sz,256-m,GTN()); m+=(ULONG32)(strlen(GTN())); }
else sz[m] = byt;
}
else sz[m] = byt;
printsz = TRUE;
}
else sz[m] = '.';
sz[m+1] = 0;
}
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),") ");
if(printsz)
{
for(j = k; j < 16; j++) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," ");
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("// %s"),sz);
}
}
mdToken ResolveTypeDefReflectionNotation(IMDInternalImport *pIMDI,
LPCUTF8 szNamespace,
__inout LPUTF8 szName,
mdToken tkEncloser)
{
mdToken tk = 0;
LPUTF8 pch = strrchr(szName, '+');
if(pch != NULL)
{
*pch = 0;
tkEncloser = ResolveTypeDefReflectionNotation(pIMDI,szNamespace,szName,tkEncloser);
szNamespace = "";
szName = pch+1;
}
if(SUCCEEDED(pIMDI->FindTypeDef(szNamespace,szName,tkEncloser,&tk)))
return tk;
else
return 0;
}
mdToken ResolveTypeRefReflectionNotation(IMDInternalImport *pIMDI,
__in __nullterminated const char* szNamespace,
__inout __nullterminated char* szName,
mdToken tkResScope)
{
mdToken tk = 0;
char* pch = strrchr(szName, '+');
if(pch != NULL)
{
*pch = 0;
tkResScope = ResolveTypeRefReflectionNotation(pIMDI,szNamespace,szName,tkResScope);
szNamespace = "";
szName = pch+1;
}
if(SUCCEEDED(pIMDI->FindTypeRefByName((LPCSTR)szNamespace,(LPCSTR)szName,tkResScope,&tk)))
return tk;
else
return 0;
}
mdToken ResolveReflectionNotation(BYTE* dataPtr,
unsigned Lstr,
IMDInternalImport *pIMDI,
void* GUICookie)
{
char* str = new char[Lstr+1];
mdToken ret = 0;
if(str)
{
char szNamespaceDefault[] = "";
char* szNamespace = szNamespaceDefault;
char* szName = str;
char* szAssembly = NULL;
char szAssemblyMscorlib[] = "mscorlib";
char* pch;
memcpy(str,dataPtr,Lstr);
str[Lstr] = 0;
//format: Namespace.Name, Assembly,...
pch = strchr(str,',');
if(pch)
{
*pch = 0;
for(szAssembly = pch+1; *szAssembly == ' '; szAssembly++);
pch = strchr(szAssembly,',');
if(pch) *pch = 0;
}
pch = strrchr(str,'.');
if(pch)
{
*pch = 0;
szNamespace = str;
szName = pch+1;
}
if(szAssembly == NULL)
{
// Look in TypeDefs
mdToken tk = ResolveTypeDefReflectionNotation(pIMDI,szNamespace,szName,mdTypeDefNil);
if(tk != 0)
ret = tk;
else
// TypeDef not found, try TypeRef from mscorlib
szAssembly = szAssemblyMscorlib;
}
if(szAssembly != NULL)
{
// Look in TypeRefs
// First, identify resolution scope
_ASSERTE(*szName);
ULONG mAsmRefs = pIMDI->GetCountWithTokenKind(mdtAssemblyRef);
if(mAsmRefs)
{
mdToken tkResScope = 0;
mdToken tk=TokenFromRid(mdtAssemblyRef,1), tkmax=TokenFromRid(mdtAssemblyRef,mAsmRefs);
LPCSTR szAsmRefName;
// these are dummies
const void* pPKT, *pHash;
ULONG ulPKT,ulHash;
AssemblyMetaDataInternal MD;
DWORD dwFlags;
for (;tk <= tkmax; tk++)
{
if (FAILED(pIMDI->GetAssemblyRefProps(tk,&pPKT,&ulPKT,&szAsmRefName,&MD,&pHash,&ulHash,&dwFlags)))
{
continue;
}
if(0==strcmp(szAsmRefName,szAssembly))
{
tkResScope = tk;
break;
}
}
if(tkResScope)
{
ret = ResolveTypeRefReflectionNotation(pIMDI,szNamespace,szName,tkResScope);
}
}
}
}
VDELETE(str);
return ret;
}
unsigned UnderlyingTypeOfEnumTypeDef(mdToken tk, IMDInternalImport *pIMDI)
{
// make sure it's a TypeDef
if(TypeFromToken(tk) != mdtTypeDef) return 0;
// make sure it's an enum
mdToken tkParent;
DWORD dwAttr;
if (FAILED(pIMDI->GetTypeDefProps(tk,&dwAttr,&tkParent)))
{
return 0;
}
if(RidFromToken(tkParent)==0) return 0;
LPCSTR szName, szNamespace;
switch(TypeFromToken(tkParent))
{
case mdtTypeDef:
if (FAILED(pIMDI->GetNameOfTypeDef(tkParent, &szName, &szNamespace)))
{
return 0;
}
break;
case mdtTypeRef:
if (FAILED(pIMDI->GetNameOfTypeRef(tkParent, &szNamespace, &szName)))
{
return 0;
}
break;
default:
return 0;
}
if (strcmp(szName,"Enum") != 0 || strcmp(szNamespace,"System") != 0)
{
// the parent type is not System.Enum so this type has no underlying type
return 0;
}
// OK, it's an enum; find its instance field and get its type
HENUMInternal hEnum;
mdToken tkField;
if (FAILED(pIMDI->EnumInit(mdtFieldDef,tk,&hEnum)))
{
return 0;
}
while(pIMDI->EnumNext(&hEnum,&tkField))
{
if (FAILED(pIMDI->GetFieldDefProps(tkField, &dwAttr)))
{
continue;
}
if (IsFdStatic(dwAttr))
{
continue;
}
PCCOR_SIGNATURE psig;
if (FAILED(pIMDI->GetSigOfFieldDef(tkField,(ULONG*)&dwAttr, &psig)))
{
continue;
}
pIMDI->EnumClose(&hEnum);
return (unsigned) *(psig+1);
}
// no instance field found -- error!
pIMDI->EnumClose(&hEnum);
return 0;
}
mdToken TypeRefToTypeDef(mdToken tk, IMDInternalImport *pIMDI, IMDInternalImport **ppIMDInew)
{
mdToken tkEncloser = mdTypeDefNil;
mdToken tkTypeDef = mdTypeDefNil;
*ppIMDInew = NULL;
// get the resolution scope of TypeRef
mdToken tkRS;
if (FAILED(pIMDI->GetResolutionScopeOfTypeRef(tk, &tkRS)))
{
goto AssignAndReturn;
}
if (TypeFromToken(tkRS) == mdtTypeRef)
tkEncloser = TypeRefToTypeDef(tkRS,pIMDI,ppIMDInew);
else if (TypeFromToken(tkRS) == mdtAssemblyRef)
{
*ppIMDInew = g_asmref_import[RidFromToken(tkRS)];
if (*ppIMDInew == NULL)
{
// get that assembly and open IMDInternalImport
IMetaDataAssemblyImport* pAssemblyImport;
if (FAILED(g_pPubImport->QueryInterface(IID_IMetaDataAssemblyImport, (void**) &pAssemblyImport)))
goto AssignAndReturn;
const void *pPKT, *pHash;
ULONG cHash,cName;
WCHAR wzName[2048];
ASSEMBLYMETADATA md;
WCHAR wzLocale[1024];
DWORD dwFlags;
IUnknown* pIAMDI[64];
memset(&md,0,sizeof(ASSEMBLYMETADATA));
md.szLocale = wzLocale;
md.cbLocale = 1024;
struct Param
{
IMetaDataAssemblyImport* pAssemblyImport;
WCHAR *wzName;
IUnknown **pIAMDI;
ULONG cPKT;
} param;
param.pAssemblyImport = pAssemblyImport;
param.wzName = wzName;
param.pIAMDI = pIAMDI;
pAssemblyImport->GetAssemblyRefProps(tkRS,&pPKT,¶m.cPKT,wzName,2048,&cName,&md,&pHash,&cHash,&dwFlags);
PAL_TRY(Param *, pParam, ¶m) {
if(FAILED(pParam->pAssemblyImport->FindAssembliesByName(NULL,NULL,(LPCWSTR)pParam->wzName,pParam->pIAMDI,64,&pParam->cPKT)))
pParam->cPKT=0;
} PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER) {
param.cPKT=0;
} PAL_ENDTRY
pAssemblyImport->Release();
if(param.cPKT == 0) goto AssignAndReturn;
_ASSERTE(pIAMDI[0] != NULL);
IUnknown *pUnk;
if(FAILED(pIAMDI[0]->QueryInterface(IID_IUnknown, (void**)&pUnk))) goto AssignAndReturn;
if (FAILED(GetMetaDataInternalInterfaceFromPublic(
pUnk,
IID_IMDInternalImport,
(LPVOID *)ppIMDInew)))
{
goto AssignAndReturn;
}
_ASSERTE(*ppIMDInew != NULL);
g_asmref_import[RidFromToken(tkRS)] = *ppIMDInew;
pUnk->Release();
for(cHash=0; cHash<param.cPKT; cHash++)
if(pIAMDI[cHash]) pIAMDI[cHash]->Release();
}
}
if (*ppIMDInew != NULL)
{
LPCSTR szName, szNamespace;
if (FAILED(pIMDI->GetNameOfTypeRef(tk, &szNamespace, &szName)))
{
tkTypeDef = mdTypeDefNil;
goto AssignAndReturn;
}
if (FAILED((*ppIMDInew)->FindTypeDef(szNamespace,szName,tkEncloser,&tkTypeDef)))
{
tkTypeDef = mdTypeDefNil;
}
}
AssignAndReturn:
return tkTypeDef;
}
unsigned UnderlyingTypeOfEnum(mdToken tk, IMDInternalImport *pIMDI)
{
unsigned uRet = 0;
unsigned ix = RidFromToken(tk);
if(TypeFromToken(tk)==mdtTypeDef)
{
if(g_enum_td_type[ix] == 0xFF)
{
g_enum_td_type[ix] = (BYTE)UnderlyingTypeOfEnumTypeDef(tk,pIMDI);
}
return (unsigned)g_enum_td_type[ix];
}
else if(TypeFromToken(tk)==mdtTypeRef)
{
if(g_enum_tr_type[ix] == 0xFF)
{
IMDInternalImport *pIMDInew = NULL;
mdToken tkTypeDef = TypeRefToTypeDef(tk,pIMDI, &pIMDInew);
if((RidFromToken(tkTypeDef)!=0)&&(pIMDInew != NULL))
{
uRet = UnderlyingTypeOfEnumTypeDef(tkTypeDef,pIMDInew);
}
g_enum_tr_type[ix] = (BYTE)uRet;
}
return (unsigned)g_enum_tr_type[ix];
}
else return 0;
}
/**************************************************************************/
/* move 'ptr past the exactly one type description */
BYTE* skipType(BYTE* ptr)
{
mdToken tk;
AGAIN:
switch(*ptr++) {
case ELEMENT_TYPE_VOID :
case ELEMENT_TYPE_BOOLEAN :
case ELEMENT_TYPE_CHAR :
case ELEMENT_TYPE_I1 :
case ELEMENT_TYPE_U1 :
case ELEMENT_TYPE_I2 :
case ELEMENT_TYPE_U2 :
case ELEMENT_TYPE_I4 :
case ELEMENT_TYPE_U4 :
case ELEMENT_TYPE_I8 :
case ELEMENT_TYPE_U8 :
case ELEMENT_TYPE_R4 :
case ELEMENT_TYPE_R8 :
case ELEMENT_TYPE_U :
case ELEMENT_TYPE_I :
case ELEMENT_TYPE_STRING :
case ELEMENT_TYPE_OBJECT :
case ELEMENT_TYPE_TYPEDBYREF :
case ELEMENT_TYPE_SENTINEL :
case SERIALIZATION_TYPE_TYPE :
case SERIALIZATION_TYPE_TAGGED_OBJECT :
/* do nothing */
break;
case SERIALIZATION_TYPE_ENUM :
{
unsigned Lstr = CorSigUncompressData((PCCOR_SIGNATURE&)ptr);
ptr += Lstr;
break;
}
case ELEMENT_TYPE_VALUETYPE :
case ELEMENT_TYPE_CLASS :
ptr += CorSigUncompressToken(ptr, &tk);
break;
case ELEMENT_TYPE_CMOD_REQD :
case ELEMENT_TYPE_CMOD_OPT :
ptr += CorSigUncompressToken(ptr, &tk);
goto AGAIN;
case ELEMENT_TYPE_ARRAY :
{
ptr = skipType(ptr); // element Type
unsigned rank = CorSigUncompressData((PCCOR_SIGNATURE&) ptr);
if (rank != 0)
{
unsigned numSizes = CorSigUncompressData((PCCOR_SIGNATURE&) ptr);
while(numSizes > 0)
{
CorSigUncompressData((PCCOR_SIGNATURE&) ptr);
--numSizes;
}
unsigned numLowBounds = CorSigUncompressData((PCCOR_SIGNATURE&) ptr);
while(numLowBounds > 0)
{
CorSigUncompressData((PCCOR_SIGNATURE&) ptr);
--numLowBounds;
}
}
}
break;
// Modifiers or depedant types
case ELEMENT_TYPE_PINNED :
case ELEMENT_TYPE_PTR :
case ELEMENT_TYPE_BYREF :
case ELEMENT_TYPE_SZARRAY :
// tail recursion optimization
// ptr = skipType(ptr, fFixupType);
// break
goto AGAIN;
case ELEMENT_TYPE_VAR:
case ELEMENT_TYPE_MVAR:
CorSigUncompressData((PCCOR_SIGNATURE&) ptr); // bound
break;
case ELEMENT_TYPE_FNPTR:
{
CorSigUncompressData((PCCOR_SIGNATURE&) ptr); // calling convention
unsigned argCnt = CorSigUncompressData((PCCOR_SIGNATURE&) ptr); // arg count
ptr = skipType(ptr); // return type
while(argCnt > 0)
{
ptr = skipType(ptr);
--argCnt;
}
}
break;
case ELEMENT_TYPE_GENERICINST:
{
ptr = skipType(ptr); // type constructor
unsigned argCnt = CorSigUncompressData((PCCOR_SIGNATURE&)ptr); // arg count
while(argCnt > 0) {
ptr = skipType(ptr);
--argCnt;
}
}
break;
default:
case ELEMENT_TYPE_END :
_ASSERTE(!"Unknown Type");
break;
}
return(ptr);
}
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
BYTE* PrettyPrintCABlobValue(PCCOR_SIGNATURE &typePtr,
BYTE* dataPtr,
BYTE* dataEnd,
CQuickBytes* out,
IMDInternalImport *pIMDI,
void* GUICookie)
{
char str[64];
char appendix[64];
int typ;
BOOL Reiterate;
BOOL CloseParenthesis;
unsigned numElements = 1;
unsigned n,Lstr;
unsigned underType;
mdToken tk;
appendix[0] = 0;
do {
if(dataPtr >= dataEnd)
{
_ASSERTE(!"CA blob too short");
return FALSE;
}
Reiterate = FALSE;
CloseParenthesis = TRUE;
switch(typ = *typePtr++) {
case ELEMENT_TYPE_VOID :
return NULL;
case ELEMENT_TYPE_BOOLEAN :
appendStr(out,KEYWORD("bool"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
appendStr(out,(*dataPtr)? KEYWORD("true"):KEYWORD("false"));
dataPtr++;
}
break;
case ELEMENT_TYPE_CHAR :
appendStr(out,KEYWORD("char"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
sprintf_s(str,64,"0x%4.4X",(WORD)GET_UNALIGNED_VAL16(dataPtr));
appendStr(out,str);
dataPtr += 2;
}
break;
case ELEMENT_TYPE_I1 :
appendStr(out,KEYWORD("int8"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
sprintf_s(str,64,"%d",*((char*)dataPtr));
appendStr(out,str);
dataPtr ++;
}
break;
case ELEMENT_TYPE_U1 :
appendStr(out,KEYWORD("uint8"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
sprintf_s(str,64,"%d",*dataPtr);
appendStr(out,str);
dataPtr ++;
}
break;
case ELEMENT_TYPE_I2 :
appendStr(out,KEYWORD("int16"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
sprintf_s(str,64,"%d",GET_UNALIGNED_VAL16(dataPtr));
appendStr(out,str);
dataPtr +=2;
}
break;
case ELEMENT_TYPE_U2 :
appendStr(out,KEYWORD("uint16"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
sprintf_s(str,64,"%d",(WORD)GET_UNALIGNED_VAL16(dataPtr));
appendStr(out,str);
dataPtr +=2;
}
break;
case ELEMENT_TYPE_I4 :
appendStr(out,KEYWORD("int32"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
sprintf_s(str,64,"%d",GET_UNALIGNED_VAL32(dataPtr));
appendStr(out,str);
dataPtr +=4;
}
break;
case ELEMENT_TYPE_U4 :
appendStr(out,KEYWORD("uint32"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
sprintf_s(str,64,"%d",(unsigned)GET_UNALIGNED_VAL32(dataPtr));
appendStr(out,str);
dataPtr +=4;
}
break;
case ELEMENT_TYPE_I8 :
appendStr(out,KEYWORD("int64"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
sprintf_s(str,64,"%I64d",GET_UNALIGNED_VAL64(dataPtr));
appendStr(out,str);
dataPtr +=8;
}
break;
case ELEMENT_TYPE_U8 :
appendStr(out,KEYWORD("uint64"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
sprintf_s(str,64,"%I64d",(ULONGLONG)GET_UNALIGNED_VAL64(dataPtr));
appendStr(out,str);
dataPtr +=8;
}
break;
case ELEMENT_TYPE_R4 :
appendStr(out,KEYWORD("float32"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
_gcvt_s(str,64,*((float*)dataPtr), 8);
float df = (float)atof(str);
// Must compare as underlying bytes, not floating point otherwise optmizier will
// try to enregister and comapre 80-bit precision number with 32-bit precision number!!!!
if((*(ULONG*)&df != (ULONG)GET_UNALIGNED_VAL32(dataPtr))||IsSpecialNumber(str))
sprintf_s(str, 64,"0x%08X",(ULONG)GET_UNALIGNED_VAL32(dataPtr));
appendStr(out,str);
dataPtr +=4;
}
break;
case ELEMENT_TYPE_R8 :
appendStr(out,KEYWORD("float64"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
char *pch;
_gcvt_s(str,64,*((double*)dataPtr), 17);
double df = strtod(str, &pch);
// Must compare as underlying bytes, not floating point otherwise optmizier will
// try to enregister and comapre 80-bit precision number with 64-bit precision number!!!!
if((*(ULONGLONG*)&df != (ULONGLONG)GET_UNALIGNED_VAL64(dataPtr))||IsSpecialNumber(str))
sprintf_s(str, 64, "0x%I64X",(ULONGLONG)GET_UNALIGNED_VAL64(dataPtr));
appendStr(out,str);
dataPtr +=8;
}
break;
case ELEMENT_TYPE_U :
case ELEMENT_TYPE_I :
return NULL;
case ELEMENT_TYPE_OBJECT :
case SERIALIZATION_TYPE_TAGGED_OBJECT:
appendStr(out,KEYWORD("object"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
BYTE* dataPtr1 = skipType(dataPtr);
if(n) appendStr(out," ");
dataPtr = PrettyPrintCABlobValue((PCCOR_SIGNATURE&)dataPtr, dataPtr1, dataEnd, out, pIMDI,GUICookie);
if (dataPtr == NULL) return NULL;
}
break;
case ELEMENT_TYPE_STRING :
appendStr(out,KEYWORD("string"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
if(*dataPtr == 0xFF)
{
appendStr(out,KEYWORD("nullref"));
Lstr = 1;
}
else
{
appendStr(out,"'");
Lstr = CorSigUncompressData((PCCOR_SIGNATURE&)dataPtr);
if(dataPtr + Lstr > dataEnd) return NULL;
appendStr(out,UnquotedProperName((char*)dataPtr,Lstr));
appendStr(out,"'");
}
dataPtr += Lstr;
}
break;
case ELEMENT_TYPE_CLASS :
typePtr += CorSigUncompressToken(typePtr, &tk); //skip the following token
case SERIALIZATION_TYPE_TYPE :
appendStr(out,KEYWORD("type"));
appendStr(out,appendix);
appendStr(out,"(");
for(n=0; n < numElements; n++)
{
if(n) appendStr(out," ");
if(*dataPtr == 0xFF)
{
appendStr(out,KEYWORD("nullref"));
Lstr = 1;
}
else
{
Lstr = CorSigUncompressData((PCCOR_SIGNATURE&)dataPtr);
if(dataPtr + Lstr > dataEnd) return NULL;
tk = ResolveReflectionNotation(dataPtr,Lstr,pIMDI,GUICookie);
if(IsNilToken(tk))
{
appendStr(out,KEYWORD("class "));
appendStr(out,"'");
appendStr(out,UnquotedProperName((char*)dataPtr,Lstr));
appendStr(out,"'");
}
else
{
PrettyPrintClass(out, tk, pIMDI);
}
}
dataPtr += Lstr;
}
break;
case ELEMENT_TYPE_VALUETYPE :
typePtr += CorSigUncompressToken(typePtr, &tk);
_ASSERTE(pIMDI->IsValidToken(tk));
goto GetUTSize;
case SERIALIZATION_TYPE_ENUM :
Lstr = CorSigUncompressData((PCCOR_SIGNATURE&)typePtr);
tk = ResolveReflectionNotation((BYTE*)typePtr,Lstr,pIMDI,GUICookie);
/*
if(IsNilToken(tk))
{
_ASSERTE(!"Failed to resolve Reflection notation for S_T_ENUM");
return NULL;
}
*/
typePtr += Lstr;
GetUTSize:
underType = UnderlyingTypeOfEnum(tk, pIMDI);
if(underType == 0)
{
// try to figure out the underlying type by its size
switch(dataEnd - dataPtr)
{
case 1: // bool
underType = ELEMENT_TYPE_BOOLEAN;
break;
case 2: // int16
underType = ELEMENT_TYPE_I2;
break;
case 4: // int32
underType = ELEMENT_TYPE_I4;
break;
case 8: // int64
underType = ELEMENT_TYPE_I8;
break;
default:
return NULL;
}
//_ASSERTE(!"Failed to find underlying type for S_T_ENUM");
}
{
PCCOR_SIGNATURE ps = (PCCOR_SIGNATURE)&underType;
dataPtr = PrettyPrintCABlobValue(ps, dataPtr, dataEnd, out, pIMDI,GUICookie);
}
CloseParenthesis = FALSE;
break;
case ELEMENT_TYPE_SZARRAY :
numElements *= (unsigned)GET_UNALIGNED_VAL32(dataPtr);
Reiterate = TRUE;
sprintf_s(appendix,64,"[%d]",numElements);
if(numElements == 0xFFFFFFFF)
numElements = 0;
dataPtr += 4;
break;
case ELEMENT_TYPE_ARRAY :
case ELEMENT_TYPE_VAR :
case ELEMENT_TYPE_MVAR :
case ELEMENT_TYPE_FNPTR :
case ELEMENT_TYPE_GENERICINST :
case ELEMENT_TYPE_TYPEDBYREF :
#ifdef LOGGING
case ELEMENT_TYPE_INTERNAL :
#endif // LOGGING
return NULL;
// Modifiers or depedent types
case ELEMENT_TYPE_CMOD_OPT :
case ELEMENT_TYPE_CMOD_REQD :
case ELEMENT_TYPE_PINNED :
Reiterate = TRUE;
break;
case ELEMENT_TYPE_PTR :
case ELEMENT_TYPE_BYREF :
return NULL;
default:
case ELEMENT_TYPE_SENTINEL :
case ELEMENT_TYPE_END :
_ASSERTE(!"Unknown Type");
return NULL;
} // end switch
} while(Reiterate);
if(CloseParenthesis) appendStr(out,")");
return dataPtr;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
BOOL PrettyPrintCustomAttributeNVPairs(unsigned nPairs, BYTE* dataPtr, BYTE* dataEnd, CQuickBytes* out, void* GUICookie)
{
IMDInternalImport *pIMDI = g_pImport; // ptr to IMDInternalImport class with ComSig
while(dataPtr < dataEnd)
{
// field or property?
switch(*dataPtr)
{
case SERIALIZATION_TYPE_FIELD:
appendStr(out,KEYWORD("field "));
break;
case SERIALIZATION_TYPE_PROPERTY:
appendStr(out,KEYWORD("property "));
break;
default:
_ASSERTE(!"Invalid code of name/val pair in CA blob");
return FALSE;
}
dataPtr++;
if(dataPtr >= dataEnd)
{
_ASSERTE(!"CA blob too short");
return FALSE;
}
// type of the field/property
PCCOR_SIGNATURE dataTypePtr = (PCCOR_SIGNATURE)dataPtr;
const char* szAppend = "";
if(*dataPtr == ELEMENT_TYPE_SZARRAY) // Only SZARRAY modifier can occur in ser.type
{
szAppend = "[]";
dataPtr++;
}
if(*dataPtr == SERIALIZATION_TYPE_TYPE)
{
appendStr(out,KEYWORD("type"));
dataPtr++;
}
else if(*dataPtr == SERIALIZATION_TYPE_TAGGED_OBJECT)
{
appendStr(out,KEYWORD("object"));
dataPtr++;
}
else if(*dataPtr == SERIALIZATION_TYPE_ENUM)
{
appendStr(out,KEYWORD("enum "));
dataPtr++;
unsigned Lstr = CorSigUncompressData((PCCOR_SIGNATURE&)dataPtr);
if(dataPtr + Lstr > dataEnd) return FALSE;
mdToken tk = ResolveReflectionNotation(dataPtr,Lstr,pIMDI,GUICookie);
if(IsNilToken(tk))
{
appendStr(out,KEYWORD("class "));
appendStr(out,"'");
appendStr(out,UnquotedProperName((char*)dataPtr,Lstr));
appendStr(out,"'");
}
else
{
PrettyPrintClass(out, tk, pIMDI);
}
dataPtr += Lstr;
}
else
{
szAppend = "";
dataPtr = (BYTE*)PrettyPrintType(dataTypePtr, out, pIMDI);
}
if(*szAppend != 0)
appendStr(out,szAppend);
if(dataPtr >= dataEnd)
{
_ASSERTE(!"CA blob too short");
return FALSE;
}
// name of the field/property
unsigned Lstr = CorSigUncompressData((PCCOR_SIGNATURE&)dataPtr);
if(dataPtr + Lstr > dataEnd) return FALSE;
appendStr(out," '");
appendStr(out,UnquotedProperName((char*)dataPtr,Lstr));
appendStr(out,"' = ");
dataPtr += Lstr;
if(dataPtr >= dataEnd)
{
_ASSERTE(!"CA blob too short");
return FALSE;
}
// value of the field/property
dataPtr = PrettyPrintCABlobValue(dataTypePtr, dataPtr, dataEnd, out, pIMDI,GUICookie);
if(NULL == dataPtr) return FALSE;
appendStr(out,"\n");
nPairs--;
}
_ASSERTE(nPairs == 0);
return TRUE;
}
BOOL PrettyPrintCustomAttributeBlob(mdToken tkType, BYTE* pBlob, ULONG ulLen, void* GUICookie, __inout __nullterminated char* szString)
{
char* initszptr = szString + strlen(szString);
PCCOR_SIGNATURE typePtr; // type to convert,
ULONG typeLen; // the lenght of 'typePtr'
CHECK_LOCAL_STATIC_VAR(static CQuickBytes out); // where to put the pretty printed string
IMDInternalImport *pIMDI = g_pImport; // ptr to IMDInternalImport class with ComSig
unsigned numArgs = 0;
unsigned numTyArgs = 0;
PCCOR_SIGNATURE typeEnd;
unsigned callConv;
BYTE* dataPtr = pBlob;
BYTE* dataEnd = dataPtr + ulLen;
WORD wNumNVPairs = 0;
unsigned numElements = 0;
if(TypeFromToken(tkType) == mdtMemberRef)
{
const char *szName_Ignore;
if (FAILED(pIMDI->GetNameAndSigOfMemberRef(tkType,&typePtr,&typeLen, &szName_Ignore)))
{
return FALSE;
}
}
else if(TypeFromToken(tkType) == mdtMethodDef)
{
if (FAILED(pIMDI->GetSigOfMethodDef(tkType, &typeLen, &typePtr)))
{
return FALSE;
}
}
else
return FALSE;
typeEnd = typePtr + typeLen;
callConv = CorSigUncompressData(typePtr);
if (callConv & IMAGE_CEE_CS_CALLCONV_GENERIC)
{
numTyArgs = CorSigUncompressData(typePtr);
return FALSE; // leave generic instantiations for later
}
numElements = numArgs = CorSigUncompressData(typePtr);
out.Shrink(0);
if (!isCallConv(callConv, IMAGE_CEE_CS_CALLCONV_GENERICINST))
{
// skip return type
typePtr = PrettyPrintType(typePtr, &out, pIMDI);
out.Shrink(0);
}
appendStr(&out," = {");
dataPtr += 2; // skip blob prolog 0x0001
// dump the arguments
while(typePtr < typeEnd)
{
if (*typePtr == ELEMENT_TYPE_SENTINEL)
{
typePtr++;
}
else
{
if (numArgs <= 0)
break;
dataPtr = PrettyPrintCABlobValue(typePtr, dataPtr, dataEnd-2, &out, pIMDI,GUICookie);
if(NULL == dataPtr) return FALSE;
appendStr(&out,"\n");
--numArgs;
}
}
_ASSERTE(numArgs == 0);
wNumNVPairs = (WORD)GET_UNALIGNED_VAL16(dataPtr);
dataPtr+=2;
numElements += wNumNVPairs;
// arguments done, now to field/property name-val pairs
if(!PrettyPrintCustomAttributeNVPairs((unsigned) wNumNVPairs, dataPtr, dataEnd, &out, GUICookie))
return FALSE;
{
char* sz = asString(&out);
char* ch = sz;
char* szbl;
while((ch = strchr(ch,'\n')))
{
*ch = 0;
ch++;
}
// if the string is too long already, begin on next line
if((initszptr - szString) > 80)
{
printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"%s ",g_szAsmCodeIndent);
initszptr = &szString[strlen(szString)];
}
sprintf_s(initszptr,SZSTRING_REMAINING_SIZE(initszptr), "%s", sz);
initszptr += 4; // to compensate for " = {"
szbl = szString + strlen(g_szAsmCodeIndent);
for(unsigned n = 1; n < numElements; n++)
{
printLine(GUICookie, szString);
sz = sz + strlen(sz) + 1;
for(ch = szbl; ch < initszptr; ch++) *ch = ' ';
sprintf_s(initszptr,SZSTRING_REMAINING_SIZE(initszptr), "%s", sz);
}
}
strcat_s(initszptr, SZSTRING_REMAINING_SIZE(initszptr),"}");
if(g_fShowBytes)
{
printLine(GUICookie,szString);
strcat_s(g_szAsmCodeIndent,MAX_MEMBER_LENGTH," // ");
sprintf_s(szString,SZSTRING_SIZE,"%s = ( ",g_szAsmCodeIndent);
DumpByteArray(szString,pBlob,ulLen,GUICookie);
g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-8] = 0;
}
return TRUE;
}
void DumpCustomAttributeProps(mdToken tkCA, mdToken tkType, mdToken tkOwner, BYTE* pBlob, ULONG ulLen, void *GUICookie, bool bWithOwner)
{
char* szptr = &szString[0];
BOOL fCommentItOut = FALSE;
if((TypeFromToken(tkType) == mdtMemberRef)||(TypeFromToken(tkType) == mdtMethodDef))
{
mdToken tkParent;
const char * pszClassName = NULL;
const char * pszNamespace = NULL;
if (TypeFromToken(tkType) == mdtMemberRef)
{
if (FAILED(g_pImport->GetParentOfMemberRef(tkType, &tkParent)))
{
szptr += sprintf_s(szptr, SZSTRING_REMAINING_SIZE(szptr), "Invalid MemberRef %08X record ", tkType);
return;
}
}
else
{
if (FAILED(g_pImport->GetParentToken(tkType, &tkParent)))
{
szptr += sprintf_s(szptr, SZSTRING_REMAINING_SIZE(szptr), "Invalid token %08X ", tkType);
return;
}
}
REGISTER_REF(tkOwner,tkType); // owner of the CA references the class amd method
REGISTER_REF(tkOwner,tkParent);
if (TypeFromToken(tkParent) == mdtTypeDef)
{
if (FAILED(g_pImport->GetNameOfTypeDef(tkParent, &pszClassName, &pszNamespace)))
{
szptr += sprintf_s(szptr, SZSTRING_REMAINING_SIZE(szptr), "Invalid TypeDef %08X record ", tkParent);
return;
}
}
else if (TypeFromToken(tkParent) == mdtTypeRef)
{
if (FAILED(g_pImport->GetNameOfTypeRef(tkParent, &pszNamespace, &pszClassName)))
{
szptr += sprintf_s(szptr, SZSTRING_REMAINING_SIZE(szptr), "Invalid TypeRef %08X record ", tkParent);
return;
}
}
if(pszClassName && pszNamespace
&& (strcmp(pszNamespace,"System.Diagnostics") == 0)
&& (strcmp(pszClassName,"DebuggableAttribute") == 0)) fCommentItOut = TRUE;
}
if(fCommentItOut)
{
printLine(GUICookie,COMMENT((char*)0)); // start multiline comment
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_AUTOCA),g_szAsmCodeIndent);
printLine(GUICookie, szString);
strcat_s(g_szAsmCodeIndent,MAX_MEMBER_LENGTH,"// ");
}
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".custom"));
if(bWithOwner)
{
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X*/ "),tkCA);
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(");
switch(TypeFromToken(tkOwner))
{
case mdtTypeDef :
case mdtTypeRef :
case mdtTypeSpec:
PrettyPrintToken(szString, tkOwner, g_pImport,GUICookie,0);
break;
case mdtMemberRef:
{
PCCOR_SIGNATURE typePtr;
const char* pszMemberName;
ULONG cComSig;
if (FAILED(g_pImport->GetNameAndSigOfMemberRef(
tkOwner,
&typePtr,
&cComSig,
&pszMemberName)))
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"ERROR ");
break;
}
unsigned callConv = CorSigUncompressData(typePtr);
if (isCallConv(callConv, IMAGE_CEE_CS_CALLCONV_FIELD))
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("field "));
else
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("method "));
PrettyPrintToken(szString, tkOwner, g_pImport,GUICookie,0);
}
break;
case mdtMethodDef:
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr), KEYWORD("method "));
PrettyPrintToken(szString, tkOwner, g_pImport,GUICookie,0);
break;
default :
strcat_s(szptr, SZSTRING_REMAINING_SIZE(szptr),ERRORMSG("UNKNOWN_OWNER"));
break;
}
szptr = &szString[strlen(szString)];
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X*/ "),tkOwner);
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),") ");
}
else
{
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X:%08X*/ "),tkCA,tkType);
}
switch(TypeFromToken(tkType))
{
case mdtTypeDef :
case mdtTypeRef :
case mdtMemberRef:
case mdtMethodDef:
PrettyPrintToken(szString, tkType, g_pImport,GUICookie,0);
break;
default :
strcat_s(szString, SZSTRING_SIZE,ERRORMSG("UNNAMED_CUSTOM_ATTR"));
break;
}
szptr = &szString[strlen(szString)];
if(pBlob && ulLen)
{
if(!g_fCAVerbal || !PrettyPrintCustomAttributeBlob(tkType, pBlob, ulLen, GUICookie, szString))
{
sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = ( ");
DumpByteArray(szString,pBlob,ulLen,GUICookie);
}
}
printLine(GUICookie, szString);
if(fCommentItOut)
{
g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-4] = 0;
printLine(GUICookie,COMMENT((char*)-1)); // end multiline comment
}
}
void DumpCustomAttribute(mdCustomAttribute tkCA, void *GUICookie, bool bWithOwner)
{
mdToken tkType;
BYTE* pBlob=NULL;
ULONG ulLen=0;
mdToken tkOwner;
static mdToken tkMod = 0xFFFFFFFF;
_ASSERTE((TypeFromToken(tkCA)==mdtCustomAttribute)&&(RidFromToken(tkCA)>0));
_ASSERTE(RidFromToken(tkCA) <= g_uNCA);
if(tkMod == 0xFFFFFFFF) tkMod = g_pImport->GetModuleFromScope();
// can't use InternalImport here: need the tkOwner
if (FAILED(g_pPubImport->GetCustomAttributeProps( // S_OK or error.
tkCA, // [IN] CustomValue token.
&tkOwner, // [OUT, OPTIONAL] Object token.
&tkType, // [OUT, OPTIONAL] Put TypeDef/TypeRef token here.
(const void **)&pBlob, // [OUT, OPTIONAL] Put pointer to data here.
&ulLen))) // [OUT, OPTIONAL] Put size of date here.
{
return;
}
if(!RidFromToken(tkOwner)) return;
DWORD i;
for(i = 0; i < g_NumTypedefs; i++)
{
TypeDefDescr* pTDD = &((*g_typedefs)[i]);
if(TypeFromToken(pTDD->tkTypeSpec) == mdtCustomAttribute)
{
mdToken tkTypeTD;
mdToken tkOwnerTD;
BYTE* pBlobTD=NULL;
ULONG uLenTD=0;
tkTypeTD = GET_UNALIGNED_VAL32(pTDD->psig);
if(tkTypeTD != tkType) continue;
tkOwnerTD = GET_UNALIGNED_VAL32(pTDD->psig + sizeof(mdToken));
if(pTDD->cb > 2*sizeof(mdToken))
{
pBlobTD = (BYTE*)pTDD->psig + 2*sizeof(mdToken);
uLenTD = pTDD->cb - 2*sizeof(mdToken);
}
if(uLenTD != ulLen) continue;
if(memcmp(pBlobTD,pBlob,ulLen) != 0) continue;
char* szptr = &szString[0];
szString[0] = 0;
szptr += sprintf_s(szString,SZSTRING_SIZE,"%s%s", g_szAsmCodeIndent,JUMPPT(ProperName(pTDD->szName),pTDD->tkSelf));
if(g_fDumpTokens)
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X*/ "),tkCA);
printLine(GUICookie,szString);
break;
}
}
if(i >= g_NumTypedefs)
DumpCustomAttributeProps(tkCA,tkType,tkOwner,pBlob,ulLen,GUICookie,bWithOwner);
_ASSERTE(g_rchCA);
_ASSERTE(RidFromToken(tkCA) <= g_uNCA);
g_rchCA[RidFromToken(tkCA)] = 1;
}
void DumpCustomAttributes(mdToken tkOwner, void *GUICookie)
{
if (g_fShowCA)
{
HENUMInternal hEnum;
mdCustomAttribute tkCA;
if (FAILED(g_pImport->EnumInit(mdtCustomAttribute, tkOwner,&hEnum)))
{
return;
}
while(g_pImport->EnumNext(&hEnum,&tkCA) && RidFromToken(tkCA))
{
DumpCustomAttribute(tkCA,GUICookie,false);
}
g_pImport->EnumClose( &hEnum);
}
}
void DumpDefaultValue(mdToken tok, __inout __nullterminated char* szString, void* GUICookie)
{
MDDefaultValue MDDV;
char* szptr = &szString[strlen(szString)];
if (FAILED(g_pImport->GetDefaultValue(tok, &MDDV)))
{
szptr += sprintf_s(szptr, SZSTRING_REMAINING_SIZE(szptr), ERRORMSG(" /* Invalid default value for %08X: */"), tok);
return;
}
switch(MDDV.m_bType)
{
case ELEMENT_TYPE_VOID:
strcat_s(szString, SZSTRING_SIZE," /* NO CORRESPONDING RECORD IN CONSTANTS TABLE */");
break;
case ELEMENT_TYPE_I1:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(0x%02X)",KEYWORD("int8"),MDDV.m_byteValue);
break;
case ELEMENT_TYPE_U1:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(0x%02X)",KEYWORD("uint8"),MDDV.m_byteValue);
break;
case ELEMENT_TYPE_I2:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(0x%04X)",KEYWORD("int16"),MDDV.m_usValue);
break;
case ELEMENT_TYPE_U2:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(0x%04X)",KEYWORD("uint16"),MDDV.m_usValue);
break;
case ELEMENT_TYPE_I4:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(0x%08X)",KEYWORD("int32"),MDDV.m_ulValue);
break;
case ELEMENT_TYPE_U4:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(0x%08X)",KEYWORD("uint32"),MDDV.m_ulValue);
break;
case ELEMENT_TYPE_CHAR:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(0x%04X)",KEYWORD("char"),MDDV.m_usValue);
break;
case ELEMENT_TYPE_BOOLEAN:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s",KEYWORD("bool"));
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(%s)", KEYWORD((char *)(MDDV.m_byteValue ? "true" : "false")));
break;
case ELEMENT_TYPE_I8:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(0x%I64X)",KEYWORD("int64"),MDDV.m_ullValue);
break;
case ELEMENT_TYPE_U8:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(0x%I64X)",KEYWORD("uint64"),MDDV.m_ullValue);
break;
case ELEMENT_TYPE_R4:
{
char szf[32];
_gcvt_s(szf,32,MDDV.m_fltValue, 8);
float df = (float)atof(szf);
// Must compare as underlying bytes, not floating point otherwise optmizier will
// try to enregister and comapre 80-bit precision number with 32-bit precision number!!!!
if((*(ULONG*)&df == MDDV.m_ulValue)&&!IsSpecialNumber(szf))
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(%s)",KEYWORD("float32"),szf);
else
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr), " = %s(0x%08X)",KEYWORD("float32"),MDDV.m_ulValue);
}
break;
case ELEMENT_TYPE_R8:
{
char szf[32], *pch;
_gcvt_s(szf,32,MDDV.m_dblValue, 17);
double df = strtod(szf, &pch); //atof(szf);
szf[31]=0;
// Must compare as underlying bytes, not floating point otherwise optmizier will
// try to enregister and comapre 80-bit precision number with 64-bit precision number!!!!
if((*(ULONGLONG*)&df == MDDV.m_ullValue)&&!IsSpecialNumber(szf))
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s(%s)",KEYWORD("float64"),szf);
else
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr), " = %s(0x%I64X) // %s",KEYWORD("float64"),MDDV.m_ullValue,szf);
}
break;
case ELEMENT_TYPE_STRING:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = ");
PAL_CPP_TRY {
szptr = DumpUnicodeString(GUICookie,szString,(WCHAR*)MDDV.m_wzValue,MDDV.m_cbSize/sizeof(WCHAR));
} PAL_CPP_CATCH_ALL {
strcat_s(szString, SZSTRING_SIZE,ERRORMSG("INVALID DATA ADDRESS"));
} PAL_CPP_ENDTRY;
break;
case ELEMENT_TYPE_CLASS:
if(MDDV.m_wzValue==NULL)
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = %s",KEYWORD("nullref"));
break;
}
//else fall thru to default case, to report the error
default:
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),ERRORMSG(" /* ILLEGAL CONSTANT type:0x%02X, size:%d bytes, blob: "),MDDV.m_bType,MDDV.m_cbSize);
if(MDDV.m_wzValue)
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(");
PAL_CPP_TRY {
DumpByteArray(szString,(BYTE*)MDDV.m_wzValue,MDDV.m_cbSize,GUICookie);
} PAL_CPP_CATCH_ALL {
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),ERRORMSG(" Invalid blob at 0x%08X)"), MDDV.m_wzValue);
} PAL_CPP_ENDTRY
}
else
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"NULL");
}
strcat_s(szString, SZSTRING_REMAINING_SIZE(szptr), " */");
break;
}
}
void DumpParams(ParamDescriptor* pPD, ULONG ulParams, void* GUICookie)
{
if(pPD)
{
for(ULONG i = ulParams; i<2*ulParams+1; i++) // pPD[ulParams] is return value
{
ULONG j = i % (ulParams+1);
if(RidFromToken(pPD[j].tok))
{
HENUMInternal hEnum;
mdCustomAttribute tkCA;
ULONG ulCAs= 0;
if(g_fShowCA)
{
if (FAILED(g_pImport->EnumInit(mdtCustomAttribute, pPD[j].tok, &hEnum)))
{
sprintf_s(szString, SZSTRING_SIZE, "%sERROR: MetaData error enumerating CustomAttribute for %08X", g_szAsmCodeIndent, pPD[j].tok);
printLine(GUICookie, szString);
continue;
}
ulCAs = g_pImport->EnumGetCount(&hEnum);
}
if(ulCAs || IsPdHasDefault(pPD[j].attr))
{
char *szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s [%d]",g_szAsmCodeIndent,KEYWORD(".param"),i-ulParams);
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X*/ "),pPD[j].tok);
if(IsPdHasDefault(pPD[j].attr)) DumpDefaultValue(pPD[j].tok, szString, GUICookie);
printLine(GUICookie, szString);
if(ulCAs)
{
while(g_pImport->EnumNext(&hEnum,&tkCA) && RidFromToken(tkCA))
{
DumpCustomAttribute(tkCA,GUICookie,false);
}
}
}
if(g_fShowCA) g_pImport->EnumClose( &hEnum);
}
}
}
}
BOOL DumpPermissionSetBlob(void* GUICookie,__inout __nullterminated char* szString, BYTE* pvPermission, ULONG cbPermission)
{
if(*pvPermission == '.')
{
CQuickBytes out;
pvPermission++;
char* szptr_init = &szString[strlen(szString)];
char* szptr = szptr_init;
appendStr(&out," = {");
unsigned nAttrs = CorSigUncompressData((PCCOR_SIGNATURE&)pvPermission);
for(unsigned iAttr = 0; iAttr < nAttrs; iAttr++)
{
unsigned L = CorSigUncompressData((PCCOR_SIGNATURE&)pvPermission); // class name length
mdToken tkAttr = ResolveReflectionNotation(pvPermission,L,g_pImport,GUICookie);
if(IsNilToken(tkAttr))
{
appendStr(&out,KEYWORD("class "));
appendStr(&out,"'");
appendStr(&out,UnquotedProperName((char*)pvPermission,L));
appendStr(&out,"'");
}
else
{
PrettyPrintClass(&out, tkAttr, g_pImport);
}
pvPermission += L;
appendStr(&out," = {");
// dump blob
L = CorSigUncompressData((PCCOR_SIGNATURE&)pvPermission); // blob length
if(L > 0)
{
BYTE* pvEnd = pvPermission+L;
L = CorSigUncompressData((PCCOR_SIGNATURE&)pvPermission); // number of props
if(L > 0)
{
if(!PrettyPrintCustomAttributeNVPairs(L, pvPermission, pvEnd, &out, GUICookie))
return FALSE;
out.Shrink(out.Size()-1);
}
pvPermission = pvEnd;
}
appendStr(&out, iAttr == nAttrs-1 ? "}" : "}, ");
}
appendStr(&out, "}");
char* sz = asString(&out);
while(char* pc = strstr(sz,"}, "))
{
*(pc+2) = 0;
strcpy_s(szptr,SZSTRING_REMAINING_SIZE(szptr), sz);
printLine(GUICookie,szString);
sz = pc+3;
if(szptr == szptr_init) szptr += 4; // to compensate for = {
for(pc = szString; pc < szptr; pc++) *pc = ' ';
}
strcpy_s(szptr, SZSTRING_REMAINING_SIZE(szptr),sz);
return TRUE;
}
return FALSE;
}
void DumpPermissions(mdToken tkOwner, void* GUICookie)
{
HCORENUM hEnum = NULL;
static mdPermission rPerm[16384];
ULONG count;
HRESULT hr;
//static char szString[4096];
// can't use internal import here: EnumInit not impl. for mdtPrmission
while (SUCCEEDED(hr = g_pPubImport->EnumPermissionSets( &hEnum,
tkOwner, 0, rPerm, 16384, &count)) &&
count > 0)
{
for (ULONG i = 0; i < count; i++)
{
DWORD dwAction;
const BYTE *pvPermission=NULL;
ULONG cbPermission=0;
const char *szAction;
char *szptr;
szptr = &szString[0];
if(SUCCEEDED(hr = g_pPubImport->GetPermissionSetProps( rPerm[i], &dwAction,
(const void**)&pvPermission, &cbPermission)))
{
szptr += sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".permissionset"));
switch(dwAction)
{
case dclActionNil: szAction = ""; break;
case dclRequest: szAction = KEYWORD("request"); break;
case dclDemand: szAction = KEYWORD("demand"); break;
case dclAssert: szAction = KEYWORD("assert"); break;
case dclDeny: szAction = KEYWORD("deny"); break;
case dclPermitOnly: szAction = KEYWORD("permitonly"); break;
case dclLinktimeCheck: szAction = KEYWORD("linkcheck"); break;
case dclInheritanceCheck: szAction = KEYWORD("inheritcheck"); break;
case dclRequestMinimum: szAction = KEYWORD("reqmin"); break;
case dclRequestOptional: szAction = KEYWORD("reqopt"); break;
case dclRequestRefuse: szAction = KEYWORD("reqrefuse"); break;
case dclPrejitGrant: szAction = KEYWORD("prejitgrant"); break;
case dclPrejitDenied: szAction = KEYWORD("prejitdeny"); break;
case dclNonCasDemand: szAction = KEYWORD("noncasdemand"); break;
case dclNonCasLinkDemand: szAction = KEYWORD("noncaslinkdemand"); break;
case dclNonCasInheritance: szAction = KEYWORD("noncasinheritance"); break;
default: szAction = ERRORMSG("<UNKNOWN_ACTION>"); break;
}
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),szAction);
if(pvPermission && cbPermission)
{
printLine(GUICookie, szString);
sprintf_s(szString,SZSTRING_SIZE,"%s ",g_szAsmCodeIndent);
if(!DumpPermissionSetBlob(GUICookie,szString,(BYTE*)pvPermission,cbPermission))
{
strcat_s(szString,SZSTRING_SIZE,KEYWORD("bytearray"));
strcat_s(szString,SZSTRING_SIZE," (");
DumpByteArray(szString, pvPermission, cbPermission, GUICookie);
}
printLine(GUICookie,szString);
}
else // i.e. if pvPermission == NULL or cbPermission == NULL
{
sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," = ()");
printLine(GUICookie,szString);
}
DumpCustomAttributes(rPerm[i],GUICookie);
}// end if(GetPermissionProps)
} // end for(all permissions)
}//end while(EnumPermissionSets)
g_pPubImport->CloseEnum( hEnum);
}
void PrettyPrintMethodSig(__inout __nullterminated char* szString, unsigned* puStringLen, CQuickBytes* pqbMemberSig, PCCOR_SIGNATURE pComSig, ULONG cComSig,
__inout __nullterminated char* buff, __in_opt __nullterminated char* szArgPrefix, void* GUICookie)
{
unsigned uMaxWidth = 40;
if(g_fDumpHTML || g_fDumpRTF) uMaxWidth = 240;
if(*buff && (strlen(szString) > (size_t)uMaxWidth))
{
printLine(GUICookie,szString);
strcpy_s(szString,SZSTRING_SIZE,g_szAsmCodeIndent);
strcat_s(szString,SZSTRING_SIZE," "); // to align with ".method "
}
appendStr(pqbMemberSig, szString);
{
char* pszTailSig = (char*)PrettyPrintSig(pComSig, cComSig, buff, pqbMemberSig, g_pImport, szArgPrefix);
if(*buff)
{
size_t L = strlen(pszTailSig);
char* newbuff = new char[strlen(buff)+3];
sprintf_s(newbuff,strlen(buff)+3," %s(", buff);
char* pszOffset = strstr(pszTailSig,newbuff);
if(pszOffset)
{
char* pszTailSigRemainder = new char[L+1];
if(pszOffset - pszTailSig > (int)uMaxWidth)
{
char* pszOffset2 = strstr(pszTailSig," marshal(");
if(pszOffset2 && (pszOffset2 < pszOffset))
{
*pszOffset2 = 0;
strcpy_s(pszTailSigRemainder,L,pszOffset2+1);
printLine(GUICookie,pszTailSig);
strcpy_s(pszTailSig,L,g_szAsmCodeIndent);
strcat_s(pszTailSig,L," "); // to align with ".method "
strcat_s(pszTailSig,L,pszTailSigRemainder);
pszOffset = strstr(pszTailSig,newbuff);
}
*pszOffset = 0 ;
strcpy_s(pszTailSigRemainder,L,pszOffset+1);
printLine(GUICookie,pszTailSig);
strcpy_s(pszTailSig,L,g_szAsmCodeIndent);
strcat_s(pszTailSig,L," "); // to align with ".method "
strcat_s(pszTailSig,L,pszTailSigRemainder);
pszOffset = strstr(pszTailSig,newbuff);
}
size_t i, j, k, l, indent = pszOffset - pszTailSig + strlen(buff) + 2;
char chAfterComma;
char *pComma = pszTailSig+strlen(buff), *pch;
while((pComma = strchr(pComma,',')))
{
for(pch = pszTailSig, i=0, j = 0, k=0, l=0; pch < pComma; pch++)
{
if(*pch == '\\') pch++;
else
{
if(*pch == '\'') j=1-j;
else if(*pch == '\"') k=1-k;
else if(j==0)
{
if(*pch == '[') i++;
else if(*pch == ']') i--;
else if(strncmp(pch,LTN(),strlen(LTN()))==0) l++;
else if(strncmp(pch,GTN(),strlen(GTN()))==0) l--;
}
}
}
pComma++;
if((i==0)&&(j==0)&&(k==0)&&(l==0))// no brackets/quotes or all opened/closed
{
chAfterComma = *pComma;
strcpy_s(pszTailSigRemainder,L,pComma);
*pComma = 0;
printLine(GUICookie,pszTailSig);
*pComma = chAfterComma;
for(i=0; i<indent; i++) pszTailSig[i] = ' ';
strcpy_s(&pszTailSig[indent],L-indent,pszTailSigRemainder);
pComma = pszTailSig;
}
}
if(*puStringLen < (unsigned)strlen(pszTailSig)+128)
{
//free(szString);
*puStringLen = (unsigned)strlen(pszTailSig)+128; // need additional space for "il managed" etc.
//szString = (char*)malloc(*puStringLen);
}
VDELETE(pszTailSigRemainder);
}
strcpy_s(szString,SZSTRING_SIZE,pszTailSig);
VDELETE(newbuff);
}
else // it's for GUI, don't split it into several lines
{
size_t L = strlen(szString);
if(L < 2048)
{
L = 2048-L;
strncpy_s(szString,SZSTRING_SIZE,pszTailSig,L);
}
}
}
}
// helper to avoid mixing of SEH and stack objects with destructors
BOOL DisassembleWrapper(IMDInternalImport *pImport, BYTE *ILHeader,
void *GUICookie, mdToken FuncToken, ParamDescriptor* pszArgname, ULONG ulArgs)
{
BOOL fRet = FALSE;
//char szString[4096];
PAL_CPP_TRY
{
fRet = Disassemble(pImport, ILHeader, GUICookie, FuncToken, pszArgname, ulArgs);
}
PAL_CPP_CATCH_ALL
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_DASMERR),g_szAsmCodeIndent);
printLine(GUICookie, szString);
}
PAL_CPP_ENDTRY
return fRet;
}
BOOL PrettyPrintGP( // prints name of generic param, or returns FALSE
mdToken tkOwner, // Class, method or 0
CQuickBytes *out, // where to put the pretty printed generic param
int n) // Index of generic param
{
BOOL ret = FALSE;
if(tkOwner && ((TypeFromToken(tkOwner)==mdtTypeDef)||(TypeFromToken(tkOwner)==mdtMethodDef)))
{
DWORD NumTyPars;
HENUMInternal hEnumTyPar;
if(SUCCEEDED(g_pImport->EnumInit(mdtGenericParam,tkOwner,&hEnumTyPar)))
{
NumTyPars = g_pImport->EnumGetCount(&hEnumTyPar);
if(NumTyPars > (DWORD)n)
{
// need this for name dup check
LPCSTR *pszName = new LPCSTR[NumTyPars];
if(pszName != NULL)
{
ULONG ulSequence;
DWORD ix,nx;
mdToken tk;
for(ix = 0, nx = 0xFFFFFFFF; ix < NumTyPars; ix++)
{
if(g_pImport->EnumNext(&hEnumTyPar,&tk))
{
if(SUCCEEDED(g_pImport->GetGenericParamProps(tk,&ulSequence,NULL,NULL,NULL,&pszName[ix])))
{
if(ulSequence == (ULONG)n)
nx = ix;
}
}
}
// if there are dup names, use !0 or !!0
if(nx != 0xFFFFFFFF)
{
for(ix = 0; ix < nx; ix++)
{
if(strcmp(pszName[ix],pszName[nx]) == 0)
break;
}
if(ix >= nx)
{
for(ix = nx+1; ix < NumTyPars; ix++)
{
if(strcmp(pszName[ix],pszName[nx]) == 0)
break;
}
if(ix >= NumTyPars)
{
appendStr(out, ProperName((char*)(pszName[nx])));
ret = TRUE;
}
}
} // end if(tkTyPar != 0)
delete [] pszName;
} // end if(pszName != NULL)
} // end if(NumTyPars > (DWORD)n)
} // end if(SUCCEEDED(g_pImport->EnumInit(mdtGenericParam,tkOwner,&hEnumTyPar)))
g_pImport->EnumClose(&hEnumTyPar);
} // end if(tkOwner)
return ret;
}
// Pretty-print formal type parameters for a class or method
char *DumpGenericPars(__inout_ecount(SZSTRING_SIZE) char* szString, mdToken tok, void* GUICookie/*=NULL*/, BOOL fSplit/*=FALSE*/)
{
WCHAR *wzArgName = wzUniBuf;
ULONG chName;
mdToken tkConstr[2048];
DWORD NumTyPars;
DWORD NumConstrs;
mdGenericParam tkTyPar;
ULONG ulSequence;
DWORD attr;
mdToken tkOwner;
HCORENUM hEnumTyPar = NULL;
HCORENUM hEnumTyParConstr = NULL;
char* szptr = &szString[strlen(szString)];
char* szbegin;
unsigned i;
if (FAILED(g_pPubImport->EnumGenericParams(&hEnumTyPar, tok, &tkTyPar, 1, &NumTyPars)))
return NULL;
if (NumTyPars > 0)
{
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),LTN());
szbegin = szptr;
for (i = 1; NumTyPars != 0; i++)
{
g_pPubImport->GetGenericParamProps(tkTyPar, &ulSequence, &attr, &tkOwner, NULL, wzArgName, UNIBUF_SIZE/2, &chName);
//if(wcslen(wzArgName) >= MAX_CLASSNAME_LENGTH)
// wzArgName[MAX_CLASSNAME_LENGTH-1] = 0;
hEnumTyParConstr = NULL;
if (FAILED(g_pPubImport->EnumGenericParamConstraints(&hEnumTyParConstr, tkTyPar, tkConstr, 2048, &NumConstrs)))
{
g_pPubImport->CloseEnum(hEnumTyPar);
return NULL;
}
*szptr = 0;
CHECK_REMAINING_SIZE;
switch (attr & gpVarianceMask)
{
case gpCovariant : szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr), "+ "); break;
case gpContravariant : szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr), "- "); break;
}
CHECK_REMAINING_SIZE;
if ((attr & gpReferenceTypeConstraint) != 0)
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr), "class ");
CHECK_REMAINING_SIZE;
if ((attr & gpNotNullableValueTypeConstraint) != 0)
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr), "valuetype ");
CHECK_REMAINING_SIZE;
if ((attr & gpDefaultConstructorConstraint) != 0)
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr), ".ctor ");
CHECK_REMAINING_SIZE;
if (NumConstrs)
{
CQuickBytes out;
mdToken tkConstrType,tkOwner;
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"(");
DWORD ix;
for (ix=0; ix<NumConstrs; ix++)
{
if (FAILED(g_pPubImport->GetGenericParamConstraintProps(tkConstr[ix], &tkOwner, &tkConstrType)))
return NULL;
if(ix) szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),", ");
CHECK_REMAINING_SIZE;
out.Shrink(0);
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s",PrettyPrintClass(&out,tkConstrType,g_pImport));
CHECK_REMAINING_SIZE;
}
if(ix < NumConstrs) break;
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),") ");
CHECK_REMAINING_SIZE;
}
// re-get name, wzUniBuf may not contain it any more
g_pPubImport->GetGenericParamProps(tkTyPar, NULL, &attr, NULL, NULL, wzArgName, UNIBUF_SIZE/2, &chName);
//if(wcslen(wzArgName) >= MAX_CLASSNAME_LENGTH)
// wzArgName[MAX_CLASSNAME_LENGTH-1] = 0;
if (chName)
{
char* sz = (char*)(&wzUniBuf[UNIBUF_SIZE/2]);
WszWideCharToMultiByte(CP_UTF8,0,wzArgName,-1,sz,UNIBUF_SIZE,NULL,NULL);
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s",ProperName(sz));
}
CHECK_REMAINING_SIZE;
if (FAILED(g_pPubImport->EnumGenericParams(&hEnumTyPar, tok, &tkTyPar, 1, &NumTyPars)))
return NULL;
if (NumTyPars != 0)
{
*szptr++ = ',';
if(fSplit && (i == 4))
{
*szptr = 0;
printLine(GUICookie,szString);
i = 0; // mind i++ at the end of the loop
for(szptr = szString; szptr < szbegin; szptr++) *szptr = ' ';
}
}
} // end for (i = 1; NumTyPars != 0; i++)
if(NumTyPars != 0) // all type parameters can't fit in szString, error
{
strcpy_s(szptr,4,"...");
szptr += 3;
}
else
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),GTN());
} // end if (NumTyPars > 0)
*szptr = 0;
if(hEnumTyPar) g_pPubImport->CloseEnum(hEnumTyPar);
return szptr;
}
void DumpGenericParsCA(mdToken tok, void* GUICookie/*=NULL*/)
{
DWORD NumTyPars;
mdGenericParam tkTyPar;
HCORENUM hEnumTyPar = NULL;
unsigned i;
WCHAR *wzArgName = wzUniBuf;
ULONG chName;
DWORD attr;
if(g_fShowCA)
{
for(i=0; SUCCEEDED(g_pPubImport->EnumGenericParams(&hEnumTyPar, tok, &tkTyPar, 1, &NumTyPars))
&&(NumTyPars > 0); i++)
{
HENUMInternal hEnum;
mdCustomAttribute tkCA;
ULONG ulCAs= 0;
if (FAILED(g_pImport->EnumInit(mdtCustomAttribute, tkTyPar, &hEnum)))
{
sprintf_s(szString, SZSTRING_SIZE, "%sERROR: MetaData error enumerating CustomAttribute for %08X", g_szAsmCodeIndent, tkTyPar);
printLine(GUICookie, szString);
return;
}
ulCAs = g_pImport->EnumGetCount(&hEnum);
if(ulCAs)
{
char *szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".param type"));
if(SUCCEEDED(g_pPubImport->GetGenericParamProps(tkTyPar, NULL, &attr, NULL, NULL, wzArgName, UNIBUF_SIZE/2, &chName))
&&(chName > 0))
{
//if(wcslen(wzArgName) >= MAX_CLASSNAME_LENGTH)
// wzArgName[MAX_CLASSNAME_LENGTH-1] = 0;
char* sz = (char*)(&wzUniBuf[UNIBUF_SIZE/2]);
WszWideCharToMultiByte(CP_UTF8,0,wzArgName,-1,sz,UNIBUF_SIZE,NULL,NULL);
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s ",ProperName(sz));
}
else
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"[%d] ",i+1);
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X*/ "),tkTyPar);
printLine(GUICookie, szString);
strcat_s(g_szAsmCodeIndent, MAX_MEMBER_LENGTH, " ");
while(g_pImport->EnumNext(&hEnum,&tkCA) && RidFromToken(tkCA))
{
DumpCustomAttribute(tkCA,GUICookie,false);
}
g_szAsmCodeIndent[strlen(g_szAsmCodeIndent) - 2] = 0;
}
g_pImport->EnumClose( &hEnum); // mdtCustomAttribute
ULONG ulSequence;
DWORD attr;
mdToken tkOwner;
HCORENUM hEnumTyParConstraint;
mdToken tkConstraint[2048];
DWORD NumConstraints;
g_pPubImport->GetGenericParamProps(tkTyPar, &ulSequence, &attr, &tkOwner, NULL, wzArgName, UNIBUF_SIZE / 2, &chName);
hEnumTyParConstraint = NULL;
if (FAILED(g_pPubImport->EnumGenericParamConstraints(&hEnumTyParConstraint, tkTyPar, tkConstraint, 2048, &NumConstraints)))
{
g_pPubImport->CloseEnum(hEnumTyPar);
return;
}
if (NumConstraints > 0)
{
CQuickBytes out;
mdToken tkConstraintType;
mdToken tkGenericParam;
ULONG ulSequence;
for (DWORD ix = 0; ix < NumConstraints; ix++)
{
mdGenericParamConstraint tkParamConstraint = tkConstraint[ix];
if (FAILED(g_pPubImport->GetGenericParamConstraintProps(tkParamConstraint, &tkGenericParam, &tkConstraintType)))
{
sprintf_s(szString, SZSTRING_SIZE, "%sERROR: MetaData error in GetGenericParamConstraintProps for %08X", g_szAsmCodeIndent, tkParamConstraint);
return;
}
if (FAILED(g_pImport->EnumInit(mdtCustomAttribute, tkParamConstraint, &hEnum)))
{
sprintf_s(szString, SZSTRING_SIZE, "%sERROR: MetaData error enumerating CustomAttribute for mdGenericParamConstraint %08X", g_szAsmCodeIndent, tkParamConstraint);
printLine(GUICookie, szString);
return;
}
ulCAs = g_pImport->EnumGetCount(&hEnum);
if (ulCAs)
{
char *szptr = &szString[0];
szptr += sprintf_s(szptr, SZSTRING_SIZE, "%s%s ", g_szAsmCodeIndent, KEYWORD(".param constraint"));
if (FAILED(g_pPubImport->GetGenericParamProps(tkGenericParam, &ulSequence, &attr, NULL, NULL, wzArgName, UNIBUF_SIZE / 2, &chName)))
{
sprintf_s(szString, SZSTRING_SIZE, "%sERROR: MetaData error in GetGenericParamProps for %08X", g_szAsmCodeIndent, tkGenericParam);
printLine(GUICookie, szString);
return;
}
if (chName > 0)
{
char* sz = (char*)(&wzUniBuf[UNIBUF_SIZE / 2]);
WszWideCharToMultiByte(CP_UTF8, 0, wzArgName, -1, sz, UNIBUF_SIZE, NULL, NULL);
szptr += sprintf_s(szptr, SZSTRING_REMAINING_SIZE(szptr), " %s", ProperName(sz));
}
else
{
szptr += sprintf_s(szptr, SZSTRING_REMAINING_SIZE(szptr), " [%d]", ulSequence + 1);
}
if (g_fDumpTokens)
{
szptr += sprintf_s(szptr, SZSTRING_REMAINING_SIZE(szptr), COMMENT("/*%08X*/ "), tkGenericParam);
}
szptr += sprintf_s(szptr, SZSTRING_REMAINING_SIZE(szptr), ", ");
out.Shrink(0);
szptr += sprintf_s(szptr, SZSTRING_REMAINING_SIZE(szptr), "%s", PrettyPrintClass(&out, tkConstraintType, g_pImport));
printLine(GUICookie, szString);
strcat_s(g_szAsmCodeIndent, MAX_MEMBER_LENGTH, " ");
while (g_pImport->EnumNext(&hEnum, &tkCA) && RidFromToken(tkCA))
{
DumpCustomAttribute(tkCA, GUICookie, false);
}
g_szAsmCodeIndent[strlen(g_szAsmCodeIndent) - 2] = 0;
}
g_pImport->EnumClose(&hEnum); // mdtCustomAttribute
}
}
} //end for(i=0;...
} //end if(g_fShowCA)
}
// Sets *pbOverridingTypeSpec to TRUE if we are overriding a method declared by a type spec.
// In that case the syntax is slightly different (there are additional 'method' keywords).
// Refer to Expert .NET 2.0 IL Assembler page 242.
void PrettyPrintOverrideDecl(ULONG i, __inout __nullterminated char* szString, void* GUICookie, mdToken tkOverrider,
BOOL *pbOverridingTypeSpec)
{
const char * pszMemberName;
mdToken tkDecl,tkDeclParent=0;
char szBadToken[256];
char pszTailSigDefault[] = "";
char* pszTailSig = pszTailSigDefault;
CQuickBytes qbInstSig;
char* szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".override"));
tkDecl = (*g_pmi_list)[i].tkDecl;
*pbOverridingTypeSpec = FALSE;
if(g_pImport->IsValidToken(tkDecl))
{
if(SUCCEEDED(g_pImport->GetParentToken(tkDecl,&tkDeclParent)))
{
if(g_pImport->IsValidToken(tkDeclParent))
{
if(TypeFromToken(tkDeclParent) == mdtMethodDef) //get the parent's parent
{
mdTypeRef cr1;
if(FAILED(g_pImport->GetParentToken(tkDeclParent,&cr1))) cr1 = mdTypeRefNil;
tkDeclParent = cr1;
}
if(RidFromToken(tkDeclParent))
{
if(TypeFromToken(tkDeclParent)==mdtTypeSpec)
{
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr), " %s ",KEYWORD("method"));
PrettyPrintToken(szString,tkDecl,g_pImport,GUICookie,tkOverrider);
*pbOverridingTypeSpec = TRUE;
return;
}
PrettyPrintToken(szString, tkDeclParent, g_pImport,GUICookie,tkOverrider);
strcat_s(szString, SZSTRING_SIZE,"::");
szptr = &szString[strlen(szString)];
}
}
else
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s",ERRORMSG("INVALID OVERRIDDEN METHOD'S PARENT TOKEN"));
}
if(TypeFromToken(tkDecl) == mdtMethodSpec)
{
mdToken meth=0;
PCCOR_SIGNATURE pSig=NULL;
ULONG cSig=0;
if (FAILED(g_pImport->GetMethodSpecProps(tkDecl, &meth, &pSig, &cSig)))
{
meth = mdTokenNil;
pSig = NULL;
cSig = 0;
}
if (pSig && cSig)
{
qbInstSig.Shrink(0);
pszTailSig = (char*)PrettyPrintSig(pSig, cSig, "", &qbInstSig, g_pImport, NULL);
}
tkDecl = meth;
}
if(TypeFromToken(tkDecl) == mdtMethodDef)
{
if (FAILED(g_pImport->GetNameOfMethodDef(tkDecl, &pszMemberName)))
{
sprintf_s(szBadToken,256,ERRORMSG("INVALID RECORD: 0x%8.8X"),tkDecl);
pszMemberName = (const char *)szBadToken;
}
}
else if(TypeFromToken(tkDecl) == mdtMemberRef)
{
PCCOR_SIGNATURE pComSig;
ULONG cComSig;
if (FAILED(g_pImport->GetNameAndSigOfMemberRef(
tkDecl,
&pComSig,
&cComSig,
&pszMemberName)))
{
sprintf_s(szBadToken,256,ERRORMSG("INVALID RECORD: 0x%8.8X"),tkDecl);
pszMemberName = (const char *)szBadToken;
}
}
else
{
sprintf_s(szBadToken,256,ERRORMSG("INVALID TOKEN: 0x%8.8X"),tkDecl);
pszMemberName = (const char*)szBadToken;
}
MAKE_NAME_IF_NONE(pszMemberName,tkDecl);
}
else
{
sprintf_s(szBadToken,256,ERRORMSG("INVALID TOKEN: 0x%8.8X"),tkDecl);
pszMemberName = (const char*)szBadToken;
}
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s%s",ProperName((char*)pszMemberName),pszTailSig);
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT(" /*%08X::%08X*/ "),tkDeclParent,(*g_pmi_list)[i].tkDecl);
}
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
BOOL DumpMethod(mdToken FuncToken, const char *pszClassName, DWORD dwEntryPointToken,void *GUICookie,BOOL DumpBody)
{
const char *pszMemberName = NULL;//[MAX_MEMBER_LENGTH];
const char *pszMemberSig = NULL;
DWORD dwAttrs = 0;
DWORD dwImplAttrs;
DWORD dwOffset;
DWORD dwTargetRVA;
CQuickBytes qbMemberSig;
PCCOR_SIGNATURE pComSig = NULL;
ULONG cComSig;
char *buff = NULL;//[MAX_MEMBER_LENGTH];
ParamDescriptor* pszArgname = NULL;
ULONG ulArgs=0;
unsigned retParamIx = 0;
unsigned uStringLen = SZSTRING_SIZE;
char szArgPrefix[MAX_PREFIX_SIZE];
char* szptr = NULL;
mdToken tkMVarOwner = g_tkMVarOwner;
if (FAILED(g_pImport->GetMethodDefProps(FuncToken, &dwAttrs)))
{
sprintf_s(szString, SZSTRING_SIZE, "%sERROR: MethodDef %08X has wrong record", g_szAsmCodeIndent, FuncToken);
printError(GUICookie, ERRORMSG(szString));
return FALSE;
}
if (g_fLimitedVisibility)
{
if(g_fHidePub && IsMdPublic(dwAttrs)) return FALSE;
if(g_fHidePriv && IsMdPrivate(dwAttrs)) return FALSE;
if(g_fHideFam && IsMdFamily(dwAttrs)) return FALSE;
if(g_fHideAsm && IsMdAssem(dwAttrs)) return FALSE;
if(g_fHideFOA && IsMdFamORAssem(dwAttrs)) return FALSE;
if(g_fHideFAA && IsMdFamANDAssem(dwAttrs)) return FALSE;
if(g_fHidePrivScope && IsMdPrivateScope(dwAttrs)) return FALSE;
}
if (FAILED(g_pImport->GetMethodImplProps(FuncToken, &dwOffset, &dwImplAttrs)))
{
sprintf_s(szString, SZSTRING_SIZE, "%sERROR: Invalid MethodImpl %08X record", g_szAsmCodeIndent, FuncToken);
printError(GUICookie, ERRORMSG(szString));
return FALSE;
}
if (FAILED(g_pImport->GetNameOfMethodDef(FuncToken, &pszMemberName)))
{
sprintf_s(szString, SZSTRING_SIZE, "%sERROR: MethodDef %08X has wrong record", g_szAsmCodeIndent, FuncToken);
printError(GUICookie, ERRORMSG(szString));
return FALSE;
}
MAKE_NAME_IF_NONE(pszMemberName,FuncToken);
if (FAILED(g_pImport->GetSigOfMethodDef(FuncToken, &cComSig, &pComSig)))
{
pComSig = NULL;
}
if (cComSig == NULL)
{
sprintf_s(szString, SZSTRING_SIZE, "%sERROR: method '%s' has no signature", g_szAsmCodeIndent, pszMemberName);
printError(GUICookie, ERRORMSG(szString));
return FALSE;
}
bool bRet = FALSE;
PAL_CPP_TRY {
if((*pComSig & IMAGE_CEE_CS_CALLCONV_MASK) > IMAGE_CEE_CS_CALLCONV_VARARG)
{
sprintf_s(szString,SZSTRING_SIZE,"%sERROR: signature of method '%s' has invalid calling convention 0x%2.2X",g_szAsmCodeIndent,pszMemberName,*pComSig);
printError(GUICookie,ERRORMSG(szString));
bRet = TRUE;
goto lDone;
}
g_tkMVarOwner = FuncToken;
szString[0] = 0;
DumpGenericPars(szString,FuncToken); //,NULL,FALSE);
pszMemberSig = PrettyPrintSig(pComSig, cComSig, szString, &qbMemberSig, g_pImport,NULL);
lDone: ;
} PAL_CPP_CATCH_ALL {
printError(GUICookie,"INVALID DATA ADDRESS");
bRet = TRUE;
} PAL_CPP_ENDTRY;
if (bRet)
{
g_tkMVarOwner = tkMVarOwner;
return FALSE;
}
if (g_Mode == MODE_DUMP_CLASS_METHOD || g_Mode == MODE_DUMP_CLASS_METHOD_SIG)
{
if (strcmp(pszMemberName, g_pszMethodToDump) != 0) return FALSE;
if (g_Mode == MODE_DUMP_CLASS_METHOD_SIG)
{
// we want plain signature without token values
const char *pszPlainSig;
if (g_fDumpTokens)
{
// temporarily disable token dumping
g_fDumpTokens = FALSE;
PAL_CPP_TRY
{
CQuickBytes qbTempSig;
pszPlainSig = PrettyPrintSig(pComSig, cComSig, "", &qbTempSig, g_pImport, NULL);
}
PAL_CPP_CATCH_ALL
{
pszPlainSig = "";
}
PAL_CPP_ENDTRY;
g_fDumpTokens = TRUE;
}
else
{
pszPlainSig = pszMemberSig;
}
if (strcmp(pszPlainSig, g_pszSigToDump) != 0) return FALSE;
}
}
if(!DumpBody)
{
printLine(GUICookie,(char*)pszMemberSig);
g_tkMVarOwner = tkMVarOwner;
return TRUE;
}
szptr = &szString[0];
szString[0] = 0;
if(DumpBody) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s%s ",g_szAsmCodeIndent,ANCHORPT(KEYWORD(".method"),FuncToken));
else szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s ",ANCHORPT(KEYWORD(".method"),FuncToken));
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X*/ "),FuncToken);
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD((char*)0));
if(IsMdPublic(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"public ");
if(IsMdPrivate(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"private ");
if(IsMdFamily(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"family ");
if(IsMdAssem(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"assembly ");
if(IsMdFamANDAssem(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"famandassem ");
if(IsMdFamORAssem(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"famorassem ");
if(IsMdPrivateScope(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"privatescope ");
if(IsMdHideBySig(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"hidebysig ");
if(IsMdNewSlot(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"newslot ");
if(IsMdSpecialName(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"specialname ");
if(IsMdRTSpecialName(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"rtspecialname ");
if (IsMdStatic(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"static ");
if (IsMdAbstract(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"abstract ");
if (dwAttrs & 0x00000200) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"strict ");
if (IsMdVirtual(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"virtual ");
if (IsMdFinal(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"final ");
if (IsMdUnmanagedExport(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"unmanagedexp ");
if(IsMdRequireSecObject(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"reqsecobj ");
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD((char*)-1));
if (IsMdPinvokeImpl(dwAttrs))
{
DWORD dwMappingFlags;
const char *szImportName;
mdModuleRef mrImportDLL;
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s(",KEYWORD("pinvokeimpl"));
if(FAILED(g_pImport->GetPinvokeMap(FuncToken,&dwMappingFlags,
&szImportName,&mrImportDLL))) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/* No map */"));
else
szptr=DumpPinvokeMap(dwMappingFlags, (strcmp(szImportName,pszMemberName)? szImportName : NULL),
mrImportDLL,szString,GUICookie);
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),") ");
}
// A little hack to get the formatting we need for Assem.
buff = new char[SZSTRING_SIZE];
if(buff==NULL)
{
printError(GUICookie,"Out of memory");
g_tkMVarOwner = tkMVarOwner;
return FALSE;
}
g_fThisIsInstanceMethod = !IsMdStatic(dwAttrs);
{
const char *psz = NULL;
if(IsMdPrivateScope(dwAttrs))
sprintf_s(buff,SZSTRING_SIZE,"%s$PST%08X", pszMemberName,FuncToken );
else
strcpy_s(buff,SZSTRING_SIZE, pszMemberName );
psz = ProperName(buff);
if(psz != buff)
{
strcpy_s(buff,SZSTRING_SIZE,psz);
}
}
DumpGenericPars(buff, FuncToken); //, NULL, FALSE);
qbMemberSig.Shrink(0);
// Get the argument names, if any
strcpy_s(szArgPrefix,MAX_PREFIX_SIZE,(g_fThisIsInstanceMethod ? "A1": "A0"));
{
PCCOR_SIGNATURE typePtr = pComSig;
unsigned ulCallConv = CorSigUncompressData(typePtr); // get the calling convention out of the way
if (ulCallConv & IMAGE_CEE_CS_CALLCONV_GENERIC)
CorSigUncompressData(typePtr); // get the num of generic args out of the way
unsigned numArgs = CorSigUncompressData(typePtr)+1;
HENUMInternal hArgEnum;
mdParamDef tkArg;
if (FAILED(g_pImport->EnumInit(mdtParamDef,FuncToken,&hArgEnum)))
{
printError(GUICookie, "Invalid MetaDataFormat");
g_tkMVarOwner = tkMVarOwner;
return FALSE;
}
ulArgs = g_pImport->EnumGetCount(&hArgEnum);
retParamIx = numArgs-1;
if (ulArgs < numArgs) ulArgs = numArgs;
if (ulArgs != 0)
{
pszArgname = new ParamDescriptor[ulArgs+2];
memset(pszArgname,0,(ulArgs+2)*sizeof(ParamDescriptor));
LPCSTR szName;
ULONG ulSequence, ix;
USHORT wSequence;
DWORD dwAttr;
ULONG j;
for (j=0; g_pImport->EnumNext(&hArgEnum,&tkArg) && RidFromToken(tkArg); j++)
{
if (FAILED(g_pImport->GetParamDefProps(tkArg, &wSequence, &dwAttr, &szName)))
{
char sz[256];
sprintf_s(sz, COUNTOF(sz), RstrUTF(IDS_E_INVALIDRECORD), tkArg);
printError(GUICookie, sz);
continue;
}
ulSequence = wSequence;
if (ulSequence > ulArgs+1)
{
char sz[256];
sprintf_s(sz,256,RstrUTF(IDS_E_PARAMSEQNO),j,ulSequence,ulSequence);
printError(GUICookie,sz);
}
else
{
ix = retParamIx;
if (ulSequence != 0)
{
ix = ulSequence-1;
if (*szName != 0)
{
pszArgname[ix].name = new char[strlen(szName)+1];
strcpy_s(pszArgname[ix].name,strlen(szName)+1,szName);
}
}
pszArgname[ix].attr = dwAttr;
pszArgname[ix].tok = tkArg;
}
}// end for( along the params)
for (j=0; j <numArgs; j++)
{
if(pszArgname[j].name == NULL) // we haven't got the name!
{
pszArgname[j].name = new char[16];
*pszArgname[j].name = 0;
}
if(*pszArgname[j].name == 0) // we haven't got the name!
{
sprintf_s(pszArgname[j].name,16,"A_%d",g_fThisIsInstanceMethod ? j+1 : j);
}
}// end for( along the argnames)
sprintf_s(szArgPrefix,MAX_PREFIX_SIZE,"@%Id0",(size_t)pszArgname);
} //end if (ulArgs)
g_pImport->EnumClose(&hArgEnum);
}
g_tkRefUser = FuncToken;
PrettyPrintMethodSig(szString, &uStringLen, &qbMemberSig, pComSig, cComSig,
buff, szArgPrefix, GUICookie);
g_tkRefUser = 0;
szptr = &szString[strlen(szString)];
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD((char*)0));
if(IsMiNative(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," native");
if(IsMiIL(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," cil");
if(IsMiOPTIL(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," optil");
if(IsMiRuntime(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," runtime");
if(IsMiUnmanaged(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," unmanaged");
if(IsMiManaged(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," managed");
if(IsMiPreserveSig(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," preservesig");
if(IsMiForwardRef(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," forwardref");
if(IsMiInternalCall(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," internalcall");
if(IsMiSynchronized(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," synchronized");
if(IsMiNoInlining(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," noinlining");
if(IsMiAggressiveInlining(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," aggressiveinlining");
if(IsMiNoOptimization(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," nooptimization");
if(IsMiAggressiveOptimization(dwImplAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," aggressiveoptimization");
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD((char*)-1));
printLine(GUICookie, szString);
VDELETE(buff);
if(!DumpBody)
{
g_tkMVarOwner = tkMVarOwner;
return TRUE;
}
if(g_fShowBytes)
{
if (FAILED(g_pImport->GetSigOfMethodDef(FuncToken, &cComSig, &pComSig)))
{
sprintf_s(szString,SZSTRING_SIZE,"%sERROR: method %08X has wrong record",g_szAsmCodeIndent,FuncToken);
printError(GUICookie,ERRORMSG(szString));
return FALSE;
}
const char* szt = "SIG:";
for(ULONG i=0; i<cComSig;)
{
szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s// %s", g_szAsmCodeIndent, szt);
while(i<cComSig)
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," %02X",pComSig[i]);
i++;
if((i & 0x1F)==0) break; // print only 32 per line
}
printLine(GUICookie, COMMENT(szString));
szt = " ";
}
}
szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s", g_szAsmCodeIndent,SCOPE());
printLine(GUICookie, szString);
szptr = &szString[0];
strcat_s(g_szAsmCodeIndent,MAX_MEMBER_LENGTH," ");
// We have recoreded the entry point token from the CLR Header. Check to see if this
// method is the entry point.
if(FuncToken == static_cast<mdToken>(dwEntryPointToken))
{
sprintf_s(szString,SZSTRING_SIZE,"%s%s", g_szAsmCodeIndent,KEYWORD(".entrypoint"));
printLine(GUICookie, szString);
}
DumpCustomAttributes(FuncToken,GUICookie);
DumpGenericParsCA(FuncToken,GUICookie);
DumpParams(pszArgname, retParamIx, GUICookie);
DumpPermissions(FuncToken,GUICookie);
// Check if the method represents entry in VTable fixups and in EATable
{
ULONG j;
for(j=0; j<g_nVTableRef; j++)
{
if((*g_prVTableRef)[j].tkTok == FuncToken)
{
sprintf_s(szString,SZSTRING_SIZE,"%s%s %d : %d",
g_szAsmCodeIndent,KEYWORD(".vtentry"),(*g_prVTableRef)[j].wEntry+1,(*g_prVTableRef)[j].wSlot+1);
printLine(GUICookie, szString);
break;
}
}
for(j=0; j<g_nEATableRef; j++)
{
if((*g_prEATableRef)[j].tkTok == FuncToken)
{
szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s [%d] ",
g_szAsmCodeIndent,KEYWORD(".export"),j+g_nEATableBase);
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s %s",
KEYWORD("as"), ProperName((*g_prEATableRef)[j].pszName));
printLine(GUICookie, szString);
break;
}
}
}
// Dump method impls of this method:
for(ULONG i = 0; i < g_NumMI; i++)
{
if((*g_pmi_list)[i].tkBody == FuncToken)
{
BOOL bOverridingTypeSpec;
PrettyPrintOverrideDecl(i,szString,GUICookie,FuncToken,&bOverridingTypeSpec);
printLine(GUICookie,szString);
}
}
dwTargetRVA = dwOffset;
if (IsMdPinvokeImpl(dwAttrs))
{
if(dwOffset)
{
sprintf_s(szString,SZSTRING_SIZE,"%s// Embedded native code",g_szAsmCodeIndent);
printLine(GUICookie, COMMENT(szString));
goto ItsMiNative;
}
if(g_szAsmCodeIndent[0]) g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-2] = 0;
sprintf_s(szString,SZSTRING_SIZE,"%s%s",g_szAsmCodeIndent,UNSCOPE());
printLine(GUICookie, szString);
g_tkMVarOwner = tkMVarOwner;
return TRUE;
}
if(IsMiManaged(dwImplAttrs))
{
if(IsMiIL(dwImplAttrs) || IsMiOPTIL(dwImplAttrs))
{
if(g_fShowBytes)
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_METHBEG), g_szAsmCodeIndent,dwTargetRVA);
printLine(GUICookie, COMMENT(szString));
}
szString[0] = 0;
if (dwTargetRVA != 0)
{
void* newTarget;
if(g_pPELoader->getVAforRVA(dwTargetRVA,&newTarget))
{
DisassembleWrapper(g_pImport, (unsigned char*)newTarget, GUICookie, FuncToken,pszArgname, ulArgs);
}
else
{
sprintf_s(szString,SZSTRING_SIZE, "INVALID METHOD ADDRESS: 0x%8.8X (RVA: 0x%8.8X)",(size_t)newTarget,dwTargetRVA);
printError(GUICookie,szString);
}
}
}
else if(IsMiNative(dwImplAttrs))
{
ItsMiNative:
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_DASMNATIVE), g_szAsmCodeIndent);
printLine(GUICookie, COMMENT(szString));
sprintf_s(szString,SZSTRING_SIZE,"%s// Managed TargetRVA = 0x%8.8X", g_szAsmCodeIndent, dwTargetRVA);
printLine(GUICookie, COMMENT(szString));
}
}
else if(IsMiUnmanaged(dwImplAttrs)&&IsMiNative(dwImplAttrs))
{
_ASSERTE(IsMiNative(dwImplAttrs));
sprintf_s(szString,SZSTRING_SIZE,"%s// Unmanaged TargetRVA = 0x%8.8X", g_szAsmCodeIndent, dwTargetRVA);
printLine(GUICookie, COMMENT(szString));
}
else if(IsMiRuntime(dwImplAttrs))
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_METHODRT), g_szAsmCodeIndent);
printLine(GUICookie, COMMENT(szString));
}
#ifdef _DEBUG
else _ASSERTE(!"Bad dwImplAttrs");
#endif
if(g_szAsmCodeIndent[0]) g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-2] = 0;
{
szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,UNSCOPE());
if(pszClassName)
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("// end of method %s::"), ProperName((char*)pszClassName));
strcpy_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT(ProperName((char*)pszMemberName)));
}
else
sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("// end of global method %s"), ProperName((char*)pszMemberName));
}
printLine(GUICookie, szString);
szString[0] = 0;
printLine(GUICookie, szString);
if(pszArgname)
{
for(ULONG i=0; i < ulArgs; i++)
{
if(pszArgname[i].name) VDELETE(pszArgname[i].name);
}
VDELETE(pszArgname);
}
g_tkMVarOwner = tkMVarOwner;
return TRUE;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
BOOL DumpField(mdToken FuncToken, const char *pszClassName,void *GUICookie, BOOL DumpBody)
{
char *pszMemberName = NULL;//[MAX_MEMBER_LENGTH];
DWORD dwAttrs = 0;
CQuickBytes qbMemberSig;
PCCOR_SIGNATURE pComSig = NULL;
ULONG cComSig;
const char *szStr = NULL;//[1024];
char* szptr;
const char *psz;
if (FAILED(g_pImport->GetNameOfFieldDef(FuncToken, &psz)))
{
char sz[2048];
sprintf_s(sz, 2048, "%sERROR: FieldDef %08X has no signature", g_szAsmCodeIndent, FuncToken);
printError(GUICookie, sz);
return FALSE;
}
MAKE_NAME_IF_NONE(psz,FuncToken);
if (FAILED(g_pImport->GetFieldDefProps(FuncToken, &dwAttrs)))
{
char sz[2048];
sprintf_s(sz, 2048, "%sERROR: FieldDef %08X record error", g_szAsmCodeIndent, FuncToken);
printError(GUICookie, sz);
return FALSE;
}
if (g_fLimitedVisibility)
{
if(g_fHidePub && IsFdPublic(dwAttrs)) return FALSE;
if(g_fHidePriv && IsFdPrivate(dwAttrs)) return FALSE;
if(g_fHideFam && IsFdFamily(dwAttrs)) return FALSE;
if(g_fHideAsm && IsFdAssembly(dwAttrs)) return FALSE;
if(g_fHideFOA && IsFdFamORAssem(dwAttrs)) return FALSE;
if(g_fHideFAA && IsFdFamANDAssem(dwAttrs)) return FALSE;
if(g_fHidePrivScope && IsFdPrivateScope(dwAttrs)) return FALSE;
}
{
const char* psz1 = NULL;
if(IsFdPrivateScope(dwAttrs))
{
pszMemberName = new char[strlen(psz)+15];
sprintf_s(pszMemberName,strlen(psz)+15,"%s$PST%08X", psz,FuncToken );
}
else
{
pszMemberName = new char[strlen(psz)+3];
strcpy_s(pszMemberName, strlen(psz)+3, psz );
}
psz1 = ProperName(pszMemberName);
VDELETE(pszMemberName);
pszMemberName = new char[strlen(psz1)+1];
strcpy_s(pszMemberName,strlen(psz1)+1,psz1);
}
if (FAILED(g_pImport->GetSigOfFieldDef(FuncToken, &cComSig, &pComSig)))
{
pComSig = NULL;
}
if (cComSig == NULL)
{
char sz[2048];
sprintf_s(sz,2048,"%sERROR: field '%s' has no signature",g_szAsmCodeIndent,pszMemberName);
VDELETE(pszMemberName);
printError(GUICookie,sz);
return FALSE;
}
g_tkRefUser = FuncToken;
bool bRet = FALSE;
PAL_CPP_TRY {
szStr = PrettyPrintSig(pComSig, cComSig, (DumpBody ? pszMemberName : ""), &qbMemberSig, g_pImport,NULL);
}
PAL_CPP_CATCH_ALL
{
printError(GUICookie,"INVALID ADDRESS IN FIELD SIGNATURE");
bRet = TRUE;
} PAL_CPP_ENDTRY;
if (bRet)
return FALSE;
g_tkRefUser = 0;
if (g_Mode == MODE_DUMP_CLASS_METHOD || g_Mode == MODE_DUMP_CLASS_METHOD_SIG)
{
if (strcmp(pszMemberName, g_pszMethodToDump) != 0)
{
VDELETE(pszMemberName);
return FALSE;
}
if (g_Mode == MODE_DUMP_CLASS_METHOD_SIG)
{
// we want plain signature without token values and without the field name
BOOL fDumpTokens = g_fDumpTokens;
g_fDumpTokens = FALSE;
const char *pszPlainSig;
PAL_CPP_TRY
{
CQuickBytes qbTempSig;
pszPlainSig = PrettyPrintSig(pComSig, cComSig, "", &qbTempSig, g_pImport, NULL);
}
PAL_CPP_CATCH_ALL
{
pszPlainSig = "";
}
PAL_CPP_ENDTRY;
g_fDumpTokens = fDumpTokens;
if (strcmp(pszPlainSig, g_pszSigToDump) != 0)
{
VDELETE(pszMemberName);
return FALSE;
}
}
}
VDELETE(pszMemberName);
szptr = &szString[0];
if(DumpBody)
{
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ", g_szAsmCodeIndent,ANCHORPT(KEYWORD(".field"),FuncToken));
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X*/ "),FuncToken);
}
// put offset (if any)
for(ULONG i=0; i < g_cFieldOffsets; i++)
{
if(g_rFieldOffset[i].ridOfField == FuncToken)
{
if(g_rFieldOffset[i].ulOffset != 0xFFFFFFFF) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"[%d] ",g_rFieldOffset[i].ulOffset);
break;
}
}
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD((char*)0));
if(IsFdPublic(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"public ");
if(IsFdPrivate(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"private ");
if(IsFdStatic(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"static ");
if(IsFdFamily(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"family ");
if(IsFdAssembly(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"assembly ");
if(IsFdFamANDAssem(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"famandassem ");
if(IsFdFamORAssem(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"famorassem ");
if(IsFdPrivateScope(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"privatescope ");
if(IsFdInitOnly(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"initonly ");
if(IsFdLiteral(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"literal ");
if(IsFdNotSerialized(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"notserialized ");
if(IsFdSpecialName(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"specialname ");
if(IsFdRTSpecialName(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"rtspecialname ");
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD((char*)-1));
if (IsFdPinvokeImpl(dwAttrs))
{
DWORD dwMappingFlags;
const char *szImportName;
mdModuleRef mrImportDLL;
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s(",KEYWORD("pinvokeimpl"));
if(FAILED(g_pImport->GetPinvokeMap(FuncToken,&dwMappingFlags,
&szImportName,&mrImportDLL))) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/* No map */"));
else
szptr = DumpPinvokeMap(dwMappingFlags, (strcmp(szImportName,psz)? szImportName : NULL),
mrImportDLL, szString,GUICookie);
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),") ");
}
szptr = DumpMarshaling(g_pImport,szString,SZSTRING_SIZE,FuncToken);
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s",szStr);
if (IsFdHasFieldRVA(dwAttrs)) // Do we have an RVA associated with this?
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr), KEYWORD(" at "));
ULONG fieldRVA;
if (SUCCEEDED(g_pImport->GetFieldRVA(FuncToken, &fieldRVA)))
{
szptr = DumpDataPtr(&szString[strlen(szString)], fieldRVA, SizeOfField(FuncToken,g_pImport));
}
else
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),RstrUTF(IDS_E_NORVA));
}
}
// dump default value (if any):
if(IsFdHasDefault(dwAttrs) && DumpBody) DumpDefaultValue(FuncToken,szString,GUICookie);
printLine(GUICookie, szString);
if(DumpBody)
{
DumpCustomAttributes(FuncToken,GUICookie);
DumpPermissions(FuncToken,GUICookie);
}
return TRUE;
}
BOOL DumpEvent(mdToken FuncToken, const char *pszClassName, DWORD dwClassAttrs, void *GUICookie, BOOL DumpBody)
{
DWORD dwAttrs;
mdToken tkEventType;
LPCSTR psz;
HENUMInternal hAssoc;
ASSOCIATE_RECORD rAssoc[128];
CQuickBytes qbMemberSig;
ULONG nAssoc;
char* szptr;
if (FAILED(g_pImport->GetEventProps(FuncToken,&psz,&dwAttrs,&tkEventType)))
{
char sz[2048];
sprintf_s(sz, 2048, "%sERROR: Invalid Event %08X record", g_szAsmCodeIndent, FuncToken);
printError(GUICookie, sz);
return FALSE;
}
MAKE_NAME_IF_NONE(psz,FuncToken);
if (g_Mode == MODE_DUMP_CLASS_METHOD || g_Mode == MODE_DUMP_CLASS_METHOD_SIG)
{
if (strcmp(psz, g_pszMethodToDump) != 0) return FALSE;
}
if (FAILED(g_pImport->EnumAssociateInit(FuncToken,&hAssoc)))
{
char sz[2048];
sprintf_s(sz, 2048, "%sERROR: MetaData error enumerating Associate for %08X", g_szAsmCodeIndent, FuncToken);
printError(GUICookie, sz);
return FALSE;
}
if ((nAssoc = hAssoc.m_ulCount))
{
memset(rAssoc,0,sizeof(rAssoc));
if (FAILED(g_pImport->GetAllAssociates(&hAssoc,rAssoc,nAssoc)))
{
char sz[2048];
sprintf_s(sz, 2048, "%sERROR: MetaData error enumerating all Associates", g_szAsmCodeIndent);
printError(GUICookie, sz);
return FALSE;
}
if (g_fLimitedVisibility)
{
unsigned i;
for (i=0; i < nAssoc;i++)
{
if ((TypeFromToken(rAssoc[i].m_memberdef) == mdtMethodDef) && g_pImport->IsValidToken(rAssoc[i].m_memberdef))
{
DWORD dwMethodAttrs;
if (FAILED(g_pImport->GetMethodDefProps(rAssoc[i].m_memberdef, &dwMethodAttrs)))
{
continue;
}
if(g_fHidePub && IsMdPublic(dwMethodAttrs)) continue;
if(g_fHidePriv && IsMdPrivate(dwMethodAttrs)) continue;
if(g_fHideFam && IsMdFamily(dwMethodAttrs)) continue;
if(g_fHideAsm && IsMdAssem(dwMethodAttrs)) continue;
if(g_fHideFOA && IsMdFamORAssem(dwMethodAttrs)) continue;
if(g_fHideFAA && IsMdFamANDAssem(dwMethodAttrs)) continue;
if(g_fHidePrivScope && IsMdPrivateScope(dwMethodAttrs)) continue;
break;
}
}
if (i >= nAssoc) return FALSE;
}
}
szptr = &szString[0];
if (DumpBody)
{
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ", g_szAsmCodeIndent,KEYWORD(".event"));
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X*/ "),FuncToken);
}
else
{
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s : ",ProperName((char*)psz));
}
if(IsEvSpecialName(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("specialname "));
if(IsEvRTSpecialName(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("rtspecialname "));
if(RidFromToken(tkEventType)&&g_pImport->IsValidToken(tkEventType))
{
switch(TypeFromToken(tkEventType))
{
case mdtTypeRef:
case mdtTypeDef:
case mdtTypeSpec:
{
PrettyPrintToken(szString, tkEventType, g_pImport,GUICookie,0);
szptr = &szString[strlen(szString)];
}
break;
default:
break;
}
}
if(!DumpBody)
{
printLine(GUICookie,szString);
return TRUE;
}
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," %s", ProperName((char*)psz));
printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"%s%s",g_szAsmCodeIndent,SCOPE());
printLine(GUICookie,szString);
strcat_s(g_szAsmCodeIndent,MAX_MEMBER_LENGTH," ");
DumpCustomAttributes(FuncToken,GUICookie);
DumpPermissions(FuncToken,GUICookie);
if(nAssoc)
{
for(unsigned i=0; i < nAssoc;i++)
{
mdToken tk = rAssoc[i].m_memberdef;
DWORD sem = rAssoc[i].m_dwSemantics;
szptr = &szString[0];
if(IsMsAddOn(sem)) szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".addon"));
else if(IsMsRemoveOn(sem)) szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".removeon"));
else if(IsMsFire(sem)) szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".fire"));
else if(IsMsOther(sem)) szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".other"));
else szptr+=sprintf_s(szptr,SZSTRING_SIZE,ERRORMSG("UNKNOWN SEMANTICS: 0x%X "),sem);
if(g_pImport->IsValidToken(tk))
PrettyPrintToken(szString, tk, g_pImport,GUICookie,0);
else szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),ERRORMSG("INVALID TOKEN 0x%8.8X"),tk);
printLine(GUICookie,szString);
}
}
if(g_szAsmCodeIndent[0]) g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-2] = 0;
szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,UNSCOPE());
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("// end of event %s::"),ProperName((char*)pszClassName));
strcpy_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT(ProperName((char*)psz)));
printLine(GUICookie,szString);
return TRUE;
}
BOOL DumpProp(mdToken FuncToken, const char *pszClassName, DWORD dwClassAttrs, void *GUICookie, BOOL DumpBody)
{
DWORD dwAttrs;
LPCSTR psz;
HENUMInternal hAssoc;
ASSOCIATE_RECORD rAssoc[128];
CQuickBytes qbMemberSig;
PCCOR_SIGNATURE pComSig;
ULONG cComSig, nAssoc;
unsigned uStringLen = SZSTRING_SIZE;
char* szptr;
if (FAILED(g_pImport->GetPropertyProps(FuncToken,&psz,&dwAttrs,&pComSig,&cComSig)))
{
char sz[2048];
sprintf_s(sz, 2048, "%sERROR: Invalid Property %08X record", g_szAsmCodeIndent, FuncToken);
printError(GUICookie, sz);
return FALSE;
}
MAKE_NAME_IF_NONE(psz,FuncToken);
if(cComSig == 0)
{
char sz[2048];
sprintf_s(sz,2048,"%sERROR: property '%s' has no signature",g_szAsmCodeIndent,psz);
printError(GUICookie,sz);
return FALSE;
}
if (g_Mode == MODE_DUMP_CLASS_METHOD || g_Mode == MODE_DUMP_CLASS_METHOD_SIG)
{
if (strcmp(psz, g_pszMethodToDump) != 0) return FALSE;
}
if (FAILED(g_pImport->EnumAssociateInit(FuncToken,&hAssoc)))
{
char sz[2048];
sprintf_s(sz, 2048, "%sERROR: MetaData error enumerating Associate for %08X", g_szAsmCodeIndent, FuncToken);
printError(GUICookie, sz);
return FALSE;
}
if ((nAssoc = hAssoc.m_ulCount) != 0)
{
memset(rAssoc,0,sizeof(rAssoc));
if (FAILED(g_pImport->GetAllAssociates(&hAssoc,rAssoc,nAssoc)))
{
char sz[2048];
sprintf_s(sz, 2048, "%sERROR: MetaData error enumerating all Associates", g_szAsmCodeIndent);
printError(GUICookie, sz);
return FALSE;
}
if (g_fLimitedVisibility)
{
unsigned i;
for (i=0; i < nAssoc;i++)
{
if ((TypeFromToken(rAssoc[i].m_memberdef) == mdtMethodDef) && g_pImport->IsValidToken(rAssoc[i].m_memberdef))
{
DWORD dwMethodAttrs;
if (FAILED(g_pImport->GetMethodDefProps(rAssoc[i].m_memberdef, &dwMethodAttrs)))
{
continue;
}
if(g_fHidePub && IsMdPublic(dwMethodAttrs)) continue;
if(g_fHidePriv && IsMdPrivate(dwMethodAttrs)) continue;
if(g_fHideFam && IsMdFamily(dwMethodAttrs)) continue;
if(g_fHideAsm && IsMdAssem(dwMethodAttrs)) continue;
if(g_fHideFOA && IsMdFamORAssem(dwMethodAttrs)) continue;
if(g_fHideFAA && IsMdFamANDAssem(dwMethodAttrs)) continue;
if(g_fHidePrivScope && IsMdPrivateScope(dwMethodAttrs)) continue;
break;
}
}
if( i >= nAssoc) return FALSE;
}
}
szptr = &szString[0];
if (DumpBody)
{
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ", g_szAsmCodeIndent,KEYWORD(".property"));
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%08X*/ "),FuncToken);
}
else
{
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s : ",ProperName((char*)psz));
}
if(IsPrSpecialName(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("specialname "));
if(IsPrRTSpecialName(dwAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("rtspecialname "));
{
char pchDefault[] = "";
char *pch = pchDefault;
if(DumpBody)
{
pch = szptr+1;
strcpy_s(pch,SZSTRING_REMAINING_SIZE(pch),ProperName((char*)psz));
}
qbMemberSig.Shrink(0);
PrettyPrintMethodSig(szString, &uStringLen, &qbMemberSig, pComSig, cComSig,
pch, NULL, GUICookie);
if(IsPrHasDefault(dwAttrs) && DumpBody) DumpDefaultValue(FuncToken,szString,GUICookie);
}
printLine(GUICookie,szString);
if(DumpBody)
{
sprintf_s(szString,SZSTRING_SIZE,"%s%s",g_szAsmCodeIndent,SCOPE());
printLine(GUICookie,szString);
strcat_s(g_szAsmCodeIndent,MAX_MEMBER_LENGTH," ");
DumpCustomAttributes(FuncToken,GUICookie);
DumpPermissions(FuncToken,GUICookie);
if(nAssoc)
{
for(unsigned i=0; i < nAssoc;i++)
{
mdToken tk = rAssoc[i].m_memberdef;
DWORD sem = rAssoc[i].m_dwSemantics;
szptr = &szString[0];
if(IsMsSetter(sem)) szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".set"));
else if(IsMsGetter(sem)) szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".get"));
else if(IsMsOther(sem)) szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".other"));
else szptr+=sprintf_s(szptr,SZSTRING_SIZE,ERRORMSG("UNKNOWN SEMANTICS: 0x%X "),sem);
if(g_pImport->IsValidToken(tk))
PrettyPrintToken(szString, tk, g_pImport,GUICookie,0);
else szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),ERRORMSG("INVALID TOKEN 0x%8.8X"),tk);
printLine(GUICookie,szString);
}
}
if(g_szAsmCodeIndent[0]) g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-2] = 0;
szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,UNSCOPE());
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("// end of property %s::"),ProperName((char*)pszClassName));
strcpy_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT(ProperName((char*)psz)));
printLine(GUICookie,szString);
} // end if(DumpBody)
return TRUE;
}
BOOL DumpMembers(mdTypeDef cl, const char *pszClassNamespace, const char *pszClassName,
DWORD dwClassAttrs, DWORD dwEntryPointToken, void* GUICookie)
{
HRESULT hr;
mdToken *pMemberList = NULL;
DWORD NumMembers, NumFields,NumMethods,NumEvents,NumProps;
DWORD i;
HENUMInternal hEnumMethod;
HENUMInternal hEnumField;
HENUMInternal hEnumEvent;
HENUMInternal hEnumProp;
CQuickBytes qbMemberSig;
BOOL ret;
// Get the total count of methods + fields
hr = g_pImport->EnumInit(mdtMethodDef, cl, &hEnumMethod);
if (FAILED(hr))
{
FailedToEnum:
printLine(GUICookie,RstrUTF(IDS_E_MEMBRENUM));
ret = FALSE;
goto CloseHandlesAndReturn;
}
NumMembers = NumMethods = g_pImport->EnumGetCount(&hEnumMethod);
if (FAILED(g_pImport->EnumInit(mdtFieldDef, cl, &hEnumField))) goto FailedToEnum;
NumFields = g_pImport->EnumGetCount(&hEnumField);
NumMembers += NumFields;
if (FAILED(g_pImport->EnumInit(mdtEvent, cl, &hEnumEvent))) goto FailedToEnum;
NumEvents = g_pImport->EnumGetCount(&hEnumEvent);
NumMembers += NumEvents;
if (FAILED(g_pImport->EnumInit(mdtProperty, cl, &hEnumProp))) goto FailedToEnum;
NumProps = g_pImport->EnumGetCount(&hEnumProp);
NumMembers += NumProps;
ret = TRUE;
if(NumMembers)
{
pMemberList = new (nothrow) mdToken[NumMembers];
if(pMemberList == NULL) ret = FALSE;
}
if ((NumMembers == 0)||(pMemberList == NULL)) goto CloseHandlesAndReturn;
for (i = 0; g_pImport->EnumNext(&hEnumField, &pMemberList[i]); i++);
for (; g_pImport->EnumNext(&hEnumMethod, &pMemberList[i]); i++);
for (; g_pImport->EnumNext(&hEnumEvent, &pMemberList[i]); i++);
for (; g_pImport->EnumNext(&hEnumProp, &pMemberList[i]); i++);
_ASSERTE(i == NumMembers);
for (i = 0; i < NumMembers; i++)
{
mdToken tk = pMemberList[i];
if(g_pImport->IsValidToken(tk))
{
switch (TypeFromToken(tk))
{
case mdtFieldDef:
ret = DumpField(pMemberList[i], pszClassName, GUICookie,TRUE);
break;
case mdtMethodDef:
ret = DumpMethod(pMemberList[i], pszClassName, dwEntryPointToken,GUICookie,TRUE);
break;
case mdtEvent:
ret = DumpEvent(pMemberList[i], pszClassName, dwClassAttrs,GUICookie,TRUE);
break;
case mdtProperty:
ret = DumpProp(pMemberList[i], pszClassName, dwClassAttrs,GUICookie,TRUE);
break;
default:
{
char szStr[4096];
sprintf_s(szStr,4096,RstrUTF(IDS_E_ODDMEMBER),pMemberList[i],pszClassName);
printLine(GUICookie,szStr);
}
ret = FALSE;
break;
} // end switch
}
else
{
char szStr[256];
sprintf_s(szStr,256,ERRORMSG("INVALID MEMBER TOKEN: 0x%8.8X"),tk);
printLine(GUICookie,szStr);
ret= FALSE;
}
if(ret && (g_Mode == MODE_DUMP_CLASS_METHOD_SIG)) break;
} // end for
ret = TRUE;
CloseHandlesAndReturn:
g_pImport->EnumClose(&hEnumMethod);
g_pImport->EnumClose(&hEnumField);
g_pImport->EnumClose(&hEnumEvent);
g_pImport->EnumClose(&hEnumProp);
if(pMemberList) delete[] pMemberList;
return ret;
}
BOOL GetClassLayout(mdTypeDef cl, ULONG* pulPackSize, ULONG* pulClassSize)
{ // Dump class layout
HENUMInternal hEnumField;
BOOL ret = FALSE;
if(g_rFieldOffset)
VDELETE(g_rFieldOffset);
g_cFieldOffsets = 0;
g_cFieldsMax = 0;
if(RidFromToken(cl)==0) return TRUE;
if (SUCCEEDED(g_pImport->EnumInit(mdtFieldDef, cl, &hEnumField)))
{
g_cFieldsMax = g_pImport->EnumGetCount(&hEnumField);
g_pImport->EnumClose(&hEnumField);
}
if(SUCCEEDED(g_pImport->GetClassPackSize(cl,pulPackSize))) ret = TRUE;
else *pulPackSize = 0xFFFFFFFF;
if(SUCCEEDED(g_pImport->GetClassTotalSize(cl,pulClassSize))) ret = TRUE;
else *pulClassSize = 0xFFFFFFFF;
if(g_cFieldsMax)
{
MD_CLASS_LAYOUT Layout;
if(SUCCEEDED(g_pImport->GetClassLayoutInit(cl,&Layout)))
{
g_rFieldOffset = new COR_FIELD_OFFSET[g_cFieldsMax+1];
if(g_rFieldOffset)
{
COR_FIELD_OFFSET* pFO = g_rFieldOffset;
for(g_cFieldOffsets=0;
SUCCEEDED(g_pImport->GetClassLayoutNext(&Layout,&(pFO->ridOfField),&(pFO->ulOffset)))
&&RidFromToken(pFO->ridOfField);
g_cFieldOffsets++, pFO++) ret = TRUE;
}
}
}
return ret;
}
BOOL IsANestedInB(mdTypeDef A, mdTypeDef B)
{
DWORD i;
for(i = 0; i < g_NumClasses; i++)
{
if(g_cl_list[i] == A)
{
A = g_cl_enclosing[i];
if(A == B) return TRUE;
if(A == mdTypeDefNil) return FALSE;
return IsANestedInB(A,B);
}
}
return FALSE;
}
mdTypeDef TopEncloser(mdTypeDef A)
{
DWORD i;
for(i = 0; i < g_NumClasses; i++)
{
if(g_cl_list[i] == A)
{
if(g_cl_enclosing[i] == mdTypeDefNil) return A;
return TopEncloser(g_cl_enclosing[i]);
}
}
return A;
}
BOOL DumpClass(mdTypeDef cl, DWORD dwEntryPointToken, void* GUICookie, ULONG WhatToDump)
// WhatToDump: 0-title,flags,extends,implements;
// +1-pack,size and custom attrs;
// +2-nested classes
// +4-members
{
char *pszClassName; // name associated with this CL
char *pszNamespace;
const char *pc1,*pc2;
DWORD dwClassAttrs;
mdTypeRef crExtends;
HRESULT hr;
mdInterfaceImpl ii;
DWORD NumInterfaces;
DWORD i;
HENUMInternal hEnumII; // enumerator for interface impl
//char *szString;
char* szptr;
mdToken tkVarOwner = g_tkVarOwner;
ULONG WhatToDumpOrig = WhatToDump;
if (FAILED(g_pImport->GetNameOfTypeDef(
cl,
&pc1, //&pszClassName,
&pc2))) //&pszNamespace
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), cl);
printError(GUICookie, sz);
g_tkVarOwner = tkVarOwner;
return FALSE;
}
MAKE_NAME_IF_NONE(pc1,cl);
if (g_Mode == MODE_DUMP_CLASS || g_Mode == MODE_DUMP_CLASS_METHOD || g_Mode == MODE_DUMP_CLASS_METHOD_SIG)
{
if(cl != g_tkClassToDump)
{
if(IsANestedInB(g_tkClassToDump,cl))
WhatToDump = 2; // nested classes only
else
return TRUE;
}
}
if (FAILED(g_pImport->GetTypeDefProps(
cl,
&dwClassAttrs,
&crExtends)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), cl);
printError(GUICookie, sz);
g_tkVarOwner = tkVarOwner;
return FALSE;
}
if(g_fLimitedVisibility)
{
if(g_fHidePub && (IsTdPublic(dwClassAttrs)||IsTdNestedPublic(dwClassAttrs))) return FALSE;
if(g_fHidePriv && (IsTdNotPublic(dwClassAttrs)||IsTdNestedPrivate(dwClassAttrs))) return FALSE;
if(g_fHideFam && IsTdNestedFamily(dwClassAttrs)) return FALSE;
if(g_fHideAsm && IsTdNestedAssembly(dwClassAttrs)) return FALSE;
if(g_fHideFOA && IsTdNestedFamORAssem(dwClassAttrs)) return FALSE;
if(g_fHideFAA && IsTdNestedFamANDAssem(dwClassAttrs)) return FALSE;
}
g_tkVarOwner = cl;
pszClassName = (char*)(pc1 ? pc1 : "");
pszNamespace = (char*)(pc2 ? pc2 : "");
szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".class"));
if(g_fDumpTokens) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("/*%8.8X*/ "),cl);
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD((char*)0));
if (IsTdInterface(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"interface ");
if (IsTdPublic(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"public ");
if (IsTdNotPublic(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"private ");
if (IsTdAbstract(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"abstract ");
if (IsTdAutoLayout(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"auto ");
if (IsTdSequentialLayout(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"sequential ");
if (IsTdExplicitLayout(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"explicit ");
if (IsTdAnsiClass(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"ansi ");
if (IsTdUnicodeClass(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"unicode ");
if (IsTdAutoClass(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"autochar ");
if (IsTdImport(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"import ");
if (IsTdWindowsRuntime(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"windowsruntime ");
if (IsTdSerializable(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"serializable ");
if (IsTdSealed(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"sealed ");
if (IsTdNestedPublic(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"nested public ");
if (IsTdNestedPrivate(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"nested private ");
if (IsTdNestedFamily(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"nested family ");
if (IsTdNestedAssembly(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"nested assembly ");
if (IsTdNestedFamANDAssem(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"nested famandassem ");
if (IsTdNestedFamORAssem(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"nested famorassem ");
if (IsTdBeforeFieldInit(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"beforefieldinit ");
if (IsTdSpecialName(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"specialname ");
if (IsTdRTSpecialName(dwClassAttrs)) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"rtspecialname ");
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD((char*)-1));
if(*pszNamespace != 0)
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s.",ProperName(pszNamespace));
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),WhatToDump > 2 ? ANCHORPT(ProperName(pszClassName),cl) : JUMPPT(ProperName(pszClassName),cl));
szptr = DumpGenericPars(szString, cl, GUICookie,TRUE);
if (szptr == NULL)
{
g_tkVarOwner = tkVarOwner;
return FALSE;
}
printLine(GUICookie,szString);
if (!IsNilToken(crExtends))
{
CQuickBytes out;
szptr = szString;
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s %s ",g_szAsmCodeIndent,KEYWORD("extends"));
if(g_pImport->IsValidToken(crExtends))
PrettyPrintToken(szString, crExtends, g_pImport,GUICookie,cl);
else
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),ERRORMSG("INVALID TOKEN: 0x%8.8X"),crExtends);
printLine(GUICookie,szString);
}
hr = g_pImport->EnumInit(
mdtInterfaceImpl,
cl,
&hEnumII);
if (FAILED(hr))
{
printError(GUICookie,RstrUTF(IDS_E_ENUMINIT));
g_tkVarOwner = tkVarOwner;
return FALSE;
}
NumInterfaces = g_pImport->EnumGetCount(&hEnumII);
if (NumInterfaces > 0)
{
CQuickBytes out;
mdTypeRef crInterface;
for (i=0; g_pImport->EnumNext(&hEnumII, &ii); i++)
{
szptr = szString;
if(i) szptr+=sprintf_s(szptr,SZSTRING_SIZE, "%s ",g_szAsmCodeIndent);
else szptr+=sprintf_s(szptr,SZSTRING_SIZE, "%s %s ",g_szAsmCodeIndent,KEYWORD("implements"));
if (FAILED(g_pImport->GetTypeOfInterfaceImpl(ii, &crInterface)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), ii);
printError(GUICookie, sz);
g_tkVarOwner = tkVarOwner;
return FALSE;
}
if(g_pImport->IsValidToken(crInterface))
PrettyPrintToken(szString, crInterface, g_pImport,GUICookie,cl);
else
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),ERRORMSG("INVALID TOKEN: 0x%8.8X"),crInterface);
if(i < NumInterfaces-1) strcat_s(szString, SZSTRING_SIZE,",");
printLine(GUICookie,szString);
out.Shrink(0);
}
// The assertion will fire if the enumerator is bad
_ASSERTE(NumInterfaces == i);
g_pImport->EnumClose(&hEnumII);
}
if(WhatToDump == 0) // 0 = title only
{
sprintf_s(szString,SZSTRING_SIZE,"%s%s %s",g_szAsmCodeIndent,SCOPE(),UNSCOPE());
printLine(GUICookie,szString);
g_tkVarOwner = tkVarOwner;
return TRUE;
}
sprintf_s(szString,SZSTRING_SIZE,"%s%s",g_szAsmCodeIndent,SCOPE());
printLine(GUICookie,szString);
strcat_s(g_szAsmCodeIndent,MAX_MEMBER_LENGTH," ");
ULONG ulPackSize=0xFFFFFFFF,ulClassSize=0xFFFFFFFF;
if(WhatToDump & 1)
{
if(GetClassLayout(cl,&ulPackSize,&ulClassSize))
{ // Dump class layout
if(ulPackSize != 0xFFFFFFFF)
{
sprintf_s(szString,SZSTRING_SIZE,"%s%s %d",g_szAsmCodeIndent,KEYWORD(".pack"),ulPackSize);
printLine(GUICookie,szString);
}
if(ulClassSize != 0xFFFFFFFF)
{
sprintf_s(szString,SZSTRING_SIZE,"%s%s %d",g_szAsmCodeIndent,KEYWORD(".size"),ulClassSize);
printLine(GUICookie,szString);
}
}
DumpCustomAttributes(cl,GUICookie);
// Dev11 #10745
// Dump InterfaceImpl custom attributes here
if (NumInterfaces > 0 && g_fShowCA)
{
hr = g_pImport->EnumInit(
mdtInterfaceImpl,
cl,
&hEnumII);
if (FAILED(hr))
{
printError(GUICookie,RstrUTF(IDS_E_ENUMINIT));
g_tkVarOwner = tkVarOwner;
return FALSE;
}
ASSERT_AND_CHECK(NumInterfaces == g_pImport->EnumGetCount(&hEnumII));
CQuickBytes out;
mdTypeRef crInterface;
for (i = 0; g_pImport->EnumNext(&hEnumII, &ii); i++)
{
HENUMInternal hEnum;
mdCustomAttribute tkCA;
bool fFirst = true;
if (FAILED(g_pImport->EnumInit(mdtCustomAttribute, ii,&hEnum)))
{
return FALSE;
}
while(g_pImport->EnumNext(&hEnum,&tkCA) && RidFromToken(tkCA))
{
if (fFirst)
{
// Print .interfaceImpl type {type} before the custom attribute list
szptr = szString;
szptr += sprintf_s(szptr, SZSTRING_SIZE, "%s.%s ", g_szAsmCodeIndent, KEYWORD("interfaceimpl type"));
if (FAILED(g_pImport->GetTypeOfInterfaceImpl(ii, &crInterface)))
{
char sz[2048];
sprintf_s(sz, 2048, RstrUTF(IDS_E_INVALIDRECORD), ii);
printError(GUICookie, sz);
g_tkVarOwner = tkVarOwner;
return FALSE;
}
if(g_pImport->IsValidToken(crInterface))
PrettyPrintToken(szString, crInterface, g_pImport,GUICookie,cl);
else
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),ERRORMSG("INVALID TOKEN: 0x%8.8X"),crInterface);
printLine(GUICookie,szString);
out.Shrink(0);
szptr = szString;
fFirst = false;
}
DumpCustomAttribute(tkCA,GUICookie,false);
}
g_pImport->EnumClose( &hEnum);
}
// The assertion will fire if the enumerator is bad
_ASSERTE(NumInterfaces == i);
g_pImport->EnumClose(&hEnumII);
}
DumpGenericParsCA(cl,GUICookie);
DumpPermissions(cl,GUICookie);
}
// Dump method impls declared in this class whose implementing methods belong somewhere else:
if(WhatToDump & 1) // 1 - dump headers
{
for(i = 0; i < g_NumMI; i++)
{
if(((*g_pmi_list)[i].tkClass == cl)&&((*g_pmi_list)[i].tkBodyParent != cl))
{
BOOL bOverridingTypeSpec;
PrettyPrintOverrideDecl(i,szString,GUICookie,cl,&bOverridingTypeSpec);
strcat_s(szString, SZSTRING_SIZE,KEYWORD(" with "));
if (bOverridingTypeSpec)
{
// If PrettyPrintOverrideDecl printed the 'method' keyword, we need it here as well
// to satisfy the following grammar rule (simplified):
// _OVERRIDE METHOD_ ... DCOLON methodName ... WITH_ METHOD_ ... DCOLON methodName ...
strcat_s(szString, SZSTRING_SIZE,KEYWORD("method "));
}
PrettyPrintToken(szString, (*g_pmi_list)[i].tkBody, g_pImport,GUICookie,0);
printLine(GUICookie,szString);
}
}
}
if(WhatToDump & 2) // nested classes
{
BOOL fRegetClassLayout=FALSE;
DWORD dwMode = g_Mode;
if(g_Mode == MODE_DUMP_CLASS)
g_Mode = MODE_DUMP_ALL;
for(i = 0; i < g_NumClasses; i++)
{
if(g_cl_enclosing[i] == cl)
{
DumpClass(g_cl_list[i],dwEntryPointToken,GUICookie,WhatToDumpOrig);
fRegetClassLayout = TRUE;
}
}
if(fRegetClassLayout) GetClassLayout(cl,&ulPackSize,&ulClassSize);
g_Mode = dwMode;
}
if(WhatToDump & 4)
{
DumpMembers(cl, pszNamespace, pszClassName, dwClassAttrs, dwEntryPointToken,GUICookie);
}
if(g_szAsmCodeIndent[0]) g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-2] = 0;
szptr = szString;
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s %s// end of class ",g_szAsmCodeIndent,UNSCOPE(),COMMENT((char*)0));
if(*pszNamespace != 0) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s.",ProperName(pszNamespace));
sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s%s", ProperName(pszClassName),COMMENT((char*)-1));
printLine(GUICookie,szString);
printLine(GUICookie,"");
g_tkVarOwner = tkVarOwner;
return TRUE;
}
void DumpGlobalMethods(DWORD dwEntryPointToken)
{
HENUMInternal hEnumMethod;
mdToken FuncToken;
DWORD i;
CQuickBytes qbMemberSig;
if (FAILED(g_pImport->EnumGlobalFunctionsInit(&hEnumMethod)))
return;
for (i = 0; g_pImport->EnumNext(&hEnumMethod, &FuncToken); i++)
{
if (i == 0)
{
printLine(g_pFile,"");
printLine(g_pFile,COMMENT("// ================== GLOBAL METHODS ========================="));
printLine(g_pFile,"");
}
if(DumpMethod(FuncToken, NULL, dwEntryPointToken, g_pFile, TRUE)&&
(g_Mode == MODE_DUMP_CLASS_METHOD || g_Mode == MODE_DUMP_CLASS_METHOD_SIG)) break;
}
g_pImport->EnumClose(&hEnumMethod);
if(i)
{
printLine(g_pFile,"");
printLine(g_pFile,COMMENT("// ============================================================="));
printLine(g_pFile,"");
}
}
void DumpGlobalFields()
{
HENUMInternal hEnum;
mdToken FieldToken;
DWORD i;
CQuickBytes qbMemberSig;
if (FAILED(g_pImport->EnumGlobalFieldsInit(&hEnum)))
return;
for (i = 0; g_pImport->EnumNext(&hEnum, &FieldToken); i++)
{
if (i == 0)
{
printLine(g_pFile,"");
printLine(g_pFile,COMMENT("// ================== GLOBAL FIELDS =========================="));
printLine(g_pFile,"");
}
if(DumpField(FieldToken, NULL, g_pFile, TRUE)&&
(g_Mode == MODE_DUMP_CLASS_METHOD || g_Mode == MODE_DUMP_CLASS_METHOD_SIG)) break;
}
g_pImport->EnumClose(&hEnum);
if(i)
{
printLine(g_pFile,"");
printLine(g_pFile,COMMENT("// ============================================================="));
printLine(g_pFile,"");
}
}
void DumpVTables(IMAGE_COR20_HEADER *CORHeader, void* GUICookie)
{
IMAGE_COR_VTABLEFIXUP *pFixup,*pDummy;
DWORD iCount;
DWORD i;
USHORT iSlot;
char* szStr = &szString[0];
if (VAL32(CORHeader->VTableFixups.VirtualAddress) == 0) return;
sprintf_s(szString,SZSTRING_SIZE,"// VTableFixup Directory:");
printLine(GUICookie,szStr);
// Pull back a pointer to it.
iCount = VAL32(CORHeader->VTableFixups.Size) / sizeof(IMAGE_COR_VTABLEFIXUP);
if ((g_pPELoader->getVAforRVA(VAL32(CORHeader->VTableFixups.VirtualAddress), (void **) &pFixup) == FALSE)
||(g_pPELoader->getVAforRVA(VAL32(CORHeader->VTableFixups.VirtualAddress)+VAL32(CORHeader->VTableFixups.Size)-1, (void **) &pDummy) == FALSE))
{
printLine(GUICookie,RstrUTF(IDS_E_VTFUTABLE));
goto exit;
}
// Walk every v-table fixup entry and dump the slots.
for (i=0; i<iCount; i++)
{
sprintf_s(szString,SZSTRING_SIZE,"// IMAGE_COR_VTABLEFIXUP[%d]:", i);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// RVA: 0x%08x", VAL32(pFixup->RVA));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Count: 0x%04x", VAL16(pFixup->Count));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Type: 0x%04x", VAL16(pFixup->Type));
printLine(GUICookie,szStr);
BYTE *pSlot;
if (g_pPELoader->getVAforRVA(VAL32(pFixup->RVA), (void **) &pSlot) == FALSE)
{
printLine(GUICookie,RstrUTF(IDS_E_BOGUSRVA));
goto NextEntry;
}
for (iSlot=0; iSlot<pFixup->Count; iSlot++)
{
mdMethodDef tkMethod = VAL32(*(DWORD *) pSlot);
if (pFixup->Type & VAL16(COR_VTABLE_32BIT))
{
sprintf_s(szString,SZSTRING_SIZE,"// [0x%04x] (0x%08x)", iSlot, tkMethod);
pSlot += sizeof(DWORD);
}
else
{
sprintf_s(szString,SZSTRING_SIZE,"// [0x%04x] (0x%16x)", iSlot, VAL64(*(unsigned __int64 *) pSlot));
pSlot += sizeof(unsigned __int64);
}
printLine(GUICookie,szStr);
ValidateToken(tkMethod, mdtMethodDef);
}
// Pointer to next fixup entry.
NextEntry:
++pFixup;
}
exit:
printLine(GUICookie,"");
}
void DumpEATTable(IMAGE_COR20_HEADER *CORHeader, void* GUICookie)
{
BYTE *pFixup,*pDummy;
DWORD iCount;
DWORD BufferRVA;
DWORD i;
char* szStr = &szString[0];
sprintf_s(szString,SZSTRING_SIZE,"// Export Address Table Jumps:");
printLine(GUICookie,szStr);
if (VAL32(CORHeader->ExportAddressTableJumps.VirtualAddress) == 0)
{
printLine(GUICookie,RstrUTF(IDS_E_NODATA));
return;
}
// Pull back a pointer to it.
iCount = VAL32(CORHeader->ExportAddressTableJumps.Size) / IMAGE_COR_EATJ_THUNK_SIZE;
if ((g_pPELoader->getVAforRVA(VAL32(CORHeader->ExportAddressTableJumps.VirtualAddress), (void **) &pFixup) == FALSE)
||(g_pPELoader->getVAforRVA(VAL32(CORHeader->ExportAddressTableJumps.VirtualAddress)+VAL32(CORHeader->ExportAddressTableJumps.Size)-1, (void **) &pDummy) == FALSE))
{
printLine(GUICookie,RstrUTF(IDS_E_EATJTABLE));
goto exit;
}
// Quick sanity check on the linker.
if (VAL32(CORHeader->ExportAddressTableJumps.Size) % IMAGE_COR_EATJ_THUNK_SIZE)
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_EATJSIZE),
VAL32(CORHeader->ExportAddressTableJumps.Size), IMAGE_COR_EATJ_THUNK_SIZE);
printLine(GUICookie,szStr);
}
// Walk every v-table fixup entry and dump the slots.
BufferRVA = VAL32(CORHeader->ExportAddressTableJumps.VirtualAddress);
for (i=0; i<iCount; i++)
{
ULONG ReservedFlag = VAL32(*(ULONG *) (pFixup + sizeof(ULONG)));
sprintf_s(szString,SZSTRING_SIZE,"// Fixup Jump Entry [%d], at RVA 0x%08x:", i, BufferRVA);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// RVA of slot: 0x%08x", VAL32(*(ULONG *) pFixup));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Reserved flag: 0x%08x", ReservedFlag);
printLine(GUICookie,szStr);
if (ReservedFlag != 0)
{
printLine(GUICookie,RstrUTF(IDS_E_RESFLAGS));
}
pFixup += IMAGE_COR_EATJ_THUNK_SIZE;
BufferRVA += IMAGE_COR_EATJ_THUNK_SIZE;
}
exit:
printLine(GUICookie,"");
}
void DumpCodeManager(IMAGE_COR20_HEADER *CORHeader, void* GUICookie)
{
char* szStr = &szString[0];
sprintf_s(szString,SZSTRING_SIZE,"// Code Manager Table:");
printLine(GUICookie,szStr);
if (!VAL32(CORHeader->CodeManagerTable.Size))
{
sprintf_s(szString,SZSTRING_SIZE,"// default");
printLine(GUICookie,szStr);
return;
}
const GUID *pcm;
if (g_pPELoader->getVAforRVA(VAL32(CORHeader->CodeManagerTable.VirtualAddress), (void **) &pcm) == FALSE)
{
printLine(GUICookie,RstrUTF(IDS_E_CODEMGRTBL));
return;
}
sprintf_s(szString,SZSTRING_SIZE,"// [index] ID");
printLine(GUICookie,szStr);
ULONG iCount = VAL32(CORHeader->CodeManagerTable.Size) / sizeof(GUID);
for (ULONG i=0; i<iCount; i++)
{
WCHAR rcguid[128];
GUID Guid = *pcm;
SwapGuid(&Guid);
StringFromGUID2(Guid, rcguid, NumItems(rcguid));
sprintf_s(szString,SZSTRING_SIZE,"// [0x%08x] %S", i, rcguid);
printLine(GUICookie,szStr);
pcm++;
}
printLine(GUICookie,"");
}
void DumpSectionHeaders(IMAGE_SECTION_HEADER* pSH, USHORT nSH, void* GUICookie)
{
char* szStr = &szString[0];
char name[16];
printLine(GUICookie,"");
strcpy_s(szString,SZSTRING_SIZE,"// Image sections:");
printLine(GUICookie,szStr);
for(USHORT iSH=0; iSH < nSH; iSH++,pSH++)
{
strncpy_s(name,16,(const char*)(pSH->Name),8);
name[8]=0;
sprintf_s(szString,SZSTRING_SIZE,"// %s",name);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Virtual Size", pSH->Misc.VirtualSize);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Virtual Address", pSH->VirtualAddress);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Size of Raw Data", pSH->SizeOfRawData);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Pointer to Raw Data", pSH->PointerToRawData);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Pointer to Relocations", pSH->PointerToRelocations);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Pointer to Linenumbers", pSH->PointerToLinenumbers);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%04x Number of Relocations", pSH->NumberOfRelocations);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%04x Number of Linenumbers", pSH->NumberOfLinenumbers);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Characteristics", pSH->Characteristics);
printLine(GUICookie,szStr);
if((pSH->Characteristics & IMAGE_SCN_SCALE_INDEX))
{
strcpy_s(szString,SZSTRING_SIZE,"// SCALE_INDEX");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_CNT_CODE))
{
strcpy_s(szString,SZSTRING_SIZE,"// CNT_CODE");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA))
{
strcpy_s(szString,SZSTRING_SIZE,"// CNT_INITIALIZED_DATA");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA))
{
strcpy_s(szString,SZSTRING_SIZE,"// CNT_UNINITIALIZED_DATA");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_NO_DEFER_SPEC_EXC))
{
strcpy_s(szString,SZSTRING_SIZE,"// NO_DEFER_SPEC_EXC");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_LNK_NRELOC_OVFL))
{
strcpy_s(szString,SZSTRING_SIZE,"// LNK_NRELOC_OVFL");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_MEM_DISCARDABLE))
{
strcpy_s(szString,SZSTRING_SIZE,"// MEM_DISCARDABLE");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_MEM_NOT_CACHED))
{
strcpy_s(szString,SZSTRING_SIZE,"// MEM_NOT_CACHED");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_MEM_NOT_PAGED))
{
strcpy_s(szString,SZSTRING_SIZE,"// MEM_NOT_PAGED");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_MEM_SHARED))
{
strcpy_s(szString,SZSTRING_SIZE,"// MEM_SHARED");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_MEM_EXECUTE))
{
strcpy_s(szString,SZSTRING_SIZE,"// MEM_EXECUTE");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_MEM_READ))
{
strcpy_s(szString,SZSTRING_SIZE,"// MEM_READ");
printLine(GUICookie,szStr);
}
if((pSH->Characteristics & IMAGE_SCN_MEM_WRITE))
{
strcpy_s(szString,SZSTRING_SIZE,"// MEM_WRITE");
printLine(GUICookie,szStr);
}
printLine(GUICookie,"");
}
}
void DumpBaseReloc(const char *szName, IMAGE_DATA_DIRECTORY *pDir, void* GUICookie)
{
char* szStr = &szString[0];
sprintf_s(szString,SZSTRING_SIZE,"// %s", szName);
printLine(GUICookie,szStr);
if (!VAL32(pDir->Size))
{
printLine(GUICookie,RstrUTF(IDS_E_NODATA));
return;
}
char *pBegin, *pEnd;
DWORD *pdw, i, Nentries;
WORD *pw;
if (g_pPELoader->getVAforRVA(VAL32(pDir->VirtualAddress), (void **) &pBegin) == FALSE)
{
printLine(GUICookie,RstrUTF(IDS_E_IMPORTDATA));
return;
}
pEnd = pBegin + VAL32(pDir->Size);
for(pdw = (DWORD*)pBegin; pdw < (DWORD*)pEnd; )
{
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Page RVA", *pdw);
printLine(GUICookie,szStr);
pdw++;
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Block Size", *pdw);
printLine(GUICookie,szStr);
Nentries = (*pdw - 2*sizeof(DWORD)) / sizeof(WORD);
pdw++;
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Number of Entries", Nentries);
printLine(GUICookie,szStr);
for(i = 1, pw = (WORD*)pdw; i <= Nentries; i++, pw++)
{
sprintf_s(szString,SZSTRING_SIZE,"// Entry %d: Type 0x%x Offset 0x%08x", i, ((*pw)>>12), ((*pw)&0x0FFF));
printLine(GUICookie,szStr);
}
if((Nentries & 1)) pw++; // to make pdw DWORD-aligned
pdw = (DWORD*)pw;
printLine(GUICookie,"");
}
}
void DumpIAT(const char *szName, IMAGE_DATA_DIRECTORY *pDir, void* GUICookie)
{
char* szStr = &szString[0];
sprintf_s(szString,SZSTRING_SIZE,"// %s", szName);
printLine(GUICookie,szStr);
if (!VAL32(pDir->Size))
{
printLine(GUICookie,RstrUTF(IDS_E_NODATA));
return;
}
const char *szDLLName;
const IMAGE_IMPORT_DESCRIPTOR *pImportDesc;
if (g_pPELoader->getVAforRVA(VAL32(pDir->VirtualAddress), (void **) &pImportDesc) == FALSE)
{
printLine(GUICookie,RstrUTF(IDS_E_IMPORTDATA));
return;
}
const DWORD *pImportTableID;
while (VAL32(pImportDesc->FirstThunk))
{
if (g_pPELoader->getVAforRVA(VAL32(pImportDesc->Name), (void **) &szDLLName) == FALSE ||
g_pPELoader->getVAforRVA(VAL32(pImportDesc->FirstThunk), (void **) &pImportTableID) == FALSE)
{
printLine(GUICookie,RstrUTF(IDS_E_IMPORTDATA));
return;
}
sprintf_s(szString,SZSTRING_SIZE,"// DLL : %s", szDLLName);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Import Address Table", VAL32(pImportDesc->FirstThunk));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Import Name Table", VAL32(pImportDesc->Name));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// %-8d Time Date Stamp", VAL32(pImportDesc->TimeDateStamp));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// %-8d Index of First Forwarder Reference", VAL32(pImportDesc->ForwarderChain));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"//");
printLine(GUICookie,szStr);
for ( ; VAL32(*pImportTableID); pImportTableID++)
{
if (VAL32(*pImportTableID) & 0x80000000)
sprintf_s(szString,SZSTRING_SIZE,"// by Ordinal %d", VAL32(*pImportTableID) & 0x7fffffff);
else
{
const IMAGE_IMPORT_BY_NAME *pName;
if(g_pPELoader->getVAforRVA(VAL32(*pImportTableID) & 0x7fffffff, (void **) &pName))
sprintf_s(szString,SZSTRING_SIZE,"// 0x%04x %s", VAL16(pName->Hint), pName->Name);
else
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x bad RVA of IMAGE_IMPORT_BY_NAME", VAL32(*pImportTableID));
}
printLine(GUICookie,szStr);
}
printLine(GUICookie,"");
// Next import descriptor.
pImportDesc++;
}
}
struct MDStreamHeader
{
DWORD Reserved;
BYTE Major;
BYTE Minor;
BYTE Heaps;
BYTE Rid;
ULONGLONG MaskValid;
ULONGLONG Sorted;
};
void DumpMetadataHeader(const char *szName, IMAGE_DATA_DIRECTORY *pDir, void* GUICookie)
{
char* szStr = &szString[0];
printLine(GUICookie,"");
sprintf_s(szString,SZSTRING_SIZE,"// %s", szName);
printLine(GUICookie,szStr);
if (!VAL32(pDir->Size))
{
printLine(GUICookie,RstrUTF(IDS_E_NODATA));
return;
}
const STORAGESIGNATURE *pSSig;
char verstr[1024];
if (g_pPELoader->getVAforRVA(VAL32(pDir->VirtualAddress), (void **) &pSSig) == FALSE)
{
printLine(GUICookie,RstrUTF(IDS_E_IMPORTDATA));
return;
}
strcpy_s(szString,SZSTRING_SIZE,"// Storage Signature:");
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Signature", VAL32(pSSig->lSignature));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%04x Major Version", VAL16(pSSig->iMajorVer));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%04x Minor Version", VAL16(pSSig->iMinorVer));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Extra Data Offset", VAL32(pSSig->iExtraData));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Version String Length", VAL32(pSSig->iVersionString));
printLine(GUICookie,szStr);
memset(verstr,0,1024);
strncpy_s(verstr,1024,(const char*)(pSSig->pVersion),VAL32(pSSig->iVersionString));
sprintf_s(szString,SZSTRING_SIZE,"// '%s' Version String", verstr);
printLine(GUICookie,szStr);
size_t pb = (size_t)pSSig;
pb += (3*sizeof(DWORD)+2*sizeof(WORD)+VAL32(pSSig->iVersionString)+3)&~3;
PSTORAGEHEADER pSHdr = (PSTORAGEHEADER)pb;
strcpy_s(szString,SZSTRING_SIZE,"// Storage Header:");
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%02x Flags", pSHdr->fFlags);
printLine(GUICookie,szStr);
short nStr = VAL16(pSHdr->iStreams);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%04x Number of Streams", nStr);
if(nStr > 5)
{
strcat_s(szString, SZSTRING_SIZE, " -- BOGUS!");
nStr = 5;
}
printLine(GUICookie,szStr);
PSTORAGESTREAM pStr = (PSTORAGESTREAM)(pSHdr+1);
BYTE* pbMDstream = NULL;
size_t cbMDstream = 0;
for(short iStr = 1; iStr <= nStr; iStr++)
{
sprintf_s(szString,SZSTRING_SIZE,"// Stream %d:",iStr);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Offset", VAL32(pStr->iOffset));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Size", VAL32(pStr->iSize));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// '%s' Name", pStr->rcName);
printLine(GUICookie,szStr);
if((strcmp(pStr->rcName,"#-")==0)||(strcmp(pStr->rcName,"#~")==0))
{
pbMDstream = (BYTE*)pSSig + VAL32(pStr->iOffset);
cbMDstream = VAL32(pStr->iSize);
}
pb = (size_t)pStr;
pb += (2*sizeof(DWORD)+strlen(pStr->rcName)+1+3)&~3;
pStr = (PSTORAGESTREAM)pb;
}
if((pbMDstream)&&(cbMDstream >= sizeof(MDStreamHeader)))
{
printLine(GUICookie,"");
strcpy_s(szString,SZSTRING_SIZE,"// Metadata Stream Header:");
printLine(GUICookie,szStr);
MDStreamHeader* pMDSH = (MDStreamHeader*)pbMDstream;
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x Reserved", VAL32(pMDSH->Reserved));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%02x Major", pMDSH->Major);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%02x Minor", pMDSH->Minor);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%02x Heaps", pMDSH->Heaps);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%02x Rid", pMDSH->Rid);
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%016I64x MaskValid", (ULONGLONG)GET_UNALIGNED_VAL64(&(pMDSH->MaskValid)));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// 0x%016I64x Sorted", (ULONGLONG)GET_UNALIGNED_VAL64(&(pMDSH->Sorted)));
printLine(GUICookie,szStr);
}
}
void DumpEntryPoint(DWORD dwAddrOfEntryPoint,DWORD dwEntryPointSize,void* GUICookie)
{
BYTE* pB;
char* szStr = &szString[0];
char* szptr = szStr+2;
DWORD i;
printLine(GUICookie,"");
strcpy_s(szString,SZSTRING_SIZE,"// Entry point code:");
printLine(GUICookie,szStr);
if (g_pPELoader->getVAforRVA(dwAddrOfEntryPoint, (void **) &pB) == FALSE)
{
printLine(GUICookie,"Bad RVA of entry point");
return;
}
if(dwEntryPointSize == 48) pB -= 32;
// on IA64, AddressOfEntryPoint points at PLabelDescriptor, not at the stub itself
for(i=0; i<dwEntryPointSize; i++)
{
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%2.2X ",pB[i]);
}
printLine(GUICookie,szStr);
}
#define DUMP_DIRECTORY(szName, Directory) \
sprintf_s(szString,SZSTRING_SIZE,"// 0x%08x [0x%08x] address [size] of " szName, \
VAL32(Directory.VirtualAddress), VAL32(Directory.Size)); \
printLine(GUICookie,szStr)
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
void DumpHeader(IMAGE_COR20_HEADER *CORHeader, void* GUICookie)
{
char* szStr = &szString[0];
DWORD dwAddrOfEntryPoint=0, dwEntryPointSize=0;
PIMAGE_DOS_HEADER pDOSHeader = g_pPELoader->dosHeader();
strcpy_s(szString,SZSTRING_SIZE,"// ----- DOS Header:");
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Magic: 0x%04x", VAL16(pDOSHeader->e_magic));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Bytes on last page: 0x%04x", VAL16(pDOSHeader->e_cblp));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Pages in file: 0x%04x", VAL16(pDOSHeader->e_cp));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Relocations: 0x%04x", VAL16(pDOSHeader->e_crlc));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of header (paragraphs):0x%04x", VAL16(pDOSHeader->e_cparhdr));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Min extra paragraphs: 0x%04x", VAL16(pDOSHeader->e_minalloc));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Max extra paragraphs: 0x%04x", VAL16(pDOSHeader->e_maxalloc));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Initial (relative) SS: 0x%04x", VAL16(pDOSHeader->e_ss));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Initial SP: 0x%04x", VAL16(pDOSHeader->e_sp));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Checksum: 0x%04x", VAL16(pDOSHeader->e_csum));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Initial IP: 0x%04x", VAL16(pDOSHeader->e_ip));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Initial (relative) CS: 0x%04x", VAL16(pDOSHeader->e_ip));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// File addr. of reloc table: 0x%04x", VAL16(pDOSHeader->e_lfarlc));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Overlay number: 0x%04x", VAL16(pDOSHeader->e_ovno));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// OEM identifier: 0x%04x", VAL16(pDOSHeader->e_oemid));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// OEM info: 0x%04x", VAL16(pDOSHeader->e_oeminfo));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// File addr. of COFF header: 0x%04x", VAL16(pDOSHeader->e_lfanew));
printLine(GUICookie,szStr);
strcpy_s(szString,SZSTRING_SIZE,"// ----- COFF/PE Headers:");
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Signature: 0x%08x", VAL32(g_pPELoader->Signature()));
printLine(GUICookie,szStr);
strcpy_s(szString,SZSTRING_SIZE,"// ----- COFF Header:");
printLine(GUICookie,szStr);
PIMAGE_FILE_HEADER pCOFF = g_pPELoader->coffHeader();
sprintf_s(szString,SZSTRING_SIZE,"// Machine: 0x%04x", VAL16(pCOFF->Machine));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Number of sections: 0x%04x", VAL16(pCOFF->NumberOfSections));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Time-date stamp: 0x%08x", VAL32(pCOFF->TimeDateStamp));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Ptr to symbol table: 0x%08x", VAL32(pCOFF->PointerToSymbolTable));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Number of symbols: 0x%08x", VAL32(pCOFF->NumberOfSymbols));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of optional header: 0x%04x", VAL16(pCOFF->SizeOfOptionalHeader));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Characteristics: 0x%04x", VAL16(pCOFF->Characteristics));
printLine(GUICookie,szStr);
if (g_pPELoader->IsPE32())
{
IMAGE_NT_HEADERS32 *pNTHeader = g_pPELoader->ntHeaders32();
IMAGE_OPTIONAL_HEADER32 *pOptHeader = &pNTHeader->OptionalHeader;
strcpy_s(szString,SZSTRING_SIZE,"// ----- PE Optional Header (32 bit):");
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Magic: 0x%04x", VAL16(pOptHeader->Magic));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Major linker version: 0x%02x", VAL16(pOptHeader->MajorLinkerVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Minor linker version: 0x%02x", VAL16(pOptHeader->MinorLinkerVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of code: 0x%08x", VAL32(pOptHeader->SizeOfCode));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of init.data: 0x%08x", VAL32(pOptHeader->SizeOfInitializedData));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of uninit.data: 0x%08x", VAL32(pOptHeader->SizeOfUninitializedData));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Addr. of entry point: 0x%08x", VAL32(pOptHeader->AddressOfEntryPoint));
printLine(GUICookie,szStr);
dwAddrOfEntryPoint = VAL32(pOptHeader->AddressOfEntryPoint);
dwEntryPointSize = 6;
sprintf_s(szString,SZSTRING_SIZE,"// Base of code: 0x%08x", VAL32(pOptHeader->BaseOfCode));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Base of data: 0x%08x", VAL32(pOptHeader->BaseOfData));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Image base: 0x%08x", VAL32(pOptHeader->ImageBase));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Section alignment: 0x%08x", VAL32(pOptHeader->SectionAlignment));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// File alignment: 0x%08x", VAL32(pOptHeader->FileAlignment));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Major OS version: 0x%04x", VAL16(pOptHeader->MajorOperatingSystemVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Minor OS version: 0x%04x", VAL16(pOptHeader->MinorOperatingSystemVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Major image version: 0x%04x", VAL16(pOptHeader->MajorImageVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Minor image version: 0x%04x", VAL16(pOptHeader->MinorImageVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Major subsystem version: 0x%04x", VAL16(pOptHeader->MajorSubsystemVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Minor subsystem version: 0x%04x", VAL16(pOptHeader->MinorSubsystemVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of image: 0x%08x", VAL32(pOptHeader->SizeOfImage));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of headers: 0x%08x", VAL32(pOptHeader->SizeOfHeaders));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Checksum: 0x%08x", VAL32(pOptHeader->CheckSum));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Subsystem: 0x%04x", VAL16(pOptHeader->Subsystem));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// DLL characteristics: 0x%04x", VAL16(pOptHeader->DllCharacteristics));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of stack reserve: 0x%08x", VAL32(pOptHeader->SizeOfStackReserve));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of stack commit: 0x%08x", VAL32(pOptHeader->SizeOfStackCommit));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of heap reserve: 0x%08x", VAL32(pOptHeader->SizeOfHeapReserve));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of heap commit: 0x%08x", VAL32(pOptHeader->SizeOfHeapCommit));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Loader flags: 0x%08x", VAL32(pOptHeader->LoaderFlags));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Directories: 0x%08x", VAL32(pOptHeader->NumberOfRvaAndSizes));
printLine(GUICookie,szStr);
DUMP_DIRECTORY("Export Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]);
DUMP_DIRECTORY("Import Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]);
DUMP_DIRECTORY("Resource Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE]);
DUMP_DIRECTORY("Exception Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]);
DUMP_DIRECTORY("Security Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]);
DUMP_DIRECTORY("Base Relocation Table: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]);
DUMP_DIRECTORY("Debug Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG]);
DUMP_DIRECTORY("Architecture Specific: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_ARCHITECTURE]);
DUMP_DIRECTORY("Global Pointer: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_GLOBALPTR]);
DUMP_DIRECTORY("TLS Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]);
DUMP_DIRECTORY("Load Config Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG]);
DUMP_DIRECTORY("Bound Import Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT]);
DUMP_DIRECTORY("Import Address Table: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT]);
DUMP_DIRECTORY("Delay Load IAT: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]);
DUMP_DIRECTORY("CLR Header: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR]);
printLine(GUICookie,"");
DumpSectionHeaders((IMAGE_SECTION_HEADER*)(pOptHeader+1),pNTHeader->FileHeader.NumberOfSections,GUICookie);
DumpBaseReloc("Base Relocation Table",&pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC],GUICookie);
DumpIAT("Import Address Table", &pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT],GUICookie);
DumpIAT("Delay Load Import Address Table", &pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT],GUICookie);
}
else
{
IMAGE_NT_HEADERS64 *pNTHeader = g_pPELoader->ntHeaders64();
IMAGE_OPTIONAL_HEADER64 *pOptHeader = &pNTHeader->OptionalHeader;
strcpy_s(szString,SZSTRING_SIZE,"// ----- PE Optional Header (64 bit):");
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Magic: 0x%04x", VAL16(pOptHeader->Magic));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Major linker version: 0x%02x", VAL16(pOptHeader->MajorLinkerVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Minor linker version: 0x%02x", VAL16(pOptHeader->MinorLinkerVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of code: 0x%08x", VAL32(pOptHeader->SizeOfCode));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of init.data: 0x%08x", VAL32(pOptHeader->SizeOfInitializedData));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of uninit.data: 0x%08x", VAL32(pOptHeader->SizeOfUninitializedData));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Addr. of entry point: 0x%08x", VAL32(pOptHeader->AddressOfEntryPoint));
printLine(GUICookie,szStr);
dwAddrOfEntryPoint = VAL32(pOptHeader->AddressOfEntryPoint);
dwEntryPointSize = (VAL16(pCOFF->Machine)==IMAGE_FILE_MACHINE_IA64) ? 48 : 12;
sprintf_s(szString,SZSTRING_SIZE,"// Base of code: 0x%08x", VAL32(pOptHeader->BaseOfCode));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Image base: 0x%016I64x", VAL64(pOptHeader->ImageBase));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Section alignment: 0x%08x", VAL32(pOptHeader->SectionAlignment));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// File alignment: 0x%08x", VAL32(pOptHeader->FileAlignment));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Major OS version: 0x%04x", VAL16(pOptHeader->MajorOperatingSystemVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Minor OS version: 0x%04x", VAL16(pOptHeader->MinorOperatingSystemVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Major image version: 0x%04x", VAL16(pOptHeader->MajorImageVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Minor image version: 0x%04x", VAL16(pOptHeader->MinorImageVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Major subsystem version: 0x%04x", VAL16(pOptHeader->MajorSubsystemVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Minor subsystem version: 0x%04x", VAL16(pOptHeader->MinorSubsystemVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of image: 0x%08x", VAL32(pOptHeader->SizeOfImage));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of headers: 0x%08x", VAL32(pOptHeader->SizeOfHeaders));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Checksum: 0x%08x", VAL32(pOptHeader->CheckSum));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Subsystem: 0x%04x", VAL16(pOptHeader->Subsystem));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// DLL characteristics: 0x%04x", VAL16(pOptHeader->DllCharacteristics));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of stack reserve: 0x%016I64x", VAL64(pOptHeader->SizeOfStackReserve));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of stack commit: 0x%016I64x", VAL64(pOptHeader->SizeOfStackCommit));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of heap reserve: 0x%016I64x", VAL64(pOptHeader->SizeOfHeapReserve));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Size of heap commit: 0x%016I64x", VAL64(pOptHeader->SizeOfHeapCommit));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Loader flags: 0x%08x", VAL32(pOptHeader->LoaderFlags));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Directories: 0x%08x", VAL32(pOptHeader->NumberOfRvaAndSizes));
printLine(GUICookie,szStr);
DUMP_DIRECTORY("Export Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]);
DUMP_DIRECTORY("Import Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]);
DUMP_DIRECTORY("Resource Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE]);
DUMP_DIRECTORY("Exception Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]);
DUMP_DIRECTORY("Security Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]);
DUMP_DIRECTORY("Base Relocation Table: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]);
DUMP_DIRECTORY("Debug Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG]);
DUMP_DIRECTORY("Architecture Specific: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_ARCHITECTURE]);
DUMP_DIRECTORY("Global Pointer: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_GLOBALPTR]);
DUMP_DIRECTORY("TLS Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]);
DUMP_DIRECTORY("Load Config Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG]);
DUMP_DIRECTORY("Bound Import Directory: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT]);
DUMP_DIRECTORY("Import Address Table: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT]);
DUMP_DIRECTORY("Delay Load IAT: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]);
DUMP_DIRECTORY("CLR Header: ", pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR]);
printLine(GUICookie,"");
DumpSectionHeaders((IMAGE_SECTION_HEADER*)(pOptHeader+1),pNTHeader->FileHeader.NumberOfSections,GUICookie);
DumpBaseReloc("Base Relocation Table",&pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC],GUICookie);
DumpIAT("Import Address Table", &pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT],GUICookie);
DumpIAT("Delay Load Import Address Table", &pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT],GUICookie);
}
if(dwAddrOfEntryPoint != 0) DumpEntryPoint(dwAddrOfEntryPoint,dwEntryPointSize,GUICookie);
printLine(GUICookie,"");
printLine(GUICookie,"");
if (!CORHeader)
{
printLine(GUICookie,RstrUTF(IDS_E_COMIMAGE));
return;
}
strcpy_s(szString,SZSTRING_SIZE,"// ----- CLR Header:");
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Header size: 0x%08x", VAL32(CORHeader->cb));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Major runtime version: 0x%04x", VAL16(CORHeader->MajorRuntimeVersion));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Minor runtime version: 0x%04x", VAL16(CORHeader->MinorRuntimeVersion));
printLine(GUICookie,szStr);
// Metadata
DUMP_DIRECTORY("Metadata Directory: ", CORHeader->MetaData);
sprintf_s(szString,SZSTRING_SIZE,"// Flags: 0x%08x", VAL32(CORHeader->Flags));
printLine(GUICookie,szStr);
sprintf_s(szString,SZSTRING_SIZE,"// Entry point token: 0x%08x",
VAL32(IMAGE_COR20_HEADER_FIELD(*CORHeader, EntryPointToken)));
printLine(GUICookie,szStr);
// Binding
DUMP_DIRECTORY("Resources Directory: ", CORHeader->Resources);
DUMP_DIRECTORY("Strong Name Signature: ", CORHeader->StrongNameSignature);
DUMP_DIRECTORY("CodeManager Table: ", CORHeader->CodeManagerTable);
// Fixups
DUMP_DIRECTORY("VTableFixups Directory: ", CORHeader->VTableFixups);
DUMP_DIRECTORY("Export Address Table: ", CORHeader->ExportAddressTableJumps);
// Managed Native Code
DUMP_DIRECTORY("Precompile Header: ", CORHeader->ManagedNativeHeader);
DumpMetadataHeader("Metadata Header",&(CORHeader->MetaData),GUICookie);
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
void DumpHeaderDetails(IMAGE_COR20_HEADER *CORHeader, void* GUICookie)
{
printLine(GUICookie,"");
DumpCodeManager(CORHeader,GUICookie);
printLine(GUICookie,"");
DumpVTables(CORHeader,GUICookie);
printLine(GUICookie,"");
DumpEATTable(CORHeader,GUICookie);
printLine(GUICookie,"");
}
void WritePerfData(const char *KeyDesc, const char *KeyName, const char *UnitDesc, const char *UnitName, void* Value, BOOL IsInt)
{
DWORD BytesWritten;
if(!g_fDumpToPerfWriter) return;
if (!g_PerfDataFilePtr)
{
if((g_PerfDataFilePtr = WszCreateFile(W("c:\\temp\\perfdata.dat"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL) ) == INVALID_HANDLE_VALUE)
{
printLine(NULL,"PefTimer::LogStoppedTime(): Unable to open the FullPath file. No performance data will be generated");
g_fDumpToPerfWriter = FALSE;
return;
}
WriteFile(g_PerfDataFilePtr,"ExecTime=0\r\n",13,&BytesWritten,NULL);
WriteFile(g_PerfDataFilePtr,"ExecUnit=bytes\r\n",17,&BytesWritten,NULL);
WriteFile(g_PerfDataFilePtr,"ExecUnitDescr=File Size\r\n",26,&BytesWritten,NULL);
WriteFile(g_PerfDataFilePtr,"ExeciDirection=False\r\n",23,&BytesWritten,NULL);
}
char ValueStr[10];
char TmpStr[201];
if (IsInt)
{
sprintf_s(ValueStr,10,"%d",(int)*(int*)Value);
}
else
{
sprintf_s(ValueStr,10,"%5.2f",(float)*(float*)Value);
}
sprintf_s(TmpStr, 201, "%s=%s\r\n", KeyName, ValueStr);
WriteFile(g_PerfDataFilePtr, TmpStr, (DWORD)strlen(TmpStr), &BytesWritten, NULL);
sprintf_s(TmpStr, 201, "%s Descr=%s\r\n", KeyName, KeyDesc);
WriteFile(g_PerfDataFilePtr, TmpStr, (DWORD)strlen(TmpStr), &BytesWritten, NULL);
sprintf_s(TmpStr, 201, "%s Unit=%s\r\n", KeyName, UnitName);
WriteFile(g_PerfDataFilePtr, TmpStr, (DWORD)strlen(TmpStr), &BytesWritten, NULL);
sprintf_s(TmpStr, 201, "%s Unit Descr=%s\r\n", KeyName, UnitDesc);
WriteFile(g_PerfDataFilePtr, TmpStr, (DWORD)strlen(TmpStr), &BytesWritten, NULL);
sprintf_s(TmpStr, 201, "%s IDirection=%s\r\n", KeyName, "False");
WriteFile(g_PerfDataFilePtr, TmpStr, (DWORD)strlen(TmpStr), &BytesWritten, NULL);
}
void WritePerfDataInt(const char *KeyDesc, const char *KeyName, const char *UnitDesc, const char *UnitName, int Value)
{
WritePerfData(KeyDesc,KeyName,UnitDesc,UnitName, (void*)&Value, TRUE);
}
void WritePerfDataFloat(const char *KeyDesc, const char *KeyName, const char *UnitDesc, const char *UnitName, float Value)
{
WritePerfData(KeyDesc,KeyName,UnitDesc,UnitName, (void*)&Value, FALSE);
}
IMetaDataTables *pITables = NULL;
//ULONG sizeRec, count;
//int size, size2;
int metaSize = 0;
__int64 fTableSeen;
inline void TableSeen(unsigned long n) { fTableSeen |= (I64(1) << n); }
inline int IsTableSeen(unsigned long n) { return (fTableSeen & (I64(1) << n)) ? 1 : 0;}
inline void TableSeenReset() { fTableSeen = 0;}
void DumpTable(unsigned long Table, const char *TableName, void* GUICookie)
{
char *szStr = &szString[0];
const char **ppTableName = 0;
int size;
ULONG sizeRec, count;
// Record that this table has been seen.
TableSeen(Table);
// If no name passed in, get from table info.
if (!TableName)
ppTableName = &TableName;
pITables->GetTableInfo(Table, &sizeRec, &count, NULL, NULL, ppTableName);
if(count > 0)
{
metaSize += size = count * sizeRec;
WritePerfDataInt(TableName,TableName,"count","count",count);
WritePerfDataInt(TableName,TableName,"bytes","bytes",size);
sprintf_s(szString,SZSTRING_SIZE,"// %-14s- %4d (%d bytes)", TableName, count, size);
printLine(GUICookie,szStr);
}
}
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
void DumpStatistics(IMAGE_COR20_HEADER *CORHeader, void* GUICookie)
{
int fileSize, miscPESize, miscCOMPlusSize, methodHeaderSize, methodBodySize;
int methodBodies, fatHeaders, tinyHeaders, deprecatedHeaders;
int size, size2;
int fatSections, smallSections;
ULONG methodDefs;
ULONG i;
ULONG sizeRec, count;
char buf[MAX_MEMBER_LENGTH];
char* szStr = &szString[0];
TableSeenReset();
metaSize = 0;
sprintf_s(szString,SZSTRING_SIZE,"// File size : %d", fileSize = SafeGetFileSize(g_pPELoader->getHFile(), NULL));
printLine(GUICookie,szStr);
WritePerfDataInt("FileSize","FileSize","standard byte","bytes",fileSize);
if (g_pPELoader->IsPE32())
{
size = VAL32(((IMAGE_DOS_HEADER*) g_pPELoader->getHModule())->e_lfanew) +
sizeof(IMAGE_NT_HEADERS32) - sizeof(IMAGE_OPTIONAL_HEADER32) +
VAL16(g_pPELoader->ntHeaders32()->FileHeader.SizeOfOptionalHeader) +
VAL16(g_pPELoader->ntHeaders32()->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER);
size2 = (size + VAL32(g_pPELoader->ntHeaders32()->OptionalHeader.FileAlignment) - 1) & ~(VAL32(g_pPELoader->ntHeaders32()->OptionalHeader.FileAlignment) - 1);
}
else
{
size = VAL32(((IMAGE_DOS_HEADER*) g_pPELoader->getHModule())->e_lfanew) +
sizeof(IMAGE_NT_HEADERS64) - sizeof(IMAGE_OPTIONAL_HEADER64) +
VAL16(g_pPELoader->ntHeaders64()->FileHeader.SizeOfOptionalHeader) +
VAL16(g_pPELoader->ntHeaders64()->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER);
size2 = (size + VAL32(g_pPELoader->ntHeaders64()->OptionalHeader.FileAlignment) - 1) & ~(VAL32(g_pPELoader->ntHeaders64()->OptionalHeader.FileAlignment) - 1);
}
DWORD sizeOfHeaders;
if (g_pPELoader->IsPE32())
{
sizeOfHeaders = VAL32(g_pPELoader->ntHeaders32()->OptionalHeader.SizeOfHeaders);
WritePerfDataInt("PE header size", "PE header size", "standard byte", "bytes", sizeOfHeaders);
WritePerfDataInt("PE header size used", "PE header size used", "standard byte", "bytes", size);
WritePerfDataFloat("PE header size", "PE header size", "percentage", "percentage", (float)((sizeOfHeaders * 100) / fileSize));
sprintf_s(szString,SZSTRING_SIZE,"// PE header size : %d (%d used) (%5.2f%%)",
sizeOfHeaders, size, (double) (sizeOfHeaders * 100) / fileSize);
printLine(GUICookie,szStr);
miscPESize = 0;
for (i=0; i < VAL32(g_pPELoader->ntHeaders32()->OptionalHeader.NumberOfRvaAndSizes); ++i)
{
// Skip the CLR header.
if (i != 15) miscPESize += (int) VAL32(g_pPELoader->ntHeaders32()->OptionalHeader.DataDirectory[i].Size);
}
}
else
{
sizeOfHeaders = VAL32(g_pPELoader->ntHeaders64()->OptionalHeader.SizeOfHeaders);
WritePerfDataInt("PE+ header size", "PE header size", "standard byte", "bytes", sizeOfHeaders);
WritePerfDataInt("PE+ header size used", "PE header size used", "standard byte", "bytes", size);
WritePerfDataFloat("PE+ header size", "PE header size", "percentage", "percentage", (float)((sizeOfHeaders * 100) / fileSize));
sprintf_s(szString,SZSTRING_SIZE,"// PE header size : %d (%d used) (%5.2f%%)",
sizeOfHeaders, size, (double) (sizeOfHeaders * 100) / fileSize);
printLine(GUICookie,szStr);
miscPESize = 0;
for (i=0; i < VAL32(g_pPELoader->ntHeaders64()->OptionalHeader.NumberOfRvaAndSizes); ++i)
{
// Skip the CLR header.
if (i != IMAGE_DIRECTORY_ENTRY_COMHEADER) miscPESize += (int) VAL32(g_pPELoader->ntHeaders64()->OptionalHeader.DataDirectory[i].Size);
}
}
WritePerfDataInt("PE additional info", "PE additional info", "standard byte", "bytes",miscPESize);
WritePerfDataFloat("PE additional info", "PE additional info", "percentage", "percent", (float) ((miscPESize * 100) / fileSize));
sprintf_s(buf, MAX_MEMBER_LENGTH, "PE additional info : %d", miscPESize);
sprintf_s(szString,SZSTRING_SIZE,"// %-40s (%5.2f%%)", buf, (double) (miscPESize * 100) / fileSize);
printLine(GUICookie,szStr);
WORD numberOfSections;
if (g_pPELoader->IsPE32())
{
numberOfSections = VAL16(g_pPELoader->ntHeaders32()->FileHeader.NumberOfSections);
}
else
{
numberOfSections = VAL16(g_pPELoader->ntHeaders64()->FileHeader.NumberOfSections);
}
WritePerfDataInt("Num.of PE sections", "Num.of PE sections", "Nbr of sections", "sections",numberOfSections);
sprintf_s(szString,SZSTRING_SIZE,"// Num.of PE sections : %d", numberOfSections);
printLine(GUICookie,szStr);
WritePerfDataInt("CLR header size", "CLR header size", "byte", "bytes",VAL32(CORHeader->cb));
WritePerfDataFloat("CLR header size", "CLR header size", "percentage", "percent",(float) ((VAL32(CORHeader->cb) * 100) / fileSize));
sprintf_s(buf, MAX_MEMBER_LENGTH, "CLR header size : %d", VAL32(CORHeader->cb));
sprintf_s(szString,SZSTRING_SIZE,"// %-40s (%5.2f%%)", buf, (double) (VAL32(CORHeader->cb) * 100) / fileSize);
printLine(GUICookie,szStr);
DWORD dwMetaSize = g_cbMetaData;
WritePerfDataInt("CLR meta-data size", "CLR meta-data size", "bytes", "bytes",dwMetaSize);
WritePerfDataFloat("CLR meta-data size", "CLR meta-data size", "percentage", "percent",(float) ((dwMetaSize * 100) / fileSize));
sprintf_s(buf, MAX_MEMBER_LENGTH, "CLR meta-data size : %d", dwMetaSize);
sprintf_s(szString,SZSTRING_SIZE,"// %-40s (%5.2f%%)", buf, (double) (dwMetaSize * 100) / fileSize);
printLine(GUICookie,szStr);
IMAGE_DATA_DIRECTORY *pFirst = &CORHeader->Resources;
ULONG32 iCount = (ULONG32)((BYTE *) &CORHeader->ManagedNativeHeader - (BYTE *) &CORHeader->Resources) / sizeof(IMAGE_DATA_DIRECTORY) + 1;
miscCOMPlusSize = 0;
for (ULONG32 iDir=0; iDir<iCount; iDir++)
{
miscCOMPlusSize += VAL32(pFirst->Size);
pFirst++;
}
WritePerfDataInt("CLR Additional info", "CLR Additional info", "bytes", "bytes",miscCOMPlusSize);
WritePerfDataFloat("CLR Additional info", "CLR Additional info", "percentage", "percent",(float) ((miscCOMPlusSize * 100) / fileSize));
sprintf_s(buf, MAX_MEMBER_LENGTH, "CLR additional info : %d", miscCOMPlusSize);
sprintf_s(szString,SZSTRING_SIZE,"// %-40s (%5.2f%%)", buf, (double) (miscCOMPlusSize * 100) / fileSize);
printLine(GUICookie,szStr);
// Go through each method def collecting some statistics.
methodHeaderSize = methodBodySize = 0;
methodBodies = fatHeaders = tinyHeaders = deprecatedHeaders = fatSections = smallSections = 0;
methodDefs = g_pImport->GetCountWithTokenKind(mdtMethodDef);
for (i=1; i <= methodDefs; ++i) {
ULONG rva;
DWORD flags;
if (FAILED(g_pImport->GetMethodImplProps(TokenFromRid(i, mdtMethodDef), &rva, &flags)))
{
continue;
}
if ((rva != 0)&&(IsMiIL(flags) || IsMiOPTIL(flags))) // We don't handle native yet.
{
++methodBodies;
COR_ILMETHOD_FAT *pMethod;
g_pPELoader->getVAforRVA(rva, (void **) &pMethod);
if (pMethod->IsFat())
{
++fatHeaders;
methodHeaderSize += pMethod->GetSize() * 4;
methodBodySize += pMethod->GetCodeSize();
// Add in the additional sections.
BYTE *sectsBegin = (BYTE *) (pMethod->GetCode() + pMethod->GetCodeSize());
const COR_ILMETHOD_SECT *pSect = pMethod->GetSect();
const COR_ILMETHOD_SECT *pOldSect;
if (pSect != NULL) {
// Keep skipping a pointer past each section.
do
{
pOldSect = pSect;
if (((COR_ILMETHOD_SECT_FAT *) pSect)->GetKind() & CorILMethod_Sect_FatFormat)
{
++fatSections;
pSect = (COR_ILMETHOD_SECT *)((BYTE *) pSect + ((COR_ILMETHOD_SECT_FAT *) pSect)->GetDataSize());
}
else
{
++smallSections;
pSect = (COR_ILMETHOD_SECT *)((BYTE *) pSect + ((COR_ILMETHOD_SECT_SMALL *) pSect)->DataSize);
}
pSect = (COR_ILMETHOD_SECT *) (((UINT_PTR) pSect + 3) & ~3);
}
while (pOldSect->More());
// Add on the section sizes.
methodHeaderSize += (int) ((BYTE *) pSect - sectsBegin);
}
}
else if (((COR_ILMETHOD_TINY *) pMethod)->IsTiny())
{
++tinyHeaders;
methodHeaderSize += sizeof(COR_ILMETHOD_TINY);
methodBodySize += ((COR_ILMETHOD_TINY *) pMethod)->GetCodeSize();
}
else
{
_ASSERTE(!"Unrecognized header type");
}
}
}
WritePerfDataInt("CLR method headers", "CLR method headers", "bytes", "bytes",methodHeaderSize);
WritePerfDataFloat("CLR method headers", "CLR method headers", "percentage", "percent",(float) ((methodHeaderSize * 100) / fileSize));
sprintf_s(buf, MAX_MEMBER_LENGTH, "CLR method headers : %d", methodHeaderSize);
sprintf_s(szString,SZSTRING_SIZE,"// %-40s (%5.2f%%)", buf, (double) (methodHeaderSize * 100) / fileSize);
printLine(GUICookie,szStr);
WritePerfDataInt("Managed code", "Managed code", "bytes", "bytes",methodBodySize);
WritePerfDataFloat("Managed code", "Managed code", "percentage", "percent",(float) ((methodBodySize * 100) / fileSize));
sprintf_s(buf, MAX_MEMBER_LENGTH, "Managed code : %d", methodBodySize);
sprintf_s(szString,SZSTRING_SIZE,"// %-40s (%5.2f%%)", buf, (double) (methodBodySize * 100) / fileSize);
printLine(GUICookie,szStr);
if (g_pPELoader->IsPE32())
{
DWORD sizeOfInitializedData = VAL32(g_pPELoader->ntHeaders32()->OptionalHeader.SizeOfInitializedData);
WritePerfDataInt("Data", "Data", "bytes", "bytes",sizeOfInitializedData);
WritePerfDataFloat("Data", "Data", "percentage", "percent",(float) ((sizeOfInitializedData * 100) / fileSize));
sprintf_s(buf, MAX_MEMBER_LENGTH, "Data : %d", sizeOfInitializedData);
sprintf_s(szString,SZSTRING_SIZE,"// %-40s (%5.2f%%)", buf, (double) (sizeOfInitializedData * 100) / fileSize);
printLine(GUICookie,szStr);
size = fileSize - g_pPELoader->ntHeaders32()->OptionalHeader.SizeOfHeaders - miscPESize - CORHeader->cb -
g_cbMetaData - miscCOMPlusSize -
sizeOfInitializedData -
methodHeaderSize - methodBodySize;
}
else
{
DWORD sizeOfInitializedData = VAL32(g_pPELoader->ntHeaders64()->OptionalHeader.SizeOfInitializedData);
WritePerfDataInt("Data", "Data", "bytes", "bytes",sizeOfInitializedData);
WritePerfDataFloat("Data", "Data", "percentage", "percent",(float) ((sizeOfInitializedData * 100) / fileSize));
sprintf_s(buf, MAX_MEMBER_LENGTH, "Data : %d", sizeOfInitializedData);
sprintf_s(szString,SZSTRING_SIZE,"// %-40s (%5.2f%%)", buf, (double) (sizeOfInitializedData * 100) / fileSize);
printLine(GUICookie,szStr);
size = fileSize - g_pPELoader->ntHeaders64()->OptionalHeader.SizeOfHeaders - miscPESize - CORHeader->cb -
g_cbMetaData - miscCOMPlusSize -
sizeOfInitializedData -
methodHeaderSize - methodBodySize;
}
WritePerfDataInt("Unaccounted", "Unaccounted", "bytes", "bytes",size);
WritePerfDataFloat("Unaccounted", "Unaccounted", "percentage", "percent",(float) ((size * 100) / fileSize));
sprintf_s(buf, MAX_MEMBER_LENGTH, "Unaccounted : %d", size);
sprintf_s(szString,SZSTRING_SIZE,"// %-40s (%5.2f%%)", buf, (double) (size * 100) / fileSize);
printLine(GUICookie,szStr);
// Detail...
if (g_pPELoader->IsPE32())
{
numberOfSections = VAL16(g_pPELoader->ntHeaders32()->FileHeader.NumberOfSections);
WritePerfDataInt("Num.of PE sections", "Num.of PE sections", "bytes", "bytes",numberOfSections);
printLine(GUICookie,"");
sprintf_s(szString,SZSTRING_SIZE,"// Num.of PE sections : %d", numberOfSections);
printLine(GUICookie,szStr);
IMAGE_SECTION_HEADER *pSecHdr = IMAGE_FIRST_SECTION(g_pPELoader->ntHeaders32());
for (i=0; i < numberOfSections; ++i)
{
WritePerfDataInt((char*)pSecHdr->Name,(char*)pSecHdr->Name, "bytes", "bytes",VAL32(pSecHdr->SizeOfRawData));
sprintf_s(szString,SZSTRING_SIZE,"// %-8s - %d", pSecHdr->Name, VAL32(pSecHdr->SizeOfRawData));
printLine(GUICookie,szStr);
++pSecHdr;
}
}
else
{
numberOfSections = VAL16(g_pPELoader->ntHeaders64()->FileHeader.NumberOfSections);
WritePerfDataInt("Num.of PE sections", "Num.of PE sections", "bytes", "bytes",numberOfSections);
printLine(GUICookie,"");
sprintf_s(szString,SZSTRING_SIZE,"// Num.of PE sections : %d", numberOfSections);
printLine(GUICookie,szStr);
IMAGE_SECTION_HEADER *pSecHdr = IMAGE_FIRST_SECTION(g_pPELoader->ntHeaders64());
for (i=0; i < numberOfSections; ++i)
{
WritePerfDataInt((char*)pSecHdr->Name,(char*)pSecHdr->Name, "bytes", "bytes",pSecHdr->SizeOfRawData);
sprintf_s(szString,SZSTRING_SIZE,"// %-8s - %d", pSecHdr->Name, pSecHdr->SizeOfRawData);
printLine(GUICookie,szStr);
++pSecHdr;
}
}
if (FAILED(g_pPubImport->QueryInterface(IID_IMetaDataTables, (void**)&pITables)))
{
sprintf_s(szString,SZSTRING_SIZE,"// Unable to get IMetaDataTables interface");
printLine(GUICookie,szStr);
return;
}
if (pITables == 0)
{
printLine(GUICookie,RstrUTF(IDS_E_MDDETAILS));
return;
}
else
{
DWORD Size = g_cbMetaData;
WritePerfDataInt("CLR meta-data size", "CLR meta-data size", "bytes", "bytes",Size);
printLine(GUICookie,"");
sprintf_s(szString,SZSTRING_SIZE,"// CLR meta-data size : %d", Size);
printLine(GUICookie,szStr);
metaSize = 0;
pITables->GetTableInfo(TBL_Module, &sizeRec, &count, NULL, NULL, NULL);
TableSeen(TBL_Module);
metaSize += size = count * sizeRec; \
WritePerfDataInt("Module (count)", "Module (count)", "count", "count",count);
WritePerfDataInt("Module (bytes)", "Module (bytes)", "bytes", "bytes",size);
sprintf_s(szString,SZSTRING_SIZE,"// %-14s- %4d (%d bytes)", "Module", count, size); \
printLine(GUICookie,szStr);
if ((count = g_pImport->GetCountWithTokenKind(mdtTypeDef)) > 0)
{
int flags, interfaces = 0, explicitLayout = 0;
for (i=1; i <= count; ++i)
{
if (FAILED(g_pImport->GetTypeDefProps(TokenFromRid(i, mdtTypeDef), (ULONG *) &flags, NULL)))
{
continue;
}
if (flags & tdInterface) ++interfaces;
if (flags & tdExplicitLayout) ++explicitLayout;
}
// Get count from table -- count reported by GetCount... doesn't include the "global" typedef.
pITables->GetTableInfo(TBL_TypeDef, &sizeRec, &count, NULL, NULL, NULL);
TableSeen(TBL_TypeDef);
metaSize += size = count * sizeRec;
WritePerfDataInt("TypeDef (count)", "TypeDef (count)", "count", "count", count);
WritePerfDataInt("TypeDef (bytes)", "TypeDef (bytes)", "bytes", "bytes", size);
WritePerfDataInt("interfaces", "interfaces", "count", "count", interfaces);
WritePerfDataInt("explicitLayout", "explicitLayout", "count", "count", explicitLayout);
sprintf_s(buf, MAX_MEMBER_LENGTH, " TypeDef - %4d (%d bytes)", count, size);
sprintf_s(szString,SZSTRING_SIZE,"// %-38s %d interfaces, %d explicit layout", buf, interfaces, explicitLayout);
printLine(GUICookie,szStr);
}
}
pITables->GetTableInfo(TBL_TypeRef, &sizeRec, &count, NULL, NULL, NULL);
TableSeen(TBL_TypeRef);
if (count > 0)
{
metaSize += size = count * sizeRec; \
WritePerfDataInt("TypeRef (count)", "TypeRef (count)", "count", "count", count);
WritePerfDataInt("TypeRef (bytes)", "TypeRef (bytes)", "bytes", "bytes", size);
sprintf_s(szString,SZSTRING_SIZE,"// %-14s- %4d (%d bytes)", "TypeRef", count, size); \
printLine(GUICookie,szStr);
}
if ((count = g_pImport->GetCountWithTokenKind(mdtMethodDef)) > 0)
{
int flags, abstract = 0, native = 0;
for (i=1; i <= count; ++i)
{
if (FAILED(g_pImport->GetMethodDefProps(TokenFromRid(i, mdtMethodDef), (DWORD *)&flags)))
{
sprintf_s(szString, SZSTRING_SIZE, "// Invalid MethodDef %08X record", TokenFromRid(i, mdtMethodDef));
printLine(GUICookie, szStr);
return;
}
if (flags & mdAbstract) ++abstract;
}
pITables->GetTableInfo(TBL_Method, &sizeRec, NULL, NULL, NULL, NULL);
TableSeen(TBL_Method);
if (count > 0)
{
metaSize += size = count * sizeRec;
WritePerfDataInt("MethodDef (count)", "MethodDef (count)", "count", "count", count);
WritePerfDataInt("MethodDef (bytes)", "MethodDef (bytes)", "bytes", "bytes", size);
WritePerfDataInt("abstract", "abstract", "count", "count", abstract);
WritePerfDataInt("native", "native", "count", "count", native);
WritePerfDataInt("methodBodies", "methodBodies", "count", "count", methodBodies);
sprintf_s(buf, MAX_MEMBER_LENGTH, " MethodDef - %4d (%d bytes)", count, size);
sprintf_s(szString,SZSTRING_SIZE,"// %-38s %d abstract, %d native, %d bodies", buf, abstract, native, methodBodies);
printLine(GUICookie,szStr);
}
}
if ((count = g_pImport->GetCountWithTokenKind(mdtFieldDef)) > 0)
{
int flags, constants = 0;
for (i=1; i <= count; ++i)
{
if (FAILED(g_pImport->GetFieldDefProps(TokenFromRid(i, mdtFieldDef), (DWORD *)&flags)))
{
sprintf_s(szString, SZSTRING_SIZE, "// Invalid FieldDef %08X record", TokenFromRid(i, mdtFieldDef));
printLine(GUICookie, szStr);
return;
}
if ((flags & (fdStatic|fdInitOnly)) == (fdStatic|fdInitOnly)) ++constants;
}
pITables->GetTableInfo(TBL_Field, &sizeRec, NULL, NULL, NULL, NULL);
metaSize += size = count * sizeRec;
WritePerfDataInt("FieldDef (count)", "FieldDef (count)", "count", "count", count);
WritePerfDataInt("FieldDef (bytes)", "FieldDef (bytes)", "bytes", "bytes", size);
WritePerfDataInt("constant", "constant", "count", "count", constants);
sprintf_s(buf, MAX_MEMBER_LENGTH, " FieldDef - %4d (%d bytes)", count, size);
sprintf_s(szString,SZSTRING_SIZE,"// %-38s %d constant", buf, constants);
printLine(GUICookie,szStr);
TableSeen(TBL_Field);
}
DumpTable(TBL_MemberRef, "MemberRef", GUICookie);
DumpTable(TBL_Param, "ParamDef", GUICookie);
DumpTable(TBL_MethodImpl, "MethodImpl", GUICookie);
DumpTable(TBL_Constant, "Constant", GUICookie);
DumpTable(TBL_CustomAttribute, "CustomAttribute", GUICookie);
DumpTable(TBL_FieldMarshal, "NativeType", GUICookie);
DumpTable(TBL_ClassLayout, "ClassLayout", GUICookie);
DumpTable(TBL_FieldLayout, "FieldLayout", GUICookie);
DumpTable(TBL_StandAloneSig, "StandAloneSig", GUICookie);
DumpTable(TBL_InterfaceImpl, "InterfaceImpl", GUICookie);
DumpTable(TBL_PropertyMap, "PropertyMap", GUICookie);
DumpTable(TBL_Property, "Property", GUICookie);
DumpTable(TBL_MethodSemantics, "MethodSemantic", GUICookie);
DumpTable(TBL_DeclSecurity, "Security", GUICookie);
DumpTable(TBL_TypeSpec, "TypeSpec", GUICookie);
DumpTable(TBL_ModuleRef, "ModuleRef", GUICookie);
DumpTable(TBL_Assembly, "Assembly", GUICookie);
DumpTable(TBL_AssemblyProcessor, "AssemblyProcessor", GUICookie);
DumpTable(TBL_AssemblyOS, "AssemblyOS", GUICookie);
DumpTable(TBL_AssemblyRef, "AssemblyRef", GUICookie);
DumpTable(TBL_AssemblyRefProcessor, "AssemblyRefProcessor", GUICookie);
DumpTable(TBL_AssemblyRefOS, "AssemblyRefOS", GUICookie);
DumpTable(TBL_File, "File", GUICookie);
DumpTable(TBL_ExportedType, "ExportedType", GUICookie);
DumpTable(TBL_ManifestResource, "ManifestResource", GUICookie);
DumpTable(TBL_NestedClass, "NestedClass", GUICookie);
// Rest of the tables.
pITables->GetNumTables(&count);
for (i=0; i<count; ++i)
{
if (!IsTableSeen(i))
DumpTable(i, NULL, GUICookie);
}
// String heap
pITables->GetStringHeapSize(&sizeRec);
if (sizeRec > 0)
{
metaSize += sizeRec;
WritePerfDataInt("Strings", "Strings", "bytes", "bytes",sizeRec);
sprintf_s(szString,SZSTRING_SIZE,"// Strings - %5d bytes", sizeRec);
printLine(GUICookie,szStr);
}
// Blob heap
pITables->GetBlobHeapSize(&sizeRec);
if (sizeRec > 0)
{
metaSize += sizeRec;
WritePerfDataInt("Blobs", "Blobs", "bytes", "bytes",sizeRec);
sprintf_s(szString,SZSTRING_SIZE,"// Blobs - %5d bytes", sizeRec);
printLine(GUICookie,szStr);
}
// User String Heap
pITables->GetUserStringHeapSize(&sizeRec);
if (sizeRec > 0)
{
metaSize += sizeRec;
WritePerfDataInt("UserStrings", "UserStrings", "bytes", "bytes",sizeRec);
sprintf_s(szString,SZSTRING_SIZE,"// UserStrings - %5d bytes", sizeRec);
printLine(GUICookie,szStr);
}
// Guid heap
pITables->GetGuidHeapSize(&sizeRec);
if (sizeRec > 0)
{
metaSize += sizeRec;
WritePerfDataInt("Guids", "Guids", "bytes", "bytes", sizeRec);
sprintf_s(szString,SZSTRING_SIZE,"// Guids - %5d bytes", sizeRec);
printLine(GUICookie,szStr);
}
if (g_cbMetaData - metaSize > 0)
{
WritePerfDataInt("Uncategorized", "Uncategorized", "bytes", "bytes",g_cbMetaData - metaSize);
sprintf_s(szString,SZSTRING_SIZE,"// Uncategorized - %5d bytes", g_cbMetaData - metaSize);
printLine(GUICookie,szStr);
}
if (miscCOMPlusSize != 0)
{
WritePerfDataInt("CLR additional info", "CLR additional info", "bytes", "bytes", miscCOMPlusSize);
sprintf_s(szString,SZSTRING_SIZE,"// CLR additional info : %d", miscCOMPlusSize);
printLine(GUICookie,"");
printLine(GUICookie,szStr);
if (CORHeader->CodeManagerTable.Size != 0)
{
WritePerfDataInt("CodeManagerTable", "CodeManagerTable", "bytes", "bytes", VAL32(CORHeader->CodeManagerTable.Size));
sprintf_s(szString,SZSTRING_SIZE,"// CodeManagerTable - %d", VAL32(CORHeader->CodeManagerTable.Size));
printLine(GUICookie,szStr);
}
if (CORHeader->VTableFixups.Size != 0)
{
WritePerfDataInt("VTableFixups", "VTableFixups", "bytes", "bytes", VAL32(CORHeader->VTableFixups.Size));
sprintf_s(szString,SZSTRING_SIZE,"// VTableFixups - %d", VAL32(CORHeader->VTableFixups.Size));
printLine(GUICookie,szStr);
}
if (CORHeader->Resources.Size != 0)
{
WritePerfDataInt("Resources", "Resources", "bytes", "bytes", VAL32(CORHeader->Resources.Size));
sprintf_s(szString,SZSTRING_SIZE,"// Resources - %d", VAL32(CORHeader->Resources.Size));
printLine(GUICookie,szStr);
}
}
WritePerfDataInt("CLR method headers", "CLR method headers", "count", "count", methodHeaderSize);
sprintf_s(szString,SZSTRING_SIZE,"// CLR method headers : %d", methodHeaderSize);
printLine(GUICookie,"");
printLine(GUICookie,szStr);
WritePerfDataInt("Num.of method bodies", "Num.of method bodies", "count", "count",methodBodies);
sprintf_s(szString,SZSTRING_SIZE,"// Num.of method bodies - %d", methodBodies);
printLine(GUICookie,szStr);
WritePerfDataInt("Num.of fat headers", "Num.of fat headers", "count", "count", fatHeaders);
sprintf_s(szString,SZSTRING_SIZE,"// Num.of fat headers - %d", fatHeaders);
printLine(GUICookie,szStr);
WritePerfDataInt("Num.of tiny headers", "Num.of tiny headers", "count", "count", tinyHeaders);
sprintf_s(szString,SZSTRING_SIZE,"// Num.of tiny headers - %d", tinyHeaders);
printLine(GUICookie,szStr);
if (deprecatedHeaders > 0) {
WritePerfDataInt("Num.of old headers", "Num.of old headers", "count", "count", deprecatedHeaders);
sprintf_s(szString,SZSTRING_SIZE,"// Num.of old headers - %d", deprecatedHeaders);
printLine(GUICookie,szStr);
}
if (fatSections != 0 || smallSections != 0) {
WritePerfDataInt("Num.of fat sections", "Num.of fat sections", "count", "count", fatSections);
sprintf_s(szString,SZSTRING_SIZE,"// Num.of fat sections - %d", fatSections);
printLine(GUICookie,szStr);
WritePerfDataInt("Num.of small section", "Num.of small section", "count", "count", smallSections);
sprintf_s(szString,SZSTRING_SIZE,"// Num.of small sections - %d", smallSections);
printLine(GUICookie,szStr);
}
WritePerfDataInt("Managed code", "Managed code", "bytes", "bytes", methodBodySize);
sprintf_s(szString,SZSTRING_SIZE,"// Managed code : %d", methodBodySize);
printLine(GUICookie,"");
printLine(GUICookie,szStr);
if (methodBodies != 0) {
WritePerfDataInt("Ave method size", "Ave method size", "bytes", "bytes", methodBodySize / methodBodies);
sprintf_s(szString,SZSTRING_SIZE,"// Ave method size - %d", methodBodySize / methodBodies);
printLine(GUICookie,szStr);
}
if (pITables)
pITables->Release();
if(g_fDumpToPerfWriter)
CloseHandle((char*) g_PerfDataFilePtr);
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
void DumpHexbytes(__inout __nullterminated char* szptr,BYTE *pb, DWORD fromPtr, DWORD toPtr, DWORD limPtr)
{
char sz[256];
int k = 0,i;
DWORD curPtr = 0;
bool printsz = FALSE;
BYTE zero = 0;
*szptr = 0;
for(i = 0,k = 0,curPtr=fromPtr; curPtr < toPtr; i++,k++,curPtr++,pb++)
{
if(k == 16)
{
if(printsz) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT(" // %s"),sz);
printLine(g_pFile,szString);
szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s ",g_szAsmCodeIndent);
k = 0;
printsz = FALSE;
}
if(curPtr >= limPtr) pb = &zero; // at limPtr and after, pad with 0
else
{
PAL_CPP_TRY
{
sz[k] = *pb; // check the ptr validity
}
PAL_CPP_CATCH_ALL
{
pb = &zero;
} PAL_CPP_ENDTRY;
}
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," %2.2X", *pb);
if(isprint(*pb))
{
if(g_fDumpRTF)
{
if((*pb == '\\')||(*pb=='{')||(*pb=='}')) sz[k++]='\\';
sz[k] = *pb;
}
else if(g_fDumpHTML)
{
if(*pb == '<') { sz[k] = 0; strcat_s(sz,256-k,LTN()); k+=(int)(strlen(LTN())); }
else if(*pb == '>') { sz[k] = 0; strcat_s(sz,256-k,GTN()); k+=(int)(strlen(GTN())); }
}
else sz[k] = *pb;
printsz = TRUE;
}
else
{
sz[k] = '.';
}
sz[k+1] = 0;
}
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),") ");
if(printsz)
{
for(i = k; i < 16; i++) szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," ");
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("// %s"),sz);
}
printLine(g_pFile,szString);
}
struct VTableEntry
{
DWORD dwAddr;
WORD wCount;
WORD wType;
};
struct ExpDirTable
{
DWORD dwFlags;
DWORD dwDateTime;
WORD wVMajor;
WORD wVMinor;
DWORD dwNameRVA;
DWORD dwOrdinalBase;
DWORD dwNumATEntries;
DWORD dwNumNamePtrs;
DWORD dwAddrTableRVA;
DWORD dwNamePtrRVA;
DWORD dwOrdTableRVA;
};
void DumpEATEntries(void* GUICookie,
IMAGE_NT_HEADERS32 *pNTHeader32, IMAGE_OPTIONAL_HEADER32 *pOptHeader32,
IMAGE_NT_HEADERS64 *pNTHeader64, IMAGE_OPTIONAL_HEADER64 *pOptHeader64)
{
IMAGE_DATA_DIRECTORY *pExportDir = NULL;
IMAGE_SECTION_HEADER *pSecHdr = NULL;
DWORD i,j,N;
BOOL bpOpt = FALSE;
if (g_pPELoader->IsPE32())
{
pExportDir = pOptHeader32->DataDirectory;
pSecHdr = IMAGE_FIRST_SECTION(pNTHeader32);
N = VAL16(pNTHeader32->FileHeader.NumberOfSections);
if (pOptHeader32->NumberOfRvaAndSizes)
bpOpt = TRUE;
}
else
{
pExportDir = pOptHeader64->DataDirectory;
pSecHdr = IMAGE_FIRST_SECTION(pNTHeader64);
N = VAL16(pNTHeader64->FileHeader.NumberOfSections);
if (pOptHeader64->NumberOfRvaAndSizes)
bpOpt = TRUE;
}
if(bpOpt)
{
ExpDirTable *pExpTable = NULL;
if(pExportDir->Size)
{
#ifdef _DEBUG
printLine(GUICookie,COMMENT((char*)0)); // start multiline comment
sprintf_s(szString,SZSTRING_SIZE,"// Export dir VA=%X size=%X ",VAL32(pExportDir->VirtualAddress),VAL32(pExportDir->Size));
printLine(GUICookie,szString);
#endif
DWORD vaExpTable = VAL32(pExportDir->VirtualAddress);
for (i=0; i < N; i++,pSecHdr++)
{
if((vaExpTable >= VAL32(pSecHdr->VirtualAddress))&&
(vaExpTable < VAL32(pSecHdr->VirtualAddress)+VAL32(pSecHdr->Misc.VirtualSize)))
{
pExpTable = (ExpDirTable*)( g_pPELoader->base()
+ VAL32(pSecHdr->PointerToRawData)
+ vaExpTable - VAL32(pSecHdr->VirtualAddress));
#ifdef _DEBUG
sprintf_s(szString,SZSTRING_SIZE,"// in section '%s': VA=%X Misc.VS=%X PRD=%X ",(char*)(pSecHdr->Name),
VAL32(pSecHdr->VirtualAddress),VAL32(pSecHdr->Misc.VirtualSize),VAL32(pSecHdr->PointerToRawData));
printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// Export Directory Table:"); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// dwFlags = %X",VAL32(pExpTable->dwFlags)); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// dwDateTime = %X",VAL32(pExpTable->dwDateTime)); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// wVMajor = %X",VAL16(pExpTable->wVMajor)); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// wVMinor = %X",VAL16(pExpTable->wVMinor)); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// dwNameRVA = %X",VAL32(pExpTable->dwNameRVA)); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// dwOrdinalBase = %X",VAL32(pExpTable->dwOrdinalBase)); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// dwNumATEntries = %X",VAL32(pExpTable->dwNumATEntries)); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// dwNumNamePtrs = %X",VAL32(pExpTable->dwNumNamePtrs)); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// dwAddrTableRVA = %X",VAL32(pExpTable->dwAddrTableRVA)); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// dwNamePtrRVA = %X",VAL32(pExpTable->dwNamePtrRVA)); printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"// dwOrdTableRVA = %X",VAL32(pExpTable->dwOrdTableRVA)); printLine(GUICookie,szString);
if(pExpTable->dwNameRVA)
{
char* szName;
if(g_pPELoader->getVAforRVA(VAL32(pExpTable->dwNameRVA), (void **) &szName))
sprintf_s(szString,SZSTRING_SIZE,"// DLL Name: '%s'",szName);
else
sprintf_s(szString,SZSTRING_SIZE,"// DLL Name: BAD RVA: 0x%8.8X",VAL32(pExpTable->dwNameRVA));
printLine(GUICookie,szString);
}
#endif
if(pExpTable->dwNumATEntries && pExpTable->dwAddrTableRVA)
{
DWORD* pExpAddr;
BYTE *pCont;
DWORD dwTokRVA;
mdToken* pTok;
g_pPELoader->getVAforRVA(VAL32(pExpTable->dwAddrTableRVA), (void **) &pExpAddr);
#ifdef _DEBUG
sprintf_s(szString,SZSTRING_SIZE,"// Export Address Table:"); printLine(GUICookie,szString);
#endif
g_nEATableRef = VAL32(pExpTable->dwNumATEntries);
if (g_prEATableRef == NULL)
{
g_prEATableRef = new DynamicArray<EATableRef>;
}
(*g_prEATableRef)[g_nEATableRef].tkTok = 0; // to avoid multiple reallocations of DynamicArray
for(j=0; j < VAL32(pExpTable->dwNumATEntries); j++,pExpAddr++)
{
g_pPELoader->getVAforRVA(VAL32(*pExpAddr), (void **) &pCont);
#ifdef _DEBUG
sprintf_s(szString,SZSTRING_SIZE,"// [%d]: RVA=%X VA=%p(",j,VAL32(*pExpAddr),pCont);
DumpByteArray(szString,pCont,16,GUICookie);
printLine(GUICookie,szString);
#endif
(*g_prEATableRef)[j].tkTok = 0;
if(g_pPELoader->IsPE32())
{
dwTokRVA = VAL32(*((DWORD*)(pCont+2))); // first two bytes - JumpIndirect (0x25FF)
dwTokRVA -= VAL32((DWORD)pOptHeader32->ImageBase);
}
else
{
ULONGLONG ullTokRVA;
if(pNTHeader64->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64)
ullTokRVA = VAL64(*((ULONGLONG*)(pCont+8)));
else
ullTokRVA = VAL64(*((ULONGLONG*)(pCont+2)));
dwTokRVA =(DWORD)(ullTokRVA - VAL64((DWORD)pOptHeader64->ImageBase));
}
if(g_pPELoader->getVAforRVA(dwTokRVA,(void**)&pTok))
(*g_prEATableRef)[j].tkTok = VAL32(*pTok);
(*g_prEATableRef)[j].pszName = NULL;
}
}
if(pExpTable->dwNumNamePtrs && pExpTable->dwNamePtrRVA && pExpTable->dwOrdTableRVA)
{
DWORD *pNamePtr;
WORD *pOrd;
char* szName;
g_pPELoader->getVAforRVA(VAL32(pExpTable->dwNamePtrRVA), (void **) &pNamePtr);
g_pPELoader->getVAforRVA(VAL32(pExpTable->dwOrdTableRVA), (void **) &pOrd);
#ifdef _DEBUG
sprintf_s(szString,SZSTRING_SIZE,"// Export Names:"); printLine(GUICookie,szString);
#endif
for(j=0; j < VAL32(pExpTable->dwNumATEntries); j++,pNamePtr++,pOrd++)
{
g_pPELoader->getVAforRVA(VAL32(*pNamePtr), (void **) &szName);
#ifdef _DEBUG
sprintf_s(szString,SZSTRING_SIZE,"// [%d]: NamePtr=%X Ord=%X Name='%s'",j,VAL32(*pNamePtr),*pOrd,szName);
printLine(GUICookie,szString);
#endif
(*g_prEATableRef)[VAL16(*pOrd)].pszName = szName;
}
}
g_nEATableBase = pExpTable->dwOrdinalBase;
break;
}
}
#ifdef _DEBUG
printLine(GUICookie,COMMENT((char*)-1)); // end multiline comment
#endif
}
}
}
// helper to avoid mixing of SEH and stack objects with destructors
void DumpEATEntriesWrapper(void* GUICookie,
IMAGE_NT_HEADERS32 *pNTHeader32, IMAGE_OPTIONAL_HEADER32 *pOptHeader32,
IMAGE_NT_HEADERS64 *pNTHeader64, IMAGE_OPTIONAL_HEADER64 *pOptHeader64)
{
PAL_CPP_TRY
{
DumpEATEntries(GUICookie, pNTHeader32, pOptHeader32, pNTHeader64, pOptHeader64);
}
PAL_CPP_CATCH_ALL
{
printError(GUICookie,"// ERROR READING EXPORT ADDRESS TABLE");
if (g_prEATableRef != NULL)
{
SDELETE(g_prEATableRef);
}
g_nEATableRef = 0;
}
PAL_CPP_ENDTRY
}
void DumpVtable(void* GUICookie)
{
// VTable : primary processing
DWORD pVTable=0;
VTableEntry* pVTE;
DWORD i,j,k;
char* szptr;
IMAGE_NT_HEADERS32 *pNTHeader32 = NULL;
IMAGE_OPTIONAL_HEADER32 *pOptHeader32 = NULL;
IMAGE_NT_HEADERS64 *pNTHeader64 = NULL;
IMAGE_OPTIONAL_HEADER64 *pOptHeader64 = NULL;
if (g_pPELoader->IsPE32())
{
pNTHeader32 = g_pPELoader->ntHeaders32();
pOptHeader32 = &pNTHeader32->OptionalHeader;
sprintf_s(szString,SZSTRING_SIZE,"%s%s 0x%08x", g_szAsmCodeIndent,KEYWORD(".imagebase"),VAL32(pOptHeader32->ImageBase));
printLine(GUICookie,szString);
j = VAL16(pOptHeader32->Subsystem);
sprintf_s(szString,SZSTRING_SIZE,"%s%s 0x%08x", g_szAsmCodeIndent,KEYWORD(".file alignment"),VAL32(pOptHeader32->FileAlignment));
printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"%s%s 0x%08x", g_szAsmCodeIndent,KEYWORD(".stackreserve"),VAL32(pOptHeader32->SizeOfStackReserve));
printLine(GUICookie,szString);
}
else
{
pNTHeader64 = g_pPELoader->ntHeaders64();
pOptHeader64 = &pNTHeader64->OptionalHeader;
sprintf_s(szString,SZSTRING_SIZE,"%s%s 0x%016I64x", g_szAsmCodeIndent,KEYWORD(".imagebase"),VAL64(pOptHeader64->ImageBase));
printLine(GUICookie,szString);
j = VAL16(pOptHeader64->Subsystem);
sprintf_s(szString,SZSTRING_SIZE,"%s%s 0x%08x", g_szAsmCodeIndent,KEYWORD(".file alignment"),VAL32(pOptHeader64->FileAlignment));
printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"%s%s 0x%016I64x", g_szAsmCodeIndent,KEYWORD(".stackreserve"),VAL64(pOptHeader64->SizeOfStackReserve));
printLine(GUICookie,szString);
}
szptr = &szString[0];
szptr += sprintf_s(szString,SZSTRING_SIZE,"%s%s 0x%04x", g_szAsmCodeIndent,KEYWORD(".subsystem"),j);
{
const char* psz[15] = {"// UNKNOWN",
"// NATIVE",
"// WINDOWS_GUI",
"// WINDOWS_CUI",
"// <illegal value>",
"// OS2_CUI",
"// <illegal value>",
"// POSIX_CUI",
"// NATIVE_WINDOWS",
"// WINDOWS_CE_GUI",
"// EFI_APPLICATION",
"// EFI_BOOT_SERVICE_DRIVER",
"// EFI_RUNTIME_DRIVER",
"// EFI_ROM",
"// XBOX"
};
if(j > 14) j = 4; // <illegal value>
sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," %s",COMMENT(psz[j]));
}
printLine(GUICookie,szString);
szptr = &szString[0];
i = (DWORD)VAL32(g_CORHeader->Flags);
szptr += sprintf_s(szString,SZSTRING_SIZE,"%s%s 0x%08x", g_szAsmCodeIndent,KEYWORD(".corflags"),i);
if(i != 0)
{
char sz[256], *szp = sz;
szp += sprintf_s(szp,256," // ");
if(i & COMIMAGE_FLAGS_ILONLY) szp += sprintf_s(szp,256-(szp-sz)," ILONLY");
if(COR_IS_32BIT_REQUIRED(i))
szp += sprintf_s(szp,256-(szp-sz)," 32BITREQUIRED");
if(COR_IS_32BIT_PREFERRED(i))
szp += sprintf_s(szp,256-(szp-sz)," 32BITPREFERRED");
if(i & COMIMAGE_FLAGS_IL_LIBRARY) szp += sprintf_s(szp,256-(szp-sz)," IL_LIBRARY");
if(i & COMIMAGE_FLAGS_TRACKDEBUGDATA) szp += sprintf_s(szp,256-(szp-sz)," TRACKDEBUGDATA");
szptr += sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT(sz));
}
printLine(GUICookie,szString);
sprintf_s(szString,SZSTRING_SIZE,"%s// Image base: 0x%p",g_szAsmCodeIndent,g_pPELoader->base());
printLine(GUICookie,COMMENT(szString));
DumpEATEntriesWrapper(GUICookie, pNTHeader32, pOptHeader32, pNTHeader64, pOptHeader64);
g_nVTableRef = 0;
if(VAL32(g_CORHeader->VTableFixups.Size))
{
IMAGE_SECTION_HEADER *pSecHdr = NULL;
DWORD dwNumberOfSections;
if (g_pPELoader->IsPE32())
{
pSecHdr = IMAGE_FIRST_SECTION(g_pPELoader->ntHeaders32());
dwNumberOfSections = VAL16(g_pPELoader->ntHeaders32()->FileHeader.NumberOfSections);
}
else
{
pSecHdr = IMAGE_FIRST_SECTION(g_pPELoader->ntHeaders64());
dwNumberOfSections = VAL16(g_pPELoader->ntHeaders64()->FileHeader.NumberOfSections);
}
pVTable = VAL32(g_CORHeader->VTableFixups.VirtualAddress);
for (i=0; i < dwNumberOfSections; i++,pSecHdr++)
{
if(((DWORD)pVTable >= VAL32(pSecHdr->VirtualAddress))&&
((DWORD)pVTable < VAL32(pSecHdr->VirtualAddress)+VAL32(pSecHdr->Misc.VirtualSize)))
{
pVTE = (VTableEntry*)( g_pPELoader->base()
+ VAL32(pSecHdr->PointerToRawData)
+ pVTable - VAL32(pSecHdr->VirtualAddress));
for(j=VAL32(g_CORHeader->VTableFixups.Size),k=0; j > 0; pVTE++, j-=sizeof(VTableEntry),k++)
{
szptr = &szString[0];
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s [%d] ",g_szAsmCodeIndent,KEYWORD(".vtfixup"),VAL16(pVTE->wCount));
DWORD dwSize = VAL16(pVTE->wCount) * 4;
WORD wType = VAL16(pVTE->wType);
if(wType & COR_VTABLE_32BIT)
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("int32 "));
else if(wType & COR_VTABLE_64BIT)
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("int64 "));
dwSize <<= 1;
}
if(wType & COR_VTABLE_FROM_UNMANAGED)
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("fromunmanaged "));
if(wType & COR_VTABLE_CALL_MOST_DERIVED)
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("callmostderived "));
if(wType & 0x8 /*COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN*/)
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("retainappdomain "));
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("at "));
szptr = DumpDataPtr(szptr,VAL32(pVTE->dwAddr), dwSize);
// Walk every v-table fixup entry and dump the slots.
{
BYTE *pSlot;
if (g_pPELoader->getVAforRVA(VAL32(pVTE->dwAddr), (void **) &pSlot))
{
char* szptr0 = szptr;
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," //");
for (WORD iSlot=0; iSlot<VAL16(pVTE->wCount); iSlot++)
{
mdMethodDef tkMethod = VAL32(*(DWORD *) pSlot);
if (VAL16(pVTE->wType) & COR_VTABLE_32BIT)
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," %08X", VAL32(*(DWORD *)pSlot));
pSlot += sizeof(DWORD);
}
else
{
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," %016I64X", VAL64(*(unsigned __int64 *)pSlot));
pSlot += sizeof(unsigned __int64);
}
if (g_prVTableRef == NULL)
{
g_prVTableRef = new DynamicArray<VTableRef>;
}
(*g_prVTableRef)[g_nVTableRef].tkTok = tkMethod;
(*g_prVTableRef)[g_nVTableRef].wEntry = (WORD)k;
(*g_prVTableRef)[g_nVTableRef].wSlot = iSlot;
g_nVTableRef++;
//ValidateToken(tkMethod, mdtMethodDef);
}
sprintf_s(szptr0,SZSTRING_REMAINING_SIZE(szptr0),COMMENT(szptr0));
}
else
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr)," %s",ERRORMSG(RstrUTF(IDS_E_BOGUSRVA)));
}
printLine(GUICookie,szString);
}
break;
}
}
}
}
// MetaInfo integration:
void DumpMI(__in __nullterminated const char *str)
{
static BOOL fInit = TRUE;
static char* szStr = &szString[0];
static void* GUICookie;
char* pch;
// Reset
if(str == (char*)-1)
{
fInit = TRUE;
return;
}
// Init
if(fInit)
{
strcpy_s(szString,5,"// ");
fInit = FALSE;
GUICookie = (void*)str;
return;
}
// Normal work
strcat_s(szString,SZSTRING_SIZE,str);
if((pch = strchr(szStr,'\n')))
{
*pch = 0;
printLine(GUICookie,szStr);
pch++;
memcpy(&szString[3], pch, strlen(pch)+1);
}
}
void DumpMetaInfo(__in __nullterminated const WCHAR* pwzFileName, __in_opt __nullterminated const char* pszObjFileName, void* GUICookie)
{
const WCHAR* pch = wcsrchr(pwzFileName,L'.');
DumpMI((char*)GUICookie); // initialize the print function for DumpMetaInfo
if(pch && (!_wcsicmp(pch+1,W("lib")) || !_wcsicmp(pch+1,W("obj"))))
{ // This works only when all the rest does not
// Init and run.
if (MetaDataGetDispenser(CLSID_CorMetaDataDispenser,
IID_IMetaDataDispenserEx, (void **)&g_pDisp))
{
WCHAR *pwzObjFileName=NULL;
if (pszObjFileName)
{
int nLength = (int) strlen(pszObjFileName)+1;
pwzObjFileName = new WCHAR[nLength];
memset(pwzObjFileName,0,sizeof(WCHAR)*nLength);
WszMultiByteToWideChar(CP_UTF8,0,pszObjFileName,-1,pwzObjFileName,nLength);
}
DisplayFile((WCHAR*)pwzFileName, true, g_ulMetaInfoFilter, pwzObjFileName, DumpMI);
g_pDisp->Release();
g_pDisp = NULL;
if (pwzObjFileName) VDELETE(pwzObjFileName);
}
}
else
{
HRESULT hr = S_OK;
if(g_pDisp == NULL)
{
hr = MetaDataGetDispenser(CLSID_CorMetaDataDispenser,
IID_IMetaDataDispenserEx, (void **)&g_pDisp);
}
if(SUCCEEDED(hr))
{
g_ValModuleType = ValidatorModuleTypePE;
if(g_pAssemblyImport==NULL) g_pAssemblyImport = GetAssemblyImport(NULL);
printLine(GUICookie,RstrUTF(IDS_E_MISTART));
//MDInfo metaDataInfo(g_pPubImport, g_pAssemblyImport, (LPCWSTR)pwzFileName, DumpMI, g_ulMetaInfoFilter);
MDInfo metaDataInfo(g_pDisp,(LPCWSTR)pwzFileName, DumpMI, g_ulMetaInfoFilter);
metaDataInfo.DisplayMD();
printLine(GUICookie,RstrUTF(IDS_E_MIEND));
}
}
DumpMI((char*)-1); // reset the print function for DumpMetaInfo
}
void DumpPreamble()
{
printLine(g_pFile,"");
if(g_fDumpHTML)
{
printLine(g_pFile, "<FONT SIZE=4><B>");
}
else if(g_fDumpRTF)
{
}
sprintf_s(szString,SZSTRING_SIZE,"// Microsoft (R) .NET Framework IL Disassembler. Version " VER_FILEVERSION_STR);
printLine(g_pFile,COMMENT(szString));
if(g_fDumpHTML)
{
printLine(g_pFile, "</B></FONT>");
}
else if(g_fDumpRTF)
{
}
printLine(g_pFile,"");
if(g_fLimitedVisibility || (!g_fShowCA) || (!g_fDumpAsmCode)
|| (g_Mode & (MODE_DUMP_CLASS | MODE_DUMP_CLASS_METHOD | MODE_DUMP_CLASS_METHOD_SIG)))
{
printLine(g_pFile,"");
printLine(g_pFile,COMMENT(RstrUTF(IDS_E_PARTDASM)));
printLine(g_pFile,"");
}
if(g_fLimitedVisibility)
{
strcpy_s(szString, SZSTRING_SIZE, RstrUTF(IDS_E_ONLYITEMS));
if(!g_fHidePub) strcat_s(szString, SZSTRING_SIZE," Public");
if(!g_fHidePriv) strcat_s(szString, SZSTRING_SIZE," Private");
if(!g_fHideFam) strcat_s(szString, SZSTRING_SIZE," Family");
if(!g_fHideAsm) strcat_s(szString, SZSTRING_SIZE," Assembly");
if(!g_fHideFAA) strcat_s(szString, SZSTRING_SIZE," FamilyANDAssembly");
if(!g_fHidePrivScope) strcat_s(szString, SZSTRING_SIZE," PrivateScope");
printLine(g_pFile,COMMENT(szString));
}
}
void DumpSummary()
{
ULONG i;
const char *pcClass,*pcNS,*pcMember, *pcSig;
char szFQN[4096];
HENUMInternal hEnum;
mdToken tkMember;
CQuickBytes qbMemberSig;
PCCOR_SIGNATURE pComSig;
ULONG cComSig;
DWORD dwAttrs;
mdToken tkEventType;
printLine(g_pFile,"//============ S U M M A R Y =================================");
if (SUCCEEDED(g_pImport->EnumGlobalFunctionsInit(&hEnum)))
{
while(g_pImport->EnumNext(&hEnum, &tkMember))
{
if (FAILED(g_pImport->GetNameOfMethodDef(tkMember, &pcMember)) ||
FAILED(g_pImport->GetSigOfMethodDef(tkMember, &cComSig, &pComSig)))
{
sprintf_s(szString, SZSTRING_SIZE, "// ERROR in the method record %08X", tkMember);
printLine(g_pFile, szString);
continue;
}
qbMemberSig.Shrink(0);
pcSig = cComSig ? PrettyPrintSig(pComSig, cComSig, "", &qbMemberSig, g_pImport,NULL) : "NO SIGNATURE";
PREFIX_ASSUME(ProperName((char*)pcMember) != 0);
sprintf_s(szString,SZSTRING_SIZE,"// %08X [GLM] %s : %s", tkMember,ProperName((char*)pcMember),pcSig);
printLine(g_pFile,szString);
}
}
g_pImport->EnumClose(&hEnum);
if (SUCCEEDED(g_pImport->EnumGlobalFieldsInit(&hEnum)))
{
while(g_pImport->EnumNext(&hEnum, &tkMember))
{
if (FAILED(g_pImport->GetNameOfFieldDef(tkMember, &pcMember)) ||
FAILED(g_pImport->GetSigOfFieldDef(tkMember, &cComSig, &pComSig)))
{
sprintf_s(szString, SZSTRING_SIZE, "// ERROR in the field record %08X", tkMember);
printLine(g_pFile, szString);
continue;
}
qbMemberSig.Shrink(0);
pcSig = cComSig ? PrettyPrintSig(pComSig, cComSig, "", &qbMemberSig, g_pImport,NULL) : "NO SIGNATURE";
PREFIX_ASSUME(ProperName((char*)pcMember) != 0);
sprintf_s(szString,SZSTRING_SIZE,"// %08X [GLF] %s : %s", tkMember,ProperName((char*)pcMember),pcSig);
printLine(g_pFile,szString);
}
}
g_pImport->EnumClose(&hEnum);
for (i = 0; i < g_NumClasses; i++)
{
if (FAILED(g_pImport->GetNameOfTypeDef(g_cl_list[i], &pcClass, &pcNS)))
{
sprintf_s(szString, SZSTRING_SIZE, "// ERROR in the TypeDef record %08X", g_cl_list[i]);
printLine(g_pFile, szString);
continue;
}
PREFIX_ASSUME(ProperName((char*)pcClass) != 0);
if(*pcNS) sprintf_s(szFQN,4096,"%s.%s", ProperName((char*)pcNS),ProperName((char*)pcClass));
else strcpy_s(szFQN,4096,ProperName((char*)pcClass));
sprintf_s(szString,SZSTRING_SIZE,"// %08X [CLS] %s", g_cl_list[i],szFQN);
printLine(g_pFile,szString);
if(SUCCEEDED(g_pImport->EnumInit(mdtMethodDef, g_cl_list[i], &hEnum)))
{
while(g_pImport->EnumNext(&hEnum, &tkMember))
{
if (FAILED(g_pImport->GetNameOfMethodDef(tkMember, &pcMember)) ||
FAILED(g_pImport->GetSigOfMethodDef(tkMember, &cComSig, &pComSig)))
{
sprintf_s(szString, SZSTRING_SIZE, "// ERROR in the method record %08X", tkMember);
printLine(g_pFile, szString);
continue;
}
qbMemberSig.Shrink(0);
pcSig = cComSig ? PrettyPrintSig(pComSig, cComSig, "", &qbMemberSig, g_pImport,NULL) : "NO SIGNATURE";
PREFIX_ASSUME(ProperName((char*)pcMember) != 0);
sprintf_s(szString,SZSTRING_SIZE,"// %08X [MET] %s::%s : %s", tkMember,szFQN,ProperName((char*)pcMember),pcSig);
printLine(g_pFile,szString);
}
}
g_pImport->EnumClose(&hEnum);
if(SUCCEEDED(g_pImport->EnumInit(mdtFieldDef, g_cl_list[i], &hEnum)))
{
while(g_pImport->EnumNext(&hEnum, &tkMember))
{
if (FAILED(g_pImport->GetNameOfFieldDef(tkMember, &pcMember)) ||
FAILED(g_pImport->GetSigOfFieldDef(tkMember, &cComSig, &pComSig)))
{
sprintf_s(szString, SZSTRING_SIZE, "// ERROR in the field record %08X", tkMember);
printLine(g_pFile, szString);
continue;
}
qbMemberSig.Shrink(0);
pcSig = cComSig ? PrettyPrintSig(pComSig, cComSig, "", &qbMemberSig, g_pImport,NULL) : "NO SIGNATURE";
PREFIX_ASSUME(ProperName((char*)pcMember) != 0);
sprintf_s(szString,SZSTRING_SIZE,"// %08X [FLD] %s::%s : %s", tkMember,szFQN,ProperName((char*)pcMember),pcSig);
printLine(g_pFile,szString);
}
}
g_pImport->EnumClose(&hEnum);
if(SUCCEEDED(g_pImport->EnumInit(mdtEvent, g_cl_list[i], &hEnum)))
{
while(g_pImport->EnumNext(&hEnum, &tkMember))
{
if (FAILED(g_pImport->GetEventProps(tkMember,&pcMember,&dwAttrs,&tkEventType)))
{
sprintf_s(szString, SZSTRING_SIZE, "// Invalid Event %08X record", tkMember);
printLine(g_pFile, szString);
continue;
}
qbMemberSig.Shrink(0);
pcSig = "NO TYPE";
if(RidFromToken(tkEventType))
{
switch(TypeFromToken(tkEventType))
{
case mdtTypeRef:
case mdtTypeDef:
case mdtTypeSpec:
pcSig = PrettyPrintClass(&qbMemberSig,tkEventType,g_pImport);
break;
default:
break;
}
}
PREFIX_ASSUME(ProperName((char*)pcMember) != 0);
sprintf_s(szString,SZSTRING_SIZE,"// %08X [EVT] %s::%s : %s", tkMember,szFQN,ProperName((char*)pcMember),pcSig);
printLine(g_pFile,szString);
}
}
g_pImport->EnumClose(&hEnum);
if(SUCCEEDED(g_pImport->EnumInit(mdtProperty, g_cl_list[i], &hEnum)))
{
while(g_pImport->EnumNext(&hEnum, &tkMember))
{
if (FAILED(g_pImport->GetPropertyProps(tkMember,&pcMember,&dwAttrs,&pComSig,&cComSig)))
{
sprintf_s(szString, SZSTRING_SIZE, "// Invalid Property %08X record", tkMember);
printLine(g_pFile, szString);
continue;
}
qbMemberSig.Shrink(0);
pcSig = cComSig ? PrettyPrintSig(pComSig, cComSig, "", &qbMemberSig, g_pImport,NULL) : "NO SIGNATURE";
PREFIX_ASSUME(ProperName((char*)pcMember) != 0);
sprintf_s(szString,SZSTRING_SIZE,"// %08X [PRO] %s::%s : %s", tkMember,szFQN,ProperName((char*)pcMember),pcSig);
printLine(g_pFile,szString);
}
}
g_pImport->EnumClose(&hEnum);
}
printLine(g_pFile,"//=============== END SUMMARY ==================================");
}
void DumpRTFPrefix(void* GUICookie,BOOL fFontDefault)
{
g_fDumpRTF = FALSE;
printLine(GUICookie,"{\\rtf1\\ansi");
if(fFontDefault)
printLine(GUICookie,"{\\fonttbl{\\f0\\fmodern\\fprq1\\fcharset1 Courier New;}{\\f1\\fswiss\\fcharset1 Arial;}}");
printLine(GUICookie,"{\\colortbl ;\\red0\\green0\\blue128;\\red0\\green128\\blue0;\\red255\\green0\\blue0;}");
printLine(GUICookie,"\\viewkind4\\uc1\\pard\\f0\\fs20");
g_fDumpRTF = TRUE;
}
void DumpRTFPostfix(void* GUICookie)
{
g_fDumpRTF = FALSE;
printLine(GUICookie,"}");
g_fDumpRTF = TRUE;
}
mdToken ClassOf(mdToken tok)
{
mdToken retval=0;
switch(TypeFromToken(tok))
{
case mdtTypeDef:
case mdtTypeRef:
case mdtTypeSpec:
retval = tok;
break;
case mdtFieldDef:
case mdtMethodDef:
case mdtMemberRef:
if (FAILED(g_pImport->GetParentToken(tok, &retval)))
{
retval = mdTokenNil;
}
else
{
retval = ClassOf(retval);
}
break;
default:
break;
}
return retval;
}
void DumpRefs(BOOL fClassesOnly)
{
CQuickBytes out;
DynamicArray<TokPair> *refs = g_refs;
TokPair *newrefs = NULL;
mdToken tkThisUser,tkThisRef;
mdToken tkLastUser = 0xFFFFFFFF, tkLastRef=0xFFFFFFFF;
DWORD i=0,j=0;
g_refs = NULL;
printLine(g_pFile,COMMENT((char*)0));
printLine(g_pFile,"//============ R E F E R E N C E S ===========================");
strcpy_s(g_szAsmCodeIndent,MAX_MEMBER_LENGTH,"// ");
if(fClassesOnly && g_NumRefs)
{
if((newrefs = new TokPair[g_NumRefs]))
{
for(i=0; i<g_NumRefs; i++)
{
newrefs[i].tkUser = tkThisUser = ClassOf((*refs)[i].tkUser);
newrefs[i].tkRef = tkThisRef = ClassOf((*refs)[i].tkRef);
if(!tkThisUser) continue;
if(!tkThisRef) continue;
if(tkThisUser == tkThisRef) continue;
for(j = 0; j<i; j++)
{
if((newrefs[j].tkUser==tkThisUser)&&(newrefs[j].tkRef==tkThisRef))
{
newrefs[i].tkRef = 0;
break;
}
}
}
}
else fClassesOnly = FALSE;
}
for(i = 0; i <g_NumRefs; i++)
{
if(fClassesOnly)
{
tkThisUser = newrefs[i].tkUser;
tkThisRef = newrefs[i].tkRef;
}
else
{
tkThisUser = (*refs)[i].tkUser;
tkThisRef = (*refs)[i].tkRef;
}
if(!tkThisUser) continue;
if(!tkThisRef) continue;
if(tkThisUser == tkThisRef) continue;
if((tkThisUser==tkLastUser)&&(tkThisRef==tkLastRef)) continue;
strcpy_s(szString, SZSTRING_SIZE,g_szAsmCodeIndent);
if(tkThisUser != tkLastUser)
{
PrettyPrintToken(szString, tkThisUser, g_pImport,g_pFile,0); //TypeDef,TypeRef,TypeSpec,MethodDef,FieldDef,MemberRef,MethodSpec,String
strcat_s(szString, SZSTRING_SIZE, " references ");
printLine(g_pFile,szString);
tkLastUser = tkThisUser;
}
strcpy_s(szString, SZSTRING_SIZE,g_szAsmCodeIndent);
strcat_s(szString, SZSTRING_SIZE," - ");
PrettyPrintToken(szString, tkThisRef, g_pImport,g_pFile,0); //TypeDef,TypeRef,TypeSpec,MethodDef,FieldDef,MemberRef,MethodSpec,String
printLine(g_pFile,szString);
tkLastRef = tkThisRef;
}
printLine(g_pFile,"//=============== END REFERENCES =============================");
printLine(g_pFile,COMMENT((char*)-1));
g_refs = refs;
if(newrefs) VDELETE(newrefs);
}
void CloseNamespace(__inout __nullterminated char* szString)
{
if(strlen(g_szNamespace))
{
char* szptr = &szString[0];
if(g_szAsmCodeIndent[0]) g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-2] = 0;
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s%s ",g_szAsmCodeIndent, UNSCOPE());
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),COMMENT("// end of namespace %s"),ProperName(g_szNamespace));
printLine(g_pFile,szString);
printLine(g_pFile,"");
g_szNamespace[0] = 0;
}
}
FILE* OpenOutput(__in __nullterminated const WCHAR* wzFileName)
{
FILE* pfile = NULL;
if(g_uCodePage == 0xFFFFFFFF) _wfopen_s(&pfile,wzFileName,W("wb"));
else _wfopen_s(&pfile,wzFileName,W("wt"));
if(pfile)
{
if(g_uCodePage == CP_UTF8) fwrite("\357\273\277",3,1,pfile);
else if(g_uCodePage == 0xFFFFFFFF) fwrite("\377\376",2,1,pfile);
}
return pfile;
}
FILE* OpenOutput(__in __nullterminated const char* szFileName)
{
return OpenOutput(UtfToUnicode(szFileName));
}
//
// Init PELoader, dump file header info
//
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
BOOL DumpFile()
{
BOOL fSuccess = FALSE;
static WCHAR wzInputFileName[MAX_FILENAME_LENGTH];
static char szFilenameANSI[MAX_FILENAME_LENGTH*3];
IMetaDataDispenser *pMetaDataDispenser = NULL;
const char *pszFilename = g_szInputFile;
const DWORD openFlags = ofRead | (g_fProject ? 0 : ofNoTransform);
{
if(g_fDumpHTML)
{
printLine(g_pFile, "<HTML>");
printLine(g_pFile, "<HEAD>");
sprintf_s(szString,SZSTRING_SIZE,"<TITLE> %s - IL DASM</TITLE>",g_szInputFile);
printLine(g_pFile, szString);
printLine(g_pFile, "</HEAD>");
printLine(g_pFile, "<BODY>");
printLine(g_pFile, "<FONT SIZE=3 FACE=\"Arial\">");
printLine(g_pFile, "<PRE>");
}
else if(g_fDumpRTF)
{
DumpRTFPrefix(g_pFile,TRUE);
}
DumpPreamble();
}
{
char* pch = strrchr(g_szInputFile,'.');
if(pch && (!_stricmp(pch+1,"lib") || !_stricmp(pch+1,"obj")))
{
DumpMetaInfo(g_wszFullInputFile,g_pszObjFileName,g_pFile);
return FALSE;
}
}
if(g_pPELoader) goto DoneInitialization; // skip initialization, it's already done
g_pPELoader = new PELoader();
if (g_pPELoader == NULL)
{
printError(g_pFile,RstrUTF(IDS_E_INITLDR));
goto exit;
}
memset(wzInputFileName,0,sizeof(WCHAR)*MAX_FILENAME_LENGTH);
WszMultiByteToWideChar(CP_UTF8,0,pszFilename,-1,wzInputFileName,MAX_FILENAME_LENGTH);
memset(szFilenameANSI,0,MAX_FILENAME_LENGTH*3);
WszWideCharToMultiByte(g_uConsoleCP,0,wzInputFileName,-1,szFilenameANSI,MAX_FILENAME_LENGTH*3,NULL,NULL);
fSuccess = g_pPELoader->open(wzInputFileName);
if (fSuccess == FALSE)
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_FILEOPEN), pszFilename);
printError(g_pFile,szString);
SDELETE(g_pPELoader);
g_pPELoader = NULL;
goto exit;
}
fSuccess = FALSE;
if (g_pPELoader->getCOMHeader(&g_CORHeader) == FALSE)
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_NOCORHDR), pszFilename);
printError(g_pFile,szString);
if (g_fDumpHeader)
DumpHeader(g_CORHeader,g_pFile);
goto exit;
}
if (VAL16(g_CORHeader->MajorRuntimeVersion) == 1 || VAL16(g_CORHeader->MajorRuntimeVersion) > COR_VERSION_MAJOR)
{
sprintf_s(szString,SZSTRING_SIZE,"CORHeader->MajorRuntimeVersion = %d",VAL16(g_CORHeader->MajorRuntimeVersion));
printError(g_pFile,szString);
printError(g_pFile,RstrUTF(IDS_E_BADCORHDR));
goto exit;
}
g_tkEntryPoint = VAL32(IMAGE_COR20_HEADER_FIELD(*g_CORHeader, EntryPointToken)); // integration with MetaInfo
#if defined(_DEBUG) && defined(FEATURE_PREJIT)
if (g_fNGenNativeMetadata)
{
//if this is an ngen image, use the native metadata.
if( !g_CORHeader->ManagedNativeHeader.Size )
{
printError( g_pFile, "/native only works on NGen images." );
goto exit;
}
CORCOMPILE_HEADER * pNativeHeader;
g_pPELoader->getVAforRVA(VAL32(g_CORHeader->ManagedNativeHeader.VirtualAddress), (void**)&pNativeHeader);
if (pNativeHeader->Signature != CORCOMPILE_SIGNATURE)
{
printError( g_pFile, "/native only works on NGen images." );
goto exit;
}
g_pPELoader->getVAforRVA(VAL32(pNativeHeader->ManifestMetaData.VirtualAddress), &g_pMetaData);
g_cbMetaData = VAL32(pNativeHeader->ManifestMetaData.Size);
}
else
#endif
{
if (g_pPELoader->getVAforRVA(VAL32(g_CORHeader->MetaData.VirtualAddress),&g_pMetaData) == FALSE)
{
printError(g_pFile, RstrUTF(IDS_E_OPENMD));
if (g_fDumpHeader)
DumpHeader(g_CORHeader, g_pFile);
goto exit;
}
g_cbMetaData = VAL32(g_CORHeader->MetaData.Size);
}
if (FAILED(GetMetaDataInternalInterface(
(BYTE *)g_pMetaData,
g_cbMetaData,
openFlags,
IID_IMDInternalImport,
(LPVOID *)&g_pImport)))
{
if (g_fDumpHeader)
DumpHeader(g_CORHeader, g_pFile);
printError(g_pFile, RstrUTF(IDS_E_OPENMD));
goto exit;
}
TokenSigInit(g_pImport);
if (FAILED(MetaDataGetDispenser(CLSID_CorMetaDataDispenser, IID_IMetaDataDispenser, (LPVOID*)&pMetaDataDispenser)))
{
if (g_fDumpHeader)
DumpHeader(g_CORHeader, g_pFile);
printError(g_pFile, RstrUTF(IDS_E_OPENMD));
goto exit;
}
if (FAILED(pMetaDataDispenser->OpenScopeOnMemory(g_pMetaData, g_cbMetaData, openFlags, IID_IMetaDataImport2, (LPUNKNOWN *)&g_pPubImport )))
{
if (g_fDumpHeader)
DumpHeader(g_CORHeader, g_pFile);
printError(g_pFile, RstrUTF(IDS_E_OPENMD));
goto exit;
}
if((g_uNCA = g_pImport->GetCountWithTokenKind(mdtCustomAttribute)))
{
g_rchCA = new char[g_uNCA+1];
_ASSERTE(g_rchCA);
}
EnumClasses();
EnumTypedefs();
DoneInitialization:
if(g_uNCA)
{
_ASSERTE(g_rchCA);
memset(g_rchCA,0,g_uNCA+1);
}
#ifndef _DEBUG
if(HasSuppressingAttribute())
{
if (g_fDumpHeader)
DumpHeader(g_CORHeader,g_pFile);
if(g_fDumpMetaInfo)
DumpMetaInfo(g_wszFullInputFile,NULL,g_pFile);
printError(g_pFile,RstrUTF(IDS_E_SUPPRESSED));
goto CloseFileAndExit;
}
#endif
{
// Dump the CLR header info if requested.
printLine(g_pFile,COMMENT((char*)0)); // start multiline comment
if (g_fDumpHeader)
{
DumpHeader(g_CORHeader,g_pFile);
DumpHeaderDetails(g_CORHeader,g_pFile);
}
else
DumpVTables(g_CORHeader,g_pFile);
if (g_fDumpStats)
DumpStatistics(g_CORHeader,g_pFile);
if(g_fDumpClassList) PrintClassList();
// MetaInfo integration:
if(g_fDumpMetaInfo) DumpMetaInfo(g_wszFullInputFile,NULL,g_pFile);
if(g_fDumpSummary) DumpSummary();
printLine(g_pFile,COMMENT((char*)-1)); // end multiline comment
if(g_fShowRefs) g_refs = new DynamicArray<TokPair>;
if (g_fDumpAsmCode)
{
g_szNamespace[0] = 0;
if(g_tkClassToDump) //g_tkClassToDump is set in EnumClasses
{
DumpClass(TopEncloser(g_tkClassToDump), VAL32(IMAGE_COR20_HEADER_FIELD(*g_CORHeader, EntryPointToken)),g_pFile,7); //7-dump everything at once
CloseNamespace(szString);
goto ReportAndExit;
}
{
HENUMInternal hEnumMethod;
ULONG ulNumGlobalFunc=0;
if (SUCCEEDED(g_pImport->EnumGlobalFunctionsInit(&hEnumMethod)))
{
ulNumGlobalFunc = g_pImport->EnumGetCount(&hEnumMethod);
g_pImport->EnumClose(&hEnumMethod);
}
}
//DumpVtable(g_pFile);
DumpMscorlib(g_pFile);
if(g_fDumpTypeList) DumpTypelist(g_pFile);
DumpManifest(g_pFile);
DumpTypedefs(g_pFile);
/* First dump the classes w/o members*/
if(g_fForwardDecl && g_NumClasses)
{
printLine(g_pFile,COMMENT("//"));
printLine(g_pFile,COMMENT("// ============== CLASS STRUCTURE DECLARATION =================="));
printLine(g_pFile,COMMENT("//"));
for (DWORD i = 0; i < g_NumClasses; i++)
{
if(g_cl_enclosing[i] == mdTypeDefNil) // nested classes are dumped within enclosing ones
{
DumpClass(g_cl_list[i], VAL32(IMAGE_COR20_HEADER_FIELD(*g_CORHeader, EntryPointToken)),g_pFile,2); // 2=header+nested classes
}
}
CloseNamespace(szString);
printLine(g_pFile,"");
printLine(g_pFile,COMMENT("// ============================================================="));
printLine(g_pFile,"");
}
/* Second, dump the global fields and methods */
DumpGlobalFields();
DumpGlobalMethods(VAL32(IMAGE_COR20_HEADER_FIELD(*g_CORHeader, EntryPointToken)));
/* Third, dump the classes with members */
if(g_NumClasses)
{
printLine(g_pFile,"");
printLine(g_pFile,COMMENT("// =============== CLASS MEMBERS DECLARATION ==================="));
if(g_fForwardDecl)
{
printLine(g_pFile,COMMENT("// note that class flags, 'extends' and 'implements' clauses"));
printLine(g_pFile,COMMENT("// are provided here for information only"));
}
printLine(g_pFile,"");
for (DWORD i = 0; i < g_NumClasses; i++)
{
if(g_cl_enclosing[i] == mdTypeDefNil) // nested classes are dumped within enclosing ones
{
DumpClass(g_cl_list[i], VAL32(IMAGE_COR20_HEADER_FIELD(*g_CORHeader, EntryPointToken)),g_pFile,7); //7=everything
}
}
CloseNamespace(szString);
printLine(g_pFile,"");
printLine(g_pFile,COMMENT("// ============================================================="));
printLine(g_pFile,"");
}
if(g_fShowCA)
{
if(g_uNCA) _ASSERTE(g_rchCA);
for(DWORD i=1; i<= g_uNCA; i++)
{
if(g_rchCA[i] == 0) DumpCustomAttribute(TokenFromRid(i,mdtCustomAttribute),g_pFile,true);
}
}
// If there were "ldptr", dump the .rdata section with labels
if(g_iPtrCount)
{
//first, sort the pointers
int i,j;
bool swapped;
do {
swapped = FALSE;
for(i = 1; i < g_iPtrCount; i++)
{
if((*g_pPtrTags)[i-1] > (*g_pPtrTags)[i])
{
j = (*g_pPtrTags)[i-1];
(*g_pPtrTags)[i-1] = (*g_pPtrTags)[i];
(*g_pPtrTags)[i] = j;
j = (*g_pPtrSize)[i-1];
(*g_pPtrSize)[i-1] = (*g_pPtrSize)[i];
(*g_pPtrSize)[i] = j;
swapped = TRUE;
}
}
} while(swapped);
//second, dump data for each ptr as binarray
IMAGE_SECTION_HEADER *pSecHdr = NULL;
if(g_pPELoader->IsPE32())
pSecHdr = IMAGE_FIRST_SECTION(g_pPELoader->ntHeaders32());
else
pSecHdr = IMAGE_FIRST_SECTION(g_pPELoader->ntHeaders64());
DWORD dwNumberOfSections;
if(g_pPELoader->IsPE32())
dwNumberOfSections = VAL16(g_pPELoader->ntHeaders32()->FileHeader.NumberOfSections);
else
dwNumberOfSections = VAL16(g_pPELoader->ntHeaders64()->FileHeader.NumberOfSections);
DWORD fromPtr,toPtr,limPtr;
char* szptr;
for(j = 0; j < g_iPtrCount; j++)
{
BYTE *pb;
fromPtr = (*g_pPtrTags)[j];
for (i=0; i < (int)dwNumberOfSections; i++,pSecHdr++)
{
if((fromPtr >= VAL32(pSecHdr->VirtualAddress))&&
(fromPtr < VAL32(pSecHdr->VirtualAddress)+VAL32(pSecHdr->Misc.VirtualSize))) break;
}
if(i == (int)dwNumberOfSections)
{
sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_ROGUEPTR), fromPtr);
printLine(g_pFile,szString);
break;
}
// OK, now we have the section; what about end of BLOB?
const char* szTls = "D_";
if(strcmp((char*)(pSecHdr->Name),".tls")==0) szTls = "T_";
else if(strcmp((char*)(pSecHdr->Name),".text")==0) szTls = "I_";
if(j == g_iPtrCount-1)
{
toPtr = VAL32(pSecHdr->VirtualAddress)+VAL32(pSecHdr->Misc.VirtualSize);
}
else
{
toPtr = (*g_pPtrTags)[j+1];
if(toPtr > VAL32(pSecHdr->VirtualAddress)+VAL32(pSecHdr->Misc.VirtualSize))
{
toPtr = VAL32(pSecHdr->VirtualAddress)+VAL32(pSecHdr->Misc.VirtualSize);
}
}
if(toPtr - fromPtr > (*g_pPtrSize)[j]) toPtr = fromPtr + (*g_pPtrSize)[j];
limPtr = toPtr; // at limPtr and after, pad with 0
if(limPtr > VAL32(pSecHdr->VirtualAddress)+VAL32(pSecHdr->SizeOfRawData))
limPtr = VAL32(pSecHdr->VirtualAddress)+VAL32(pSecHdr->SizeOfRawData);
PrintBlob:
szptr = szString;
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s%s ",g_szAsmCodeIndent,KEYWORD(".data"));
if(*szTls=='T') szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("tls "));
else if(*szTls=='I') szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),KEYWORD("cil "));
if(fromPtr >= limPtr)
{ // uninitialized data
sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s%8.8X = %s[%d]",szTls,fromPtr,KEYWORD("int8"),toPtr-fromPtr);
printLine(g_pFile,szString);
}
else
{ // initialized data
szptr+=sprintf_s(szptr,SZSTRING_REMAINING_SIZE(szptr),"%s%8.8X = %s (",szTls,fromPtr,KEYWORD("bytearray"));
printLine(g_pFile,szString);
szptr = szString;
szptr+=sprintf_s(szptr,SZSTRING_SIZE,"%s ",g_szAsmCodeIndent);
pb = g_pPELoader->base()
+ VAL32(pSecHdr->PointerToRawData)
+ fromPtr - VAL32(pSecHdr->VirtualAddress);
// now fromPtr is the beginning of the BLOB, and toPtr is [exclusive] end of it
DumpHexbytes(szptr, pb, fromPtr, toPtr, limPtr);
}
// to preserve alignment, dump filler if any
if(limPtr == toPtr) // don't need filler if it's the last item in section
{
if((j < g_iPtrCount-1)&&(toPtr < (DWORD)((*g_pPtrTags)[j+1])))
{
DWORD align;
DWORD stptr = (DWORD)(*g_pPtrTags)[j+1];
for(align = 1; (align & stptr)==0; align = align << 1);
align -= 1;
if(toPtr & align)
{
fromPtr = toPtr;
toPtr = (toPtr + align)&~align;
goto PrintBlob;
}
}
}
}
}
ReportAndExit:
printLine(g_pFile,COMMENT(RstrUTF(IDS_E_DASMOK)));
fSuccess = TRUE;
}
fSuccess = TRUE;
#ifndef TARGET_UNIX
if(g_pFile) // dump .RES file (if any), if not to console
{
WCHAR wzResFileName[2048], *pwc;
memset(wzResFileName,0,sizeof(wzResFileName));
WszMultiByteToWideChar(CP_UTF8,0,g_szOutputFile,-1,wzResFileName,2048);
pwc = wcsrchr(wzResFileName,L'.');
if(pwc == NULL) pwc = &wzResFileName[wcslen(wzResFileName)];
wcscpy_s(pwc, 2048 - (pwc - wzResFileName), L".res");
DWORD ret = DumpResourceToFile(wzResFileName);
switch(ret)
{
case 0: szString[0] = 0; break;
case 1: sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_W_CREATEDW32RES)/*"// WARNING: Created Win32 resource file %ls"*/,
UnicodeToUtf(wzResFileName)); break;
case 0xDFFFFFFF: sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_CORRUPTW32RES)/*"// ERROR: Corrupt Win32 resources"*/); break;
case 0xEFFFFFFF: sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_CANTOPENW32RES)/*"// ERROR: Unable to open file %ls"*/,
UnicodeToUtf(wzResFileName)); break;
case 0xFFFFFFFF: sprintf_s(szString,SZSTRING_SIZE,RstrUTF(IDS_E_CANTACCESSW32RES)/*"// ERROR: Unable to access Win32 resources"*/); break;
}
if(szString[0])
{
if(ret == 1) printLine(g_pFile,COMMENT(szString));
else printError(g_pFile,szString);
}
}
#endif
if(g_fShowRefs) DumpRefs(TRUE);
if(g_fDumpHTML)
{
printLine(g_pFile, "</PRE>");
printLine(g_pFile, "</BODY>");
printLine(g_pFile, "</HTML>");
}
else if(g_fDumpRTF)
{
DumpRTFPostfix(g_pFile);
}
#ifndef _DEBUG
CloseFileAndExit:
#endif
if(g_pFile)
{
fclose(g_pFile);
g_pFile = NULL;
}
}
exit:
if (pMetaDataDispenser)
pMetaDataDispenser->Release();
return fSuccess;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
#ifdef _MSC_VER
#pragma warning(default : 4640)
#endif
|
// Copyright (C) 2005, 2006 The Trustees of Indiana University.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Authors: Douglas Gregor
// Andrew Lumsdaine
#define PBGL_ACCOUNTING
#include <boost/graph/use_mpi.hpp>
#include <boost/config.hpp>
#include <boost/throw_exception.hpp>
#include <boost/graph/distributed/delta_stepping_shortest_paths.hpp>
#include <boost/graph/distributed/mpi_process_group.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/graph/parallel/distribution.hpp>
#include <boost/graph/erdos_renyi_generator.hpp>
#include <boost/graph/distributed/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/random.hpp>
#include <boost/core/lightweight_test.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <iostream>
#include <iomanip>
#ifdef BOOST_NO_EXCEPTIONS
void
boost::throw_exception(std::exception const& ex)
{
std::cout << ex.what() << std::endl;
abort();
}
#endif
/****************************************************************************
* Timing *
****************************************************************************/
typedef double time_type;
inline time_type get_time()
{
return MPI_Wtime();
}
std::string print_time(time_type t)
{
std::ostringstream out;
out << std::setiosflags(std::ios::fixed) << std::setprecision(2) << t;
return out.str();
}
/****************************************************************************
* Edge weight generator iterator *
****************************************************************************/
template<typename F, typename RandomGenerator>
class generator_iterator
{
public:
typedef std::input_iterator_tag iterator_category;
typedef typename F::result_type value_type;
typedef const value_type& reference;
typedef const value_type* pointer;
typedef void difference_type;
explicit
generator_iterator(RandomGenerator& gen, const F& f = F())
: f(f), gen(&gen)
{
value = this->f(gen);
}
reference operator*() const { return value; }
pointer operator->() const { return &value; }
generator_iterator& operator++()
{
value = f(*gen);
return *this;
}
generator_iterator operator++(int)
{
generator_iterator temp(*this);
++(*this);
return temp;
}
bool operator==(const generator_iterator& other) const
{ return f == other.f; }
bool operator!=(const generator_iterator& other) const
{ return !(*this == other); }
private:
F f;
RandomGenerator* gen;
value_type value;
};
template<typename F, typename RandomGenerator>
inline generator_iterator<F, RandomGenerator>
make_generator_iterator( RandomGenerator& gen, const F& f)
{ return generator_iterator<F, RandomGenerator>(gen, f); }
/****************************************************************************
* Verification *
****************************************************************************/
template <typename Graph, typename DistanceMap, typename WeightMap>
void
verify_shortest_paths(const Graph& g, DistanceMap distance,
const WeightMap& weight) {
distance.set_max_ghost_cells(0);
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
get(distance, target(e, g));
}
}
synchronize(process_group(g));
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
assert(get(distance, target(e, g)) <=
get(distance, source(e, g)) + get(weight, e));
}
}
}
using namespace boost;
using boost::graph::distributed::mpi_process_group;
typedef int weight_type;
struct WeightedEdge {
WeightedEdge(weight_type weight = 0) : weight(weight) { }
weight_type weight;
template<typename Archiver>
void serialize(Archiver& ar, const unsigned int /*version*/)
{
ar & weight;
}
};
struct VertexProperties {
VertexProperties(int d = 0)
: distance(d) { }
int distance;
template<typename Archiver>
void serialize(Archiver& ar, const unsigned int /*version*/)
{
ar & distance;
}
};
void
test_distributed_shortest_paths(int n, double p, int c, int seed)
{
typedef adjacency_list<listS,
distributedS<mpi_process_group, vecS>,
undirectedS,
VertexProperties,
WeightedEdge> Graph;
typedef graph_traits<Graph>::vertices_size_type vertices_size_type;
// Build a random number generator
minstd_rand gen;
gen.seed(seed);
// Build a random graph
Graph g(erdos_renyi_iterator<minstd_rand, Graph>(gen, n, p),
erdos_renyi_iterator<minstd_rand, Graph>(),
make_generator_iterator(gen, uniform_int<int>(0, c)),
n);
uniform_int<vertices_size_type> rand_vertex(0, n);
graph::distributed::delta_stepping_shortest_paths(g,
vertex(rand_vertex(gen), g),
dummy_property_map(),
get(&VertexProperties::distance, g),
get(&WeightedEdge::weight, g));
verify_shortest_paths(g,
get(&VertexProperties::distance, g),
get(&WeightedEdge::weight, g));
}
int main(int argc, char* argv[])
{
mpi::environment env(argc, argv);
int n = 1000;
double p = 0.01;
int c = 100;
int seed = 1;
if (argc > 1) n = lexical_cast<int>(argv[1]);
if (argc > 2) p = lexical_cast<double>(argv[2]);
if (argc > 3) c = lexical_cast<int>(argv[3]);
if (argc > 4) seed = lexical_cast<int>(argv[4]);
test_distributed_shortest_paths(n, p, c, seed);
return boost::report_errors();
}
|
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#ifdef SPINE_UE4
#include "SpinePluginPrivatePCH.h"
#endif
#include "spine/SkeletonJson.h"
#include "spine/Atlas.h"
#include "spine/AtlasAttachmentLoader.h"
#include "spine/CurveTimeline.h"
#include "spine/Json.h"
#include "spine/LinkedMesh.h"
#include "spine/SkeletonData.h"
#include "spine/VertexAttachment.h"
#include "spine/AttachmentTimeline.h"
#include "spine/AttachmentType.h"
#include "spine/BoneData.h"
#include "spine/BoundingBoxAttachment.h"
#include "spine/ClippingAttachment.h"
#include "spine/ColorTimeline.h"
#include "spine/ContainerUtil.h"
#include "spine/DeformTimeline.h"
#include "spine/DrawOrderTimeline.h"
#include "spine/Event.h"
#include "spine/EventData.h"
#include "spine/EventTimeline.h"
#include "spine/IkConstraintData.h"
#include "spine/IkConstraintTimeline.h"
#include "spine/MeshAttachment.h"
#include "spine/PathAttachment.h"
#include "spine/PathConstraintData.h"
#include "spine/PathConstraintMixTimeline.h"
#include "spine/PathConstraintPositionTimeline.h"
#include "spine/PathConstraintSpacingTimeline.h"
#include "spine/PointAttachment.h"
#include "spine/RegionAttachment.h"
#include "spine/RotateTimeline.h"
#include "spine/ScaleTimeline.h"
#include "spine/ShearTimeline.h"
#include "spine/Skin.h"
#include "spine/SlotData.h"
#include "spine/TransformConstraintData.h"
#include "spine/TransformConstraintTimeline.h"
#include "spine/TranslateTimeline.h"
#include "spine/Vertices.h"
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
#define strdup _strdup
#endif
using namespace spine;
static float toColor(const char *value, size_t index) {
char digits[3];
char *error;
int color;
if (index >= strlen(value) / 2) return -1;
value += index * 2;
digits[0] = *value;
digits[1] = *(value + 1);
digits[2] = '\0';
color = (int) strtoul(digits, &error, 16);
if (*error != 0) return -1;
return color / (float) 255;
}
static void toColor(Color &color, const char *value, bool hasAlpha) {
color.r = toColor(value, 0);
color.g = toColor(value, 1);
color.b = toColor(value, 2);
if (hasAlpha) color.a = toColor(value, 3);
}
SkeletonJson::SkeletonJson(Atlas *atlas) : _attachmentLoader(new (__FILE__, __LINE__) AtlasAttachmentLoader(atlas)),
_scale(1), _ownsLoader(true) {}
SkeletonJson::SkeletonJson(AttachmentLoader *attachmentLoader, bool ownsLoader) : _attachmentLoader(attachmentLoader),
_scale(1),
_ownsLoader(ownsLoader) {
assert(_attachmentLoader != NULL);
}
SkeletonJson::~SkeletonJson() {
ContainerUtil::cleanUpVectorOfPointers(_linkedMeshes);
if (_ownsLoader) delete _attachmentLoader;
}
SkeletonData *SkeletonJson::readSkeletonDataFile(const String &path) {
int length;
SkeletonData *skeletonData;
const char *json = SpineExtension::readFile(path, &length);
if (length == 0 || !json) {
setError(NULL, "Unable to read skeleton file: ", path);
return NULL;
}
skeletonData = readSkeletonData(json);
SpineExtension::free(json, __FILE__, __LINE__);
return skeletonData;
}
SkeletonData *SkeletonJson::readSkeletonData(const char *json) {
int i, ii;
SkeletonData *skeletonData;
Json *root, *skeleton, *bones, *boneMap, *ik, *transform, *path, *slots, *skins, *animations, *events;
_error = "";
_linkedMeshes.clear();
root = new (__FILE__, __LINE__) Json(json);
if (!root) {
setError(NULL, "Invalid skeleton JSON: ", Json::getError());
return NULL;
}
skeletonData = new (__FILE__, __LINE__) SkeletonData();
skeleton = Json::getItem(root, "skeleton");
if (skeleton) {
skeletonData->_hash = Json::getString(skeleton, "hash", 0);
skeletonData->_version = Json::getString(skeleton, "spine", 0);
skeletonData->_x = Json::getFloat(skeleton, "x", 0);
skeletonData->_y = Json::getFloat(skeleton, "y", 0);
skeletonData->_width = Json::getFloat(skeleton, "width", 0);
skeletonData->_height = Json::getFloat(skeleton, "height", 0);
skeletonData->_fps = Json::getFloat(skeleton, "fps", 30);
skeletonData->_audioPath = Json::getString(skeleton, "audio", 0);
skeletonData->_imagesPath = Json::getString(skeleton, "images", 0);
}
/* Bones. */
bones = Json::getItem(root, "bones");
skeletonData->_bones.setSize(bones->_size, 0);
int bonesCount = 0;
for (boneMap = bones->_child, i = 0; boneMap; boneMap = boneMap->_next, ++i) {
BoneData *data;
const char *transformMode;
BoneData *parent = 0;
const char *parentName = Json::getString(boneMap, "parent", 0);
if (parentName) {
parent = skeletonData->findBone(parentName);
if (!parent) {
delete skeletonData;
setError(root, "Parent bone not found: ", parentName);
return NULL;
}
}
data = new (__FILE__, __LINE__) BoneData(bonesCount, Json::getString(boneMap, "name", 0), parent);
data->_length = Json::getFloat(boneMap, "length", 0) * _scale;
data->_x = Json::getFloat(boneMap, "x", 0) * _scale;
data->_y = Json::getFloat(boneMap, "y", 0) * _scale;
data->_rotation = Json::getFloat(boneMap, "rotation", 0);
data->_scaleX = Json::getFloat(boneMap, "scaleX", 1);
data->_scaleY = Json::getFloat(boneMap, "scaleY", 1);
data->_shearX = Json::getFloat(boneMap, "shearX", 0);
data->_shearY = Json::getFloat(boneMap, "shearY", 0);
transformMode = Json::getString(boneMap, "transform", "normal");
data->_transformMode = TransformMode_Normal;
if (strcmp(transformMode, "normal") == 0) data->_transformMode = TransformMode_Normal;
else if (strcmp(transformMode, "onlyTranslation") == 0)
data->_transformMode = TransformMode_OnlyTranslation;
else if (strcmp(transformMode, "noRotationOrReflection") == 0)
data->_transformMode = TransformMode_NoRotationOrReflection;
else if (strcmp(transformMode, "noScale") == 0)
data->_transformMode = TransformMode_NoScale;
else if (strcmp(transformMode, "noScaleOrReflection") == 0)
data->_transformMode = TransformMode_NoScaleOrReflection;
data->_skinRequired = Json::getBoolean(boneMap, "skin", false);
const char *color = Json::getString(boneMap, "color", NULL);
if (color) toColor(data->getColor(), color, true);
skeletonData->_bones[i] = data;
bonesCount++;
}
/* Slots. */
slots = Json::getItem(root, "slots");
if (slots) {
Json *slotMap;
skeletonData->_slots.ensureCapacity(slots->_size);
skeletonData->_slots.setSize(slots->_size, 0);
for (slotMap = slots->_child, i = 0; slotMap; slotMap = slotMap->_next, ++i) {
SlotData *data;
const char *color;
const char *dark;
Json *item;
const char *boneName = Json::getString(slotMap, "bone", 0);
BoneData *boneData = skeletonData->findBone(boneName);
if (!boneData) {
delete skeletonData;
setError(root, "Slot bone not found: ", boneName);
return NULL;
}
data = new (__FILE__, __LINE__) SlotData(i, Json::getString(slotMap, "name", 0), *boneData);
color = Json::getString(slotMap, "color", 0);
if (color) {
Color &c = data->getColor();
c.r = toColor(color, 0);
c.g = toColor(color, 1);
c.b = toColor(color, 2);
c.a = toColor(color, 3);
}
dark = Json::getString(slotMap, "dark", 0);
if (dark) {
Color &darkColor = data->getDarkColor();
darkColor.r = toColor(dark, 0);
darkColor.g = toColor(dark, 1);
darkColor.b = toColor(dark, 2);
darkColor.a = 1;
data->setHasDarkColor(true);
}
item = Json::getItem(slotMap, "attachment");
if (item) data->setAttachmentName(item->_valueString);
item = Json::getItem(slotMap, "blend");
if (item) {
if (strcmp(item->_valueString, "additive") == 0) data->_blendMode = BlendMode_Additive;
else if (strcmp(item->_valueString, "multiply") == 0)
data->_blendMode = BlendMode_Multiply;
else if (strcmp(item->_valueString, "screen") == 0)
data->_blendMode = BlendMode_Screen;
}
skeletonData->_slots[i] = data;
}
}
/* IK constraints. */
ik = Json::getItem(root, "ik");
if (ik) {
Json *constraintMap;
skeletonData->_ikConstraints.ensureCapacity(ik->_size);
skeletonData->_ikConstraints.setSize(ik->_size, 0);
for (constraintMap = ik->_child, i = 0; constraintMap; constraintMap = constraintMap->_next, ++i) {
const char *targetName;
IkConstraintData *data = new (__FILE__, __LINE__) IkConstraintData(
Json::getString(constraintMap, "name", 0));
data->setOrder(Json::getInt(constraintMap, "order", 0));
data->setSkinRequired(Json::getBoolean(constraintMap, "skin", false));
boneMap = Json::getItem(constraintMap, "bones");
data->_bones.ensureCapacity(boneMap->_size);
data->_bones.setSize(boneMap->_size, 0);
for (boneMap = boneMap->_child, ii = 0; boneMap; boneMap = boneMap->_next, ++ii) {
data->_bones[ii] = skeletonData->findBone(boneMap->_valueString);
if (!data->_bones[ii]) {
delete skeletonData;
setError(root, "IK bone not found: ", boneMap->_valueString);
return NULL;
}
}
targetName = Json::getString(constraintMap, "target", 0);
data->_target = skeletonData->findBone(targetName);
if (!data->_target) {
delete skeletonData;
setError(root, "Target bone not found: ", targetName);
return NULL;
}
data->_mix = Json::getFloat(constraintMap, "mix", 1);
data->_softness = Json::getFloat(constraintMap, "softness", 0) * _scale;
data->_bendDirection = Json::getInt(constraintMap, "bendPositive", 1) ? 1 : -1;
data->_compress = Json::getInt(constraintMap, "compress", 0) ? true : false;
data->_stretch = Json::getInt(constraintMap, "stretch", 0) ? true : false;
data->_uniform = Json::getInt(constraintMap, "uniform", 0) ? true : false;
skeletonData->_ikConstraints[i] = data;
}
}
/* Transform constraints. */
transform = Json::getItem(root, "transform");
if (transform) {
Json *constraintMap;
skeletonData->_transformConstraints.ensureCapacity(transform->_size);
skeletonData->_transformConstraints.setSize(transform->_size, 0);
for (constraintMap = transform->_child, i = 0; constraintMap; constraintMap = constraintMap->_next, ++i) {
const char *name;
TransformConstraintData *data = new (__FILE__, __LINE__) TransformConstraintData(
Json::getString(constraintMap, "name", 0));
data->setOrder(Json::getInt(constraintMap, "order", 0));
data->setSkinRequired(Json::getBoolean(constraintMap, "skin", false));
boneMap = Json::getItem(constraintMap, "bones");
data->_bones.ensureCapacity(boneMap->_size);
data->_bones.setSize(boneMap->_size, 0);
for (boneMap = boneMap->_child, ii = 0; boneMap; boneMap = boneMap->_next, ++ii) {
data->_bones[ii] = skeletonData->findBone(boneMap->_valueString);
if (!data->_bones[ii]) {
delete skeletonData;
setError(root, "Transform bone not found: ", boneMap->_valueString);
return NULL;
}
}
name = Json::getString(constraintMap, "target", 0);
data->_target = skeletonData->findBone(name);
if (!data->_target) {
delete skeletonData;
setError(root, "Target bone not found: ", name);
return NULL;
}
data->_local = Json::getInt(constraintMap, "local", 0) ? true : false;
data->_relative = Json::getInt(constraintMap, "relative", 0) ? true : false;
data->_offsetRotation = Json::getFloat(constraintMap, "rotation", 0);
data->_offsetX = Json::getFloat(constraintMap, "x", 0) * _scale;
data->_offsetY = Json::getFloat(constraintMap, "y", 0) * _scale;
data->_offsetScaleX = Json::getFloat(constraintMap, "scaleX", 0);
data->_offsetScaleY = Json::getFloat(constraintMap, "scaleY", 0);
data->_offsetShearY = Json::getFloat(constraintMap, "shearY", 0);
data->_mixRotate = Json::getFloat(constraintMap, "mixRotate", 1);
data->_mixX = Json::getFloat(constraintMap, "mixX", 1);
data->_mixY = Json::getFloat(constraintMap, "mixY", data->_mixX);
data->_mixScaleX = Json::getFloat(constraintMap, "mixScaleX", 1);
data->_mixScaleY = Json::getFloat(constraintMap, "mixScaleY", data->_mixScaleX);
data->_mixShearY = Json::getFloat(constraintMap, "mixShearY", 1);
skeletonData->_transformConstraints[i] = data;
}
}
/* Path constraints */
path = Json::getItem(root, "path");
if (path) {
Json *constraintMap;
skeletonData->_pathConstraints.ensureCapacity(path->_size);
skeletonData->_pathConstraints.setSize(path->_size, 0);
for (constraintMap = path->_child, i = 0; constraintMap; constraintMap = constraintMap->_next, ++i) {
const char *name;
const char *item;
PathConstraintData *data = new (__FILE__, __LINE__) PathConstraintData(
Json::getString(constraintMap, "name", 0));
data->setOrder(Json::getInt(constraintMap, "order", 0));
data->setSkinRequired(Json::getBoolean(constraintMap, "skin", false));
boneMap = Json::getItem(constraintMap, "bones");
data->_bones.ensureCapacity(boneMap->_size);
data->_bones.setSize(boneMap->_size, 0);
for (boneMap = boneMap->_child, ii = 0; boneMap; boneMap = boneMap->_next, ++ii) {
data->_bones[ii] = skeletonData->findBone(boneMap->_valueString);
if (!data->_bones[ii]) {
delete skeletonData;
setError(root, "Path bone not found: ", boneMap->_valueString);
return NULL;
}
}
name = Json::getString(constraintMap, "target", 0);
data->_target = skeletonData->findSlot(name);
if (!data->_target) {
delete skeletonData;
setError(root, "Target slot not found: ", name);
return NULL;
}
item = Json::getString(constraintMap, "positionMode", "percent");
if (strcmp(item, "fixed") == 0) {
data->_positionMode = PositionMode_Fixed;
} else if (strcmp(item, "percent") == 0) {
data->_positionMode = PositionMode_Percent;
}
item = Json::getString(constraintMap, "spacingMode", "length");
if (strcmp(item, "length") == 0) data->_spacingMode = SpacingMode_Length;
else if (strcmp(item, "fixed") == 0)
data->_spacingMode = SpacingMode_Fixed;
else if (strcmp(item, "percent") == 0)
data->_spacingMode = SpacingMode_Percent;
item = Json::getString(constraintMap, "rotateMode", "tangent");
if (strcmp(item, "tangent") == 0) data->_rotateMode = RotateMode_Tangent;
else if (strcmp(item, "chain") == 0)
data->_rotateMode = RotateMode_Chain;
else if (strcmp(item, "chainScale") == 0)
data->_rotateMode = RotateMode_ChainScale;
data->_offsetRotation = Json::getFloat(constraintMap, "rotation", 0);
data->_position = Json::getFloat(constraintMap, "position", 0);
if (data->_positionMode == PositionMode_Fixed) data->_position *= _scale;
data->_spacing = Json::getFloat(constraintMap, "spacing", 0);
if (data->_spacingMode == SpacingMode_Length || data->_spacingMode == SpacingMode_Fixed)
data->_spacing *= _scale;
data->_mixRotate = Json::getFloat(constraintMap, "mixRotate", 1);
data->_mixX = Json::getFloat(constraintMap, "mixX", 1);
data->_mixY = Json::getFloat(constraintMap, "mixY", data->_mixX);
skeletonData->_pathConstraints[i] = data;
}
}
/* Skins. */
skins = Json::getItem(root, "skins");
if (skins) {
Json *skinMap;
skeletonData->_skins.ensureCapacity(skins->_size);
skeletonData->_skins.setSize(skins->_size, 0);
int skinsIndex = 0;
for (skinMap = skins->_child, i = 0; skinMap; skinMap = skinMap->_next, ++i) {
Json *attachmentsMap;
Json *curves;
Skin *skin = new (__FILE__, __LINE__) Skin(Json::getString(skinMap, "name", ""));
Json *item = Json::getItem(skinMap, "bones");
if (item) {
for (item = item->_child; item; item = item->_next) {
BoneData *data = skeletonData->findBone(item->_valueString);
if (!data) {
delete skeletonData;
setError(root, String("Skin bone not found: "), item->_valueString);
return NULL;
}
skin->getBones().add(data);
}
}
item = Json::getItem(skinMap, "ik");
if (item) {
for (item = item->_child; item; item = item->_next) {
IkConstraintData *data = skeletonData->findIkConstraint(item->_valueString);
if (!data) {
delete skeletonData;
setError(root, String("Skin IK constraint not found: "), item->_valueString);
return NULL;
}
skin->getConstraints().add(data);
}
}
item = Json::getItem(skinMap, "transform");
if (item) {
for (item = item->_child; item; item = item->_next) {
TransformConstraintData *data = skeletonData->findTransformConstraint(item->_valueString);
if (!data) {
delete skeletonData;
setError(root, String("Skin transform constraint not found: "), item->_valueString);
return NULL;
}
skin->getConstraints().add(data);
}
}
item = Json::getItem(skinMap, "path");
if (item) {
for (item = item->_child; item; item = item->_next) {
PathConstraintData *data = skeletonData->findPathConstraint(item->_valueString);
if (!data) {
delete skeletonData;
setError(root, String("Skin path constraint not found: "), item->_valueString);
return NULL;
}
skin->getConstraints().add(data);
}
}
skeletonData->_skins[skinsIndex++] = skin;
if (strcmp(Json::getString(skinMap, "name", ""), "default") == 0) {
skeletonData->_defaultSkin = skin;
}
for (attachmentsMap = Json::getItem(skinMap,
"attachments")
->_child;
attachmentsMap; attachmentsMap = attachmentsMap->_next) {
SlotData *slot = skeletonData->findSlot(attachmentsMap->_name);
Json *attachmentMap;
for (attachmentMap = attachmentsMap->_child; attachmentMap; attachmentMap = attachmentMap->_next) {
Attachment *attachment = NULL;
const char *skinAttachmentName = attachmentMap->_name;
const char *attachmentName = Json::getString(attachmentMap, "name", skinAttachmentName);
const char *attachmentPath = Json::getString(attachmentMap, "path", attachmentName);
const char *color;
Json *entry;
const char *typeString = Json::getString(attachmentMap, "type", "region");
AttachmentType type;
if (strcmp(typeString, "region") == 0) type = AttachmentType_Region;
else if (strcmp(typeString, "mesh") == 0)
type = AttachmentType_Mesh;
else if (strcmp(typeString, "linkedmesh") == 0)
type = AttachmentType_Linkedmesh;
else if (strcmp(typeString, "boundingbox") == 0)
type = AttachmentType_Boundingbox;
else if (strcmp(typeString, "path") == 0)
type = AttachmentType_Path;
else if (strcmp(typeString, "clipping") == 0)
type = AttachmentType_Clipping;
else if (strcmp(typeString, "point") == 0)
type = AttachmentType_Point;
else {
delete skeletonData;
setError(root, "Unknown attachment type: ", typeString);
return NULL;
}
switch (type) {
case AttachmentType_Region: {
attachment = _attachmentLoader->newRegionAttachment(*skin, attachmentName, attachmentPath);
if (!attachment) {
delete skeletonData;
setError(root, "Error reading attachment: ", skinAttachmentName);
return NULL;
}
RegionAttachment *region = static_cast<RegionAttachment *>(attachment);
region->_path = attachmentPath;
region->_x = Json::getFloat(attachmentMap, "x", 0) * _scale;
region->_y = Json::getFloat(attachmentMap, "y", 0) * _scale;
region->_scaleX = Json::getFloat(attachmentMap, "scaleX", 1);
region->_scaleY = Json::getFloat(attachmentMap, "scaleY", 1);
region->_rotation = Json::getFloat(attachmentMap, "rotation", 0);
region->_width = Json::getFloat(attachmentMap, "width", 32) * _scale;
region->_height = Json::getFloat(attachmentMap, "height", 32) * _scale;
color = Json::getString(attachmentMap, "color", 0);
if (color) toColor(region->getColor(), color, true);
region->updateOffset();
_attachmentLoader->configureAttachment(region);
break;
}
case AttachmentType_Mesh:
case AttachmentType_Linkedmesh: {
attachment = _attachmentLoader->newMeshAttachment(*skin, attachmentName, attachmentPath);
if (!attachment) {
delete skeletonData;
setError(root, "Error reading attachment: ", skinAttachmentName);
return NULL;
}
MeshAttachment *mesh = static_cast<MeshAttachment *>(attachment);
mesh->_path = attachmentPath;
color = Json::getString(attachmentMap, "color", 0);
if (color) toColor(mesh->getColor(), color, true);
mesh->_width = Json::getFloat(attachmentMap, "width", 32) * _scale;
mesh->_height = Json::getFloat(attachmentMap, "height", 32) * _scale;
entry = Json::getItem(attachmentMap, "parent");
if (!entry) {
int verticesLength;
entry = Json::getItem(attachmentMap, "triangles");
mesh->_triangles.ensureCapacity(entry->_size);
mesh->_triangles.setSize(entry->_size, 0);
for (entry = entry->_child, ii = 0; entry; entry = entry->_next, ++ii)
mesh->_triangles[ii] = (unsigned short) entry->_valueInt;
entry = Json::getItem(attachmentMap, "uvs");
verticesLength = entry->_size;
mesh->_regionUVs.ensureCapacity(verticesLength);
mesh->_regionUVs.setSize(verticesLength, 0);
for (entry = entry->_child, ii = 0; entry; entry = entry->_next, ++ii)
mesh->_regionUVs[ii] = entry->_valueFloat;
readVertices(attachmentMap, mesh, verticesLength);
mesh->updateUVs();
mesh->_hullLength = Json::getInt(attachmentMap, "hull", 0);
entry = Json::getItem(attachmentMap, "edges");
if (entry) {
mesh->_edges.ensureCapacity(entry->_size);
mesh->_edges.setSize(entry->_size, 0);
for (entry = entry->_child, ii = 0; entry; entry = entry->_next, ++ii)
mesh->_edges[ii] = entry->_valueInt;
}
_attachmentLoader->configureAttachment(mesh);
} else {
bool inheritDeform = Json::getInt(attachmentMap, "deform", 1) ? true : false;
LinkedMesh *linkedMesh = new (__FILE__, __LINE__) LinkedMesh(mesh,
String(Json::getString(
attachmentMap,
"skin", 0)),
slot->getIndex(),
String(entry->_valueString),
inheritDeform);
_linkedMeshes.add(linkedMesh);
}
break;
}
case AttachmentType_Boundingbox: {
attachment = _attachmentLoader->newBoundingBoxAttachment(*skin, attachmentName);
BoundingBoxAttachment *box = static_cast<BoundingBoxAttachment *>(attachment);
int vertexCount = Json::getInt(attachmentMap, "vertexCount", 0) << 1;
readVertices(attachmentMap, box, vertexCount);
color = Json::getString(attachmentMap, "color", NULL);
if (color) toColor(box->getColor(), color, true);
_attachmentLoader->configureAttachment(attachment);
break;
}
case AttachmentType_Path: {
attachment = _attachmentLoader->newPathAttachment(*skin, attachmentName);
PathAttachment *pathAttatchment = static_cast<PathAttachment *>(attachment);
int vertexCount = 0;
pathAttatchment->_closed = Json::getInt(attachmentMap, "closed", 0) ? true : false;
pathAttatchment->_constantSpeed = Json::getInt(attachmentMap, "constantSpeed", 1) ? true
: false;
vertexCount = Json::getInt(attachmentMap, "vertexCount", 0);
readVertices(attachmentMap, pathAttatchment, vertexCount << 1);
pathAttatchment->_lengths.ensureCapacity(vertexCount / 3);
pathAttatchment->_lengths.setSize(vertexCount / 3, 0);
curves = Json::getItem(attachmentMap, "lengths");
for (curves = curves->_child, ii = 0; curves; curves = curves->_next, ++ii)
pathAttatchment->_lengths[ii] = curves->_valueFloat * _scale;
color = Json::getString(attachmentMap, "color", NULL);
if (color) toColor(pathAttatchment->getColor(), color, true);
_attachmentLoader->configureAttachment(attachment);
break;
}
case AttachmentType_Point: {
attachment = _attachmentLoader->newPointAttachment(*skin, attachmentName);
PointAttachment *point = static_cast<PointAttachment *>(attachment);
point->_x = Json::getFloat(attachmentMap, "x", 0) * _scale;
point->_y = Json::getFloat(attachmentMap, "y", 0) * _scale;
point->_rotation = Json::getFloat(attachmentMap, "rotation", 0);
color = Json::getString(attachmentMap, "color", NULL);
if (color) toColor(point->getColor(), color, true);
_attachmentLoader->configureAttachment(attachment);
break;
}
case AttachmentType_Clipping: {
attachment = _attachmentLoader->newClippingAttachment(*skin, attachmentName);
ClippingAttachment *clip = static_cast<ClippingAttachment *>(attachment);
int vertexCount = 0;
const char *end = Json::getString(attachmentMap, "end", 0);
if (end) clip->_endSlot = skeletonData->findSlot(end);
vertexCount = Json::getInt(attachmentMap, "vertexCount", 0) << 1;
readVertices(attachmentMap, clip, vertexCount);
color = Json::getString(attachmentMap, "color", NULL);
if (color) toColor(clip->getColor(), color, true);
_attachmentLoader->configureAttachment(attachment);
break;
}
}
skin->setAttachment(slot->getIndex(), skinAttachmentName, attachment);
}
}
}
}
/* Linked meshes. */
int n = (int) _linkedMeshes.size();
for (i = 0; i < n; ++i) {
LinkedMesh *linkedMesh = _linkedMeshes[i];
Skin *skin = linkedMesh->_skin.length() == 0 ? skeletonData->getDefaultSkin() : skeletonData->findSkin(linkedMesh->_skin);
if (skin == NULL) {
delete skeletonData;
setError(root, "Skin not found: ", linkedMesh->_skin.buffer());
return NULL;
}
Attachment *parent = skin->getAttachment(linkedMesh->_slotIndex, linkedMesh->_parent);
if (parent == NULL) {
delete skeletonData;
setError(root, "Parent mesh not found: ", linkedMesh->_parent.buffer());
return NULL;
}
linkedMesh->_mesh->_deformAttachment = linkedMesh->_inheritDeform ? static_cast<VertexAttachment *>(parent)
: linkedMesh->_mesh;
linkedMesh->_mesh->setParentMesh(static_cast<MeshAttachment *>(parent));
linkedMesh->_mesh->updateUVs();
_attachmentLoader->configureAttachment(linkedMesh->_mesh);
}
ContainerUtil::cleanUpVectorOfPointers(_linkedMeshes);
_linkedMeshes.clear();
/* Events. */
events = Json::getItem(root, "events");
if (events) {
Json *eventMap;
skeletonData->_events.ensureCapacity(events->_size);
skeletonData->_events.setSize(events->_size, 0);
for (eventMap = events->_child, i = 0; eventMap; eventMap = eventMap->_next, ++i) {
EventData *eventData = new (__FILE__, __LINE__) EventData(String(eventMap->_name));
eventData->_intValue = Json::getInt(eventMap, "int", 0);
eventData->_floatValue = Json::getFloat(eventMap, "float", 0);
const char *stringValue = Json::getString(eventMap, "string", 0);
eventData->_stringValue = stringValue;
const char *audioPath = Json::getString(eventMap, "audio", 0);
eventData->_audioPath = audioPath;
if (audioPath) {
eventData->_volume = Json::getFloat(eventMap, "volume", 1);
eventData->_balance = Json::getFloat(eventMap, "balance", 0);
}
skeletonData->_events[i] = eventData;
}
}
/* Animations. */
animations = Json::getItem(root, "animations");
if (animations) {
Json *animationMap;
skeletonData->_animations.ensureCapacity(animations->_size);
skeletonData->_animations.setSize(animations->_size, 0);
int animationsIndex = 0;
for (animationMap = animations->_child; animationMap; animationMap = animationMap->_next) {
Animation *animation = readAnimation(animationMap, skeletonData);
if (!animation) {
delete skeletonData;
delete root;
return NULL;
}
skeletonData->_animations[animationsIndex++] = animation;
}
}
delete root;
return skeletonData;
}
void SkeletonJson::setBezier(CurveTimeline *timeline, int frame, int value, int bezier, float time1, float value1, float cx1,
float cy1,
float cx2, float cy2, float time2, float value2) {
timeline->setBezier(bezier, frame, (float) value, time1, value1, cx1, cy1, cx2, cy2, time2, value2);
}
int SkeletonJson::readCurve(Json *curve, CurveTimeline *timeline, int bezier, int frame, int value, float time1,
float time2,
float value1, float value2, float scale) {
if (curve->_type == Json::JSON_STRING && strcmp(curve->_valueString, "stepped") == 0) {
timeline->setStepped(frame);
return bezier;
}
curve = Json::getItem(curve, value << 2);
float cx1 = curve->_valueFloat;
curve = curve->_next;
float cy1 = curve->_valueFloat * scale;
curve = curve->_next;
float cx2 = curve->_valueFloat;
curve = curve->_next;
float cy2 = curve->_valueFloat * scale;
setBezier(timeline, frame, value, bezier, time1, value1, cx1, cy1, cx2, cy2, time2, value2);
return bezier + 1;
}
Timeline *SkeletonJson::readTimeline(Json *keyMap, CurveTimeline1 *timeline, float defaultValue, float scale) {
float time = Json::getFloat(keyMap, "time", 0);
float value = Json::getFloat(keyMap, "value", defaultValue) * scale;
int bezier = 0;
for (int frame = 0;; frame++) {
timeline->setFrame(frame, time, value);
Json *nextMap = keyMap->_next;
if (!nextMap) break;
float time2 = Json::getFloat(nextMap, "time", 0);
float value2 = Json::getFloat(nextMap, "value", defaultValue) * scale;
Json *curve = Json::getItem(keyMap, "curve");
if (curve != NULL) bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, value, value2, scale);
time = time2;
value = value2;
keyMap = nextMap;
}
// timeline.shrink(); // BOZO
return timeline;
}
Timeline *SkeletonJson::readTimeline(Json *keyMap, CurveTimeline2 *timeline, const char *name1, const char *name2,
float defaultValue, float scale) {
float time = Json::getFloat(keyMap, "time", 0);
float value1 = Json::getFloat(keyMap, name1, defaultValue) * scale;
float value2 = Json::getFloat(keyMap, name2, defaultValue) * scale;
int bezier = 0;
for (int frame = 0;; frame++) {
timeline->setFrame(frame, time, value1, value2);
Json *nextMap = keyMap->_next;
if (!nextMap) break;
float time2 = Json::getFloat(nextMap, "time", 0);
float nvalue1 = Json::getFloat(nextMap, name1, defaultValue) * scale;
float nvalue2 = Json::getFloat(nextMap, name2, defaultValue) * scale;
Json *curve = Json::getItem(keyMap, "curve");
if (curve != NULL) {
bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, value1, nvalue1, scale);
bezier = readCurve(curve, timeline, bezier, frame, 1, time, time2, value2, nvalue2, scale);
}
time = time2;
value1 = nvalue1;
value2 = nvalue2;
keyMap = nextMap;
}
// timeline.shrink(); // BOZO
return timeline;
}
int SkeletonJson::findSlotIndex(SkeletonData *skeletonData, const String &slotName, Vector<Timeline *> timelines) {
int slotIndex = ContainerUtil::findIndexWithName(skeletonData->getSlots(), slotName);
if (slotIndex == -1) {
ContainerUtil::cleanUpVectorOfPointers(timelines);
setError(NULL, "Slot not found: ", slotName);
}
return slotIndex;
}
Animation *SkeletonJson::readAnimation(Json *root, SkeletonData *skeletonData) {
Vector<Timeline *> timelines;
Json *bones = Json::getItem(root, "bones");
Json *slots = Json::getItem(root, "slots");
Json *ik = Json::getItem(root, "ik");
Json *transform = Json::getItem(root, "transform");
Json *paths = Json::getItem(root, "path");
Json *deform = Json::getItem(root, "deform");
Json *drawOrder = Json::getItem(root, "drawOrder");
Json *events = Json::getItem(root, "events");
Json *boneMap, *slotMap, *constraintMap, *keyMap, *nextMap, *curve;
int frame, bezier;
Color color, color2, newColor, newColor2;
/** Slot timelines. */
for (slotMap = slots ? slots->_child : 0; slotMap; slotMap = slotMap->_next) {
int slotIndex = findSlotIndex(skeletonData, slotMap->_name, timelines);
if (slotIndex == -1) return NULL;
for (Json *timelineMap = slotMap->_child; timelineMap; timelineMap = timelineMap->_next) {
int frames = timelineMap->_size;
if (strcmp(timelineMap->_name, "attachment") == 0) {
AttachmentTimeline *timeline = new (__FILE__, __LINE__) AttachmentTimeline(frames, slotIndex);
for (keyMap = timelineMap->_child, frame = 0; keyMap; keyMap = keyMap->_next, ++frame) {
timeline->setFrame(frame, Json::getFloat(keyMap, "time", 0),
Json::getItem(keyMap, "name")->_valueString);
}
timelines.add(timeline);
} else if (strcmp(timelineMap->_name, "rgba") == 0) {
RGBATimeline *timeline = new (__FILE__, __LINE__) RGBATimeline(frames, frames << 2, slotIndex);
keyMap = timelineMap->_child;
float time = Json::getFloat(keyMap, "time", 0);
toColor(color, Json::getString(keyMap, "color", 0), true);
for (frame = 0, bezier = 0;; ++frame) {
timeline->setFrame(frame, time, color.r, color.g, color.b, color.a);
nextMap = keyMap->_next;
if (!nextMap) {
// timeline.shrink(); // BOZO
break;
}
float time2 = Json::getFloat(nextMap, "time", 0);
toColor(newColor, Json::getString(nextMap, "color", 0), true);
curve = Json::getItem(keyMap, "curve");
if (curve) {
bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, color.r, newColor.r, 1);
bezier = readCurve(curve, timeline, bezier, frame, 1, time, time2, color.g, newColor.g, 1);
bezier = readCurve(curve, timeline, bezier, frame, 2, time, time2, color.b, newColor.b, 1);
bezier = readCurve(curve, timeline, bezier, frame, 3, time, time2, color.a, newColor.a, 1);
}
time = time2;
color = newColor;
keyMap = nextMap;
}
timelines.add(timeline);
} else if (strcmp(timelineMap->_name, "rgb") == 0) {
RGBTimeline *timeline = new (__FILE__, __LINE__) RGBTimeline(frames, frames * 3, slotIndex);
keyMap = timelineMap->_child;
float time = Json::getFloat(keyMap, "time", 0);
toColor(color, Json::getString(keyMap, "color", 0), false);
for (frame = 0, bezier = 0;; ++frame) {
timeline->setFrame(frame, time, color.r, color.g, color.b);
nextMap = keyMap->_next;
if (!nextMap) {
// timeline.shrink(); // BOZO
break;
}
float time2 = Json::getFloat(nextMap, "time", 0);
toColor(newColor, Json::getString(nextMap, "color", 0), false);
curve = Json::getItem(keyMap, "curve");
if (curve) {
bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, color.r, newColor.r, 1);
bezier = readCurve(curve, timeline, bezier, frame, 1, time, time2, color.g, newColor.g, 1);
bezier = readCurve(curve, timeline, bezier, frame, 2, time, time2, color.b, newColor.b, 1);
}
time = time2;
color = newColor;
keyMap = nextMap;
}
timelines.add(timeline);
} else if (strcmp(timelineMap->_name, "alpha") == 0) {
timelines.add(readTimeline(timelineMap->_child,
new (__FILE__, __LINE__) AlphaTimeline(frames, frames, slotIndex),
0, 1));
} else if (strcmp(timelineMap->_name, "rgba2") == 0) {
RGBA2Timeline *timeline = new (__FILE__, __LINE__) RGBA2Timeline(frames, frames * 7, slotIndex);
keyMap = timelineMap->_child;
float time = Json::getFloat(keyMap, "time", 0);
toColor(color, Json::getString(keyMap, "light", 0), true);
toColor(color2, Json::getString(keyMap, "dark", 0), false);
for (frame = 0, bezier = 0;; ++frame) {
timeline->setFrame(frame, time, color.r, color.g, color.b, color.a, color2.g, color2.g, color2.b);
nextMap = keyMap->_next;
if (!nextMap) {
// timeline.shrink(); // BOZO
break;
}
float time2 = Json::getFloat(nextMap, "time", 0);
toColor(newColor, Json::getString(nextMap, "light", 0), true);
toColor(newColor2, Json::getString(nextMap, "dark", 0), false);
curve = Json::getItem(keyMap, "curve");
if (curve) {
bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, color.r, newColor.r, 1);
bezier = readCurve(curve, timeline, bezier, frame, 1, time, time2, color.g, newColor.g, 1);
bezier = readCurve(curve, timeline, bezier, frame, 2, time, time2, color.b, newColor.b, 1);
bezier = readCurve(curve, timeline, bezier, frame, 3, time, time2, color.a, newColor.a, 1);
bezier = readCurve(curve, timeline, bezier, frame, 4, time, time2, color2.r, newColor2.r, 1);
bezier = readCurve(curve, timeline, bezier, frame, 5, time, time2, color2.g, newColor2.g, 1);
bezier = readCurve(curve, timeline, bezier, frame, 6, time, time2, color2.b, newColor2.b, 1);
}
time = time2;
color = newColor;
color2 = newColor2;
keyMap = nextMap;
}
timelines.add(timeline);
} else if (strcmp(timelineMap->_name, "rgb2") == 0) {
RGBA2Timeline *timeline = new (__FILE__, __LINE__) RGBA2Timeline(frames, frames * 6, slotIndex);
keyMap = timelineMap->_child;
float time = Json::getFloat(keyMap, "time", 0);
toColor(color, Json::getString(keyMap, "light", 0), false);
toColor(color2, Json::getString(keyMap, "dark", 0), false);
for (frame = 0, bezier = 0;; ++frame) {
timeline->setFrame(frame, time, color.r, color.g, color.b, color.a, color2.r, color2.g, color2.b);
nextMap = keyMap->_next;
if (!nextMap) {
// timeline.shrink(); // BOZO
break;
}
float time2 = Json::getFloat(nextMap, "time", 0);
toColor(newColor, Json::getString(nextMap, "light", 0), false);
toColor(newColor2, Json::getString(nextMap, "dark", 0), false);
curve = Json::getItem(keyMap, "curve");
if (curve) {
bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, color.r, newColor.r, 1);
bezier = readCurve(curve, timeline, bezier, frame, 1, time, time2, color.g, newColor.g, 1);
bezier = readCurve(curve, timeline, bezier, frame, 2, time, time2, color.b, newColor.b, 1);
bezier = readCurve(curve, timeline, bezier, frame, 3, time, time2, color2.r, newColor2.r, 1);
bezier = readCurve(curve, timeline, bezier, frame, 4, time, time2, color2.g, newColor2.g, 1);
bezier = readCurve(curve, timeline, bezier, frame, 5, time, time2, color2.b, newColor2.b, 1);
}
time = time2;
color = newColor;
color2 = newColor2;
keyMap = nextMap;
}
timelines.add(timeline);
} else {
ContainerUtil::cleanUpVectorOfPointers(timelines);
setError(NULL, "Invalid timeline type for a slot: ", timelineMap->_name);
return NULL;
}
}
}
/** Bone timelines. */
for (boneMap = bones ? bones->_child : 0; boneMap; boneMap = boneMap->_next) {
int boneIndex = ContainerUtil::findIndexWithName(skeletonData->_bones, boneMap->_name);
if (boneIndex == -1) {
ContainerUtil::cleanUpVectorOfPointers(timelines);
setError(NULL, "Bone not found: ", boneMap->_name);
return NULL;
}
for (Json *timelineMap = boneMap->_child; timelineMap; timelineMap = timelineMap->_next) {
int frames = timelineMap->_size;
if (frames == 0) continue;
if (strcmp(timelineMap->_name, "rotate") == 0) {
timelines.add(readTimeline(timelineMap->_child,
new RotateTimeline(frames, frames, boneIndex), 0,
1));
} else if (strcmp(timelineMap->_name, "translate") == 0) {
TranslateTimeline *timeline = new TranslateTimeline(frames, frames << 1,
boneIndex);
timelines.add(readTimeline(timelineMap->_child, timeline, "x", "y", 0, _scale));
} else if (strcmp(timelineMap->_name, "translatex") == 0) {
TranslateXTimeline *timeline = new TranslateXTimeline(frames, frames,
boneIndex);
timelines.add(readTimeline(timelineMap->_child, timeline, 0, _scale));
} else if (strcmp(timelineMap->_name, "translatey") == 0) {
TranslateYTimeline *timeline = new TranslateYTimeline(frames, frames,
boneIndex);
timelines.add(readTimeline(timelineMap->_child, timeline, 0, _scale));
} else if (strcmp(timelineMap->_name, "scale") == 0) {
ScaleTimeline *timeline = new (__FILE__, __LINE__) ScaleTimeline(frames,
frames << 1, boneIndex);
timelines.add(readTimeline(timelineMap->_child, timeline, "x", "y", 1, 1));
} else if (strcmp(timelineMap->_name, "scalex") == 0) {
ScaleXTimeline *timeline = new (__FILE__, __LINE__) ScaleXTimeline(frames,
frames, boneIndex);
timelines.add(readTimeline(timelineMap->_child, timeline, 1, 1));
} else if (strcmp(timelineMap->_name, "scaley") == 0) {
ScaleYTimeline *timeline = new (__FILE__, __LINE__) ScaleYTimeline(frames,
frames, boneIndex);
timelines.add(readTimeline(timelineMap->_child, timeline, 1, 1));
} else if (strcmp(timelineMap->_name, "shear") == 0) {
ShearTimeline *timeline = new (__FILE__, __LINE__) ShearTimeline(frames,
frames << 1, boneIndex);
timelines.add(readTimeline(timelineMap->_child, timeline, "x", "y", 0, 1));
} else if (strcmp(timelineMap->_name, "shearx") == 0) {
ShearXTimeline *timeline = new (__FILE__, __LINE__) ShearXTimeline(frames,
frames, boneIndex);
timelines.add(readTimeline(timelineMap->_child, timeline, 0, 1));
} else if (strcmp(timelineMap->_name, "sheary") == 0) {
ShearYTimeline *timeline = new (__FILE__, __LINE__) ShearYTimeline(frames,
frames, boneIndex);
timelines.add(readTimeline(timelineMap->_child, timeline, 0, 1));
} else {
ContainerUtil::cleanUpVectorOfPointers(timelines);
setError(NULL, "Invalid timeline type for a bone: ", timelineMap->_name);
return NULL;
}
}
}
/** IK constraint timelines. */
for (constraintMap = ik ? ik->_child : 0; constraintMap; constraintMap = constraintMap->_next) {
keyMap = constraintMap->_child;
if (keyMap == NULL) continue;
IkConstraintData *constraint = skeletonData->findIkConstraint(constraintMap->_name);
int constraintIndex = skeletonData->_ikConstraints.indexOf(constraint);
IkConstraintTimeline *timeline = new (__FILE__, __LINE__) IkConstraintTimeline(constraintMap->_size,
constraintMap->_size << 1,
constraintIndex);
float time = Json::getFloat(keyMap, "time", 0);
float mix = Json::getFloat(keyMap, "mix", 1);
float softness = Json::getFloat(keyMap, "softness", 0) * _scale;
for (frame = 0, bezier = 0;; frame++) {
int bendDirection = Json::getBoolean(keyMap, "bendPositive", true) ? 1 : -1;
timeline->setFrame(frame, time, mix, softness, bendDirection, Json::getBoolean(keyMap, "compress", false),
Json::getBoolean(keyMap, "stretch", false));
nextMap = keyMap->_next;
if (!nextMap) {
// timeline.shrink(); // BOZO
break;
}
float time2 = Json::getFloat(nextMap, "time", 0);
float mix2 = Json::getFloat(nextMap, "mix", 1);
float softness2 = Json::getFloat(nextMap, "softness", 0) * _scale;
curve = Json::getItem(keyMap, "curve");
if (curve) {
bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, mix, mix2, 1);
bezier = readCurve(curve, timeline, bezier, frame, 1, time, time2, softness, softness2, _scale);
}
time = time2;
mix = mix2;
softness = softness2;
keyMap = nextMap;
}
timelines.add(timeline);
}
/** Transform constraint timelines. */
for (constraintMap = transform ? transform->_child : 0; constraintMap; constraintMap = constraintMap->_next) {
keyMap = constraintMap->_child;
if (keyMap == NULL) continue;
TransformConstraintData *constraint = skeletonData->findTransformConstraint(constraintMap->_name);
int constraintIndex = skeletonData->_transformConstraints.indexOf(constraint);
TransformConstraintTimeline *timeline = new (__FILE__, __LINE__) TransformConstraintTimeline(
constraintMap->_size, constraintMap->_size << 2, constraintIndex);
float time = Json::getFloat(keyMap, "time", 0);
float mixRotate = Json::getFloat(keyMap, "mixRotate", 1);
float mixShearY = Json::getFloat(keyMap, "mixShearY", 1);
float mixX = Json::getFloat(keyMap, "mixX", 1);
float mixY = Json::getFloat(keyMap, "mixY", mixX);
float mixScaleX = Json::getFloat(keyMap, "mixScaleX", 1);
float mixScaleY = Json::getFloat(keyMap, "mixScaleY", mixScaleX);
for (frame = 0, bezier = 0;; frame++) {
timeline->setFrame(frame, time, mixRotate, mixX, mixY, mixScaleX, mixScaleY, mixShearY);
nextMap = keyMap->_next;
if (!nextMap) {
// timeline.shrink(); // BOZO
break;
}
float time2 = Json::getFloat(nextMap, "time", 0);
float mixRotate2 = Json::getFloat(nextMap, "mixRotate", 1);
float mixShearY2 = Json::getFloat(nextMap, "mixShearY", 1);
float mixX2 = Json::getFloat(nextMap, "mixX", 1);
float mixY2 = Json::getFloat(nextMap, "mixY", mixX2);
float mixScaleX2 = Json::getFloat(nextMap, "mixScaleX", 1);
float mixScaleY2 = Json::getFloat(nextMap, "mixScaleY", mixScaleX2);
curve = Json::getItem(keyMap, "curve");
if (curve) {
bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, mixRotate, mixRotate2, 1);
bezier = readCurve(curve, timeline, bezier, frame, 1, time, time2, mixX, mixX2, 1);
bezier = readCurve(curve, timeline, bezier, frame, 2, time, time2, mixY, mixY2, 1);
bezier = readCurve(curve, timeline, bezier, frame, 3, time, time2, mixScaleX, mixScaleX2, 1);
bezier = readCurve(curve, timeline, bezier, frame, 4, time, time2, mixScaleY, mixScaleY2, 1);
bezier = readCurve(curve, timeline, bezier, frame, 5, time, time2, mixShearY, mixShearY2, 1);
}
time = time2;
mixRotate = mixRotate2;
mixX = mixX2;
mixY = mixY2;
mixScaleX = mixScaleX2;
mixScaleY = mixScaleY2;
mixScaleX = mixScaleX2;
keyMap = nextMap;
}
timelines.add(timeline);
}
/** Path constraint timelines. */
for (constraintMap = paths ? paths->_child : 0; constraintMap; constraintMap = constraintMap->_next) {
PathConstraintData *constraint = skeletonData->findPathConstraint(constraintMap->_name);
if (!constraint) {
ContainerUtil::cleanUpVectorOfPointers(timelines);
setError(NULL, "Path constraint not found: ", constraintMap->_name);
return NULL;
}
int constraintIndex = skeletonData->_pathConstraints.indexOf(constraint);
for (Json *timelineMap = constraintMap->_child; timelineMap; timelineMap = timelineMap->_next) {
keyMap = timelineMap->_child;
if (keyMap == NULL) continue;
const char *timelineName = timelineMap->_name;
int frames = timelineMap->_size;
if (strcmp(timelineName, "position") == 0) {
PathConstraintPositionTimeline *timeline = new (__FILE__, __LINE__) PathConstraintPositionTimeline(
frames, frames, constraintIndex);
timelines.add(
readTimeline(keyMap, timeline, 0, constraint->_positionMode == PositionMode_Fixed ? _scale : 1));
} else if (strcmp(timelineName, "spacing") == 0) {
CurveTimeline1 *timeline = new PathConstraintSpacingTimeline(frames, frames,
constraintIndex);
timelines.add(readTimeline(keyMap, timeline, 0,
constraint->_spacingMode == SpacingMode_Length ||
constraint->_spacingMode == SpacingMode_Fixed
? _scale
: 1));
} else if (strcmp(timelineName, "mix") == 0) {
PathConstraintMixTimeline *timeline = new PathConstraintMixTimeline(frames,
frames * 3, constraintIndex);
float time = Json::getFloat(keyMap, "time", 0);
float mixRotate = Json::getFloat(keyMap, "mixRotate", 1);
float mixX = Json::getFloat(keyMap, "mixX", 1);
float mixY = Json::getFloat(keyMap, "mixY", mixX);
for (frame = 0, bezier = 0;; frame++) {
timeline->setFrame(frame, time, mixRotate, mixX, mixY);
nextMap = keyMap->_next;
if (!nextMap) {
// timeline.shrink(); // BOZO
break;
}
float time2 = Json::getFloat(nextMap, "time", 0);
float mixRotate2 = Json::getFloat(nextMap, "mixRotate", 1);
float mixX2 = Json::getFloat(nextMap, "mixX", 1);
float mixY2 = Json::getFloat(nextMap, "mixY", mixX2);
curve = Json::getItem(keyMap, "curve");
if (curve != NULL) {
bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, mixRotate, mixRotate2, 1);
bezier = readCurve(curve, timeline, bezier, frame, 1, time, time2, mixX, mixX2, 1);
bezier = readCurve(curve, timeline, bezier, frame, 2, time, time2, mixY, mixY2, 1);
}
time = time2;
mixRotate = mixRotate2;
mixX = mixX2;
mixY = mixY2;
keyMap = nextMap;
}
timelines.add(timeline);
}
}
}
/** Deform timelines. */
for (constraintMap = deform ? deform->_child : NULL; constraintMap; constraintMap = constraintMap->_next) {
Skin *skin = skeletonData->findSkin(constraintMap->_name);
for (slotMap = constraintMap->_child; slotMap; slotMap = slotMap->_next) {
int slotIndex = findSlotIndex(skeletonData, slotMap->_name, timelines);
if (slotIndex == -1) return NULL;
for (Json *timelineMap = slotMap->_child; timelineMap; timelineMap = timelineMap->_next) {
keyMap = timelineMap->_child;
if (keyMap == NULL) continue;
Attachment *baseAttachment = skin->getAttachment(slotIndex, timelineMap->_name);
if (!baseAttachment) {
ContainerUtil::cleanUpVectorOfPointers(timelines);
setError(NULL, "Attachment not found: ", timelineMap->_name);
return NULL;
}
VertexAttachment *attachment = static_cast<VertexAttachment *>(baseAttachment);
bool weighted = attachment->_bones.size() != 0;
Vector<float> &verts = attachment->_vertices;
int deformLength = (int) (weighted ? verts.size() / 3 * 2 : verts.size());
DeformTimeline *timeline = new (__FILE__, __LINE__) DeformTimeline(timelineMap->_size,
timelineMap->_size, slotIndex,
attachment);
float time = Json::getFloat(keyMap, "time", 0);
for (frame = 0, bezier = 0;; frame++) {
Json *vertices = Json::getItem(keyMap, "vertices");
Vector<float> deformed;
if (!vertices) {
if (weighted) {
deformed.setSize(deformLength, 0);
} else {
deformed.clearAndAddAll(attachment->_vertices);
}
} else {
int v, start = Json::getInt(keyMap, "offset", 0);
Json *vertex;
deformed.setSize(deformLength, 0);
if (_scale == 1) {
for (vertex = vertices->_child, v = start; vertex; vertex = vertex->_next, ++v) {
deformed[v] = vertex->_valueFloat;
}
} else {
for (vertex = vertices->_child, v = start; vertex; vertex = vertex->_next, ++v) {
deformed[v] = vertex->_valueFloat * _scale;
}
}
if (!weighted) {
Vector<float> &verticesAttachment = attachment->_vertices;
for (v = 0; v < deformLength; ++v) {
deformed[v] += verticesAttachment[v];
}
}
}
timeline->setFrame(frame, time, deformed);
nextMap = keyMap->_next;
if (!nextMap) {
// timeline.shrink(); // BOZO
break;
}
float time2 = Json::getFloat(nextMap, "time", 0);
curve = Json::getItem(keyMap, "curve");
if (curve) {
bezier = readCurve(curve, timeline, bezier, frame, 0, time, time2, 0, 1, 1);
}
time = time2;
keyMap = nextMap;
}
timelines.add(timeline);
}
}
}
/** Draw order timeline. */
if (drawOrder) {
DrawOrderTimeline *timeline = new (__FILE__, __LINE__) DrawOrderTimeline(drawOrder->_size);
for (keyMap = drawOrder->_child, frame = 0; keyMap; keyMap = keyMap->_next, ++frame) {
int ii;
Vector<int> drawOrder2;
Json *offsets = Json::getItem(keyMap, "offsets");
if (offsets) {
Json *offsetMap;
Vector<int> unchanged;
unchanged.ensureCapacity(skeletonData->_slots.size() - offsets->_size);
unchanged.setSize(skeletonData->_slots.size() - offsets->_size, 0);
size_t originalIndex = 0, unchangedIndex = 0;
drawOrder2.ensureCapacity(skeletonData->_slots.size());
drawOrder2.setSize(skeletonData->_slots.size(), 0);
for (ii = (int) skeletonData->_slots.size() - 1; ii >= 0; --ii)
drawOrder2[ii] = -1;
for (offsetMap = offsets->_child; offsetMap; offsetMap = offsetMap->_next) {
int slotIndex = findSlotIndex(skeletonData, Json::getString(offsetMap, "slot", 0), timelines);
if (slotIndex == -1) return NULL;
/* Collect unchanged items. */
while (originalIndex != (size_t) slotIndex)
unchanged[unchangedIndex++] = (int) (originalIndex++);
/* Set changed items. */
drawOrder2[originalIndex + Json::getInt(offsetMap, "offset", 0)] = (int) originalIndex;
originalIndex++;
}
/* Collect remaining unchanged items. */
while (originalIndex < skeletonData->_slots.size())
unchanged[unchangedIndex++] = (int) (originalIndex++);
/* Fill in unchanged items. */
for (ii = (int) skeletonData->_slots.size() - 1; ii >= 0; ii--)
if (drawOrder2[ii] == -1) drawOrder2[ii] = unchanged[--unchangedIndex];
}
timeline->setFrame(frame, Json::getFloat(keyMap, "time", 0), drawOrder2);
}
timelines.add(timeline);
}
/** Event timeline. */
if (events) {
EventTimeline *timeline = new (__FILE__, __LINE__) EventTimeline(events->_size);
for (keyMap = events->_child, frame = 0; keyMap; keyMap = keyMap->_next, ++frame) {
Event *event;
EventData *eventData = skeletonData->findEvent(Json::getString(keyMap, "name", 0));
if (!eventData) {
ContainerUtil::cleanUpVectorOfPointers(timelines);
setError(NULL, "Event not found: ", Json::getString(keyMap, "name", 0));
return NULL;
}
event = new (__FILE__, __LINE__) Event(Json::getFloat(keyMap, "time", 0), *eventData);
event->_intValue = Json::getInt(keyMap, "int", eventData->_intValue);
event->_floatValue = Json::getFloat(keyMap, "float", eventData->_floatValue);
event->_stringValue = Json::getString(keyMap, "string", eventData->_stringValue.buffer());
if (!eventData->_audioPath.isEmpty()) {
event->_volume = Json::getFloat(keyMap, "volume", 1);
event->_balance = Json::getFloat(keyMap, "balance", 0);
}
timeline->setFrame(frame, event);
}
timelines.add(timeline);
}
float duration = 0;
for (size_t i = 0; i < timelines.size(); i++)
duration = MathUtil::max(duration, timelines[i]->getDuration());
return new (__FILE__, __LINE__) Animation(String(root->_name), timelines, duration);
}
void SkeletonJson::readVertices(Json *attachmentMap, VertexAttachment *attachment, size_t verticesLength) {
Json *entry;
size_t i, n, nn, entrySize;
Vector<float> vertices;
attachment->setWorldVerticesLength(verticesLength);
entry = Json::getItem(attachmentMap, "vertices");
entrySize = entry->_size;
vertices.ensureCapacity(entrySize);
vertices.setSize(entrySize, 0);
for (entry = entry->_child, i = 0; entry; entry = entry->_next, ++i)
vertices[i] = entry->_valueFloat;
if (verticesLength == entrySize) {
if (_scale != 1) {
for (i = 0; i < entrySize; ++i)
vertices[i] *= _scale;
}
attachment->getVertices().clearAndAddAll(vertices);
return;
}
Vertices bonesAndWeights;
bonesAndWeights._bones.ensureCapacity(verticesLength * 3);
bonesAndWeights._vertices.ensureCapacity(verticesLength * 3 * 3);
for (i = 0, n = entrySize; i < n;) {
int boneCount = (int) vertices[i++];
bonesAndWeights._bones.add(boneCount);
for (nn = i + boneCount * 4; i < nn; i += 4) {
bonesAndWeights._bones.add((int) vertices[i]);
bonesAndWeights._vertices.add(vertices[i + 1] * _scale);
bonesAndWeights._vertices.add(vertices[i + 2] * _scale);
bonesAndWeights._vertices.add(vertices[i + 3]);
}
}
attachment->getVertices().clearAndAddAll(bonesAndWeights._vertices);
attachment->getBones().clearAndAddAll(bonesAndWeights._bones);
}
void SkeletonJson::setError(Json *root, const String &value1, const String &value2) {
_error = String(value1).append(value2);
delete root;
}
|
// Copyright (c) 2014-2018 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 <chainparams.h>
#include <validation.h>
#include <net.h>
#include <test/test_neom.h>
#include <boost/signals2/signal.hpp>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup)
static void TestBlockSubsidyHalvings(const Consensus::Params& consensusParams)
{
int maxHalvings = 64;
CAmount nInitialSubsidy = 25 * COIN;
CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0
BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2);
for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) {
int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval;
CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams);
BOOST_CHECK(nSubsidy <= nInitialSubsidy);
BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2);
nPreviousSubsidy = nSubsidy;
}
BOOST_CHECK_EQUAL(GetBlockSubsidy(maxHalvings * consensusParams.nSubsidyHalvingInterval, consensusParams), 0);
}
static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval)
{
Consensus::Params consensusParams;
consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval;
TestBlockSubsidyHalvings(consensusParams);
}
BOOST_AUTO_TEST_CASE(block_subsidy_test)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
TestBlockSubsidyHalvings(chainParams->GetConsensus()); // As in main
TestBlockSubsidyHalvings(150); // As in regtest
TestBlockSubsidyHalvings(1000); // Just another interval
}
BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
CAmount nSum = 0;
for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) {
CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams->GetConsensus());
BOOST_CHECK(nSubsidy <= 25 * COIN);
nSum += nSubsidy * 1000;
BOOST_CHECK(MoneyRange(nSum));
}
BOOST_CHECK_EQUAL(nSum, CAmount{2099999997690000});
}
static bool ReturnFalse() { return false; }
static bool ReturnTrue() { return true; }
BOOST_AUTO_TEST_CASE(test_combiner_all)
{
boost::signals2::signal<bool (), CombinerAll> Test;
BOOST_CHECK(Test());
Test.connect(&ReturnFalse);
BOOST_CHECK(!Test());
Test.connect(&ReturnTrue);
BOOST_CHECK(!Test());
Test.disconnect(&ReturnFalse);
BOOST_CHECK(Test());
Test.disconnect(&ReturnTrue);
BOOST_CHECK(Test());
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "ngraph/op/util/unary_elementwise_arithmetic.hpp"
namespace ngraph
{
namespace op
{
namespace v0
{
/// \brief Elementwise hyperbolic cosine (cosh) operation.
class NGRAPH_API Cosh : public util::UnaryElementwiseArithmetic
{
public:
static constexpr NodeTypeInfo type_info{"Cosh", 0};
const NodeTypeInfo& get_type_info() const override { return type_info; }
/// \brief Constructs a hyperbolic cosine operation.
Cosh() = default;
/// \brief Constructs a hyperbolic cosine operation.
///
/// \param arg Node that produces the input tensor.
Cosh(const Output<Node>& arg);
bool visit_attributes(AttributeVisitor& visitor) override;
virtual std::shared_ptr<Node>
clone_with_new_inputs(const OutputVector& new_args) const override;
bool evaluate(const HostTensorVector& outputs,
const HostTensorVector& inputs) const override;
};
} // namespace v0
using v0::Cosh;
} // namespace op
} // namespace ngraph
|
/*****************************************************************************/
/* SFileAddFile.cpp Copyright (c) Ladislav Zezula 2010 */
/*---------------------------------------------------------------------------*/
/* MPQ Editing functions */
/*---------------------------------------------------------------------------*/
/* Date Ver Who Comment */
/* -------- ---- --- ------- */
/* 27.03.10 1.00 Lad Splitted from SFileCreateArchiveEx.cpp */
/* 21.04.13 1.01 Dea AddFile callback now part of TMPQArchive */
/*****************************************************************************/
#define __STORMLIB_SELF__
#include "StormLib.h"
#include "StormCommon.h"
//-----------------------------------------------------------------------------
// Local variables
// Mask for lossy compressions
#define MPQ_LOSSY_COMPRESSION_MASK (MPQ_COMPRESSION_ADPCM_MONO | MPQ_COMPRESSION_ADPCM_STEREO | MPQ_COMPRESSION_HUFFMANN)
// Data compression for SFileAddFile
// Kept here for compatibility with code that was created with StormLib version < 6.50
static DWORD DefaultDataCompression = MPQ_COMPRESSION_PKWARE;
//-----------------------------------------------------------------------------
// WAVE verification
#define FILE_SIGNATURE_RIFF 0x46464952
#define FILE_SIGNATURE_WAVE 0x45564157
#define FILE_SIGNATURE_FMT 0x20746D66
#define AUDIO_FORMAT_PCM 1
typedef struct _WAVE_FILE_HEADER
{
DWORD dwChunkId; // 0x52494646 ("RIFF")
DWORD dwChunkSize; // Size of that chunk, in bytes
DWORD dwFormat; // Must be 0x57415645 ("WAVE")
// Format sub-chunk
DWORD dwSubChunk1Id; // 0x666d7420 ("fmt ")
DWORD dwSubChunk1Size; // 0x16 for PCM
USHORT wAudioFormat; // 1 = PCM. Other value means some sort of compression
USHORT wChannels; // Number of channels
DWORD dwSampleRate; // 8000, 44100, etc.
DWORD dwBytesRate; // SampleRate * NumChannels * BitsPerSample/8
USHORT wBlockAlign; // NumChannels * BitsPerSample/8
USHORT wBitsPerSample; // 8 bits = 8, 16 bits = 16, etc.
// Followed by "data" sub-chunk (we don't care)
} WAVE_FILE_HEADER, *PWAVE_FILE_HEADER;
static bool IsWaveFile_16BitsPerAdpcmSample(
LPBYTE pbFileData,
DWORD cbFileData,
LPDWORD pdwChannels)
{
PWAVE_FILE_HEADER pWaveHdr = (PWAVE_FILE_HEADER)pbFileData;
// The amount of file data must be at least size of WAVE header
if(cbFileData > sizeof(WAVE_FILE_HEADER))
{
// Check for the RIFF header
if(pWaveHdr->dwChunkId == FILE_SIGNATURE_RIFF && pWaveHdr->dwFormat == FILE_SIGNATURE_WAVE)
{
// Check for ADPCM format
if(pWaveHdr->dwSubChunk1Id == FILE_SIGNATURE_FMT && pWaveHdr->wAudioFormat == AUDIO_FORMAT_PCM)
{
// Now the number of bits per sample must be at least 16.
// If not, the WAVE file gets corrupted by the ADPCM compression
if(pWaveHdr->wBitsPerSample >= 0x10)
{
*pdwChannels = pWaveHdr->wChannels;
return true;
}
}
}
}
return false;
}
static DWORD FillWritableHandle(
TMPQArchive * ha,
TMPQFile * hf,
ULONGLONG FileTime,
DWORD dwFileSize,
DWORD dwFlags)
{
TFileEntry * pFileEntry = hf->pFileEntry;
// Initialize the hash entry for the file
hf->RawFilePos = ha->MpqPos + hf->MpqFilePos;
hf->dwDataSize = dwFileSize;
// Initialize the block table entry for the file
pFileEntry->ByteOffset = hf->MpqFilePos;
pFileEntry->dwFileSize = dwFileSize;
pFileEntry->dwCmpSize = 0;
pFileEntry->dwFlags = dwFlags | MPQ_FILE_EXISTS;
// Initialize hashing of the file
if((hf->hctx = STORM_ALLOC(hash_state, 1)) != NULL)
md5_init((hash_state *)hf->hctx);
// Fill-in file time and CRC
pFileEntry->FileTime = FileTime;
pFileEntry->dwCrc32 = crc32(0, Z_NULL, 0);
// Mark the archive as modified
ha->dwFlags |= MPQ_FLAG_CHANGED;
// Call the callback, if needed
if(ha->pfnAddFileCB != NULL)
ha->pfnAddFileCB(ha->pvAddFileUserData, 0, hf->dwDataSize, false);
hf->dwAddFileError = ERROR_SUCCESS;
return ERROR_SUCCESS;
}
//-----------------------------------------------------------------------------
// MPQ write data functions
static DWORD WriteDataToMpqFile(
TMPQArchive * ha,
TMPQFile * hf,
LPBYTE pbFileData,
DWORD dwDataSize,
DWORD dwCompression)
{
TFileEntry * pFileEntry = hf->pFileEntry;
ULONGLONG ByteOffset;
LPBYTE pbCompressed = NULL; // Compressed (target) data
LPBYTE pbToWrite = hf->pbFileSector; // Data to write to the file
DWORD dwErrCode = ERROR_SUCCESS;
int nCompressionLevel; // ADPCM compression level (only used for wave files)
// Make sure that the caller won't overrun the previously initiated file size
assert(hf->dwFilePos + dwDataSize <= pFileEntry->dwFileSize);
assert(hf->dwSectorCount != 0);
assert(hf->pbFileSector != NULL);
if((hf->dwFilePos + dwDataSize) > pFileEntry->dwFileSize)
return ERROR_DISK_FULL;
// Now write all data to the file sector buffer
if(dwErrCode == ERROR_SUCCESS)
{
DWORD dwBytesInSector = hf->dwFilePos % hf->dwSectorSize;
DWORD dwSectorIndex = hf->dwFilePos / hf->dwSectorSize;
DWORD dwBytesToCopy;
// Process all data.
while(dwDataSize != 0)
{
dwBytesToCopy = dwDataSize;
// Check for sector overflow
if(dwBytesToCopy > (hf->dwSectorSize - dwBytesInSector))
dwBytesToCopy = (hf->dwSectorSize - dwBytesInSector);
// Copy the data to the file sector
memcpy(hf->pbFileSector + dwBytesInSector, pbFileData, dwBytesToCopy);
dwBytesInSector += dwBytesToCopy;
pbFileData += dwBytesToCopy;
dwDataSize -= dwBytesToCopy;
// Update the file position
hf->dwFilePos += dwBytesToCopy;
// If the current sector is full, or if the file is already full,
// then write the data to the MPQ
if(dwBytesInSector >= hf->dwSectorSize || hf->dwFilePos >= pFileEntry->dwFileSize)
{
// Set the position in the file
ByteOffset = hf->RawFilePos + pFileEntry->dwCmpSize;
// Update MD5 and CRC32 of the file
if(hf->hctx != NULL)
md5_process((hash_state *)hf->hctx, hf->pbFileSector, dwBytesInSector);
hf->dwCrc32 = crc32(hf->dwCrc32, hf->pbFileSector, dwBytesInSector);
// Compress the file sector, if needed
if(pFileEntry->dwFlags & MPQ_FILE_COMPRESS_MASK)
{
int nOutBuffer = (int)dwBytesInSector;
int nInBuffer = (int)dwBytesInSector;
// If the file is compressed, allocate buffer for the compressed data.
// Note that we allocate buffer that is a bit longer than sector size,
// for case if the compression method performs a buffer overrun
if(pbCompressed == NULL)
{
pbToWrite = pbCompressed = STORM_ALLOC(BYTE, hf->dwSectorSize + 0x100);
if(pbCompressed == NULL)
{
dwErrCode = ERROR_NOT_ENOUGH_MEMORY;
break;
}
}
//
// Note that both SCompImplode and SCompCompress copy data as-is,
// if they are unable to compress the data.
//
if(pFileEntry->dwFlags & MPQ_FILE_IMPLODE)
{
SCompImplode(pbCompressed, &nOutBuffer, hf->pbFileSector, nInBuffer);
}
if(pFileEntry->dwFlags & MPQ_FILE_COMPRESS)
{
// If this is the first sector, we need to override the given compression
// by the first sector compression. This is because the entire sector must
// be compressed by the same compression.
//
// Test case:
//
// WRITE_FILE(hFile, pvBuffer, 0x10, MPQ_COMPRESSION_PKWARE) // Write 0x10 bytes (sector 0)
// WRITE_FILE(hFile, pvBuffer, 0x10, MPQ_COMPRESSION_ADPCM_MONO) // Write 0x10 bytes (still sector 0)
// WRITE_FILE(hFile, pvBuffer, 0x10, MPQ_COMPRESSION_ADPCM_MONO) // Write 0x10 bytes (still sector 0)
// WRITE_FILE(hFile, pvBuffer, 0x10, MPQ_COMPRESSION_ADPCM_MONO) // Write 0x10 bytes (still sector 0)
dwCompression = (dwSectorIndex == 0) ? hf->dwCompression0 : dwCompression;
// If the caller wants ADPCM compression, we will set wave compression level to 4,
// which corresponds to medium quality
nCompressionLevel = (dwCompression & MPQ_LOSSY_COMPRESSION_MASK) ? 4 : -1;
SCompCompress(pbCompressed, &nOutBuffer, hf->pbFileSector, nInBuffer, (unsigned)dwCompression, 0, nCompressionLevel);
}
// Update sector positions
dwBytesInSector = nOutBuffer;
if(hf->SectorOffsets != NULL)
hf->SectorOffsets[dwSectorIndex+1] = hf->SectorOffsets[dwSectorIndex] + dwBytesInSector;
// We have to calculate sector CRC, if enabled
if(hf->SectorChksums != NULL)
hf->SectorChksums[dwSectorIndex] = adler32(0, pbCompressed, nOutBuffer);
}
// Encrypt the sector, if necessary
if(pFileEntry->dwFlags & MPQ_FILE_ENCRYPTED)
{
BSWAP_ARRAY32_UNSIGNED(pbToWrite, dwBytesInSector);
EncryptMpqBlock(pbToWrite, dwBytesInSector, hf->dwFileKey + dwSectorIndex);
BSWAP_ARRAY32_UNSIGNED(pbToWrite, dwBytesInSector);
}
// Write the file sector
if(!FileStream_Write(ha->pStream, &ByteOffset, pbToWrite, dwBytesInSector))
{
dwErrCode = GetLastError();
break;
}
// Call the compact callback, if any
if(ha->pfnAddFileCB != NULL)
ha->pfnAddFileCB(ha->pvAddFileUserData, hf->dwFilePos, hf->dwDataSize, false);
// Update the compressed file size
pFileEntry->dwCmpSize += dwBytesInSector;
dwBytesInSector = 0;
dwSectorIndex++;
}
}
}
// Cleanup
if(pbCompressed != NULL)
STORM_FREE(pbCompressed);
return dwErrCode;
}
//-----------------------------------------------------------------------------
// Recrypts file data for file renaming
static DWORD RecryptFileData(
TMPQArchive * ha,
TMPQFile * hf,
const char * szFileName,
const char * szNewFileName)
{
ULONGLONG RawFilePos;
TFileEntry * pFileEntry = hf->pFileEntry;
DWORD dwBytesToRecrypt = pFileEntry->dwCmpSize;
DWORD dwOldKey;
DWORD dwNewKey;
DWORD dwErrCode = ERROR_SUCCESS;
// The file must be encrypted
assert(pFileEntry->dwFlags & MPQ_FILE_ENCRYPTED);
// File decryption key is calculated from the plain name
szNewFileName = GetPlainFileName(szNewFileName);
szFileName = GetPlainFileName(szFileName);
// Calculate both file keys
dwOldKey = DecryptFileKey(szFileName, pFileEntry->ByteOffset, pFileEntry->dwFileSize, pFileEntry->dwFlags);
dwNewKey = DecryptFileKey(szNewFileName, pFileEntry->ByteOffset, pFileEntry->dwFileSize, pFileEntry->dwFlags);
// Incase the keys are equal, don't recrypt the file
if(dwNewKey == dwOldKey)
return ERROR_SUCCESS;
hf->dwFileKey = dwOldKey;
// Calculate the raw position of the file in the archive
hf->MpqFilePos = pFileEntry->ByteOffset;
hf->RawFilePos = ha->MpqPos + hf->MpqFilePos;
// Allocate buffer for file transfer
dwErrCode = AllocateSectorBuffer(hf);
if(dwErrCode != ERROR_SUCCESS)
return dwErrCode;
// Also allocate buffer for sector offsets
// Note: Don't load sector checksums, we don't need to recrypt them
dwErrCode = AllocateSectorOffsets(hf, true);
if(dwErrCode != ERROR_SUCCESS)
return dwErrCode;
// If we have sector offsets, recrypt these as well
if(hf->SectorOffsets != NULL)
{
// Allocate secondary buffer for sectors copy
DWORD * SectorOffsetsCopy = STORM_ALLOC(DWORD, hf->SectorOffsets[0] / sizeof(DWORD));
DWORD dwSectorOffsLen = hf->SectorOffsets[0];
if(SectorOffsetsCopy == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
// Recrypt the array of sector offsets
memcpy(SectorOffsetsCopy, hf->SectorOffsets, dwSectorOffsLen);
EncryptMpqBlock(SectorOffsetsCopy, dwSectorOffsLen, dwNewKey - 1);
BSWAP_ARRAY32_UNSIGNED(SectorOffsetsCopy, dwSectorOffsLen);
// Write the recrypted array back
if(!FileStream_Write(ha->pStream, &hf->RawFilePos, SectorOffsetsCopy, dwSectorOffsLen))
dwErrCode = GetLastError();
STORM_FREE(SectorOffsetsCopy);
}
// Now we have to recrypt all file sectors. We do it without
// recompression, because recompression is not necessary in this case
if(dwErrCode == ERROR_SUCCESS)
{
for(DWORD dwSector = 0; dwSector < hf->dwSectorCount; dwSector++)
{
DWORD dwRawDataInSector = hf->dwSectorSize;
DWORD dwRawByteOffset = dwSector * hf->dwSectorSize;
// Last sector: If there is not enough bytes remaining in the file, cut the raw size
if(dwRawDataInSector > dwBytesToRecrypt)
dwRawDataInSector = dwBytesToRecrypt;
// Fix the raw data length if the file is compressed
if(hf->SectorOffsets != NULL)
{
dwRawDataInSector = hf->SectorOffsets[dwSector+1] - hf->SectorOffsets[dwSector];
dwRawByteOffset = hf->SectorOffsets[dwSector];
}
// Calculate the raw file offset of the file sector
RawFilePos = CalculateRawSectorOffset(hf, dwRawByteOffset);
// Read the file sector
if(!FileStream_Read(ha->pStream, &RawFilePos, hf->pbFileSector, dwRawDataInSector))
{
dwErrCode = GetLastError();
break;
}
// If necessary, re-encrypt the sector
// Note: Recompression is not necessary here. Unlike encryption,
// the compression does not depend on the position of the file in MPQ.
BSWAP_ARRAY32_UNSIGNED(hf->pbFileSector, dwRawDataInSector);
DecryptMpqBlock(hf->pbFileSector, dwRawDataInSector, dwOldKey + dwSector);
EncryptMpqBlock(hf->pbFileSector, dwRawDataInSector, dwNewKey + dwSector);
BSWAP_ARRAY32_UNSIGNED(hf->pbFileSector, dwRawDataInSector);
// Write the sector back
if(!FileStream_Write(ha->pStream, &RawFilePos, hf->pbFileSector, dwRawDataInSector))
{
dwErrCode = GetLastError();
break;
}
// Decrement number of bytes remaining
dwBytesToRecrypt -= hf->dwSectorSize;
}
}
return dwErrCode;
}
//-----------------------------------------------------------------------------
// Internal support for MPQ modifications
DWORD SFileAddFile_Init(
TMPQArchive * ha,
const char * szFileName,
ULONGLONG FileTime,
DWORD dwFileSize,
LCID lcLocale,
DWORD dwFlags,
TMPQFile ** phf)
{
TFileEntry * pFileEntry = NULL;
TMPQFile * hf = NULL; // File structure for newly added file
DWORD dwHashIndex = HASH_ENTRY_FREE;
DWORD dwErrCode = ERROR_SUCCESS;
//
// Note: This is an internal function so no validity checks are done.
// It is the caller's responsibility to make sure that no invalid
// flags get to this point
//
// Sestor CRC is not allowed with single unit files
if(dwFlags & MPQ_FILE_SINGLE_UNIT)
dwFlags &= ~MPQ_FILE_SECTOR_CRC;
// Sector CRC is not allowed if the file is not compressed
if(!(dwFlags & MPQ_FILE_COMPRESS_MASK))
dwFlags &= ~MPQ_FILE_SECTOR_CRC;
// Fix Key is not allowed if the file is not enrypted
if(!(dwFlags & MPQ_FILE_ENCRYPTED))
dwFlags &= ~MPQ_FILE_FIX_KEY;
// If the MPQ is of version 3.0 or higher, we ignore file locale.
// This is because HET and BET tables have no known support for it
if(ha->pHeader->wFormatVersion >= MPQ_FORMAT_VERSION_3)
lcLocale = 0;
// Allocate the TMPQFile entry for newly added file
hf = CreateWritableHandle(ha, dwFileSize);
if(hf == NULL)
return false;
// Allocate file entry in the MPQ
if(dwErrCode == ERROR_SUCCESS)
{
// Check if the file already exists in the archive
pFileEntry = GetFileEntryExact(ha, szFileName, lcLocale, &dwHashIndex);
if(pFileEntry != NULL)
{
if(dwFlags & MPQ_FILE_REPLACEEXISTING)
InvalidateInternalFiles(ha);
else
dwErrCode = ERROR_ALREADY_EXISTS;
}
else
{
// Attempt to allocate new file entry
pFileEntry = AllocateFileEntry(ha, szFileName, lcLocale, &dwHashIndex);
if(pFileEntry != NULL)
InvalidateInternalFiles(ha);
else
dwErrCode = ERROR_DISK_FULL;
}
// Set the file entry to the file structure
hf->pFileEntry = pFileEntry;
}
// Prepare the pointer to hash table entry
if(dwErrCode == ERROR_SUCCESS && ha->pHashTable != NULL && dwHashIndex < ha->pHeader->dwHashTableSize)
{
hf->pHashEntry = ha->pHashTable + dwHashIndex;
hf->pHashEntry->lcLocale = (USHORT)lcLocale;
}
// Prepare the file key
if(dwErrCode == ERROR_SUCCESS && (dwFlags & MPQ_FILE_ENCRYPTED))
{
hf->dwFileKey = DecryptFileKey(szFileName, hf->MpqFilePos, dwFileSize, dwFlags);
if(hf->dwFileKey == 0)
dwErrCode = ERROR_UNKNOWN_FILE_KEY;
}
// Fill the file entry and TMPQFile structure
if(dwErrCode == ERROR_SUCCESS)
{
// At this point, the file name in the file entry must be set
assert(pFileEntry->szFileName != NULL);
assert(_stricmp(pFileEntry->szFileName, szFileName) == 0);
dwErrCode = FillWritableHandle(ha, hf, FileTime, dwFileSize, dwFlags);
}
// Free the file handle if failed
if(dwErrCode != ERROR_SUCCESS && hf != NULL)
FreeFileHandle(hf);
// Give the handle to the caller
*phf = hf;
return dwErrCode;
}
DWORD SFileAddFile_Init(
TMPQArchive * ha,
TMPQFile * hfSrc,
TMPQFile ** phf)
{
TFileEntry * pFileEntry = NULL;
TMPQFile * hf = NULL; // File structure for newly added file
ULONGLONG FileTime = hfSrc->pFileEntry->FileTime;
DWORD dwFileSize = hfSrc->pFileEntry->dwFileSize;
DWORD dwFlags = hfSrc->pFileEntry->dwFlags;
DWORD dwErrCode = ERROR_SUCCESS;
// Allocate the TMPQFile entry for newly added file
hf = CreateWritableHandle(ha, dwFileSize);
if(hf == NULL)
dwErrCode = ERROR_NOT_ENOUGH_MEMORY;
// We need to keep the file entry index the same like in the source archive
// This is because multiple hash table entries can point to the same file entry
if(dwErrCode == ERROR_SUCCESS)
{
// Retrieve the file entry for the target file
pFileEntry = ha->pFileTable + (hfSrc->pFileEntry - hfSrc->ha->pFileTable);
// Copy all variables except file name
if((pFileEntry->dwFlags & MPQ_FILE_EXISTS) == 0)
{
pFileEntry[0] = hfSrc->pFileEntry[0];
pFileEntry->szFileName = NULL;
}
else
dwErrCode = ERROR_ALREADY_EXISTS;
// Set the file entry to the file structure
hf->pFileEntry = pFileEntry;
}
// Prepare the pointer to hash table entry
if(dwErrCode == ERROR_SUCCESS && ha->pHashTable != NULL && hfSrc->pHashEntry != NULL)
{
hf->dwHashIndex = (DWORD)(hfSrc->pHashEntry - hfSrc->ha->pHashTable);
hf->pHashEntry = ha->pHashTable + hf->dwHashIndex;
}
// Prepare the file key (copy from source file)
if(dwErrCode == ERROR_SUCCESS && (dwFlags & MPQ_FILE_ENCRYPTED))
{
hf->dwFileKey = hfSrc->dwFileKey;
if(hf->dwFileKey == 0)
dwErrCode = ERROR_UNKNOWN_FILE_KEY;
}
// Fill the file entry and TMPQFile structure
if(dwErrCode == ERROR_SUCCESS)
{
dwErrCode = FillWritableHandle(ha, hf, FileTime, dwFileSize, dwFlags);
}
// Free the file handle if failed
if(dwErrCode != ERROR_SUCCESS && hf != NULL)
FreeFileHandle(hf);
// Give the handle to the caller
*phf = hf;
return dwErrCode;
}
DWORD SFileAddFile_Write(TMPQFile * hf, const void * pvData, DWORD dwSize, DWORD dwCompression)
{
TMPQArchive * ha;
TFileEntry * pFileEntry;
DWORD dwErrCode = ERROR_SUCCESS;
// Don't bother if the caller gave us zero size
if(pvData == NULL || dwSize == 0)
return ERROR_SUCCESS;
// Get pointer to the MPQ archive
pFileEntry = hf->pFileEntry;
ha = hf->ha;
// Allocate file buffers
if(hf->pbFileSector == NULL)
{
ULONGLONG RawFilePos = hf->RawFilePos;
// Allocate buffer for file sector
hf->dwAddFileError = dwErrCode = AllocateSectorBuffer(hf);
if(dwErrCode != ERROR_SUCCESS)
return dwErrCode;
// Allocate patch info, if the data is patch
if(hf->pPatchInfo == NULL && IsIncrementalPatchFile(pvData, dwSize, &hf->dwPatchedFileSize))
{
// Set the MPQ_FILE_PATCH_FILE flag
pFileEntry->dwFlags |= MPQ_FILE_PATCH_FILE;
// Allocate the patch info
hf->dwAddFileError = dwErrCode = AllocatePatchInfo(hf, false);
if(dwErrCode != ERROR_SUCCESS)
return dwErrCode;
}
// Allocate sector offsets
if(hf->SectorOffsets == NULL)
{
hf->dwAddFileError = dwErrCode = AllocateSectorOffsets(hf, false);
if(dwErrCode != ERROR_SUCCESS)
return dwErrCode;
}
// Create array of sector checksums
if(hf->SectorChksums == NULL && (pFileEntry->dwFlags & MPQ_FILE_SECTOR_CRC))
{
hf->dwAddFileError = dwErrCode = AllocateSectorChecksums(hf, false);
if(dwErrCode != ERROR_SUCCESS)
return dwErrCode;
}
// Pre-save the patch info, if any
if(hf->pPatchInfo != NULL)
{
if(!FileStream_Write(ha->pStream, &RawFilePos, hf->pPatchInfo, hf->pPatchInfo->dwLength))
dwErrCode = GetLastError();
pFileEntry->dwCmpSize += hf->pPatchInfo->dwLength;
RawFilePos += hf->pPatchInfo->dwLength;
}
// Pre-save the sector offset table, just to reserve space in the file.
// Note that we dont need to swap the sector positions, nor encrypt the table
// at the moment, as it will be written again after writing all file sectors.
if(hf->SectorOffsets != NULL)
{
if(!FileStream_Write(ha->pStream, &RawFilePos, hf->SectorOffsets, hf->SectorOffsets[0]))
dwErrCode = GetLastError();
pFileEntry->dwCmpSize += hf->SectorOffsets[0];
RawFilePos += hf->SectorOffsets[0];
}
}
// Write the MPQ data to the file
if(dwErrCode == ERROR_SUCCESS)
{
// Save the first sector compression to the file structure
// Note that the entire first file sector will be compressed
// by compression that was passed to the first call of SFileAddFile_Write
if(hf->dwFilePos == 0)
hf->dwCompression0 = dwCompression;
// Write the data to the MPQ
dwErrCode = WriteDataToMpqFile(ha, hf, (LPBYTE)pvData, dwSize, dwCompression);
}
// If it succeeded and we wrote all the file data,
// we need to re-save sector offset table
if(dwErrCode == ERROR_SUCCESS)
{
if(hf->dwFilePos >= pFileEntry->dwFileSize)
{
// Finish calculating CRC32
pFileEntry->dwCrc32 = hf->dwCrc32;
// Finish calculating MD5
if(hf->hctx != NULL)
md5_done((hash_state *)hf->hctx, pFileEntry->md5);
// If we also have sector checksums, write them to the file
if(hf->SectorChksums != NULL)
{
dwErrCode = WriteSectorChecksums(hf);
}
// Now write patch info
if(hf->pPatchInfo != NULL)
{
memcpy(hf->pPatchInfo->md5, pFileEntry->md5, MD5_DIGEST_SIZE);
hf->pPatchInfo->dwDataSize = pFileEntry->dwFileSize;
pFileEntry->dwFileSize = hf->dwPatchedFileSize;
dwErrCode = WritePatchInfo(hf);
}
// Now write sector offsets to the file
if(hf->SectorOffsets != NULL)
{
dwErrCode = WriteSectorOffsets(hf);
}
// Write the MD5 hashes of each file chunk, if required
if(ha->pHeader->dwRawChunkSize != 0)
{
dwErrCode = WriteMpqDataMD5(ha->pStream,
ha->MpqPos + pFileEntry->ByteOffset,
hf->pFileEntry->dwCmpSize,
ha->pHeader->dwRawChunkSize);
}
}
}
// Update the archive size
if((ha->MpqPos + pFileEntry->ByteOffset + pFileEntry->dwCmpSize) > ha->FileSize)
ha->FileSize = ha->MpqPos + pFileEntry->ByteOffset + pFileEntry->dwCmpSize;
// Store the error code from the Write File operation
hf->dwAddFileError = dwErrCode;
return dwErrCode;
}
DWORD SFileAddFile_Finish(TMPQFile * hf)
{
TMPQArchive * ha = hf->ha;
TFileEntry * pFileEntry = hf->pFileEntry;
DWORD dwErrCode = hf->dwAddFileError;
// If all previous operations succeeded, we can update the MPQ
if(dwErrCode == ERROR_SUCCESS)
{
// Verify if the caller wrote the file properly
if(hf->pPatchInfo == NULL)
{
assert(pFileEntry != NULL);
if(hf->dwFilePos != pFileEntry->dwFileSize)
dwErrCode = ERROR_CAN_NOT_COMPLETE;
}
else
{
if(hf->dwFilePos != hf->pPatchInfo->dwDataSize)
dwErrCode = ERROR_CAN_NOT_COMPLETE;
}
}
// Now we need to recreate the HET table, if exists
if(dwErrCode == ERROR_SUCCESS && ha->pHetTable != NULL)
{
dwErrCode = RebuildHetTable(ha);
}
// Update the block table size
if(dwErrCode == ERROR_SUCCESS)
{
// Call the user callback, if any
if(ha->pfnAddFileCB != NULL)
ha->pfnAddFileCB(ha->pvAddFileUserData, hf->dwDataSize, hf->dwDataSize, true);
}
else
{
// Free the file entry in MPQ tables
if(pFileEntry != NULL)
DeleteFileEntry(ha, hf);
}
// Clear the add file callback
FreeFileHandle(hf);
return dwErrCode;
}
//-----------------------------------------------------------------------------
// Adds data as file to the archive
bool WINAPI SFileCreateFile(
HANDLE hMpq,
const char * szArchivedName,
ULONGLONG FileTime,
DWORD dwFileSize,
LCID lcLocale,
DWORD dwFlags,
HANDLE * phFile)
{
TMPQArchive * ha = (TMPQArchive *)hMpq;
DWORD dwErrCode = ERROR_SUCCESS;
// Check valid parameters
if(!IsValidMpqHandle(hMpq))
dwErrCode = ERROR_INVALID_HANDLE;
if(szArchivedName == NULL || *szArchivedName == 0)
dwErrCode = ERROR_INVALID_PARAMETER;
if(phFile == NULL)
dwErrCode = ERROR_INVALID_PARAMETER;
// Don't allow to add file if the MPQ is open for read only
if(dwErrCode == ERROR_SUCCESS)
{
if(ha->dwFlags & MPQ_FLAG_READ_ONLY)
dwErrCode = ERROR_ACCESS_DENIED;
// Don't allow to add a file under pseudo-file name
if(IsPseudoFileName(szArchivedName, NULL))
dwErrCode = ERROR_INVALID_PARAMETER;
// Don't allow to add any of the internal files
if(IsInternalMpqFileName(szArchivedName))
dwErrCode = ERROR_INTERNAL_FILE;
}
// Perform validity check of the MPQ flags
if(dwErrCode == ERROR_SUCCESS)
{
// Mask all unsupported flags out
dwFlags &= ha->dwValidFileFlags;
// Check for valid flag combinations
if((dwFlags & (MPQ_FILE_IMPLODE | MPQ_FILE_COMPRESS)) == (MPQ_FILE_IMPLODE | MPQ_FILE_COMPRESS))
dwErrCode = ERROR_INVALID_PARAMETER;
}
// Initiate the add file operation
if(dwErrCode == ERROR_SUCCESS)
dwErrCode = SFileAddFile_Init(ha, szArchivedName, FileTime, dwFileSize, lcLocale, dwFlags, (TMPQFile **)phFile);
// Deal with the errors
if(dwErrCode != ERROR_SUCCESS)
SetLastError(dwErrCode);
return (dwErrCode == ERROR_SUCCESS);
}
bool WINAPI SFileWriteFile(
HANDLE hFile,
const void * pvData,
DWORD dwSize,
DWORD dwCompression)
{
TMPQFile * hf = (TMPQFile *)hFile;
DWORD dwErrCode = ERROR_SUCCESS;
// Check the proper parameters
if(!IsValidFileHandle(hFile))
dwErrCode = ERROR_INVALID_HANDLE;
if(hf->bIsWriteHandle == false)
dwErrCode = ERROR_INVALID_HANDLE;
// Special checks for single unit files
if(dwErrCode == ERROR_SUCCESS && (hf->pFileEntry->dwFlags & MPQ_FILE_SINGLE_UNIT))
{
//
// Note: Blizzard doesn't support single unit files
// that are stored as encrypted or imploded. We will allow them here,
// the calling application must ensure that such flag combination doesn't get here
//
// if(dwFlags & MPQ_FILE_IMPLODE)
// dwErrCode = ERROR_INVALID_PARAMETER;
//
// if(dwFlags & MPQ_FILE_ENCRYPTED)
// dwErrCode = ERROR_INVALID_PARAMETER;
// Lossy compression is not allowed on single unit files
if(dwCompression & MPQ_LOSSY_COMPRESSION_MASK)
dwErrCode = ERROR_INVALID_PARAMETER;
}
// Write the data to the file
if(dwErrCode == ERROR_SUCCESS)
dwErrCode = SFileAddFile_Write(hf, pvData, dwSize, dwCompression);
// Deal with errors
if(dwErrCode != ERROR_SUCCESS)
SetLastError(dwErrCode);
return (dwErrCode == ERROR_SUCCESS);
}
bool WINAPI SFileFinishFile(HANDLE hFile)
{
TMPQFile * hf = (TMPQFile *)hFile;
DWORD dwErrCode = ERROR_SUCCESS;
// Check the proper parameters
if(!IsValidFileHandle(hFile))
dwErrCode = ERROR_INVALID_HANDLE;
if(hf->bIsWriteHandle == false)
dwErrCode = ERROR_INVALID_HANDLE;
// Finish the file
if(dwErrCode == ERROR_SUCCESS)
dwErrCode = SFileAddFile_Finish(hf);
// Deal with errors
if(dwErrCode != ERROR_SUCCESS)
SetLastError(dwErrCode);
return (dwErrCode == ERROR_SUCCESS);
}
//-----------------------------------------------------------------------------
// Adds a file to the archive
bool WINAPI SFileAddFileEx(
HANDLE hMpq,
const TCHAR * szFileName,
const char * szArchivedName,
DWORD dwFlags,
DWORD dwCompression, // Compression of the first sector
DWORD dwCompressionNext) // Compression of next sectors
{
ULONGLONG FileSize = 0;
ULONGLONG FileTime = 0;
TFileStream * pStream = NULL;
HANDLE hMpqFile = NULL;
LPBYTE pbFileData = NULL;
DWORD dwBytesRemaining = 0;
DWORD dwBytesToRead;
DWORD dwSectorSize = 0x1000;
DWORD dwChannels = 0;
bool bIsAdpcmCompression = false;
bool bIsFirstSector = true;
DWORD dwErrCode = ERROR_SUCCESS;
// Check parameters
if(hMpq == NULL || szFileName == NULL || *szFileName == 0)
{
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
// Open added file
pStream = FileStream_OpenFile(szFileName, STREAM_FLAG_READ_ONLY | STREAM_PROVIDER_FLAT | BASE_PROVIDER_FILE);
if(pStream == NULL)
return false;
// Files bigger than 4GB cannot be added to MPQ
FileStream_GetTime(pStream, &FileTime);
FileStream_GetSize(pStream, &FileSize);
if(FileSize >> 32)
dwErrCode = ERROR_DISK_FULL;
// Allocate data buffer for reading from the source file
if(dwErrCode == ERROR_SUCCESS)
{
dwBytesRemaining = (DWORD)FileSize;
pbFileData = STORM_ALLOC(BYTE, dwSectorSize);
if(pbFileData == NULL)
dwErrCode = ERROR_NOT_ENOUGH_MEMORY;
}
// Deal with various combination of compressions
if(dwErrCode == ERROR_SUCCESS)
{
// When the compression for next blocks is set to default,
// we will copy the compression for the first sector
if(dwCompressionNext == MPQ_COMPRESSION_NEXT_SAME)
dwCompressionNext = dwCompression;
// If the caller wants ADPCM compression, we make sure
// that the first sector is not compressed with lossy compression
if(dwCompressionNext & (MPQ_COMPRESSION_ADPCM_MONO | MPQ_COMPRESSION_ADPCM_STEREO))
{
// The compression of the first file sector must not be ADPCM
// in order not to corrupt the headers
if(dwCompression & (MPQ_COMPRESSION_ADPCM_MONO | MPQ_COMPRESSION_ADPCM_STEREO))
dwCompression = MPQ_COMPRESSION_PKWARE;
// Remove both flag mono and stereo flags.
// They will be re-added according to WAVE type
dwCompressionNext &= ~(MPQ_COMPRESSION_ADPCM_MONO | MPQ_COMPRESSION_ADPCM_STEREO);
bIsAdpcmCompression = true;
}
// Initiate adding file to the MPQ
if(!SFileCreateFile(hMpq, szArchivedName, FileTime, (DWORD)FileSize, g_lcFileLocale, dwFlags, &hMpqFile))
dwErrCode = GetLastError();
}
// Write the file data to the MPQ
while(dwErrCode == ERROR_SUCCESS && dwBytesRemaining != 0)
{
// Get the number of bytes remaining in the source file
dwBytesToRead = dwBytesRemaining;
if(dwBytesToRead > dwSectorSize)
dwBytesToRead = dwSectorSize;
// Read data from the local file
if(!FileStream_Read(pStream, NULL, pbFileData, dwBytesToRead))
{
dwErrCode = GetLastError();
break;
}
// If the file being added is a WAVE file, we check number of channels
if(bIsFirstSector && bIsAdpcmCompression)
{
// The file must really be a WAVE file with at least 16 bits per sample,
// otherwise the ADPCM compression will corrupt it
if(IsWaveFile_16BitsPerAdpcmSample(pbFileData, dwBytesToRead, &dwChannels))
{
// Setup the compression of next sectors according to number of channels
dwCompressionNext |= (dwChannels == 1) ? MPQ_COMPRESSION_ADPCM_MONO : MPQ_COMPRESSION_ADPCM_STEREO;
}
else
{
// Setup the compression of next sectors to a lossless compression
dwCompressionNext = (dwCompression & MPQ_LOSSY_COMPRESSION_MASK) ? MPQ_COMPRESSION_PKWARE : dwCompression;
}
bIsFirstSector = false;
}
// Add the file sectors to the MPQ
if(!SFileWriteFile(hMpqFile, pbFileData, dwBytesToRead, dwCompression))
{
dwErrCode = GetLastError();
break;
}
// Set the next data compression
dwBytesRemaining -= dwBytesToRead;
dwCompression = dwCompressionNext;
}
// Finish the file writing
if(hMpqFile != NULL)
{
if(!SFileFinishFile(hMpqFile))
dwErrCode = GetLastError();
}
// Cleanup and exit
if(pbFileData != NULL)
STORM_FREE(pbFileData);
if(pStream != NULL)
FileStream_Close(pStream);
if(dwErrCode != ERROR_SUCCESS)
SetLastError(dwErrCode);
return (dwErrCode == ERROR_SUCCESS);
}
// Adds a data file into the archive
bool WINAPI SFileAddFile(HANDLE hMpq, const TCHAR * szFileName, const char * szArchivedName, DWORD dwFlags)
{
return SFileAddFileEx(hMpq,
szFileName,
szArchivedName,
dwFlags,
DefaultDataCompression,
DefaultDataCompression);
}
// Adds a WAVE file into the archive
bool WINAPI SFileAddWave(HANDLE hMpq, const TCHAR * szFileName, const char * szArchivedName, DWORD dwFlags, DWORD dwQuality)
{
DWORD dwCompression = 0;
//
// Note to wave compression level:
// The following conversion table applied:
// High quality: WaveCompressionLevel = -1
// Medium quality: WaveCompressionLevel = 4
// Low quality: WaveCompressionLevel = 2
//
// Starcraft files are packed as Mono (0x41) on medium quality.
// Because this compression is not used anymore, our compression functions
// will default to WaveCompressionLevel = 4 when using ADPCM compression
//
// Convert quality to data compression
switch(dwQuality)
{
case MPQ_WAVE_QUALITY_HIGH:
// WaveCompressionLevel = -1;
dwCompression = MPQ_COMPRESSION_PKWARE;
break;
case MPQ_WAVE_QUALITY_MEDIUM:
// WaveCompressionLevel = 4;
dwCompression = MPQ_COMPRESSION_ADPCM_STEREO | MPQ_COMPRESSION_HUFFMANN;
break;
case MPQ_WAVE_QUALITY_LOW:
// WaveCompressionLevel = 2;
dwCompression = MPQ_COMPRESSION_ADPCM_STEREO | MPQ_COMPRESSION_HUFFMANN;
break;
}
return SFileAddFileEx(hMpq,
szFileName,
szArchivedName,
dwFlags,
MPQ_COMPRESSION_PKWARE, // First sector should be compressed as data
dwCompression); // Next sectors should be compressed as WAVE
}
//-----------------------------------------------------------------------------
// bool SFileRemoveFile(HANDLE hMpq, char * szFileName)
//
// This function removes a file from the archive.
//
bool WINAPI SFileRemoveFile(HANDLE hMpq, const char * szFileName, DWORD dwSearchScope)
{
TMPQArchive * ha = IsValidMpqHandle(hMpq);
TMPQFile * hf = NULL;
DWORD dwErrCode = ERROR_SUCCESS;
// Keep compiler happy
dwSearchScope = dwSearchScope;
// Check the parameters
if(ha == NULL)
dwErrCode = ERROR_INVALID_HANDLE;
if(szFileName == NULL || *szFileName == 0)
dwErrCode = ERROR_INVALID_PARAMETER;
if(IsInternalMpqFileName(szFileName))
dwErrCode = ERROR_INTERNAL_FILE;
// Do not allow to remove files from read-only or patched MPQs
if(dwErrCode == ERROR_SUCCESS)
{
if((ha->dwFlags & MPQ_FLAG_READ_ONLY) || (ha->haPatch != NULL))
dwErrCode = ERROR_ACCESS_DENIED;
}
// If all checks have passed, we can delete the file from the MPQ
if(dwErrCode == ERROR_SUCCESS)
{
// Open the file from the MPQ
if(SFileOpenFileEx(hMpq, szFileName, SFILE_OPEN_BASE_FILE, (HANDLE *)&hf))
{
// Delete the file entry
dwErrCode = DeleteFileEntry(ha, hf);
FreeFileHandle(hf);
}
else
dwErrCode = GetLastError();
}
// If the file has been deleted, we need to invalidate
// the internal files and recreate HET table
if(dwErrCode == ERROR_SUCCESS)
{
// Invalidate the entries for internal files
// After we are done with MPQ changes, we need to re-create them anyway
InvalidateInternalFiles(ha);
//
// Don't rebuild HET table now; the file's flags indicate
// that it's been deleted, which is enough
//
}
// Resolve error and exit
if(dwErrCode != ERROR_SUCCESS)
SetLastError(dwErrCode);
return (dwErrCode == ERROR_SUCCESS);
}
// Renames the file within the archive.
bool WINAPI SFileRenameFile(HANDLE hMpq, const char * szFileName, const char * szNewFileName)
{
TMPQArchive * ha = IsValidMpqHandle(hMpq);
TMPQFile * hf;
DWORD dwErrCode = ERROR_SUCCESS;
// Test the valid parameters
if(ha == NULL)
dwErrCode = ERROR_INVALID_HANDLE;
if(szFileName == NULL || *szFileName == 0 || szNewFileName == NULL || *szNewFileName == 0)
dwErrCode = ERROR_INVALID_PARAMETER;
if(IsInternalMpqFileName(szFileName) || IsInternalMpqFileName(szNewFileName))
dwErrCode = ERROR_INTERNAL_FILE;
// Do not allow to rename files in MPQ open for read only
if(dwErrCode == ERROR_SUCCESS)
{
if(ha->dwFlags & MPQ_FLAG_READ_ONLY)
dwErrCode = ERROR_ACCESS_DENIED;
}
// Open the new file. If exists, we don't allow rename operation
if(dwErrCode == ERROR_SUCCESS)
{
if(GetFileEntryLocale(ha, szNewFileName, g_lcFileLocale) != NULL)
dwErrCode = ERROR_ALREADY_EXISTS;
}
// Open the file from the MPQ
if(dwErrCode == ERROR_SUCCESS)
{
// Attempt to open the file
if(SFileOpenFileEx(hMpq, szFileName, SFILE_OPEN_BASE_FILE, (HANDLE *)&hf))
{
ULONGLONG RawDataOffs;
TFileEntry * pFileEntry = hf->pFileEntry;
// Invalidate the entries for internal files
InvalidateInternalFiles(ha);
// Rename the file entry in the table
dwErrCode = RenameFileEntry(ha, hf, szNewFileName);
// If the file is encrypted, we have to re-crypt the file content
// with the new decryption key
if((dwErrCode == ERROR_SUCCESS) && (pFileEntry->dwFlags & MPQ_FILE_ENCRYPTED))
{
// Recrypt the file data in the MPQ
dwErrCode = RecryptFileData(ha, hf, szFileName, szNewFileName);
// Update the MD5 of the raw block
if(dwErrCode == ERROR_SUCCESS && ha->pHeader->dwRawChunkSize != 0)
{
RawDataOffs = ha->MpqPos + pFileEntry->ByteOffset;
WriteMpqDataMD5(ha->pStream,
RawDataOffs,
pFileEntry->dwCmpSize,
ha->pHeader->dwRawChunkSize);
}
}
// Free the file handle
FreeFileHandle(hf);
}
else
{
dwErrCode = GetLastError();
}
}
// We also need to rebuild the HET table, if present
if(dwErrCode == ERROR_SUCCESS && ha->pHetTable != NULL)
dwErrCode = RebuildHetTable(ha);
// Resolve error and exit
if(dwErrCode != ERROR_SUCCESS)
SetLastError(dwErrCode);
return (dwErrCode == ERROR_SUCCESS);
}
//-----------------------------------------------------------------------------
// Sets default data compression for SFileAddFile
bool WINAPI SFileSetDataCompression(DWORD DataCompression)
{
unsigned int uValidMask = (MPQ_COMPRESSION_ZLIB | MPQ_COMPRESSION_PKWARE | MPQ_COMPRESSION_BZIP2 | MPQ_COMPRESSION_SPARSE);
if((DataCompression & uValidMask) != DataCompression)
{
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
DefaultDataCompression = DataCompression;
return true;
}
//-----------------------------------------------------------------------------
// Changes locale ID of a file
bool WINAPI SFileSetFileLocale(HANDLE hFile, LCID lcNewLocale)
{
TMPQArchive * ha;
TFileEntry * pFileEntry;
TMPQFile * hf = IsValidFileHandle(hFile);
// Invalid handle => do nothing
if(hf == NULL)
{
SetLastError(ERROR_INVALID_HANDLE);
return false;
}
// Do not allow to rename files in MPQ open for read only
ha = hf->ha;
if(ha->dwFlags & MPQ_FLAG_READ_ONLY)
{
SetLastError(ERROR_ACCESS_DENIED);
return false;
}
// Do not allow unnamed access
if(hf->pFileEntry->szFileName == NULL)
{
SetLastError(ERROR_CAN_NOT_COMPLETE);
return false;
}
// Do not allow to change locale of any internal file
if(IsInternalMpqFileName(hf->pFileEntry->szFileName))
{
SetLastError(ERROR_INTERNAL_FILE);
return false;
}
// Do not allow changing file locales if there is no hash table
if(hf->pHashEntry == NULL)
{
SetLastError(ERROR_NOT_SUPPORTED);
return false;
}
// We have to check if the file+locale is not already there
pFileEntry = GetFileEntryExact(ha, hf->pFileEntry->szFileName, lcNewLocale, NULL);
if(pFileEntry != NULL)
{
SetLastError(ERROR_ALREADY_EXISTS);
return false;
}
// Update the locale in the hash table entry
hf->pHashEntry->lcLocale = (USHORT)lcNewLocale;
ha->dwFlags |= MPQ_FLAG_CHANGED;
return true;
}
//-----------------------------------------------------------------------------
// Sets add file callback
bool WINAPI SFileSetAddFileCallback(HANDLE hMpq, SFILE_ADDFILE_CALLBACK AddFileCB, void * pvUserData)
{
TMPQArchive * ha = (TMPQArchive *) hMpq;
if(!IsValidMpqHandle(hMpq))
{
SetLastError(ERROR_INVALID_HANDLE);
return false;
}
ha->pvAddFileUserData = pvUserData;
ha->pfnAddFileCB = AddFileCB;
return true;
}
|
/** @file
A brief file description
@section license License
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.
*/
/****************************************************************************
StatPages.cc
****************************************************************************/
#include "ink_config.h"
#include "ProxyConfig.h"
#include "StatPages.h"
#include "HdrUtils.h"
#include "CacheInspectorAllow.h"
#include "MatcherUtils.h"
#define MAX_STAT_PAGES 100
// Globals
StatPagesManager statPagesManager;
static struct
{
char *module;
StatPagesFunc func;
} stat_pages[MAX_STAT_PAGES];
static int n_stat_pages = 0;
void
StatPagesManager::init()
{
REC_EstablishStaticConfigInt32(m_enabled, "proxy.config.http_ui_enabled");
}
void
StatPagesManager::register_http(char *module, StatPagesFunc func)
{
ink_release_assert(n_stat_pages < MAX_STAT_PAGES);
stat_pages[n_stat_pages].module = (char *) xmalloc(strlen(module) + 3);
snprintf(stat_pages[n_stat_pages].module, strlen(module) + 3, "{%s}", module);
stat_pages[n_stat_pages++].func = func;
}
Action *
StatPagesManager::handle_http(Continuation * cont, HTTPHdr * header, int client_ip)
{
URL *url = header->url_get();
if (((m_enabled == 1 || m_enabled == 3) &&
is_cache_inspector_page(url) &&
(!cache_inspector_allow_table || cache_inspector_allow_table->match(client_ip))) ||
((m_enabled == 2 || m_enabled == 3) && is_stat_page(url) && !is_cache_inspector_page(url))) {
int host_len;
char host[1024];
const char *h;
int i;
h = url->host_get(&host_len);
strncpy(host, h, host_len);
host[host_len] = '\0';
unescapifyStr(host);
host_len = strlen(host);
for (i = 0; i < n_stat_pages; i++) {
if (ptr_len_cmp(host, host_len, stat_pages[i].module) == 0) {
return stat_pages[i].func(cont, header);
}
}
}
cont->handleEvent(STAT_PAGE_FAILURE, 0);
return ACTION_RESULT_DONE;
}
bool StatPagesManager::is_stat_page(URL * url)
{
int
length;
const char *
h = url->host_get(&length);
//Bug fixed by YTS Team, yamsat BZ58899
char *
host = (char *) xmalloc(length + 1);
if (h == NULL || length < 2) {
xfree(host);
return false;
}
strncpy(host, h, length);
host[length] = '\0';
unescapifyStr(host);
length = strlen(host);
//return ((host[0] == '{') && (host[length-1] == '}'));
//Bug fixed by YTS Team, yamsat BZ58899
bool
retVal;
if ((host[0] == '{') && (host[length - 1] == '}'))
retVal = true;
else
retVal = false;
xfree(host);
return retVal;
}
bool StatPagesManager::is_cache_inspector_page(URL * url)
{
int
length;
const char *
h = url->host_get(&length);
char
host[1024];
if (h == NULL || length < 2) {
return false;
}
strncpy(host, h, length);
host[length] = '\0';
unescapifyStr(host);
length = strlen(host);
if (strncmp(host, "{cache}", length) == 0)
return true;
else
return false;
}
void
BaseStatPagesHandler::resp_clear()
{
if (response) {
xfree(response);
}
response = NULL;
response_size = 0;
response_length = 0;
}
void
BaseStatPagesHandler::resp_add(const char *fmt, ...)
{
va_list args;
char buf[16384];
int length;
int size;
va_start(args, fmt);
length = ink_vsnprintf(buf, 16384, fmt, args);
va_end(args);
size = response_size;
if (size == 0) {
size = 1024;
}
while ((response_length + length + 1) > size) {
size *= 2;
}
if (size != response_size) {
if (!response) {
response = (char *) xmalloc(size);
} else {
response = (char *) xrealloc(response, size);
}
response_size = size;
}
memcpy(&response[response_length], buf, length + 1);
response_length += length;
}
void
BaseStatPagesHandler::resp_add_sep()
{
resp_add("<hr width=\"100%%\">\n");
}
void
BaseStatPagesHandler::resp_begin(const char *title)
{
resp_clear();
resp_add("<html>\n"
"<head><title>%s</title></head>\n"
"<body text=\"#000000\" bgcolor=\"#ffffff\" link=\"#0000ee\" vlink=\"#551a8b\" alink=\"#ff0000\">\n", title);
}
void
BaseStatPagesHandler::resp_end()
{
resp_add("</body>\n" "</html>\n");
}
void
BaseStatPagesHandler::resp_begin_numbered()
{
resp_add("<ol>\n");
}
void
BaseStatPagesHandler::resp_end_numbered()
{
resp_add("</ol>\n");
}
void
BaseStatPagesHandler::resp_begin_unnumbered()
{
resp_add("<ul>\n");
}
void
BaseStatPagesHandler::resp_end_unnumbered()
{
resp_add("</ul>\n");
}
void
BaseStatPagesHandler::resp_begin_item()
{
resp_add("<li>\n");
}
void
BaseStatPagesHandler::resp_end_item()
{
resp_add("</li>\n");
}
void
BaseStatPagesHandler::resp_begin_table(int border, int columns, int percent)
{
resp_add("<table border=%d cols=%d width=\"%d%%\">\n", border, columns, percent);
}
void
BaseStatPagesHandler::resp_end_table()
{
resp_add("</table>\n");
}
void
BaseStatPagesHandler::resp_begin_row()
{
resp_add("<tr>\n");
}
void
BaseStatPagesHandler::resp_end_row()
{
resp_add("</tr>\n");
}
void
BaseStatPagesHandler::resp_begin_column(int percent, const char *align)
{
if (percent == -1) {
resp_add("<td %s%s>\n", align ? "align=" : "", align ? align : "");
} else {
resp_add("<td width=\"%d%%\" %s%s>\n", percent, align ? "align=" : "", align ? align : "");
}
}
void
BaseStatPagesHandler::resp_end_column()
{
resp_add("</td>\n");
}
|
#include "MainWindow.h"
#include <QApplication>
#include <QStyleFactory>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setOrganizationName("RangelReale");
app.setOrganizationDomain("rangelreale.com");
app.setApplicationName("ECAppLog");
#ifdef Q_OS_DARWIN
// Use "fusion" style on Mac to have scrollable tabs in QTabWidget
app.setStyle(QStyleFactory::create("Fusion"));
#endif
MainWindow mainwindow;
mainwindow.show();
return app.exec();
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobofleetBPMessageStructs.h"
|
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SWAPBYTES_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SWAPBYTES_HPP_INCLUDED
#include <boost/simd/detail/overload.hpp>
#include <boost/simd/meta/hierarchy/simd.hpp>
#include <boost/simd/function/shuffle.hpp>
#include <boost/simd/function/bitwise_cast.hpp>
#include <boost/simd/detail/dispatch/meta/as_integer.hpp>
namespace boost { namespace simd
{
namespace detail
{
template<std::size_t N> struct swap_bytes_helper
{
template<typename I, typename C>
struct apply : std::integral_constant < std::size_t, N*(I::value/N)+N-1-I::value%N>
{};
};
}
} }
namespace boost { namespace simd { namespace ext
{
namespace bd = boost::dispatch;
namespace bs = boost::simd;
BOOST_DISPATCH_OVERLOAD_IF(swapbytes_
, (typename A0, typename X)
, (detail::is_native<X>)
, bd::cpu_
, bs::pack_<bd::arithmetic_<A0>, X>
)
{
BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT
{
using s0 = bd::scalar_of_t<A0>;
static const size_t N = A0::static_size*sizeof(s0);
using i8 = pack<uint8_t, N>;
using pattern_t = detail::swap_bytes_helper<sizeof(s0)>;
return bitwise_cast<A0>(shuffle<pattern_t>(bitwise_cast<i8>(a0)));
}
};
BOOST_DISPATCH_OVERLOAD(swapbytes_
, (typename A0, typename X)
, bd::cpu_
, bs::pack_<bd::ints8_<A0>, X>
)
{
BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT
{
return a0;
}
};
} } }
#endif
|
#pragma once
#include <jln/mp/number/number.hpp>
#include <jln/mp/functional/identity.hpp>
namespace jln::mp
{
/// \ingroup trait
/// Wrapper for alignof keyword
/// \treturn \number
template<class C = identity>
struct alignof_
{
template<class x>
using f = typename C::template f<number<alignof(x)>>;
};
namespace emp
{
template<class x>
using alignof_ = number<alignof(x)>;
}
}
|
//
// Created by k s on 2021/9/5.
//
#include <learner_pax.hpp>
namespace paxosme {
int PaxLearner::SHALLILEARN_DELAY = SHALLILEARN_TIMEOUT_CONST;
void PaxLearner::Init() {
learner_send_loop_ = std::async(std::launch::async, &PaxLearner::SendingLoop, this);
auto callback= [this]{ShallILearn();};
Publish(EventType::kShallILearnTimeout, callback, SHALLILEARN_DELAY);
// todo I: need publish this kShallILearnTimeout event in other case
}
// bool PaxLearner::Learned() {
// return ;
// }
bool PaxLearner::HandleSenderPublish(const PaxMessage &pax_message) {
LearnFromSelf(pax_message);
return true;
}
void PaxLearner::HandleOthersPublish(const PaxMessage& pax_message) {
LearnFromOthers(pax_message);
}
}
|
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
// Portions Copyright (c) 2021 anticrisis <https://github.com/anticrisis>
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
//------------------------------------------------------------------------------
//
// Example: HTTP server, synchronous
//
// Changes by anticrisis marked with 'anticrisis'
//
//------------------------------------------------------------------------------
// anticrisis: include header
#include "http_tcl/http_tcl.h"
#include <atomic>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/config.hpp>
#include <iostream>
#include <memory>
#include <optional>
#include <string>
#include <thread>
// anticrisis: add namespace
namespace http_tcl
{
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
// anticrisis: add thread_count
std::atomic<int> thread_count;
//------------------------------------------------------------------------------
// This function produces an HTTP response for the given
// request. The type of the response object depends on the
// contents of the request, so the interface requires the
// caller to pass a generic lambda for receiving the response.
// anticrisis: remove support for doc_root and static files; add support for
// alt_handler
template <class Body, class Allocator, class Send>
void
handle_request(alt_handler& alt_handler,
http::request<Body, http::basic_fields<Allocator>>&& req,
Send&& send)
{
// Returns a bad request response
auto const bad_request = [&req](beast::string_view why) {
http::response<http::string_body> res{ http::status::bad_request,
req.version() };
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = std::string(why);
res.prepare_payload();
return res;
};
// Returns a not found response
auto const not_found = [&req](beast::string_view target) {
http::response<http::string_body> res{ http::status::not_found,
req.version() };
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = "The resource '" + std::string(target) + "' was not found.";
res.prepare_payload();
return res;
};
// Returns a server error response
auto const server_error = [&req](beast::string_view what) {
http::response<http::string_body> res{ http::status::internal_server_error,
req.version() };
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = "An error occurred: '" + std::string(what) + "'";
res.prepare_payload();
return res;
};
// anticrisis
auto const send_no_content
= [&send, &req](int status, std::optional<headers>&& headers) {
http::response<http::empty_body> res{ static_cast<http::status>(status),
req.version() };
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
if (headers)
for (auto& kv: *headers)
{
res.base().set(kv.first, std::move(kv.second));
}
res.keep_alive(req.keep_alive());
return send(std::move(res));
};
auto const send_empty = [&send, &req](int status,
std::optional<headers>&& headers,
size_t content_size,
std::string&& content_type) {
http::response<http::empty_body> res{ static_cast<http::status>(status),
req.version() };
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, content_type);
res.content_length(content_size);
if (headers)
for (auto& kv: *headers)
{
res.base().set(kv.first, std::move(kv.second));
}
res.keep_alive(req.keep_alive());
return send(std::move(res));
};
auto const send_body = [&send, &req](int status,
std::optional<headers>&& headers,
std::string&& body,
std::string&& content_type) {
http::response<http::string_body> res{ static_cast<http::status>(status),
req.version() };
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, content_type);
res.content_length(body.size());
if (headers)
for (auto& kv: *headers)
{
res.base().set(kv.first, std::move(kv.second));
}
res.body() = std::move(body);
res.keep_alive(req.keep_alive());
return send(std::move(res));
};
auto get_headers = [&req]() {
http_tcl::headers hs;
for (auto const& kv: req.base())
{
hs.emplace(kv.name_string(), kv.value());
}
return hs;
};
// Make sure we can handle the method
// anticrisis: add methods
if (req.method() != http::verb::get && req.method() != http::verb::head
&& req.method() != http::verb::post && req.method() != http::verb::put
&& req.method() != http::verb::delete_
&& req.method() != http::verb::options)
return send(bad_request("Unknown HTTP-method"));
// Request path must be absolute and not contain "..".
if (req.target().empty() || req.target()[0] != '/'
|| req.target().find("..") != beast::string_view::npos)
return send(bad_request("Illegal request-target"));
// anticrisis: replace doc_root support with alt_handler
if (req.method() == http::verb::options)
{
auto [status, headers, body, content_type]
= alt_handler.options({ req.target().data(), req.target().size() },
{ req.body().data(), req.body().size() },
std::move(get_headers));
return send_body(status,
std::move(headers),
std::move(body),
std::move(content_type));
}
else if (req.method() == http::verb::head)
{
auto [status, headers, size, content_type]
= alt_handler.head({ req.target().data(), req.target().size() },
std::move(get_headers));
return send_empty(status,
std::move(headers),
size,
std::move(content_type));
}
else if (req.method() == http::verb::get)
{
auto [status, headers, body, content_type]
= alt_handler.get({ req.target().data(), req.target().size() },
std::move(get_headers));
return send_body(status,
std::move(headers),
std::move(body),
std::move(content_type));
}
else if (req.method() == http::verb::post)
{
auto [status, headers, body, content_type]
= alt_handler.post({ req.target().data(), req.target().size() },
{ req.body().data(), req.body().size() },
std::move(get_headers));
return send_body(status,
std::move(headers),
std::move(body),
std::move(content_type));
}
else if (req.method() == http::verb::put)
{
auto [status, headers]
= alt_handler.put({ req.target().data(), req.target().size() },
{ req.body().data(), req.body().size() },
std::move(get_headers));
return send_no_content(status, std::move(headers));
}
else if (req.method() == http::verb::delete_)
{
auto [status, headers, body, content_type]
= alt_handler.delete_({ req.target().data(), req.target().size() },
{ req.body().data(), req.body().size() },
std::move(get_headers));
return send_body(status,
std::move(headers),
std::move(body),
std::move(content_type));
}
return send(server_error("not implemented."));
}
//------------------------------------------------------------------------------
// Report a failure
void
fail(beast::error_code ec, char const* what)
{
// anticrisis: ignore these common errors
if (ec == net::error::operation_aborted || ec == beast::error::timeout
|| ec == net::error::connection_reset)
return;
std::cerr << what << ": " << ec.message() << "\n";
}
// This is the C++11 equivalent of a generic lambda.
// The function object is used to send an HTTP message.
template <class Stream>
struct send_lambda
{
Stream& stream_;
bool& close_;
beast::error_code& ec_;
explicit send_lambda(Stream& stream, bool& close, beast::error_code& ec)
: stream_(stream)
, close_(close)
, ec_(ec)
{
}
template <bool isRequest, class Body, class Fields>
void
operator()(http::message<isRequest, Body, Fields>&& msg) const
{
// Determine if we should close the connection after
close_ = msg.need_eof();
// We need the serializer here because the serializer requires
// a non-const file_body, and the message oriented version of
// http::write only works with const messages.
http::serializer<isRequest, Body, Fields> sr{ msg };
http::write(stream_, sr, ec_);
}
};
// Handles an HTTP server connection
void
do_session(tcp::socket& socket, alt_handler* alt_handler)
{
bool close = false;
beast::error_code ec;
// anticrisis: increment thread count, decrement on exit
thread_count++;
auto _ = finally([] { thread_count--; });
// This buffer is required to persist across reads
beast::flat_buffer buffer;
// This lambda is used to send messages
send_lambda<tcp::socket> lambda{ socket, close, ec };
for (;;)
{
// Read a request
http::request<http::string_body> req;
http::read(socket, buffer, req, ec);
if (ec == http::error::end_of_stream)
break;
if (ec)
return fail(ec, "read");
// Send the response
// anticrisis: remove doc_root
handle_request(*alt_handler, std::move(req), lambda);
if (ec)
return fail(ec, "write");
if (close)
{
// This means we should close the connection, usually because
// the response indicated the "Connection: close" semantic.
break;
}
}
// Send a TCP shutdown
socket.shutdown(tcp::socket::shutdown_send, ec);
// At this point the connection is closed gracefully
}
//------------------------------------------------------------------------------
// anticrisis: change main to run; remove doc_root
int
run(std::string_view address_,
unsigned short port,
alt_handler* alt_handler,
int max_connections)
{
try
{
thread_count = 0;
auto const address = net::ip::make_address(address_);
// The io_context is required for all I/O
net::io_context ioc{ 1 };
// The acceptor receives incoming connections
tcp::acceptor acceptor{ ioc, { address, port } };
for (;;)
{
// anticrisis busy wait until thread_count is in range - will probably
// cause client and server errors
while (thread_count >= max_connections)
{
std::this_thread::yield();
}
// This will receive the new connection
tcp::socket socket{ ioc };
// Block until we get a connection
acceptor.accept(socket);
// Launch the session, transferring ownership of the socket
std::thread{ std::bind(&do_session, std::move(socket), alt_handler) }
.detach();
}
}
catch (const std::exception& e)
{
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//------------------------------------------------------------------------------
alt_handler::options_r
options(std::string_view target)
{
return { 404, headers{}, "", "" };
}
alt_handler::head_r
head(std::string_view target)
{
return { 404, headers{}, 0, "" };
}
alt_handler::get_r
get(std::string_view target)
{
return { 404, headers{}, "", "" };
}
alt_handler::post_r
post(std::string_view target, std::string_view body)
{
return { 404, headers{}, "", "" };
}
alt_handler::put_r
put(std::string_view target, std::string_view body)
{
return { 404, headers{} };
}
alt_handler::delete_r
delete_(std::string_view target, std::string_view body)
{
return { 404, headers{}, "", "" };
}
} // namespace http_tcl
|
#include <UECS/World.h>
#include <iostream>
using namespace Ubpa::UECS;
using namespace std;
struct Data1 {};
struct Data2 {};
class DataSystem : public System {
public:
using System::System;
virtual void OnUpdate(Schedule& schedule) noexcept {
schedule.Register([](Data1* d1, Data2* d2) { cout << "writer_sys0" << endl; }, "writer_sys0");
schedule.Register([](Data1* d) { cout << "writer_sys1" << endl; }, "writer_sys1");
schedule.Register([](Data2* d2) { cout << "writer_sys2" << endl; }, "writer_sys2");
schedule.Register([](Data1* d, Data2* d2) { cout << "writer_sys3" << endl; }, "writer_sys3");
schedule
.Order("writer_sys0", "writer_sys1")
.Order("writer_sys1", "writer_sys3");
}
};
int main() {
RTDCmptTraits::Instance().Register<
Data1,
Data2
>();
World w;
w.systemMngr.Register<DataSystem>();
w.entityMngr.Create<Data1, Data2>();
w.Update();
cout << w.DumpUpdateJobGraph() << endl;
cout << w.GenUpdateFrameGraph().Dump() << endl;
return 0;
}
|
#ifndef RTCP_FB_PUB_HPP
#define RTCP_FB_PUB_HPP
#include <stdint.h>
#include <stddef.h>
#include <string>
#include <cstring>
#include <stdio.h>
#include <arpa/inet.h> // htonl(), htons(), ntohl(), ntohs()
/*
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|V=2|P| FMT | PT | length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SSRC of packet sender |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SSRC of media source |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
: Feedback Control Information (FCI) :
: :
*/
typedef struct rtcp_fb_header_s
{
uint32_t sender_ssrc;
uint32_t media_ssrc;
} rtcp_fb_header;
#endif
|
/*
Copyright (c) 2005-2019, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 the University of Oxford 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.
*/
#ifndef _ABSTRACTODESYSTEM_HPP_
#define _ABSTRACTODESYSTEM_HPP_
#include <vector>
#include <string>
#include <algorithm>
#include "ChasteSerialization.hpp"
#include "ChasteSerializationVersion.hpp"
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/vector.hpp>
#include "ClassIsAbstract.hpp"
#include "AbstractParameterisedSystem.hpp"
#include "Exception.hpp"
/**
* Abstract OdeSystem class.
*
* Sets up variables and functions for a general ODE system.
*
* ODE systems are specified primarily by the EvaluateYDerivatives() method,
* which calculates the right-hand side of the system.
*
* Instances can store their state internally in the mStateVariables vector
* in our base class AbstractParameterisedSystem (see also
* GetNumberOfStateVariables(), SetStateVariables() and rGetStateVariables()),
* although this is not essential - the vector may be empty, in which case
* AbstractIvpOdeSolver::SolveAndUpdateStateVariable may not be used to
* solve the system.
*
* ODE systems may also have a vector of parameters, which can be accessed
* through the GetParameter() and SetParameter() methods of our base class.
*
* Information about what the parameters and state variables represent is
* provided by a subclass of AbstractOdeSystemInformation. Various wrapper
* methods (e.g. rGetStateVariableNames()) are provided in our base class to
* access this information.
*
* There are two more advanced facilities available for subclass authors.
* An analytic form for the Jacobian matrix of the system may be provided,
* in which case you must subclass AbstractOdeSystemWithAnalyticJacobian.
* The GetUseAnalyticJacobian() method will test whether this is the case.
*
* Also, subclasses may define a condition at which ODE solvers should stop
* prematurely. For the Chaste solvers this is done by overriding
* CalculateStoppingEvent(); if the more advanced CVODE solvers are being used
* then implement CalculateRootFunction() instead to detect the stopping time
* more accurately.
*/
class AbstractOdeSystem : public AbstractParameterisedSystem<std::vector<double> >
{
friend class TestAbstractOdeSystem;
private:
friend class boost::serialization::access;
/**
* Archive the member variables.
*
* @param archive the archive
* @param version the current version of this class
*/
template<class Archive>
void save(Archive & archive, const unsigned int version) const
{
// Despite the fact that 3 of these variables actually live in our base class,
// we still archive them here to maintain backwards compatibility.
// Since the N_Vector version of mStateVariables and mParameters needs converting
// to a standard vector before archiving, this doesn't hurt too much.
archive & mNumberOfStateVariables;
archive & mUseAnalyticJacobian;
archive & mStateVariables;
archive & mParameters;
if (version > 0)
{
archive & rGetParameterNames();
}
// This is always set up by subclass constructors, and is essentially
// 'static' data, so shouldn't go in the archive.
//archive &mpSystemInfo;
}
/**
* Archive the member variables.
*
* @param archive the archive
* @param version the current version of this class
*/
template<class Archive>
void load(Archive & archive, const unsigned int version)
{
archive & mNumberOfStateVariables;
archive & mUseAnalyticJacobian;
archive & mStateVariables;
std::vector<double> parameters;
archive & parameters;
if (version > 0)
{
std::vector<std::string> param_names;
archive & param_names;
CheckParametersOnLoad(parameters,param_names);
}
else
{
mParameters = parameters;
}
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
protected:
/** Whether to use an analytic Jacobian. */
bool mUseAnalyticJacobian;
public:
/**
* Constructor.
*
* @param numberOfStateVariables the number of state variables in the ODE system
*/
AbstractOdeSystem(unsigned numberOfStateVariables);
/**
* Virtual destructor since we have virtual methods.
*/
virtual ~AbstractOdeSystem();
/**
* Method to evaluate the derivatives of the system.
*
* @param time the current time
* @param rY the current values of the state variables
* @param rDY storage for the derivatives of the system; will be filled in on return
*/
virtual void EvaluateYDerivatives(double time, const std::vector<double>& rY,
std::vector<double>& rDY)=0;
/**
* CalculateStoppingEvent() - can be overloaded if the ODE is to be solved
* only until a particular event (for example, only until the y value becomes
* negative.
*
* After each timestep the solver will call this method on the ODE to see if
* it should stop there.
* @return true if the solver should stop now. By default, false is returned here.
*
* @param time the current time
* @param rY the current values of the state variables
*/
virtual bool CalculateStoppingEvent(double time, const std::vector<double>& rY);
/**
* An alternative approach to stopping events; currently only useful with CVODE.
* CVODE can search for roots (zeros) of this function while solving the ODE system,
* and home in on them to find sign transitions to high precision.
*
* The default implementation here fakes a root function using CalculateStoppingEvent.
*
* @param time the current time
* @param rY the current values of the state variables
* @return value of the root function
*/
virtual double CalculateRootFunction(double time, const std::vector<double>& rY);
/**
* Get whether an analytic Jacobian is used.
*
* @return #mUseAnalyticJacobian
*/
bool GetUseAnalyticJacobian();
/**
* \todo move to AbstractParameterisedSystem? (1540)
*
* @return const reference to the state variables in the ODE system (used in archiving).
*/
const std::vector<double>& rGetConstStateVariables() const;
};
CLASS_IS_ABSTRACT(AbstractOdeSystem)
BOOST_CLASS_VERSION(AbstractOdeSystem, 1u)
#endif //_ABSTRACTODESYSTEM_HPP_
|
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Timer/PWM Module
namespace Tpm0Sc{ ///<Status and Control
using Addr = Register::Address<0x40038000,0xffffff00,0x00000000,unsigned>;
///Prescale Factor Selection
enum class PsVal {
v000=0x00000000, ///<Divide by 1
v001=0x00000001, ///<Divide by 2
v010=0x00000002, ///<Divide by 4
v011=0x00000003, ///<Divide by 8
v100=0x00000004, ///<Divide by 16
v101=0x00000005, ///<Divide by 32
v110=0x00000006, ///<Divide by 64
v111=0x00000007, ///<Divide by 128
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,PsVal> ps{};
namespace PsValC{
constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v000> v000{};
constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v001> v001{};
constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v010> v010{};
constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v011> v011{};
constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v100> v100{};
constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v101> v101{};
constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v110> v110{};
constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v111> v111{};
}
///Clock Mode Selection
enum class CmodVal {
v00=0x00000000, ///<TPM counter is disabled
v01=0x00000001, ///<TPM counter increments on every TPM counter clock
v10=0x00000002, ///<TPM counter increments on rising edge of TPM_EXTCLK synchronized to the TPM counter clock
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,3),Register::ReadWriteAccess,CmodVal> cmod{};
namespace CmodValC{
constexpr Register::FieldValue<decltype(cmod)::Type,CmodVal::v00> v00{};
constexpr Register::FieldValue<decltype(cmod)::Type,CmodVal::v01> v01{};
constexpr Register::FieldValue<decltype(cmod)::Type,CmodVal::v10> v10{};
}
///Center-Aligned PWM Select
enum class CpwmsVal {
v0=0x00000000, ///<TPM counter operates in up counting mode.
v1=0x00000001, ///<TPM counter operates in up-down counting mode.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,CpwmsVal> cpwms{};
namespace CpwmsValC{
constexpr Register::FieldValue<decltype(cpwms)::Type,CpwmsVal::v0> v0{};
constexpr Register::FieldValue<decltype(cpwms)::Type,CpwmsVal::v1> v1{};
}
///Timer Overflow Interrupt Enable
enum class ToieVal {
v0=0x00000000, ///<Disable TOF interrupts. Use software polling.
v1=0x00000001, ///<Enable TOF interrupts. An interrupt is generated when TOF equals one.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,ToieVal> toie{};
namespace ToieValC{
constexpr Register::FieldValue<decltype(toie)::Type,ToieVal::v0> v0{};
constexpr Register::FieldValue<decltype(toie)::Type,ToieVal::v1> v1{};
}
///Timer Overflow Flag
enum class TofVal {
v0=0x00000000, ///<TPM counter has not overflowed.
v1=0x00000001, ///<TPM counter has overflowed.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,TofVal> tof{};
namespace TofValC{
constexpr Register::FieldValue<decltype(tof)::Type,TofVal::v0> v0{};
constexpr Register::FieldValue<decltype(tof)::Type,TofVal::v1> v1{};
}
}
namespace Tpm0Cnt{ ///<Counter
using Addr = Register::Address<0x40038004,0xffff0000,0x00000000,unsigned>;
///Counter value
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> count{};
}
namespace Tpm0Mod{ ///<Modulo
using Addr = Register::Address<0x40038008,0xffff0000,0x00000000,unsigned>;
///Modulo value
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> mod{};
}
namespace Tpm0Status{ ///<Capture and Compare Status
using Addr = Register::Address<0x40038050,0xfffffefc,0x00000000,unsigned>;
///Channel 0 Flag
enum class Ch0fVal {
v0=0x00000000, ///<No channel event has occurred.
v1=0x00000001, ///<A channel event has occurred.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,Ch0fVal> ch0f{};
namespace Ch0fValC{
constexpr Register::FieldValue<decltype(ch0f)::Type,Ch0fVal::v0> v0{};
constexpr Register::FieldValue<decltype(ch0f)::Type,Ch0fVal::v1> v1{};
}
///Channel 1 Flag
enum class Ch1fVal {
v0=0x00000000, ///<No channel event has occurred.
v1=0x00000001, ///<A channel event has occurred.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,Ch1fVal> ch1f{};
namespace Ch1fValC{
constexpr Register::FieldValue<decltype(ch1f)::Type,Ch1fVal::v0> v0{};
constexpr Register::FieldValue<decltype(ch1f)::Type,Ch1fVal::v1> v1{};
}
///Timer Overflow Flag
enum class TofVal {
v0=0x00000000, ///<TPM counter has not overflowed.
v1=0x00000001, ///<TPM counter has overflowed.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,TofVal> tof{};
namespace TofValC{
constexpr Register::FieldValue<decltype(tof)::Type,TofVal::v0> v0{};
constexpr Register::FieldValue<decltype(tof)::Type,TofVal::v1> v1{};
}
}
namespace Tpm0Conf{ ///<Configuration
using Addr = Register::Address<0x40038084,0xf0f8fd1f,0x00000000,unsigned>;
///Doze Enable
enum class DozeenVal {
v0=0x00000000, ///<Internal TPM counter continues in Doze mode.
v1=0x00000001, ///<Internal TPM counter is paused and does not increment during Doze mode. Trigger inputs and input capture events are also ignored.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,DozeenVal> dozeen{};
namespace DozeenValC{
constexpr Register::FieldValue<decltype(dozeen)::Type,DozeenVal::v0> v0{};
constexpr Register::FieldValue<decltype(dozeen)::Type,DozeenVal::v1> v1{};
}
///Debug Mode
enum class DbgmodeVal {
v00=0x00000000, ///<TPM counter is paused and does not increment during debug mode. Trigger inputs and input capture events are also ignored.
v11=0x00000003, ///<TPM counter continues in debug mode.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,DbgmodeVal> dbgmode{};
namespace DbgmodeValC{
constexpr Register::FieldValue<decltype(dbgmode)::Type,DbgmodeVal::v00> v00{};
constexpr Register::FieldValue<decltype(dbgmode)::Type,DbgmodeVal::v11> v11{};
}
///Global time base enable
enum class GtbeenVal {
v0=0x00000000, ///<All channels use the internally generated TPM counter as their timebase
v1=0x00000001, ///<All channels use an externally generated global timebase as their timebase
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,GtbeenVal> gtbeen{};
namespace GtbeenValC{
constexpr Register::FieldValue<decltype(gtbeen)::Type,GtbeenVal::v0> v0{};
constexpr Register::FieldValue<decltype(gtbeen)::Type,GtbeenVal::v1> v1{};
}
///Counter Start on Trigger
enum class CsotVal {
v0=0x00000000, ///<TPM counter starts to increment immediately, once it is enabled.
v1=0x00000001, ///<TPM counter only starts to increment when it a rising edge on the selected input trigger is detected, after it has been enabled or after it has stopped due to overflow.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,CsotVal> csot{};
namespace CsotValC{
constexpr Register::FieldValue<decltype(csot)::Type,CsotVal::v0> v0{};
constexpr Register::FieldValue<decltype(csot)::Type,CsotVal::v1> v1{};
}
///Counter Stop On Overflow
enum class CsooVal {
v0=0x00000000, ///<TPM counter continues incrementing or decrementing after overflow
v1=0x00000001, ///<TPM counter stops incrementing or decrementing after overflow.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,CsooVal> csoo{};
namespace CsooValC{
constexpr Register::FieldValue<decltype(csoo)::Type,CsooVal::v0> v0{};
constexpr Register::FieldValue<decltype(csoo)::Type,CsooVal::v1> v1{};
}
///Counter Reload On Trigger
enum class CrotVal {
v0=0x00000000, ///<Counter is not reloaded due to a rising edge on the selected input trigger
v1=0x00000001, ///<Counter is reloaded when a rising edge is detected on the selected input trigger
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,CrotVal> crot{};
namespace CrotValC{
constexpr Register::FieldValue<decltype(crot)::Type,CrotVal::v0> v0{};
constexpr Register::FieldValue<decltype(crot)::Type,CrotVal::v1> v1{};
}
///Trigger Select
constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> trgsel{};
}
namespace Tpm0C0sc{ ///<Channel (n) Status and Control
using Addr = Register::Address<0x4003800c,0xffffff03,0x00000000,unsigned>;
///Edge or Level Select
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> elsa{};
///Edge or Level Select
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> elsb{};
///Channel Mode Select
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> msa{};
///Channel Mode Select
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> msb{};
///Channel Interrupt Enable
enum class ChieVal {
v0=0x00000000, ///<Disable channel interrupts.
v1=0x00000001, ///<Enable channel interrupts.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,ChieVal> chie{};
namespace ChieValC{
constexpr Register::FieldValue<decltype(chie)::Type,ChieVal::v0> v0{};
constexpr Register::FieldValue<decltype(chie)::Type,ChieVal::v1> v1{};
}
///Channel Flag
enum class ChfVal {
v0=0x00000000, ///<No channel event has occurred.
v1=0x00000001, ///<A channel event has occurred.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,ChfVal> chf{};
namespace ChfValC{
constexpr Register::FieldValue<decltype(chf)::Type,ChfVal::v0> v0{};
constexpr Register::FieldValue<decltype(chf)::Type,ChfVal::v1> v1{};
}
}
namespace Tpm0C1sc{ ///<Channel (n) Status and Control
using Addr = Register::Address<0x40038014,0xffffff03,0x00000000,unsigned>;
///Edge or Level Select
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> elsa{};
///Edge or Level Select
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> elsb{};
///Channel Mode Select
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> msa{};
///Channel Mode Select
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> msb{};
///Channel Interrupt Enable
enum class ChieVal {
v0=0x00000000, ///<Disable channel interrupts.
v1=0x00000001, ///<Enable channel interrupts.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,ChieVal> chie{};
namespace ChieValC{
constexpr Register::FieldValue<decltype(chie)::Type,ChieVal::v0> v0{};
constexpr Register::FieldValue<decltype(chie)::Type,ChieVal::v1> v1{};
}
///Channel Flag
enum class ChfVal {
v0=0x00000000, ///<No channel event has occurred.
v1=0x00000001, ///<A channel event has occurred.
};
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,ChfVal> chf{};
namespace ChfValC{
constexpr Register::FieldValue<decltype(chf)::Type,ChfVal::v0> v0{};
constexpr Register::FieldValue<decltype(chf)::Type,ChfVal::v1> v1{};
}
}
namespace Tpm0C0v{ ///<Channel (n) Value
using Addr = Register::Address<0x40038010,0xffff0000,0x00000000,unsigned>;
///Channel Value
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> val{};
}
namespace Tpm0C1v{ ///<Channel (n) Value
using Addr = Register::Address<0x40038018,0xffff0000,0x00000000,unsigned>;
///Channel Value
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> val{};
}
}
|
// { dg-do compile }
// Copyright (C) 2007-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <tr1/functional>
namespace gnu
{
using namespace std::tr1::placeholders;
}
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/lite/utils/tftext_utils.h"
#include "flatbuffers/flexbuffers.h" // from @flatbuffers
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/Builders.h" // from @llvm-project
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/IR/Identifier.h" // from @llvm-project
#include "mlir/IR/Location.h" // from @llvm-project
#include "mlir/IR/MLIRContext.h" // from @llvm-project
#include "mlir/IR/Matchers.h" // from @llvm-project
#include "mlir/IR/OpDefinition.h" // from @llvm-project
#include "mlir/IR/Operation.h" // from @llvm-project
#include "mlir/IR/StandardTypes.h" // from @llvm-project
#include "mlir/IR/Types.h" // from @llvm-project
#include "mlir/IR/Value.h" // from @llvm-project
#include "mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
namespace mlir {
namespace TFL {
namespace {
constexpr char kNgrams[] = "tftext:Ngrams";
constexpr char kWhitespaceTokenizer[] = "tftext:WhitespaceTokenizer";
constexpr char kCustomSgnnProjection[] = "tftext:custom:SgnnProjection";
constexpr char kTFImplements[] = "tf._implements";
using mlir::TF::FuncAttr;
using mlir::TF::StringType;
inline OpaqueElementsAttr CustomOption(OpBuilder* builder,
const std::string& content) {
ShapedType type = RankedTensorType::get(
{static_cast<int64_t>(content.size())}, builder->getIntegerType(8));
return OpaqueElementsAttr::get(builder->getContext()->getLoadedDialect("tfl"),
type,
StringRef(content.data(), content.size()));
}
inline TensorType GetInputType(FuncOp func, int idx) {
return func.getType().getInput(idx).dyn_cast_or_null<TensorType>();
}
inline TensorType GetResultType(FuncOp func, int idx) {
return func.getType().getResult(idx).dyn_cast_or_null<TensorType>();
}
inline bool RankEquals(const TensorType& type, int rank) {
return type && type.hasRank() && type.getRank() == rank;
}
LogicalResult VerifyWhitespaceTokenizer(FuncOp func) {
// In the case of input tensor with 0 rank.
// Whitespace tokenizer generates 1 output:
// * String tensor for tokens.
//
// In the case of 1-D input tensor,
// Whitespace tokenizer generates 2 outputs to make up a ragged tensor:
// * 1st output is the value of ragged tensor;
// * 2nd output is the offset.
//
// In the case of batched input tesnor,
// Whitespace tokenizer has 3 outputs to make up a nested ragged tensor:
// * 1st output is the value of ragged tensor;
// * 2nd output is the inner offset;
// * 3rd output is the outer offset.
auto input_type = GetInputType(func, 0);
if (!input_type || !input_type.getElementType().isa<StringType>() ||
!input_type.hasRank()) {
return func.emitError() << "Input should be a string tensor";
}
const std::vector<int> kValidNumOfOutput = {1, 2, 3};
if (input_type.getRank() >= kValidNumOfOutput.size()) {
return func.emitError()
<< "Unrecognized input rank: " << input_type.getRank();
}
if (func.getNumResults() != kValidNumOfOutput[input_type.getRank()]) {
return func.emitError()
<< "Expect " << kValidNumOfOutput[input_type.getRank()]
<< "output(s) when input has rank " << input_type.getRank();
}
auto value_type = GetResultType(func, 0);
if (!RankEquals(value_type, 1) ||
!value_type.getElementType().isa<StringType>()) {
return func.emitError() << "1st output should be string tensor";
}
if (func.getNumResults() > 1) {
auto offset_type = GetResultType(func, 1);
if (!RankEquals(offset_type, 1) ||
!offset_type.getElementType().isInteger(64)) {
return func.emitError() << "2nd output should be int64 tensor";
}
}
if (func.getNumResults() > 2) {
auto offset_type = GetResultType(func, 2);
if (!RankEquals(offset_type, 1) ||
!offset_type.getElementType().isInteger(64)) {
return func.emitError() << "3rd output should be int64 tensor";
}
}
return success();
}
LogicalResult ConvertWhitespaceTokenizer(FuncOp func, llvm::StringRef api,
FuncAttr attr) {
func.eraseBody();
func.addEntryBlock();
func.setAttr(kTFImplements, attr);
OpBuilder builder(func.getBody());
std::string empty_option_buffer;
auto op = builder.create<CustomOp>(
func.getLoc(), func.getType().getResults(), func.getArguments(), api,
CustomOption(&builder, empty_option_buffer));
builder.create<ReturnOp>(func.getLoc(), op.getResults());
return success();
}
LogicalResult VerifyNgrams(FuncOp func) {
// The inputs and outputs should be the same:
// * A string tensor for tokens/ragged tensor values.
// * Zero or more row_split tensors.
constexpr int kValues = 0;
constexpr int kRowSplits = 1;
if (func.getType().getInputs().size() != func.getType().getResults().size()) {
return func.emitError() << "Mismatched number of inputs and outputs.";
}
int row_splits = func.getType().getInputs().size() - kRowSplits;
if (row_splits == 0) {
auto input_values = GetInputType(func, kValues);
if (!input_values || !input_values.getElementType().isa<StringType>()) {
return func.emitError()
<< "Input " << kValues << " should be a string tensor";
}
auto output_values = GetResultType(func, kValues);
if (!output_values || !output_values.getElementType().isa<StringType>()) {
return func.emitError()
<< "Output " << kValues << " should be a string tensor";
}
if (input_values.hasRank() && output_values.hasRank() &&
input_values.getRank() != output_values.getRank()) {
return func.emitError() << "Input " << kValues << " and output "
<< kValues << " should have the same rank";
}
} else {
auto input_values = GetInputType(func, kValues);
if (!RankEquals(input_values, 1) ||
!input_values.getElementType().isa<StringType>()) {
return func.emitError()
<< "Input " << kValues << " should be a 1D string tensor";
}
auto output_values = GetResultType(func, kValues);
if (!RankEquals(output_values, 1) ||
!output_values.getElementType().isa<StringType>()) {
return func.emitError()
<< "Output " << kValues << " should be a 1D string tensor";
}
for (int i = 0; i < row_splits; ++i) {
const int row_index = i + kRowSplits;
auto input_row_splits = GetInputType(func, row_index);
if (!RankEquals(input_row_splits, 1) ||
!input_row_splits.getElementType().isInteger(64)) {
return func.emitError()
<< "Input " << row_index << " should be a 1D int64 tensor";
}
auto output_row_splits = GetResultType(func, row_index);
if (!RankEquals(output_row_splits, 1) ||
!output_row_splits.getElementType().isInteger(64)) {
return func.emitError()
<< "Output " << row_index << " should be a 1D int64 tensor";
}
}
}
return success();
}
LogicalResult CreateNgramsCustomOption(FuncOp func, DictionaryAttr attrs,
std::string& custom_option_buffer) {
flexbuffers::Builder fbb;
size_t start_map = fbb.StartMap();
auto width = attrs.get("width").dyn_cast_or_null<IntegerAttr>();
if (!width) {
return func.emitError() << "'width' attribute is not set or not an integer";
}
fbb.Int("width", width.getInt());
auto string_separator =
attrs.get("string_separator").dyn_cast_or_null<StringAttr>();
if (!string_separator) {
return func.emitError()
<< "'string_separator' attribute is not set or not a string";
}
// StringAttrs are not guaranteed to be NUL terminated, but flexbuffers
// strings expect NUL terminated strings.
std::string string_separator_str(string_separator.getValue().data(),
string_separator.getValue().size());
fbb.String("string_separator", string_separator_str);
auto axis = attrs.get("axis").dyn_cast_or_null<IntegerAttr>();
if (!axis) {
return func.emitError() << "'axis' attribute is not set or not an integer";
}
fbb.Int("axis", axis.getInt());
auto reduction_type =
attrs.get("reduction_type").dyn_cast_or_null<StringAttr>();
if (!reduction_type) {
return func.emitError()
<< "'reduction_type' attribute is not set or not a string";
}
// StringAttrs are not guaranteed to be NUL terminated, but flexbuffers
// strings expect NUL terminated strings.
std::string reduction_type_str(reduction_type.getValue().data(),
reduction_type.getValue().size());
fbb.String("reduction_type", reduction_type_str);
fbb.EndMap(start_map);
fbb.Finish();
custom_option_buffer.assign(fbb.GetBuffer().begin(), fbb.GetBuffer().end());
return success();
}
LogicalResult ConvertNgrams(FuncOp func, llvm::StringRef api, FuncAttr attr) {
func.eraseBody();
func.addEntryBlock();
func.setAttr(kTFImplements, attr);
OpBuilder builder(func.getBody());
std::string custom_option_buffer;
if (failed(CreateNgramsCustomOption(func, attr.GetAttrs(),
custom_option_buffer))) {
return failure();
}
auto op = builder.create<CustomOp>(
func.getLoc(), func.getType().getResults(), func.getArguments(), api,
CustomOption(&builder, custom_option_buffer));
builder.create<ReturnOp>(func.getLoc(), op.getResults());
return success();
}
LogicalResult VerifySgnnProjection(FuncOp func, FuncAttr attr) {
if (func.getType().getNumInputs() != 2 ||
func.getType().getNumResults() != 1) {
return func.emitError() << "Mismatched number of inputs and outputs.";
}
auto values_type = GetInputType(func, 0);
if (!values_type || !values_type.getElementType().isa<StringType>()) {
return func.emitError() << "First input should be a string tensor";
}
auto row_splits_type = GetInputType(func, 1);
if (!row_splits_type ||
!row_splits_type.getElementType().isa<IntegerType>()) {
return func.emitError() << "Second input should be an integer tensor";
}
auto hash_seed =
attr.GetAttrs().get("hash_seed").dyn_cast_or_null<ArrayAttr>();
if (!hash_seed) {
return func.emitError()
<< "'hash_seed' attribute is not set or not an array";
}
auto output_type = GetResultType(func, 0);
if (!output_type || !output_type.getElementType().isa<FloatType>() ||
!RankEquals(output_type, 2)) {
return func.emitError() << "Output should be a 2D float tensor.";
}
if (output_type.getDimSize(1) != hash_seed.size()) {
return func.emitError()
<< "Output 2nd dimension should be the num of hash seeds.";
}
auto buckets = attr.GetAttrs().get("buckets").dyn_cast_or_null<IntegerAttr>();
if (!buckets) {
return func.emitError() << "'buckets' attribute is not set or not int";
}
return success();
}
LogicalResult CreateSgnnProjectionCustomOption(
FuncOp func, DictionaryAttr attrs, std::string& custom_option_buffer) {
flexbuffers::Builder fbb;
size_t start_map = fbb.StartMap();
auto hash_seed = attrs.get("hash_seed").dyn_cast_or_null<ArrayAttr>();
auto vector_start = fbb.StartVector("hash_seed");
for (int i = 0; i < hash_seed.size(); i++) {
fbb.Add(static_cast<int32_t>(
(hash_seed.getValue().data() + i)->dyn_cast<IntegerAttr>().getInt()));
}
fbb.EndVector(vector_start, /*typed=*/true, /*fixed=*/false);
auto buckets = attrs.get("buckets").dyn_cast_or_null<IntegerAttr>();
fbb.Int("buckets", buckets.getInt());
fbb.EndMap(start_map);
fbb.Finish();
custom_option_buffer.assign(fbb.GetBuffer().begin(), fbb.GetBuffer().end());
return success();
}
LogicalResult ConvertSgnnProjection(FuncOp func, llvm::StringRef api,
FuncAttr attr) {
// See more details in tensorflow_models/sequence_projection/sgnn/sgnn.py
func.eraseBody();
func.addEntryBlock();
func.setAttr(kTFImplements, attr);
OpBuilder builder(func.getBody());
std::string custom_option_buffer;
if (failed(CreateSgnnProjectionCustomOption(func, attr.GetAttrs(),
custom_option_buffer))) {
return failure();
}
auto op = builder.create<CustomOp>(
func.getLoc(), func.getType().getResults(), func.getArguments(), api,
CustomOption(&builder, custom_option_buffer));
builder.create<ReturnOp>(func.getLoc(), op.getResults());
return success();
}
} // namespace
LogicalResult ConvertTFTextAPI(FuncOp func, llvm::StringRef api,
FuncAttr attr) {
if (api.str() == kWhitespaceTokenizer) {
if (succeeded(VerifyWhitespaceTokenizer(func))) {
return ConvertWhitespaceTokenizer(func, api, attr);
}
} else if (api.str() == kNgrams) {
if (succeeded(VerifyNgrams(func))) {
return ConvertNgrams(func, api, attr);
}
} else if (api.str() == kCustomSgnnProjection) {
if (succeeded(VerifySgnnProjection(func, attr))) {
return ConvertSgnnProjection(func, api, attr);
}
}
return failure();
}
bool IsTFTextRegistered(const tensorflow::OpRegistry* op_registery) {
const std::vector<std::string> kTFTextOps = {
"WhitespaceTokenizeWithOffsets",
};
for (const auto& iter : kTFTextOps) {
if (op_registery->LookUp(iter)) {
return true;
}
}
return false;
}
} // namespace TFL
} // namespace mlir
|
#include "filereader.h"
ImageRotator::ImageRotator(const QString &pathToSourceSvg, const QString &pathToRendedImage, const QString &fileType, const char slash, const QString &svgType, QObject *parent)
: QObject(parent)
, m_file(new QFile())
, m_pathToSourceSvgFolder(pathToSourceSvg)
, m_pathToRendedImageFolder(pathToRendedImage)
, m_fileType(fileType)
, m_slash(slash)
, m_svgType(svgType)
, m_image(new QImage(497, 279, QImage::Format_RGB32))
, m_renderer(new QSvgRenderer())
, m_painter(new QPainter(m_image))
, index(40)
, m_previousCharInArray(' ')
, m_openBracket('(')
, m_whiteSpace(' ')
, m_array(Q_NULLPTR)
{
m_painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
m_painter->setRenderHints(QPainter::Antialiasing, true);
m_renderer->setFramesPerSecond(0);
}
ImageRotator::~ImageRotator()
{
delete m_file;
delete m_image;
delete m_renderer;
delete m_painter;
}
void ImageRotator::SetParams(const QString &tile, QString &azm, QString &layer, char firstNum, char secondNum, char thirdNum)
{
m_pathToSource.append(m_pathToSourceSvgFolder).append(layer).append(m_slash).append(tile).append(m_svgType);
m_pathToRender.append(m_pathToRendedImageFolder).append(layer).append(m_slash).append(azm).append(m_slash).append(tile).append(m_fileType);
m_firstNum=firstNum;
m_secondNum=secondNum;
m_thirdNum=thirdNum;
}
void ImageRotator::OnMakingImage()
{
m_file->setFileName(m_pathToSource);
m_file->open(QIODevice::ReadOnly);
m_array=m_file->readAll();
m_file->close();
for (index; index<m_array.size()-10; index=index+1)
{
if(m_openBracket==m_previousCharInArray&&m_array.at(index)==m_whiteSpace&&m_array.at(index+1)==m_whiteSpace)
{
m_array.operator[](index+2)=m_firstNum;
m_array.operator[](index+3)=m_secondNum;
m_array.operator[](index+4)=m_thirdNum;
index=index+60;
}
m_previousCharInArray=m_array.at(index);
}
m_renderer->load(m_array);
m_renderer->render(m_painter);
m_image->save(m_pathToRender);
index=40;
m_pathToSource.clear();
m_pathToRender.clear();
m_previousCharInArray=' ';
Q_EMIT ToFinished();
}
|
// Copyright 2020 The Hds Team
//
// 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 "shielded.h"
namespace hds
{
void ShieldedTxo::Ticket::get_Hash(ECC::Hash::Value& hv) const
{
ECC::Hash::Processor()
<< "Out-S"
<< m_SerialPub
>> hv;
}
bool ShieldedTxo::Ticket::IsValid(ECC::Point::Native& comm) const
{
if (!comm.Import(m_SerialPub))
return false;
ECC::Hash::Value hv;
get_Hash(hv);
return m_Signature.IsValid(ECC::Context::get().m_Sig.m_CfgGJ1, hv, m_Signature.m_pK, &comm);
}
void ShieldedTxo::Prepare(ECC::Oracle& oracle) const
{
// Since m_Ticket doesn't contribute to the transaction balance, it MUST be exposed to the Oracle used with m_RangeProof.
// m_Commitment also should be used (for the same reason it's used in regular Output)
oracle
<< m_Ticket.m_SerialPub
<< m_Ticket.m_Signature.m_NoncePub
<< m_Commitment;
}
bool ShieldedTxo::IsValid(ECC::Oracle& oracle, ECC::Point::Native& comm, ECC::Point::Native& ser) const
{
if (!(m_Ticket.IsValid(ser) && comm.Import(m_Commitment)))
return false;
ECC::Point::Native hGen;
if (m_pAsset && !m_pAsset->IsValid(hGen))
return false;
Prepare(oracle);
return m_RangeProof.IsValid(comm, oracle, &hGen);
}
void ShieldedTxo::operator = (const ShieldedTxo& v)
{
m_Ticket = v.m_Ticket;
m_Commitment = v.m_Commitment;
m_RangeProof = v.m_RangeProof;
if (v.m_pAsset)
v.m_pAsset->Clone(m_pAsset);
else
m_pAsset.reset();
}
void ShieldedTxo::Voucher::get_Hash(ECC::Hash::Value& hv) const
{
ECC::Hash::Processor()
<< "voucher.1"
<< m_Ticket.m_SerialPub
<< m_Ticket.m_Signature.m_NoncePub
<< m_SharedSecret
>> hv;
}
bool ShieldedTxo::Voucher::IsValid(const ECC::Point::Native& pk) const
{
ECC::Point::Native pt;
if (!m_Ticket.IsValid(pt))
return false;
ECC::Hash::Value hv;
get_Hash(hv);
return m_Signature.IsValid(hv, pk);
}
bool ShieldedTxo::Voucher::IsValid(const PeerID& pid) const
{
ECC::Point::Native pk;
return
pid.ExportNnz(pk) &&
IsValid(pk);
}
/////////////
// Shielded keygen
struct ShieldedTxo::Data::HashTxt
{
ECC::Hash::Processor m_Processor;
ECC::Hash::Value m_hv;
template <uint32_t n>
HashTxt(const char(&sz)[n])
{
m_Processor
<< "Output.Shielded."
<< sz;
}
template <typename T>
HashTxt& operator << (const T& t) { m_Processor << t; return *this; }
void operator >> (ECC::Hash::Value& hv)
{
m_Processor >> m_hv;
hv = m_hv;
}
operator const ECC::Hash::Value& ()
{
m_Processor >> m_hv;
return m_hv;
}
};
/////////////
// TicketParams
void ShieldedTxo::Data::TicketParams::DoubleBlindedCommitment(ECC::Point::Native& res, const ECC::Scalar::Native* pK)
{
res = ECC::Context::get().G * pK[0];
res += ECC::Context::get().J * pK[1];
}
void ShieldedTxo::Data::TicketParams::Generate(Ticket& s, const PublicGen& gen, const ECC::Hash::Value& nonce)
{
GenerateInternal(s, nonce, *gen.m_pGen, nullptr, *gen.m_pSer);
}
void ShieldedTxo::Data::TicketParams::Generate(Ticket& s, const Viewer& v, const ECC::Hash::Value& nonce)
{
GenerateInternal(s, nonce, *v.m_pGen, v.m_pGen.get(), *v.m_pSer);
}
void ShieldedTxo::Data::TicketParams::set_FromkG(Key::IPKdf& gen, Key::IKdf* pGenPriv, Key::IPKdf& ser)
{
ECC::NoLeak<ECC::Scalar> sk;
sk.V = m_pK[0];
HashTxt htxt("kG-k");
htxt << sk.V.m_Value;
const ECC::Hash::Value& hv = htxt;
ECC::Scalar::Native k;
m_IsCreatedByViewer = !!pGenPriv;
if (pGenPriv)
pGenPriv->DeriveKey(k, hv);
else
gen.DerivePKey(k, hv);
sk.V = k;
m_SerialPreimage = Cast::Down<const ECC::Hash::Value>(HashTxt("k-pI") << sk.V.m_Value);
ECC::Point::Native pt;
ser.DerivePKeyG(pt, m_SerialPreimage);
m_SpendPk = pt;
Lelantus::SpendKey::ToSerial(m_pK[1], m_SpendPk);
}
void ShieldedTxo::Data::TicketParams::get_DH(ECC::Hash::Value& res, const ECC::Point& ptSerialPub)
{
HashTxt("DH") << ptSerialPub >> res;
}
void ShieldedTxo::Data::TicketParams::get_Nonces(Key::IPKdf& gen, ECC::Scalar::Native* pN) const
{
gen.DerivePKey(pN[0], HashTxt("nG") << m_SharedSecret);
gen.DerivePKey(pN[1], HashTxt("nJ") << m_SharedSecret);
}
void ShieldedTxo::Data::TicketParams::GenerateInternal(Ticket& s, const ECC::Hash::Value& nonce, Key::IPKdf& gen, Key::IKdf* pGenPriv, Key::IPKdf& ser)
{
gen.DerivePKey(m_pK[0], HashTxt("kG") << nonce);
set_FromkG(gen, pGenPriv, ser);
set_SharedSecretFromKs(s.m_SerialPub, gen);
ECC::Scalar::Native pN[2];
get_Nonces(gen, pN);
// generalized Schnorr's sig
ECC::Hash::Value hv;
s.get_Hash(hv);
s.m_Signature.SetNoncePub(ECC::Context::get().m_Sig.m_CfgGJ1, pN);
s.m_Signature.SignRaw(ECC::Context::get().m_Sig.m_CfgGJ1, hv, s.m_Signature.m_pK, m_pK, pN);
}
void ShieldedTxo::Data::TicketParams::set_SharedSecretFromKs(ECC::Point& ptSerialPub, Key::IPKdf& gen)
{
ECC::Point::Native pt, pt1;
DoubleBlindedCommitment(pt, m_pK);
ptSerialPub = pt;
ECC::Hash::Value hv;
get_DH(hv, ptSerialPub);
gen.DerivePKeyG(pt, hv);
gen.DerivePKeyJ(pt1, hv);
pt = pt * m_pK[0];
pt += pt1 * m_pK[1]; // shared point
set_SharedSecret(pt);
}
void ShieldedTxo::Data::TicketParams::set_SharedSecret(const ECC::Point::Native& pt)
{
HashTxt("sp-sec") << pt >> m_SharedSecret;
}
bool ShieldedTxo::Data::TicketParams::Recover(const Ticket& s, const Viewer& v)
{
ECC::Mode::Scope scope(ECC::Mode::Fast);
ECC::Point::Native pt;
if (!pt.Import(s.m_SerialPub))
return false;
ECC::Hash::Value hv;
get_DH(hv, s.m_SerialPub);
ECC::Scalar::Native k;
v.m_pGen->DeriveKey(k, hv);
pt = pt * k; // shared point
set_SharedSecret(pt);
ECC::Scalar::Native pN[2];
get_Nonces(*v.m_pGen, pN);
DoubleBlindedCommitment(pt, pN);
if (!(pt == s.m_Signature.m_NoncePub))
return false;
// there's a match with high probability. Reverse-engineer the keys
s.get_Hash(hv);
s.m_Signature.get_Challenge(k, hv);
k.Inv();
k = -k;
for (size_t i = 0; i < _countof(m_pK); i++)
{
m_pK[i] = s.m_Signature.m_pK[i];
m_pK[i] += pN[i];
m_pK[i] *= k;
}
k = m_pK[1];
set_FromkG(*v.m_pGen, v.m_pGen.get(), *v.m_pSer);
if (k == m_pK[1])
return true;
set_FromkG(*v.m_pGen, nullptr, *v.m_pSer);
if (k == m_pK[1])
return true;
return false;
}
void ShieldedTxo::Data::TicketParams::Restore(const Viewer& v)
{
set_FromkG(*v.m_pGen, v.m_pGen.get(), *v.m_pSer);
ECC::Point ptSerialPub;
set_SharedSecretFromKs(ptSerialPub, *v.m_pGen);
}
/////////////
// OutputParams
void ShieldedTxo::Data::OutputParams::get_Seed(ECC::uintBig& res, const ECC::Hash::Value& hvShared, const ECC::Oracle& oracle)
{
ECC::Oracle(oracle) // copy
<< "bp-s"
<< hvShared
>> res;
}
void ShieldedTxo::Data::OutputParams::get_skGen(ECC::Scalar::Native& skGen, const ECC::Hash::Value& hvShared) const
{
ECC::NonceGenerator("skG-O")
<< hvShared
>> skGen;
}
void ShieldedTxo::Data::OutputParams::get_sk(ECC::Scalar::Native& sk, const ECC::Hash::Value& hvShared) const
{
ECC::NonceGenerator("kG-O")
<< hvShared
>> sk;
}
#pragma pack (push, 1)
struct ShieldedTxo::Data::OutputParams::Packed
{
uintBigFor<Asset::ID>::Type m_Asset;
uint8_t m_Flags;
};
#pragma pack (pop)
uint8_t ShieldedTxo::Data::OutputParams::set_kG(const ECC::Hash::Value& hvShared, ECC::Scalar::Native& kTmp)
{
uint8_t nFlag = Msg2Scalar(kTmp, m_User.m_Sender);
get_sk(m_k, hvShared);
m_k += kTmp;
return nFlag;
}
void ShieldedTxo::Data::OutputParams::Restore_kG(const ECC::Hash::Value& hvShared)
{
ECC::Scalar::Native kTmp;
set_kG(hvShared, kTmp);
}
void ShieldedTxo::Data::OutputParams::Generate(ShieldedTxo& txo, const ECC::Hash::Value& hvShared, ECC::Oracle& oracle, bool bHideAssetAlways /* = false */)
{
ECC::Scalar::Native pExtra[2];
Packed p;
p.m_Asset = m_AssetID;
p.m_Flags = set_kG(hvShared, pExtra[0]);
static_assert(_countof(m_User.m_pMessage) == _countof(pExtra));
for (size_t i = 0; i < _countof(m_User.m_pMessage); i++)
p.m_Flags |= (Msg2Scalar(pExtra[i], m_User.m_pMessage[i]) << (i + 1));
ECC::RangeProof::CreatorParams cp;
cp.m_Value = m_Value;
CoinID::Generator g(m_AssetID);
ECC::Point::Native pt = ECC::Context::get().G * m_k;
g.AddValue(pt, m_Value);
txo.m_Commitment = pt;
cp.m_pExtra = pExtra;
cp.m_Blob.p = &p;
cp.m_Blob.n = sizeof(p);
ECC::Scalar::Native skSign = m_k;
if (m_AssetID || bHideAssetAlways)
{
ECC::Scalar::Native skGen;
get_skGen(skGen, hvShared);
txo.m_pAsset = std::make_unique<Asset::Proof>();
txo.m_pAsset->Create(g.m_hGen, skGen, m_AssetID, g.m_hGen);
Asset::Proof::ModifySk(skSign, skGen, m_Value);
}
else
txo.m_pAsset.reset();
txo.Prepare(oracle);
get_Seed(cp.m_Seed.V, hvShared, oracle);
txo.m_RangeProof.CoSign(cp.m_Seed.V, skSign, cp, oracle, ECC::RangeProof::Confidential::Phase::SinglePass, &g.m_hGen);
}
bool ShieldedTxo::Data::OutputParams::Recover(const ShieldedTxo& txo, const ECC::Hash::Value& hvShared, ECC::Oracle& oracle)
{
txo.Prepare(oracle);
ECC::RangeProof::CreatorParams cp;
get_Seed(cp.m_Seed.V, hvShared, oracle);
ECC::Scalar::Native pExtra[2];
cp.m_pSeedSk = &cp.m_Seed.V; // same seed
cp.m_pSk = &m_k;
cp.m_pExtra = pExtra;
Packed p;
cp.m_Blob.p = &p;
cp.m_Blob.n = sizeof(p);
if (!txo.m_RangeProof.Recover(oracle, cp))
return false;
m_Value = cp.m_Value;
p.m_Asset.Export(m_AssetID);
CoinID::Generator g(m_AssetID);
if (txo.m_pAsset)
{
ECC::Scalar::Native skGen;
get_skGen(skGen, hvShared);
skGen = -skGen;
Asset::Proof::ModifySk(m_k, skGen, m_Value);
}
ECC::Point::Native pt = ECC::Context::get().G * m_k;
ECC::Tag::AddValue(pt, &g.m_hGen, m_Value);
if (!(pt == txo.m_Commitment))
return false;
for (size_t i = 0; i < _countof(m_User.m_pMessage); i++)
Scalar2Msg(m_User.m_pMessage[i], pExtra[i], (2 << i) & p.m_Flags);
get_sk(pExtra[0], hvShared);
pExtra[0] = m_k - pExtra[0];
Scalar2Msg(m_User.m_Sender, pExtra[0], 1 & p.m_Flags);
return true;
}
uint8_t ShieldedTxo::Data::OutputParams::Msg2Scalar(ECC::Scalar::Native& s, const ECC::uintBig& x)
{
static_assert(sizeof(x) == sizeof(ECC::Scalar));
s = reinterpret_cast<const ECC::Scalar&>(x);
return (x >= ECC::Scalar::s_Order);
}
void ShieldedTxo::Data::OutputParams::Scalar2Msg(ECC::uintBig& x, const ECC::Scalar::Native& s, uint32_t nOverflow)
{
static_assert(sizeof(x) == sizeof(ECC::Scalar));
reinterpret_cast<ECC::Scalar&>(x) = s;
if (nOverflow)
x += ECC::Scalar::s_Order;
}
/////////////
// Params (both)
void ShieldedTxo::Data::Params::GenerateOutp(ShieldedTxo& txo, ECC::Oracle& oracle, bool bHideAssetAlways /* = false */)
{
m_Output.Generate(txo, m_Ticket.m_SharedSecret, oracle, bHideAssetAlways);
}
bool ShieldedTxo::Data::Params::Recover(const ShieldedTxo& txo, ECC::Oracle& oracle, const Viewer& v)
{
return
m_Ticket.Recover(txo.m_Ticket, v) &&
m_Output.Recover(txo, m_Ticket.m_SharedSecret, oracle);
}
/////////////
// Generators
void ShieldedTxo::Viewer::FromOwner(Key::IPKdf& key, Key::Index nIdx/* = 0 */)
{
ECC::Scalar::Native sk;
key.DerivePKey(sk, Data::HashTxt("Own.Gen") << nIdx);
ECC::NoLeak<ECC::Scalar> s;
s.V = sk;
ECC::HKdf::Create(m_pGen, s.V.m_Value);
GenerateSerSrc(s.V.m_Value, key, nIdx);
m_pSer.reset(new ECC::HKdfPub);
Cast::Up<ECC::HKdfPub>(*m_pSer).GenerateChildParallel(key, s.V.m_Value);
}
void ShieldedTxo::Viewer::GenerateSerSrc(ECC::Hash::Value& res, Key::IPKdf& key, Key::Index nIdx)
{
ECC::Scalar::Native sk;
key.DerivePKey(sk, Data::HashTxt("Own.Ser") << nIdx);
static_assert(sizeof(res) == sizeof(ECC::Scalar));
((ECC::Scalar&) res) = sk;
}
void ShieldedTxo::Viewer::GenerateSerPrivate(Key::IKdf::Ptr& pOut, Key::IKdf& key, Key::Index nIdx /* = 0 */)
{
ECC::NoLeak<ECC::Hash::Value> hv;
GenerateSerSrc(hv.V, key, nIdx);
pOut.reset(new ECC::HKdf);
Cast::Up<ECC::HKdf>(*pOut).GenerateChildParallel(key, hv.V);
}
void ShieldedTxo::PublicGen::FromViewer(const Viewer& v)
{
m_pSer = v.m_pSer;
m_pGen = v.m_pGen;
}
} // namespace hds
|
// Copyright 2020 Phyronnaz
#include "AssetTypeActions_VoxelDataAsset.h"
#include "VoxelEditorModule.h"
#include "VoxelMessages.h"
#include "Framework/MultiBox/MultiBoxBuilder.h"
#include "Framework/Commands/UIAction.h"
#include "EditorStyleSet.h"
#include "EditorReimportHandler.h"
void FAssetTypeActions_VoxelDataAsset::OpenAssetEditor(const TArray<UObject *>& InObjects, TSharedPtr<class IToolkitHost> EditWithinLevelEditor)
{
FVoxelMessages::ShowVoxelPluginProError("The Voxel Data Asset Editor is only available in Voxel Plugin Pro");
}
void FAssetTypeActions_VoxelDataAsset::GetActions(const TArray<UObject*>& InObjects, FMenuBuilder& MenuBuilder)
{
const auto Assets = GetTypedWeakObjectPtrs<UVoxelDataAsset>(InObjects);
MenuBuilder.AddMenuEntry(
VOXEL_LOCTEXT("Reimport"),
VOXEL_LOCTEXT("Reimport the selected asset(s)."),
FSlateIcon(FEditorStyle::GetStyleSetName(), "ContentBrowser.AssetActions.ReimportAsset"),
FUIAction(
FExecuteAction::CreateSP(this, &FAssetTypeActions_VoxelDataAsset::ExecuteReimport, Assets),
FCanExecuteAction::CreateSP(this, &FAssetTypeActions_VoxelDataAsset::CanExecuteReimport, Assets)
)
);
}
bool FAssetTypeActions_VoxelDataAsset::CanExecuteReimport(const TArray<TWeakObjectPtr<UVoxelDataAsset>> Objects) const
{
for (auto& Object : Objects)
{
if (Object.IsValid() && (Object->Source == EVoxelDataAssetImportSource::MagicaVox || Object->Source == EVoxelDataAssetImportSource::RawVox))
{
return true;
}
}
return false;
}
void FAssetTypeActions_VoxelDataAsset::ExecuteReimport(const TArray<TWeakObjectPtr<UVoxelDataAsset>> Objects) const
{
for (auto& Object : Objects)
{
if (Object.IsValid() && (Object->Source == EVoxelDataAssetImportSource::MagicaVox || Object->Source == EVoxelDataAssetImportSource::RawVox))
{
FReimportManager::Instance()->Reimport(Object.Get(), /*bAskForNewFileIfMissing=*/true);
}
}
}
|
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "PeripheralNyxboard.h"
#include "PeripheralHID.h"
#include "utils/log.h"
#include "Application.h"
using namespace PERIPHERALS;
CPeripheralNyxboard::CPeripheralNyxboard(const PeripheralScanResult& scanResult) :
CPeripheralHID(scanResult)
{
m_features.push_back(FEATURE_NYXBOARD);
}
bool CPeripheralNyxboard::LookupSymAndUnicode(XBMC_keysym &keysym, uint8_t *key, char *unicode)
{
std::string strCommand;
if (keysym.sym == XBMCK_F7 && keysym.mod == XBMCKMOD_NONE && GetSettingBool("enable_flip_commands"))
{
/* switched to keyboard side */
CLog::Log(LOGDEBUG, "%s - switched to keyboard side", __FUNCTION__);
strCommand = GetSettingString("flip_keyboard");
}
else if (keysym.sym == XBMCK_F7 && keysym.mod == XBMCKMOD_LCTRL && GetSettingBool("enable_flip_commands"))
{
/* switched to remote side */
CLog::Log(LOGDEBUG, "%s - switched to remote side", __FUNCTION__);
strCommand = GetSettingString("flip_remote");
}
if (!strCommand.empty())
{
CLog::Log(LOGDEBUG, "%s - executing command '%s'", __FUNCTION__, strCommand.c_str());
if (g_application.ExecuteXBMCAction(strCommand))
{
*key = 0;
*unicode = (char) 0;
return true;
}
}
return false;
}
|
// ======================================================================
// \title DataPacket.cpp
// \author bocchino
// \brief cpp file for FilePacket::DataPacket
//
// \copyright
// Copyright 2009-2016, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Fw/FilePacket/FilePacket.hpp>
#include <Fw/Types/Assert.hpp>
namespace Fw {
void FilePacket::DataPacket ::
initialize(
const U32 sequenceIndex,
const U32 byteOffset,
const U16 dataSize,
const U8 *const data
)
{
this->header.initialize(FilePacket::T_DATA, sequenceIndex);
this->byteOffset = byteOffset;
this->dataSize = dataSize;
this->data = data;
}
U32 FilePacket::DataPacket ::
bufferSize(void) const
{
return
this->header.bufferSize() +
sizeof(this->byteOffset) +
sizeof(this->dataSize) +
this->dataSize;
}
SerializeStatus FilePacket::DataPacket ::
toBuffer(Buffer& buffer) const
{
SerialBuffer serialBuffer(
buffer.getData(),
buffer.getSize()
);
return this->toSerialBuffer(serialBuffer);
}
SerializeStatus FilePacket::DataPacket ::
fromSerialBuffer(SerialBuffer& serialBuffer)
{
FW_ASSERT(this->header.type == T_DATA);
SerializeStatus status = serialBuffer.deserialize(this->byteOffset);
if (status != FW_SERIALIZE_OK)
return status;
status = serialBuffer.deserialize(this->dataSize);
if (status != FW_SERIALIZE_OK)
return status;
if (serialBuffer.getBuffLeft() != this->dataSize)
return FW_DESERIALIZE_SIZE_MISMATCH;
U8 *const addr = serialBuffer.getBuffAddr();
this->data = &addr[this->fixedLengthSize()];
return FW_SERIALIZE_OK;
}
U32 FilePacket::DataPacket ::
fixedLengthSize(void) const
{
return
this->header.bufferSize() +
sizeof(this->byteOffset) +
sizeof(this->dataSize);
}
SerializeStatus FilePacket::DataPacket ::
toSerialBuffer(SerialBuffer& serialBuffer) const
{
FW_ASSERT(this->header.type == T_DATA);
SerializeStatus status;
status = this->header.toSerialBuffer(serialBuffer);
if (status != FW_SERIALIZE_OK)
return status;
status = serialBuffer.serialize(this->byteOffset);
if (status != FW_SERIALIZE_OK)
return status;
status = serialBuffer.serialize(this->dataSize);
if (status != FW_SERIALIZE_OK)
return status;
status = serialBuffer.pushBytes(this->data, dataSize);
return status;
}
}
|
/*******************************************************************************
* This file was auto-generated using the AutoGemm.py python script.
* DO NOT modify this file! Instead, make changes to scripts in
* clBLAS/src/library/blas/AutoGemm/ then re-generate files
* (otherwise local changes will be lost after re-generation).
******************************************************************************/
#ifndef KERNEL_CGEMM_COL_CT_B0_MX032_NX032_KX01_SRC_H
#define KERNEL_CGEMM_COL_CT_B0_MX032_NX032_KX01_SRC_H
const unsigned int cgemm_Col_CT_B0_MX032_NX032_KX01_workGroupNumRows = 16;
const unsigned int cgemm_Col_CT_B0_MX032_NX032_KX01_workGroupNumCols = 16;
const unsigned int cgemm_Col_CT_B0_MX032_NX032_KX01_microTileNumRows = 2;
const unsigned int cgemm_Col_CT_B0_MX032_NX032_KX01_microTileNumCols = 2;
const unsigned int cgemm_Col_CT_B0_MX032_NX032_KX01_unroll = 1;
const char * const cgemm_Col_CT_B0_MX032_NX032_KX01_src ="\n"
"/* cgemm_Col_CT_B0_MX032_NX032_KX01 */\n"
"\n"
"/* kernel parameters */\n"
"#define WG_NUM_ROWS 16\n"
"#define WG_NUM_COLS 16\n"
"#define MICRO_TILE_NUM_ROWS 2\n"
"#define MICRO_TILE_NUM_COLS 2\n"
"#define MACRO_TILE_NUM_ROWS 32\n"
"#define MACRO_TILE_NUM_COLS 32\n"
"#define NUM_UNROLL_ITER 1\n"
"\n"
"#define LOCAL_ROW_PAD 0\n"
"#define LOCAL_COL_PAD 0\n"
"\n"
"/* global memory indices */\n"
"#define GET_GLOBAL_INDEX_A(ROW,COL) ((ROW)*lda+(COL))\n"
"#define GET_GLOBAL_INDEX_B(ROW,COL) ((ROW)*ldb+(COL))\n"
"#define GET_GLOBAL_INDEX_C(ROW,COL) ((COL)*ldc+(ROW))\n"
"\n"
"/* local memory indices */\n"
"#define GET_LOCAL_INDEX_A(ROW,COL) ((ROW) + (COL)*((MACRO_TILE_NUM_ROWS)+(LOCAL_COL_PAD)) )\n"
"#define GET_LOCAL_INDEX_B(ROW,COL) ((COL) + (ROW)*((MACRO_TILE_NUM_COLS)+(LOCAL_ROW_PAD)) )\n"
"\n"
"/* data types */\n"
"#define DATA_TYPE_STR float2\n"
"#define TYPE_MAD(MULA,MULB,DST) \\\n"
" DST.s0 = mad( MULA.s0, MULB.s0, DST.s0 ); \\\n"
" DST.s0 = mad( MULA.s1, MULB.s1, DST.s0 ); \\\n"
" DST.s1 = mad( MULA.s0, MULB.s1, DST.s1 ); \\\n"
" DST.s1 = mad( -MULA.s1, MULB.s0, DST.s1 );\n"
"#define TYPE_MAD_WRITE( DST, ALPHA, REG, BETA ) \\\n"
" /* (1) */ \\\n"
" type_mad_tmp = REG.s0; \\\n"
" REG.s0 *= ALPHA.s0; \\\n"
" REG.s0 = mad( -ALPHA.s1, REG.s1, REG.s0 ); \\\n"
" REG.s1 *= ALPHA.s0; \\\n"
" REG.s1 = mad( ALPHA.s1, type_mad_tmp, REG.s1 ); \\\n"
" DST = REG;\n"
"\n"
"/* 2x2 micro-tile */\n"
"#define MICRO_TILE \\\n"
" rA[0] = localA[offA + 0*WG_NUM_ROWS]; \\\n"
" rA[1] = localA[offA + 1*WG_NUM_ROWS]; \\\n"
" rB[0] = localB[offB + 0*WG_NUM_COLS]; \\\n"
" rB[1] = localB[offB + 1*WG_NUM_COLS]; \\\n"
" offA += (MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD); \\\n"
" offB += (MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD); \\\n"
" TYPE_MAD(rA[0],rB[0],rC[0][0]); \\\n"
" TYPE_MAD(rA[0],rB[1],rC[0][1]); \\\n"
" TYPE_MAD(rA[1],rB[0],rC[1][0]); \\\n"
" TYPE_MAD(rA[1],rB[1],rC[1][1]); \\\n"
" mem_fence(CLK_LOCAL_MEM_FENCE);\n"
"\n"
"__attribute__((reqd_work_group_size(WG_NUM_COLS,WG_NUM_ROWS,1)))\n"
"__kernel void cgemm_Col_CT_B0_MX032_NX032_KX01(\n"
" __global DATA_TYPE_STR const * restrict A,\n"
" __global DATA_TYPE_STR const * restrict B,\n"
" __global DATA_TYPE_STR * C,\n"
" DATA_TYPE_STR const alpha,\n"
" DATA_TYPE_STR const beta,\n"
" uint const M,\n"
" uint const N,\n"
" uint const K,\n"
" uint const lda,\n"
" uint const ldb,\n"
" uint const ldc,\n"
" uint const offsetA,\n"
" uint const offsetB,\n"
" uint const offsetC\n"
") {\n"
"\n"
" /* apply offsets */\n"
" A += offsetA;\n"
" B += offsetB;\n"
" C += offsetC;\n"
"\n"
" /* allocate registers */\n"
" DATA_TYPE_STR rC[MICRO_TILE_NUM_ROWS][MICRO_TILE_NUM_COLS] = { {0} };\n"
" DATA_TYPE_STR rA[MICRO_TILE_NUM_ROWS];\n"
" DATA_TYPE_STR rB[MICRO_TILE_NUM_COLS];\n"
"\n"
" /* allocate local memory */\n"
" __local DATA_TYPE_STR localA[NUM_UNROLL_ITER*(MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD)];\n"
" __local DATA_TYPE_STR localB[NUM_UNROLL_ITER*(MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD)];\n"
"\n"
" /* work item indices */\n"
" uint groupRow = get_group_id(0);\n"
" uint groupCol = get_group_id(1);\n"
" uint localRow = get_local_id(0);\n"
" uint localCol = get_local_id(1);\n"
" uint localSerial = localRow + localCol*WG_NUM_ROWS;\n"
"\n"
" /* global indices being loaded */\n"
"#define globalARow(LID) (groupRow*MACRO_TILE_NUM_ROWS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/NUM_UNROLL_ITER)\n"
"#define globalACol(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%NUM_UNROLL_ITER)\n"
"#define globalBRow(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/MACRO_TILE_NUM_COLS)\n"
"#define globalBCol(LID) (groupCol*MACRO_TILE_NUM_COLS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%MACRO_TILE_NUM_COLS)\n"
"\n"
" /* loop over k */\n"
" uint block_k = K / NUM_UNROLL_ITER;\n"
" do {\n"
"\n"
" /* local indices being written */\n"
"#define localARow (localSerial / NUM_UNROLL_ITER)\n"
"#define localACol (localSerial % NUM_UNROLL_ITER)\n"
"#define localAStride (WG_NUM_ROWS*WG_NUM_COLS/NUM_UNROLL_ITER)\n"
"#define localBRow ( localSerial / MACRO_TILE_NUM_COLS )\n"
"#define localBCol ( localSerial % MACRO_TILE_NUM_COLS )\n"
"#define localBStride (WG_NUM_ROWS*WG_NUM_COLS)\n"
" __local DATA_TYPE_STR *lA = localA + GET_LOCAL_INDEX_A(localARow, localACol);\n"
" __local DATA_TYPE_STR *lB = localB + GET_LOCAL_INDEX_B(localBRow, localBCol);\n"
" barrier(CLK_LOCAL_MEM_FENCE);\n"
"\n"
" /* load global -> local */\n"
" if ( localSerial + 0*WG_NUM_ROWS*WG_NUM_COLS < (WG_NUM_ROWS*MICRO_TILE_NUM_ROWS*NUM_UNROLL_ITER) ) {\n"
" lA[ 0*localAStride ] = A[ GET_GLOBAL_INDEX_A( globalARow(0), globalACol(0) ) ];\n"
" }\n"
" if ( localSerial + 0*WG_NUM_ROWS*WG_NUM_COLS < (WG_NUM_COLS*MICRO_TILE_NUM_COLS*NUM_UNROLL_ITER) ) {\n"
" lB[ 0*localBStride ] = B[ GET_GLOBAL_INDEX_B( globalBRow(0), globalBCol(0) ) ];\n"
" }\n"
" barrier(CLK_LOCAL_MEM_FENCE);\n"
" uint offA = localRow;\n"
" uint offB = localCol;\n"
"\n"
" /* do mads */\n"
" MICRO_TILE\n"
"\n"
" /* shift to next k block */\n"
" A += NUM_UNROLL_ITER;\n"
" B += ldb*NUM_UNROLL_ITER;\n"
"\n"
" } while (--block_k > 0);\n"
"\n"
"\n"
" /* which global Cij index */\n"
" uint globalCRow = groupRow * MACRO_TILE_NUM_ROWS + localRow;\n"
" uint globalCCol = groupCol * MACRO_TILE_NUM_COLS + localCol;\n"
"\n"
" /* write global Cij */\n"
" float type_mad_tmp;\n"
" TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[0][0], beta )\n"
" TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[0][1], beta )\n"
" TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[1][0], beta )\n"
" TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[1][1], beta )\n"
"\n"
"}\n"
"";
#else
#endif
|
/*
What
Creating message categories
Why
We want custom categories with filtering
How
QLoggingCategory
Q_DECLARE_LOGGING_CATEGORY
Q_LOGGING_CATEGORY
setFilterRules
*/
#include <QCoreApplication>
#include <QDebug>
#include <QLoggingCategory>
//Declare a logging category
Q_DECLARE_LOGGING_CATEGORY(network);
Q_LOGGING_CATEGORY(network,"network");
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qInfo() << "test";
qInfo(network) << "test";
qWarning(network) << "test";
//turn it off
QLoggingCategory::setFilterRules("network.debug=false");
//Will not log
qDebug(network) << "kitty";
if(!network().isDebugEnabled())
{
QLoggingCategory::setFilterRules("network.debug=true");
qDebug(network) << "We turned it back on!";
}
qDebug(network) << "yes";
return a.exec();
}
|
/*******************************************************************************
Title : tree.cpp
Author : Lashana Tello
Created on : February 23, 2018
Description : The implementation file for the Tree class
Purpose : To provide a means of representing a single tree in New York
City
Usage : Use to store data from NYC Tree Census
Build with : g++ -c -std=c++11 tree.cpp
Modifications : March 1, 2018
Added new method implementations
*******************************************************************************/
#include <iomanip>
#include <sstream>
#include <iostream>
#include "tree.h"
#include <string>
Tree::Tree() {
spc_common_ = "";
tree_id_ = 0;
tree_dbh_ = 0;
status_ = "";
health_ = "";
address_ = "";
boroname_ = "";
zipcode_ = 0;
latitude_ = 0;
longitude_ = 0;
}
Tree::Tree(const std::string& treedata) {
std::string data;
int count = 1;
std::istringstream line(treedata);
std::stringstream convert;
// Extract the specific information we need from specific columns/spots in
// the treedata string using stringstream to convert the string data
while ((std::getline(line, data, ',')) && (40 > count)) {
if (1 == count) {
convert << data << " ";
convert >> tree_id_;
} else if (4 == count) {
convert << data << " ";
convert >> tree_dbh_;
} else if (7 == count) {
status_ = data;
} else if (8 == count) {
health_ = data;
} else if (10 == count) {
spc_common_ = data;
} else if (25 == count) {
if (isdigit(data[0])) {
address_ = data;
} else {
// The column right before the address column may have more than one
// piece of data separated by commas. We need to skip over this data to
// get the address. The address always begins with a number so we will
// read until we get data that begins with a number, which will be the
// address
while (!isdigit(data[0])) {
std::getline(line, data, ',');
}
address_ = data;
}
} else if (26 == count) {
convert << data << " ";
convert >> zipcode_;
} else if (30 == count) {
boroname_ = data;
} else if (38 == count) {
convert << data << " ";
convert >> latitude_;
} else if (39 == count) {
convert << data;
convert >> longitude_;
}
convert.str(std::string()); // clear the stringstream
++count;
}
}
Tree::Tree(int id, int diam, std::string status, std::string health,
std::string spc, int zip, std::string addr, std::string boro,
double latitude, double longitude) {
spc_common_ = spc;
tree_id_ = id;
tree_dbh_ = diam;
status_ = status;
health_ = health;
address_ = addr;
boroname_ = boro;
zipcode_ = zip;
latitude_ = latitude;
longitude_ = longitude;
}
Tree::Tree(const Tree& other_tree) {
spc_common_ = other_tree.spc_common_;
tree_id_ = other_tree.tree_id_;
tree_dbh_ = other_tree.tree_dbh_;
status_ = other_tree.status_;
health_ = other_tree.health_;
address_ = other_tree.address_;
boroname_ = other_tree.boroname_;
zipcode_ = other_tree.zipcode_;
latitude_ = other_tree.latitude_;
longitude_ = other_tree.longitude_;
}
Tree::~Tree() {
}
bool operator==(const Tree& t1, const Tree& t2) {
if ((t1.spc_common_ == t2.spc_common_) && (t1.tree_id_ == t2.tree_id_)) {
return true;
} else {
return false;
}
}
bool operator<(const Tree& t1, const Tree& t2) {
if (t1.spc_common_ < t2.spc_common_) {
return true;
} else if (t1.spc_common_ == t2.spc_common_) {
if (t1.tree_id_ < t2.tree_id_) {
return true;
}
}
return false;
}
std::ostream& operator<<(std::ostream& os, const Tree& t) {
os << t.spc_common_ << ", ";
os << t.tree_id_ << ", ";
os << t.tree_dbh_ << ", ";
os << t.status_ << ", ";
os << t.health_ << ", ";
os << t.address_ << ", ";
os << t.boroname_ << ", ";
os << std::setfill('0') << std::setw(5) << t.zipcode_ << ", ";
os << std::setprecision(10) << t.latitude_ << ", ";
os << std::setprecision(10) << t.longitude_ << std::endl;
return os;
}
bool samename(const Tree& t1, const Tree& t2) {
if (t1.spc_common_ == t2.spc_common_) {
return true;
} else {
return false;
}
}
bool islessname(const Tree& t1, const Tree& t2) {
if (t1.spc_common_ < t2.spc_common_) {
return true;
} else {
return false;
}
}
Tree& Tree::operator=(const Tree& other_tree) {
spc_common_ = other_tree.spc_common_;
tree_id_ = other_tree.tree_id_;
tree_dbh_ = other_tree.tree_dbh_;
status_ = other_tree.status_;
health_ = other_tree.health_;
address_ = other_tree.address_;
boroname_ = other_tree.boroname_;
zipcode_ = other_tree.zipcode_;
latitude_ = other_tree.latitude_;
longitude_ = other_tree.longitude_;
return *this;
}
bool Tree::operator!=(const Tree& other_tree) {
if ((spc_common_ != other_tree.spc_common_) &&
(tree_id_ == other_tree.tree_id_)) {
return true;
}
return false;
}
std::string Tree::common_name() const {
return spc_common_;
}
std::string Tree::borough_name() const {
return boroname_;
}
std::string Tree::nearest_address() const {
return address_;
}
int Tree::diameter() const {
return tree_dbh_;
}
int Tree::zip() const {
return zipcode_;
}
void Tree::get_position(double& latitude, double& longitude) const {
latitude = latitude_;
longitude = longitude_;
}
|
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
double pi = 3.14159;
double r;
cout << fixed << setprecision(3);
cin >> r;
double v = 4.0 / 3.0 * pi * pow(r, 3);
cout << "VOLUME = " << v << 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 "SkPixelRef.h"
#include "SkFlattenableBuffers.h"
#include "SkThread.h"
SK_DEFINE_INST_COUNT(SkPixelRef)
// must be a power-of-2. undef to just use 1 mutex
#define PIXELREF_MUTEX_RING_COUNT 32
#ifdef PIXELREF_MUTEX_RING_COUNT
static int32_t gPixelRefMutexRingIndex;
static SK_DECLARE_MUTEX_ARRAY(gPixelRefMutexRing, PIXELREF_MUTEX_RING_COUNT);
#else
SK_DECLARE_STATIC_MUTEX(gPixelRefMutex);
#endif
static SkBaseMutex* get_default_mutex() {
#ifdef PIXELREF_MUTEX_RING_COUNT
// atomic_inc might be overkill here. It may be fine if once in a while
// we hit a race-condition and two subsequent calls get the same index...
int index = sk_atomic_inc(&gPixelRefMutexRingIndex);
return &gPixelRefMutexRing[index & (PIXELREF_MUTEX_RING_COUNT - 1)];
#else
return &gPixelRefMutex;
#endif
}
///////////////////////////////////////////////////////////////////////////////
int32_t SkNextPixelRefGenerationID() {
static int32_t gPixelRefGenerationID;
// do a loop in case our global wraps around, as we never want to
// return a 0
int32_t genID;
do {
genID = sk_atomic_inc(&gPixelRefGenerationID) + 1;
} while (0 == genID);
return genID;
}
///////////////////////////////////////////////////////////////////////////////
void SkPixelRef::setMutex(SkBaseMutex* mutex) {
if (NULL == mutex) {
mutex = get_default_mutex();
}
fMutex = mutex;
}
// just need a > 0 value, so pick a funny one to aid in debugging
#define SKPIXELREF_PRELOCKED_LOCKCOUNT 123456789
SkPixelRef::SkPixelRef(SkBaseMutex* mutex) : fPreLocked(false) {
this->setMutex(mutex);
fPixels = NULL;
fColorTable = NULL; // we do not track ownership of this
fLockCount = 0;
fGenerationID = 0; // signal to rebuild
fIsImmutable = false;
fPreLocked = false;
}
SkPixelRef::SkPixelRef(SkFlattenableReadBuffer& buffer, SkBaseMutex* mutex)
: INHERITED(buffer) {
this->setMutex(mutex);
fPixels = NULL;
fColorTable = NULL; // we do not track ownership of this
fLockCount = 0;
fIsImmutable = buffer.readBool();
fGenerationID = buffer.readUInt();
fPreLocked = false;
}
void SkPixelRef::setPreLocked(void* pixels, SkColorTable* ctable) {
// only call me in your constructor, otherwise fLockCount tracking can get
// out of sync.
fPixels = pixels;
fColorTable = ctable;
fLockCount = SKPIXELREF_PRELOCKED_LOCKCOUNT;
fPreLocked = true;
}
void SkPixelRef::flatten(SkFlattenableWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeBool(fIsImmutable);
// We write the gen ID into the picture for within-process recording. This
// is safe since the same genID will never refer to two different sets of
// pixels (barring overflow). However, each process has its own "namespace"
// of genIDs. So for cross-process recording we write a zero which will
// trigger assignment of a new genID in playback.
if (buffer.isCrossProcess()) {
buffer.writeUInt(0);
} else {
buffer.writeUInt(fGenerationID);
}
}
void SkPixelRef::lockPixels() {
SkASSERT(!fPreLocked || SKPIXELREF_PRELOCKED_LOCKCOUNT == fLockCount);
if (!fPreLocked) {
SkAutoMutexAcquire ac(*fMutex);
if (1 == ++fLockCount) {
fPixels = this->onLockPixels(&fColorTable);
}
}
}
void SkPixelRef::unlockPixels() {
SkASSERT(!fPreLocked || SKPIXELREF_PRELOCKED_LOCKCOUNT == fLockCount);
if (!fPreLocked) {
SkAutoMutexAcquire ac(*fMutex);
SkASSERT(fLockCount > 0);
if (0 == --fLockCount) {
this->onUnlockPixels();
fPixels = NULL;
fColorTable = NULL;
}
}
}
bool SkPixelRef::lockPixelsAreWritable() const {
return this->onLockPixelsAreWritable();
}
bool SkPixelRef::onLockPixelsAreWritable() const {
return true;
}
uint32_t SkPixelRef::getGenerationID() const {
if (0 == fGenerationID) {
fGenerationID = SkNextPixelRefGenerationID();
}
return fGenerationID;
}
void SkPixelRef::notifyPixelsChanged() {
#ifdef SK_DEBUG
if (fIsImmutable) {
SkDebugf("========== notifyPixelsChanged called on immutable pixelref");
}
#endif
// this signals us to recompute this next time around
fGenerationID = 0;
}
void SkPixelRef::setImmutable() {
fIsImmutable = true;
}
bool SkPixelRef::readPixels(SkBitmap* dst, const SkIRect* subset) {
return this->onReadPixels(dst, subset);
}
bool SkPixelRef::onReadPixels(SkBitmap* dst, const SkIRect* subset) {
return false;
}
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_BUILD_FOR_ANDROID
void SkPixelRef::globalRef(void* data) {
this->ref();
}
void SkPixelRef::globalUnref() {
this->unref();
}
#endif
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iot1click-projects/model/UntagResourceResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::IoT1ClickProjects::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
UntagResourceResult::UntagResourceResult()
{
}
UntagResourceResult::UntagResourceResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
UntagResourceResult& UntagResourceResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
AWS_UNREFERENCED_PARAM(result);
return *this;
}
|
//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2018 Michael Fink
//
/// \file SerialPort.cpp serial port classes
//
#include "stdafx.h"
#include "SerialPort.hpp"
#include "SerialPortImpl.hpp"
#include "SerialPortConfig.hpp"
#include <atlstr.h>
using Serial::SerialPort;
SerialPort::SerialPort(LPCTSTR deviceName, boost::asio::io_service& service)
{
m_spImpl.reset(new SerialPort::Impl(CStringA(deviceName), service));
}
SerialPort::~SerialPort()
{
try
{
m_spImpl->Close();
}
catch (...)
{
}
}
Serial::SerialPortConfig SerialPort::Config()
{
return Serial::SerialPortConfig(*this);
}
bool SerialPort::IsOpen() const
try
{
return m_spImpl->IsOpen();
}
catch (...)
{
return false;
}
void SerialPort::SendBreak()
{
m_spImpl->SendBreak();
}
void SerialPort::Send(const std::vector<BYTE>& data)
{
m_spImpl->Send(data);
}
void SerialPort::Receive(std::vector<BYTE>& data, unsigned int numMaxSize)
{
m_spImpl->Receive(data, numMaxSize);
}
void SerialPort::AsyncReceive(T_fnAsyncReceiveHandler asyncReceiveHandler, unsigned int numMaxSize)
{
m_spImpl->AsyncReceive(asyncReceiveHandler, numMaxSize);
}
void SerialPort::Close()
{
m_spImpl->Close();
}
|
/****************************************************************************
* Copyright (C) from 2009 to Present EPAM Systems.
*
* This file is part of Indigo toolkit.
*
* 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 "base_cpp/d_bitset.h"
#include "base_cpp/obj_array.h"
using namespace indigo;
// private---------------------------------------------------------------------------------------
void Dbitset::_recalculateWordsInUse()
{
// Traverse the bitset until a used word is found
int i;
for (i = _length - 1; i >= 0; --i)
if (_words[i] != 0)
break;
_wordsInUse = i + 1; // The new logical size
}
void Dbitset::_initWords(int nbits)
{
_wordsInUse = 0;
_length = _wordIndex(nbits - 1) + 1;
_words.clear_resize(_length);
_words.zerofill();
_bitsNumber = nbits;
}
void Dbitset::_expandTo(int wordIndex)
{
int wordsRequired = wordIndex + 1;
if (_wordsInUse < wordsRequired)
{
_wordsInUse = wordsRequired;
}
}
int Dbitset::_bitCount(qword b) const
{
b = (b & 0x5555555555555555LL) + ((b >> 1) & 0x5555555555555555LL);
b = (b & 0x3333333333333333LL) + ((b >> 2) & 0x3333333333333333LL);
b = (b + (b >> 4)) & 0x0F0F0F0F0F0F0F0FLL;
b = b + (b >> 8);
b = b + (b >> 16);
b = (b + (b >> 32)) & 0x0000007F;
return (int)b;
}
int Dbitset::_leastSignificantBitPosition(qword n) const
{
if (n == 0)
return -1;
int pos = 63;
if (n & 0x00000000FFFFFFFFLL)
{
pos -= 32;
}
else
{
n >>= 32;
}
if (n & 0x000000000000FFFFLL)
{
pos -= 16;
}
else
{
n >>= 16;
}
if (n & 0x00000000000000FFLL)
{
pos -= 8;
}
else
{
n >>= 8;
}
if (n & 0x000000000000000FLL)
{
pos -= 4;
}
else
{
n >>= 4;
}
if (n & 0x0000000000000003LL)
{
pos -= 2;
}
else
{
n >>= 2;
}
if (n & 0x0000000000000001LL)
{
pos -= 1;
}
return pos;
}
// public------------------------------------------------------------------------------------------------------
Dbitset::Dbitset()
{
_initWords(BITS_PER_WORD);
}
Dbitset::Dbitset(int nbits)
{
_initWords(nbits);
}
Dbitset::~Dbitset()
{
}
void Dbitset::copy(const Dbitset& set)
{
if (_length != set._length)
{
_length = set._length;
_words.resize(_length);
}
_bitsNumber = set._bitsNumber;
_wordsInUse = set._wordsInUse;
_words.copy(set._words);
}
void Dbitset::copySubset(const Dbitset& set)
{
if (_bitsNumber == set._bitsNumber)
copy(set);
if (_bitsNumber < set._bitsNumber)
return;
_wordsInUse = __max(_wordsInUse, set._wordsInUse);
for (int i = 0; i < set._length; ++i)
{
_words[i] = set._words[i];
}
}
void Dbitset::flip()
{
flip(0, _bitsNumber);
}
void Dbitset::flip(int bitIndex)
{
int wordindex = _wordIndex(bitIndex);
bitIndex -= (wordindex << ADDRESS_BITS_PER_WORD);
_expandTo(wordindex);
_words[wordindex] ^= ((qword)1 << bitIndex);
_recalculateWordsInUse();
}
void Dbitset::flip(int fromIndex, int toIndex)
{
if (fromIndex == toIndex)
return;
int start_word_index = _wordIndex(fromIndex);
int end_word_index = _wordIndex(toIndex - 1);
_expandTo(end_word_index);
fromIndex -= (start_word_index << ADDRESS_BITS_PER_WORD);
toIndex -= (end_word_index << ADDRESS_BITS_PER_WORD);
qword first_word_mask = WORD_MASK << fromIndex;
qword last_word_mask = shiftOne(toIndex) - 1;
if (start_word_index == end_word_index)
{
_words[start_word_index] ^= (first_word_mask & last_word_mask);
}
else
{
_words[start_word_index] ^= first_word_mask;
for (int i = start_word_index + 1; i < end_word_index; ++i)
_words[i] ^= WORD_MASK;
_words[end_word_index] ^= last_word_mask;
}
_recalculateWordsInUse();
}
void Dbitset::set(int bitIndex)
{
int wordindex = _wordIndex(bitIndex);
bitIndex -= (wordindex << ADDRESS_BITS_PER_WORD);
_expandTo(wordindex);
_words[wordindex] |= ((qword)1 << bitIndex); // Restores invariants
}
void Dbitset::set(int fromIndex, int toIndex)
{
if (fromIndex == toIndex)
return;
int start_word_index = _wordIndex(fromIndex);
int end_word_index = _wordIndex(toIndex - 1);
fromIndex -= (start_word_index << ADDRESS_BITS_PER_WORD);
toIndex -= (end_word_index << ADDRESS_BITS_PER_WORD);
qword first_word_mask = WORD_MASK << fromIndex;
qword last_word_mask = shiftOne(toIndex) - 1;
if (start_word_index == end_word_index)
{
_words[start_word_index] |= (first_word_mask & last_word_mask);
}
else
{
_words[start_word_index] |= first_word_mask;
for (int i = start_word_index + 1; i < end_word_index; ++i)
_words[i] |= WORD_MASK;
_words[end_word_index] |= last_word_mask;
}
_recalculateWordsInUse();
}
void Dbitset::set()
{
set(0, _bitsNumber);
}
void Dbitset::set(int bitIndex, bool value)
{
if (value)
set(bitIndex);
else
reset(bitIndex);
}
void Dbitset::reset(int bitIndex)
{
int wordindex = _wordIndex(bitIndex);
bitIndex -= (wordindex << ADDRESS_BITS_PER_WORD);
if (wordindex >= _wordsInUse)
return;
_words[wordindex] &= ~((qword)1 << bitIndex);
_recalculateWordsInUse();
}
void Dbitset::clear()
{
while (_wordsInUse > 0)
_words[--_wordsInUse] = 0;
}
bool Dbitset::get(int bitIndex) const
{
int word_index = _wordIndex(bitIndex);
bitIndex -= (word_index << ADDRESS_BITS_PER_WORD);
return (word_index < _wordsInUse) && ((_words[word_index] & ((qword)1 << bitIndex)) != 0);
}
int Dbitset::nextSetBit(int fromIndex) const
{
int u = _wordIndex(fromIndex);
if (u >= _wordsInUse)
return -1;
fromIndex -= (u << ADDRESS_BITS_PER_WORD);
qword word = _words[u] & (WORD_MASK << fromIndex);
for (; word == 0; word = _words[u])
{
if (++u >= _wordsInUse)
return -1;
}
return _leastSignificantBitPosition(word) + (u << ADDRESS_BITS_PER_WORD);
}
bool Dbitset::intersects(const Dbitset& set) const
{
for (int i = __min(_wordsInUse, set._wordsInUse) - 1; i >= 0; --i)
if ((_words[i] & set._words[i]) != 0)
return true;
return false;
}
bool Dbitset::complements(const Dbitset& set) const
{
if (_wordsInUse > set._wordsInUse)
for (int i = _wordsInUse - 1; i >= set._wordsInUse; --i)
if (_words[i])
return true;
for (int i = _wordsInUse - 1; i >= 0; --i)
if ((_words[i] & ~set._words[i]) != 0)
return true;
return false;
}
void Dbitset::andWith(const Dbitset& set)
{
while (_wordsInUse > set._wordsInUse)
_words[--_wordsInUse] = 0;
// Perform logical AND on words in common
for (int i = 0; i < _wordsInUse; ++i)
_words[i] &= set._words[i];
_recalculateWordsInUse();
}
void Dbitset::orWith(const Dbitset& set)
{
if (_wordsInUse < set._wordsInUse)
_wordsInUse = set._wordsInUse;
// Perform logical OR on words in common
for (int i = 0; i < _wordsInUse; ++i)
{
_words[i] |= set._words[i];
}
}
void Dbitset::xorWith(const Dbitset& set)
{
if (_wordsInUse < set._wordsInUse)
{
_wordsInUse = set._wordsInUse;
}
// Perform logical XOR on words in common
for (int i = 0; i < _wordsInUse; ++i)
_words[i] ^= set._words[i];
_recalculateWordsInUse();
}
void Dbitset::andNotWith(const Dbitset& set)
{
for (int i = __min(_wordsInUse, set._wordsInUse) - 1; i >= 0; --i)
_words[i] &= ~set._words[i];
_recalculateWordsInUse();
}
bool Dbitset::equals(const Dbitset& set) const
{
if (_wordsInUse != set._wordsInUse)
return false;
// Check words in use by both BitSets
for (int i = 0; i < _wordsInUse; ++i)
if (_words[i] != set._words[i])
return false;
return true;
}
void Dbitset::resize(int size)
{
int new_length = _wordIndex(size - 1) + 1;
_words.resize(new_length);
if (new_length > _length)
for (int i = _length; i < new_length; ++i)
_words[i] = 0;
_bitsNumber = size;
_length = new_length;
}
bool Dbitset::isSubsetOf(const Dbitset& set) const
{
for (int i = 0; i < _wordsInUse; ++i)
if (_words[i] & ~set._words[i])
return false;
return true;
}
bool Dbitset::isProperSubsetOf(const Dbitset& set) const
{
bool proper = false;
for (int i = 0; i < _wordsInUse; ++i)
{
if (set._words[i] & ~_words[i])
proper = true;
if (_words[i] & ~set._words[i])
return false;
}
return proper;
}
void Dbitset::zeroFill()
{
_words.zerofill();
_recalculateWordsInUse();
}
void Dbitset::bsOrBs(const Dbitset& set1, const Dbitset& set2)
{
int max_words = __max(set1._wordsInUse, set2._wordsInUse);
for (int i = 0; i < max_words; ++i)
{
_words[i] = set1._words[i] | set2._words[i];
}
for (int i = max_words; i < _wordsInUse; ++i)
{
_words[i] = 0;
}
_wordsInUse = max_words;
}
void Dbitset::bsAndNotBs(const Dbitset& set1, const Dbitset& set2)
{
for (int i = 0; i < set1._wordsInUse; ++i)
{
_words[i] = set1._words[i] & ~set2._words[i];
}
for (int i = set1._wordsInUse; i < _wordsInUse; ++i)
{
_words[i] = 0;
}
_recalculateWordsInUse();
}
void Dbitset::bsAndBs(const Dbitset& set1, const Dbitset& set2)
{
for (int i = 0; i < set1._wordsInUse; ++i)
{
_words[i] = set1._words[i] & set2._words[i];
}
for (int i = set1._wordsInUse; i < _wordsInUse; ++i)
{
_words[i] = 0;
}
_recalculateWordsInUse();
}
int Dbitset::bitsNumber() const
{
int bits_num = 0;
for (int i = 0; i < _wordsInUse; ++i)
bits_num += _bitCount(_words[i]);
return bits_num;
}
// some 64-bit compilators can not correctly work with big values shift. So it must be processed manually
qword Dbitset::shiftOne(int shiftNumber)
{
qword result = (qword)1;
while (shiftNumber > MAX_SHIFT_NUMBER)
{
result = result << MAX_SHIFT_NUMBER;
shiftNumber -= MAX_SHIFT_NUMBER;
}
result = result << shiftNumber;
return result;
}
Dbitset::Iterator::Iterator(Dbitset& self) : _fromWordIdx(0), _fromByteIdx(-1), _fromBitIdx(-1), _fromIndexes(0)
{
_words = self._words.ptr();
_wordsInUse = self._wordsInUse;
}
static ObjArray<Array<int>> all_indexes;
int Dbitset::Iterator::begin()
{
if (all_indexes.size() == 0)
{
for (unsigned int buf = 0; buf < 256; ++buf)
{
Array<int>& indexes = all_indexes.push();
_fillIndexes(buf, indexes);
}
}
if (_wordsInUse == 0)
return -1;
_fromWordIdx = -1;
_fromBitIdx = -1;
_fromByteIdx = -1;
_fromIndexes = 0;
_fromWord = 0;
return next();
}
int Dbitset::Iterator::next()
{
if (_fromIndexes)
{
++_fromBitIdx;
if (_fromBitIdx < _fromIndexes->size())
return _fromIndexes->at(_fromBitIdx) + _shiftByte + _shiftWord;
}
_fromIndexes = 0;
if (_fromWord)
{
for (++_fromByteIdx; _fromByteIdx < 8; ++_fromByteIdx)
{
int from_byte = ((byte*)_fromWord)[_fromByteIdx];
if (from_byte == 0)
continue;
_fromIndexes = &(all_indexes.at(from_byte));
_fromBitIdx = 0;
_shiftByte = _fromByteIdx << 3;
return _fromIndexes->at(_fromBitIdx) + _shiftByte + _shiftWord;
}
}
_fromWord = 0;
for (++_fromWordIdx; _fromWordIdx < _wordsInUse; ++_fromWordIdx)
{
_fromWord = &_words[_fromWordIdx];
if (*_fromWord == 0)
continue;
for (_fromByteIdx = 0; _fromByteIdx < 8; ++_fromByteIdx)
{
int from_byte = ((byte*)_fromWord)[_fromByteIdx];
if (from_byte == 0)
continue;
_fromIndexes = &(all_indexes.at(from_byte));
_fromBitIdx = 0;
_shiftByte = _fromByteIdx << 3;
_shiftWord = _fromWordIdx << 6;
return _fromIndexes->at(_fromBitIdx) + _shiftByte + _shiftWord;
}
}
return -1;
}
void Dbitset::Iterator::_fillIndexes(byte buf, Array<int>& indexes)
{
byte test_buf;
for (int buf_idx = 0; buf_idx < 8; ++buf_idx)
{
test_buf = (byte)1 << buf_idx;
if (buf & test_buf)
{
indexes.push(buf_idx);
}
}
}
|
#include "testApp.h"
//--------------------------------------------------------------
void testApp::setup() {
ofSetVerticalSync(true);
ofBackgroundHex(0xfdefc2);
ofSetLogLevel(OF_LOG_NOTICE);
ofDisableAntiAliasing();
box2d.init();
box2d.setGravity(10, 0);
box2d.setFPS(30.0);
box2d.registerGrabbing();
anchor.setup(box2d.getWorld(), 20, ofGetHeight()/2, 4);
// first we add just a few circles
for (int i=0; i<3; i++) {
ofPtr<ofxBox2dCircle> circle = ofPtr<ofxBox2dCircle>(new ofxBox2dCircle);
circle.get()->setPhysics(3.0, 0.53, 0.1);
circle.get()->setup(box2d.getWorld(), ofGetWidth()/2, 100+(i*20), 8);
circles.push_back(circle);
}
// now connect each circle with a joint
for (int i=0; i<circles.size(); i++) {
ofPtr<ofxBox2dJoint> joint = ofPtr<ofxBox2dJoint>(new ofxBox2dJoint);
// if this is the first point connect to the top anchor.
if(i == 0) {
joint.get()->setup(box2d.getWorld(), anchor.body, circles[i].get()->body);
}
else {
joint.get()->setup(box2d.getWorld(), circles[i-1].get()->body, circles[i].get()->body);
}
joint.get()->setLength(25);
joints.push_back(joint);
}
}
//--------------------------------------------------------------
void testApp::update() {
box2d.update();
}
//--------------------------------------------------------------
void testApp::draw() {
ofSetHexColor(0xf2ab01);
anchor.draw();
for(int i=0; i<circles.size(); i++) {
ofFill();
ofSetHexColor(0x01b1f2);
circles[i].get()->draw();
}
for(int i=0; i<joints.size(); i++) {
ofSetHexColor(0x444342);
joints[i].get()->draw();
}
string info = "";
info += "Press [n] to add a new joint\n";
info += "click and pull the chain around\n";
info += "FPS: "+ofToString(ofGetFrameRate(), 1)+"\n";
ofSetHexColor(0x444342);
ofDrawBitmapString(info, 30, 30);
}
//--------------------------------------------------------------
void testApp::keyPressed(int key) {
if(key == 'n') {
// add a new circle
ofPtr<ofxBox2dCircle> circle = ofPtr<ofxBox2dCircle>(new ofxBox2dCircle);
circle.get()->setPhysics(3.0, 0.53, 0.1);
circle.get()->setup(box2d.getWorld(), circles.back().get()->getPosition().x+ofRandom(-30, 30), circles.back().get()->getPosition().y-30, 8);
circles.push_back(circle);
// get this cirlce and the prev cirlce
int a = (int)circles.size()-2;
int b = (int)circles.size()-1;
// now connect the new circle with a joint
ofPtr<ofxBox2dJoint> joint = ofPtr<ofxBox2dJoint>(new ofxBox2dJoint);
joint.get()->setup(box2d.getWorld(), circles[a].get()->body, circles[b].get()->body);
joint.get()->setLength(25);
joints.push_back(joint);
}
if(key == 't') ofToggleFullscreen();
}
//--------------------------------------------------------------
void testApp::keyReleased(int key) {
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ) {
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::resized(int w, int h){
}
|
/*
* Copyright 2010-2016 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/ec2/model/CreateRouteTableRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::EC2::Model;
using namespace Aws::Utils;
CreateRouteTableRequest::CreateRouteTableRequest() :
m_dryRun(false),
m_dryRunHasBeenSet(false),
m_vpcIdHasBeenSet(false)
{
}
Aws::String CreateRouteTableRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=CreateRouteTable&";
if(m_dryRunHasBeenSet)
{
ss << "DryRun=" << m_dryRun << "&";
}
if(m_vpcIdHasBeenSet)
{
ss << "VpcId=" << StringUtils::URLEncode(m_vpcId.c_str()) << "&";
}
ss << "Version=2015-10-01";
return ss.str();
}
|
// Copyright 2020 The Defold Foundation
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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 "dns.h"
#include "socket.h"
namespace dmDNS
{
static Result SocketToDNSResult(const dmSocket::Result res)
{
Result dns_res;
switch (res)
{
case dmSocket::RESULT_OK:
dns_res = dmDNS::RESULT_OK;
break;
case dmSocket::RESULT_HOST_NOT_FOUND:
dns_res = dmDNS::RESULT_HOST_NOT_FOUND;
break;
default:
dns_res = dmDNS::RESULT_UNKNOWN_ERROR;
}
return dns_res;
}
Result Initialize()
{
return RESULT_OK;
}
Result Finalize()
{
return RESULT_OK;
}
Result NewChannel(HChannel* channel)
{
*channel = 0; // so it evaluates to false
return RESULT_OK;
}
Result RefreshChannel(HChannel channel)
{
return RESULT_OK;
}
void StopChannel(HChannel channel) {}
void DeleteChannel(HChannel channel) {}
Result GetHostByName(const char* name, dmSocket::Address* address, HChannel channel, bool ipv4, bool ipv6)
{
return SocketToDNSResult(dmSocket::GetHostByName(name, address, ipv4, ipv6));
}
const char* ResultToString(Result result){
return "";
}
} // namespace dmDNS
|
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
long maxWeight(pair<long, long>* arr, long* memo, int n)
{
if (memo[n] != 0)
return memo[n];
long tw = arr[n].second;
for (int i = 0; i < n; i++)
if (arr[i].first < arr[n].first)
tw = max(tw, arr[n].second + maxWeight(arr, memo, i));
memo[n] = tw;
return tw;
}
int main()
{
int T;
cin >> T;
while (T > 0)
{
T--;
int n;
cin >> n;
pair<long, long>* arr = new pair<long, long>[n];
long* memo = new long[n];
memset(memo, 0LL, sizeof(memo));
for (int i = 0; i < n; i++)
{
long temp;
cin >> temp;
arr[i].first = temp;
}
for (int i = 0; i < n; i++)
{
long temp;
cin >> temp;
arr[i].second = temp;
}
long answer = 0;
for (int i = 0; i < n; i++)
answer = max(answer, maxWeight(arr, memo, i));
cout << answer << endl;
}
return 0;
}
|
#include<iostream>
using namespace std;
template <typename T>
int search (T A[],int n,T key){
for (int i = 0; i < n; i++)
{
if (A[i]==key)
{
return i;
}
}
return -1;
}
int main (){
int n;
cin>>n;
int A[n];
for (int i = 0; i < n; i++)
{
cin>>A[i];
}
int key;
cin>>key;
cout<<search (A,n,key)<<endl;
return 0;
}
|
/*
* Copyright (C) 2021 Frank Mertens.
*
* Distribution and use is allowed under the terms of the zlib license
* (see cc/LICENSE-zlib).
*
*/
#include <cc/ForegroundLoggingInstance>
#include <cc/IoStream>
namespace cc {
struct ForegroundLoggingInstance::State: public HttpLoggingServiceInstance::State
{
State(const MetaObject &config):
HttpLoggingServiceInstance::State{config}
{}
void logDelivery(const HttpClientConnection &client, const HttpRequest &request, HttpStatus status, long long bytesWritten, const String &statusMessage) const override
{
IoStream::output().write(
formatDeliveryNotice(client, request, status, bytesWritten, statusMessage)
);
}
void logMessage(const String &message, LoggingLevel level) const override
{
if (verbosity() >= level) IoStream::error().write(message);
}
};
ForegroundLoggingInstance::ForegroundLoggingInstance(const MetaObject &config):
HttpLoggingServiceInstance{new State{config}}
{}
} // namespace cc
|
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinamountfield.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include "qvalidatedlineedit.h"
#include "qvaluecombobox.h"
#include <QCheckBox>
#include <QDir>
#include <QIntValidator>
#include <QLabel>
#include <QLineEdit>
#include <QLocale>
#include <QMessageBox>
#include <QPushButton>
#include <QRegExp>
#include <QRegExpValidator>
#include <QTabWidget>
#include <QWidget>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(0, 65535, this));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_WS_MAC
ui->tabWindow->setVisible(false);
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
connect(ui->lang, SIGNAL(activated(int)), this, SLOT(showRestartWarning_Lang()));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable save buttons when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableSaveButtons()));
/* disable save buttons when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableSaveButtons()));
/* disable/enable save buttons when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(bool)), this, SLOT(setSaveButtonState(bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
mapper->addMapping(ui->detachDatabases, OptionsModel::DetachDatabases);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
/* Window */
#ifndef Q_WS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
}
void OptionsDialog::enableSaveButtons()
{
// prevent enabling of the save buttons when data modified, if there is an invalid proxy address present
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
ui->applyButton->setEnabled(false);
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting orangecoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting orangecoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
// Update transactionFee with the current unit
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(object == ui->proxyIp && event->type() == QEvent::FocusOut)
{
// Check proxyIP for a valid IPv4/IPv6 address
CService addr;
if(!LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr))
{
ui->proxyIp->setValid(false);
fProxyIpValid = false;
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
emit proxyIpValid(false);
}
else
{
fProxyIpValid = true;
ui->statusLabel->clear();
emit proxyIpValid(true);
}
}
return QDialog::eventFilter(object, event);
}
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/base/code-coverage.h"
#include <fstream>
#include <vector>
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/util/logger.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
/*
* The function below will be called by the interpreter on each
* evaluated expression when running hhvm with:
* $ hhvm -v Eval.RecordCodeCoverage=1 <phpfile>
*
* The (line0, line1) pair is supposed to represent the start and end
* of an evaluated expression. One should normally increment the line
* usage counters for all the lines between line0 and line1 but certain
* constructs like including a file, eval-ing a string, or even
* executing a for loop do not have a good value for line1.
*
* Indeed on this toy cover.php file:
*
* <?php
*
* echo "here\n";
* for($i = 0; $i < 2; $i++) {
* echo "here $i\n";
* }
*
* echo 1 +
* 2 +
* (3 + 4);
*
* eval("echo 'bar\n';");
*
* and with this command:
*
* $ hhvm -v Eval.RecordCodeCoverage=1 \
* -v Eval.CodeCoverageOutputFile=/tmp/cov.log \
* -f cover.php
*
* one get this output (with appropriate printf in this file):
*
* /home/pad/cover.php, (1, 12)
* /home/pad/cover.php, (3, 3)
* here
* /home/pad/cover.php, (4, 6)
* /home/pad/cover.php, (4, 4)
* /home/pad/cover.php, (5, 5)
* here 0
* /home/pad/cover.php, (4, 4)
* /home/pad/cover.php, (4, 4)
* /home/pad/cover.php, (5, 5)
* here 1
* /home/pad/cover.php, (4, 4)
* /home/pad/cover.php, (4, 4)
* /home/pad/cover.php, (8, 10)
* /home/pad/cover.php, (8, 9)
* /home/pad/cover.php, (8, 10)
* 6/home/pad/cover.php, (12, 12)
* /home/pad/cover.php, (12, 12)
* /home/pad/cover.php, (1, 2)
* /home/pad/cover.php, (1, 2)
*
* So right now it is just simpler to ignore line1.
*/
void CodeCoverage::Record(const char *filename, int line0, int line1) {
if (!filename || !*filename || line0 <= 0 || line1 <= 0 || line0 > line1) {
return;
}
Logger::Verbose("%s, (%d, %d)\n", filename, line0, line1);
CodeCoverageMap::iterator iter = m_hits.find(filename);
if (iter == m_hits.end()) {
std::vector<int> &lines = m_hits[filename];
lines.resize(line1 + 1);
for (int i = line0; i <= line0 /* should be line1 one day */; i++) {
lines[i] = 1;
}
} else {
std::vector<int> &lines = iter->second;
if ((int)lines.size() < line1 + 1) {
lines.resize(line1 + 1);
}
for (int i = line0; i <= line0 /* should be line1 one day */; i++) {
++lines[i];
}
}
}
Array CodeCoverage::Report() {
Array ret = Array::Create();
for (CodeCoverageMap::const_iterator iter = m_hits.begin();
iter != m_hits.end(); ++iter) {
const std::vector<int> &lines = iter->second;
Array tmp = Array::Create();
for (int i = 1; i < (int)lines.size(); i++) {
if (lines[i]) {
tmp.set(i, Variant((int64_t)lines[i]));
}
}
ret.set(String(iter->first), Variant(tmp));
}
return ret;
}
void CodeCoverage::Report(const std::string &filename) {
std::ofstream f(filename.c_str());
if (!f) {
Logger::Error("unable to open %s", filename.c_str());
return;
}
f << "{\n";
for (CodeCoverageMap::const_iterator iter = m_hits.begin();
iter != m_hits.end();) {
const std::vector<int> &lines = iter->second;
f << "\"" << iter->first << "\": [";
int count = lines.size();
for (int i = 0 /* not 1 */; i < count; i++) {
f << lines[i];
if (i < count - 1) {
f << ",";
}
}
f << "]";
if (++iter != m_hits.end()) {
f << ",";
}
f << "\n";
}
f << "}\n";
f.close();
}
void CodeCoverage::Reset() {
m_hits.clear();
g_vmContext->resetCoverageCounters();
}
///////////////////////////////////////////////////////////////////////////////
}
|
//
// Created by marandil on 08.09.15.
//
#ifndef MDLUTILS_MULTITHREADING_HELPERS_HPP
#define MDLUTILS_MULTITHREADING_HELPERS_HPP
#include <chrono>
#include <thread>
#include <mutex>
#include <mdlutils/typedefs.hpp>
namespace mdl
{
typedef std::lock_guard<std::mutex> mutex_lock;
namespace helper
{
unsigned inline hw_concurrency()
{
return std::thread::hardware_concurrency() ? std::thread::hardware_concurrency() : 1;
}
time_point_t inline delay_by(duration_t duration)
{
return std::chrono::high_resolution_clock::now() + duration;
}
bool inline is_after(time_point_t time)
{
return (std::chrono::high_resolution_clock::now() > time);
}
}
}
#endif //MDLUTILS_MULTITHREADING_HELPERS_HPP
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkGDALRasterReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkLASReader.h"
#include <vtkCellArray.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkNew.h>
#include <vtkObjectFactory.h>
#include <vtkPoints.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
#include <vtkUnsignedShortArray.h>
#include <vtkVertexGlyphFilter.h>
#include <liblas/liblas.hpp>
#include <fstream>
#include <iostream>
#include <valarray>
vtkStandardNewMacro(vtkLASReader)
//----------------------------------------------------------------------------
vtkLASReader::vtkLASReader()
{
this->FileName = nullptr;
this->SetNumberOfInputPorts(0);
this->SetNumberOfOutputPorts(1);
}
//----------------------------------------------------------------------------
vtkLASReader::~vtkLASReader()
{
if ( ! this->FileName )
delete[] this->FileName;
}
//----------------------------------------------------------------------------
int vtkLASReader::RequestData(vtkInformation* vtkNotUsed(request),
vtkInformationVector** vtkNotUsed(request),
vtkInformationVector* outputVector)
{
// Get the info object
vtkInformation* outInfo = outputVector->GetInformationObject(0);
// Get the ouptut
vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
// Open LAS File for reading
std::ifstream ifs;
ifs.open(this->FileName, std::ios_base::binary | std::ios_base::in);
if ( ! ifs.is_open() )
{
vtkErrorMacro (<< "Unable to open file for reading: " << this->FileName );
return VTK_ERROR;
}
// Read header data
liblas::ReaderFactory readerFactory;
liblas::Reader reader = readerFactory.CreateWithStream(ifs);
vtkNew<vtkPolyData> pointsPolyData;
this->ReadPointRecordData(reader, pointsPolyData);
ifs.close();
// Convert points to verts in output polydata
vtkNew<vtkVertexGlyphFilter> vertexFilter;
vertexFilter->SetInputData(pointsPolyData);
vertexFilter->Update();
output->ShallowCopy(vertexFilter->GetOutput());
return VTK_OK;
}
//----------------------------------------------------------------------------
void vtkLASReader::ReadPointRecordData(liblas::Reader &reader, vtkPolyData* pointsPolyData)
{
vtkNew<vtkPoints> points;
// scalars associated with points
vtkNew<vtkUnsignedShortArray> color;
color->SetName("color");
color->SetNumberOfComponents(3);
vtkNew<vtkUnsignedShortArray> classification;
classification->SetName("classification");
classification->SetNumberOfComponents(1);
vtkNew<vtkUnsignedShortArray> intensity;
intensity->SetName("intensity");
intensity->SetNumberOfComponents(1);
liblas::Header header = liblas::Header(reader.GetHeader());
std::valarray<double> scale = {
header.GetScaleX(), header.GetScaleY(), header.GetScaleZ()
};
std::valarray<double> offset = {
header.GetOffsetX(), header.GetOffsetY(), header.GetOffsetZ()
};
liblas::PointFormatName pointFormat = header.GetDataFormatId();
int pointRecordsCount = header.GetPointRecordsCount();
for ( int i= 0; i < pointRecordsCount && reader.ReadNextPoint(); i++)
{
liblas::Point const& p = reader.GetPoint();
std::valarray<double> lasPoint = {
p.GetX(), p.GetY(), p.GetZ()
};
points->InsertNextPoint(&lasPoint[0]);
//std::valarray<double> point = lasPoint * scale + offset;
// We have seen a file where the scaled points were much smaller than the offset
// So, all points ended up in the same place.
std::valarray<double> point = lasPoint * scale;
switch(pointFormat)
{
case liblas::ePointFormat2:
case liblas::ePointFormat3:
case liblas::ePointFormat5:
{
unsigned short c[3];
c[0] = p.GetColor().GetRed();
c[1] = p.GetColor().GetGreen();
c[2] = p.GetColor().GetBlue();
color->InsertNextTypedTuple(c);
intensity->InsertNextValue(p.GetIntensity());
}
break;
case liblas::ePointFormat0:
case liblas::ePointFormat1:
classification->InsertNextValue(p.GetClassification().GetClass());
intensity->InsertNextValue(p.GetIntensity());
break;
case liblas::ePointFormatUnknown:
default:
intensity->InsertNextValue(p.GetIntensity());
break;
}
}
pointsPolyData->SetPoints(points);
pointsPolyData->GetPointData()->AddArray(intensity);
switch(pointFormat)
{
case liblas::ePointFormat2:
case liblas::ePointFormat3:
case liblas::ePointFormat5:
pointsPolyData->GetPointData()->AddArray(color);
break;
case liblas::ePointFormat0:
case liblas::ePointFormat1:
pointsPolyData->GetPointData()->AddArray(classification);
break;
case liblas::ePointFormatUnknown:
default:
break;
}
}
//----------------------------------------------------------------------------
void vtkLASReader::PrintSelf(ostream &os, vtkIndent indent)
{
Superclass::PrintSelf(os, indent);
os << "vtkLASReader" << std::endl;
os << "Filename: " << this->FileName << std::endl;
}
|
#include <llhelm.hpp>
#include <algorithm>
#include <set>
#define SCALE_FACTOR 1000000.
namespace OptCompiler
{
Length::Length() = default;
Length::Length(float f)
{
l = f;
}
int Length::cost_material(Length l)
{
return 0;
}
Atom Length::get_type()
{
return TYPE_LENGTH;
}
Angle::Angle() = default;
Angle::Angle(float f)
{
a = f;
}
int Angle::cost_material(Angle a)
{
return 0;
}
Atom Angle::get_type()
{
return TYPE_ANGLE;
}
Lumber::Lumber() = default;
Lumber::Lumber(std::string s)
{
uuid = s;
}
int Lumber::cost_material(Lumber l)
{
return 1;
}
Atom Lumber::get_type()
{
return TYPE_LUMBER;
}
XPrime::XPrime() = default;
Atom XPrime::get_type()
{
return TYPE_XPRIME;
}
Face::Face() = default;
Face::Face(std::string s)
{
uuid = s;
}
int Face::cost_material(Face l)
{
return 0;
}
Atom Face::get_type()
{
return TYPE_FACE;
}
Edge::Edge() = default;
Edge::Edge(std::string s)
{
uuid = s;
}
int Edge::cost_material(Edge l)
{
return 0;
}
Atom Edge::get_type()
{
return TYPE_EDGE;
}
Refc::Refc() = default;
int Refc::cost_material(Refc r)
{
return 0;
}
Atom Refc::get_type()
{
return TYPE_REFC;
}
void Refc::FinalizeRef()
{
intValues.reserve(values.size());
for (auto& v : values)
{
intValues.push_back(SCALE_FACTOR * v);
}
}
Refk::Refk() = default;
int Refk::cost_material(Refk r)
{
return 0;
}
Atom Refk::get_type()
{
return TYPE_REFK;
}
void Refk::FinalizeRef()
{
intValues.reserve(values.size());
for (auto& v : values)
{
intValues.push_back(SCALE_FACTOR * v);
}
}
Refj::Refj() = default;
int Refj::cost_material(Refj r)
{
return 0;
}
Atom Refj::get_type()
{
return TYPE_REFJ;
}
void Refj::FinalizeRef()
{
std::set<int> unqiueSet;
intValues.reserve(values.size());
for (auto& v : values)
{
const int scaledV = SCALE_FACTOR * v;
if (unqiueSet.find(scaledV) == unqiueSet.end())
{
intValues.push_back(scaledV);
unqiueSet.insert(scaledV);
}
}
}
Refb::Refb() = default;
int Refb::cost_material(Refb r)
{
return 0;
}
Atom Refb::get_type()
{
return TYPE_REFB;
}
void Refb::FinalizeRef()
{
std::set<int> unqiueSet;
intValues.reserve(values.size());
for (auto& v : values)
{
const int scaledV = SCALE_FACTOR * v;
if (unqiueSet.find(scaledV) == unqiueSet.end())
{
intValues.push_back(scaledV);
unqiueSet.insert(scaledV);
}
}
}
Refd::Refd() = default;
int Refd::cost_material(Refd r)
{
return 0;
}
Atom Refd::get_type()
{
return TYPE_REFD;
}
void Refd::FinalizeRef()
{
std::set<int> unqiueSet;
intValues.reserve(values.size());
for (auto& v : values)
{
const int scaledV = SCALE_FACTOR * v;
if (unqiueSet.find(scaledV) == unqiueSet.end())
{
intValues.push_back(scaledV);
unqiueSet.insert(scaledV);
}
}
}
Height::Height() = default;
int Height::cost_material(Height h)
{
return 0;
}
Atom Height::get_type()
{
return TYPE_HEIGHT;
}
Pick::Pick() = default;
Pick::Pick(int i)
{
id = i;
}
int Pick::getid()
{
return id;
}
int Pick::cost_material(Pick p)
{
return 10000000;
}
Atom Pick::get_type()
{
return TYPE_PICK;
}
Stackable::Stackable() = default;
Stackable::Stackable(bool b)
{
stackable = b;
}
int Stackable::cost_material(Stackable b)
{
return 0;
}
Atom Stackable::get_type()
{
return TYPE_STACKABLE;
}
Bandsaw::Bandsaw() = default;
Atom Bandsaw::get_type()
{
return TYPE_BANDSAW;
}
Tracksaw::Tracksaw() = default;
Atom Tracksaw::get_type()
{
return TYPE_TRACKSAW;
}
Path::Path() = default;
Atom Path::get_type()
{
return TYPE_PATH;
}
Chopsaw::Chopsaw() = default;
Chopsaw::Chopsaw(Lumber l1, Face f1, Edge e1, Refc r, Stackable b, Height h1)
{
l = l1;
f = f1;
e = e1;
rc = r;
s = b;
h = h1;
}
int Chopsaw::cost_material(Chopsaw cs)
{
return 0;
}
Atom Chopsaw::get_type()
{
return TYPE_CHOPSAW;
}
Var::Var() = default;
Var::Var(std::string s)
{
name = s;
}
int Var::cost_material(Var v)
{
return 0;
}
Atom Var::get_type()
{
return TYPE_VAR;
}
Tuple::Tuple() = default;
Tuple::Tuple(LLHelm l1, LLHelm r1)
{
l = l1;
r = r1;
}
int Tuple::cost_material(Tuple t)
{
return 0;
}
Atom Tuple::get_type()
{
return TYPE_TUPLE;
}
Assign::Assign() = default;
Assign::Assign(LLHelm l1, LLHelm r1)
{
l = l1;
r = r1;
}
int Assign::cost_material(Assign a)
{
return 0;
}
Atom Assign::get_type()
{
return TYPE_ASSIGN;
}
Seq::Seq() = default;
Seq::Seq(LLHelm l1, LLHelm r1)
{
l = l1;
r = r1;
}
int Seq::cost_material(Seq s)
{
return 0;
}
Atom Seq::get_type()
{
return TYPE_SEQ;
}
Float::Float(float f) : num(f)
{
}
Atom Float::get_type()
{
return TYPE_FLOAT;
}
Drill::Drill()
{
}
Atom Drill::get_type()
{
return TYPE_DRILL;
}
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestOSPRayTime.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This test verifies that time varying data works as expected in ospray
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkDataSetSurfaceFilter.h"
#include "vtkInformation.h"
#include "vtkOSPRayPass.h"
#include "vtkOSPRayRendererNode.h"
#include "vtkPolyDataMapper.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkSmartPointer.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTimeSourceExample.h"
int TestOSPRayTime(int argc, char* argv[])
{
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New();
iren->SetRenderWindow(renWin);
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
renWin->AddRenderer(renderer);
renderer->SetBackground(0.0, 0.0, 0.0);
renWin->SetSize(400, 400);
renWin->Render();
vtkSmartPointer<vtkOSPRayPass> ospray = vtkSmartPointer<vtkOSPRayPass>::New();
renderer->SetPass(ospray);
for (int i = 0; i < argc; ++i)
{
if (!strcmp(argv[i], "--OptiX"))
{
vtkOSPRayRendererNode::SetRendererType("optix pathtracer", renderer);
break;
}
}
vtkSmartPointer<vtkTimeSourceExample> timeywimey = vtkSmartPointer<vtkTimeSourceExample>::New();
timeywimey->GrowingOn();
vtkSmartPointer<vtkDataSetSurfaceFilter> dsf = vtkSmartPointer<vtkDataSetSurfaceFilter>::New();
dsf->SetInputConnection(timeywimey->GetOutputPort());
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(dsf->GetOutputPort());
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
renderer->AddActor(actor);
actor->SetMapper(mapper);
renWin->Render();
renderer->ResetCamera();
double pos[3];
vtkCamera* camera = renderer->GetActiveCamera();
camera->SetFocalPoint(0.0, 2.5, 0.0);
camera->GetPosition(pos);
pos[0] = pos[0] + 6;
pos[1] = pos[1] + 6;
pos[2] = pos[2] + 6;
camera->SetPosition(pos);
renderer->ResetCameraClippingRange();
renWin->Render();
for (int i = 0; i < 20; i++)
{
double updateTime = (double)(i % 10) / 10.0;
cerr << "t=" << updateTime << endl;
renderer->SetActiveCamera(camera);
vtkInformation* outInfo = dsf->GetExecutive()->GetOutputInformation(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP(), updateTime);
renderer->ResetCameraClippingRange();
renWin->Render();
}
iren->Start();
return 0;
}
|
/*
* 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.
*/
/*!
* \brief Tensor Compute Op.
* \file tensor_compute_op.cc
*/
#include <tvm/runtime/registry.h>
#include <tvm/te/operation.h>
#include <tvm/arith/analyzer.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/stmt_functor.h>
#include <unordered_set>
#include "./op_util.h"
#include "./compute_op.h"
#include "../../arith/compute_expr.h"
namespace tvm {
namespace te {
using namespace tir;
// TensorComputeOpNode
TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<TensorComputeOpNode>([](const ObjectRef& node, ReprPrinter* p) {
auto* op = static_cast<const TensorComputeOpNode*>(node.get());
p->stream << "tensor_compute_op(" << op->name << ", " << op << ")";
});
TVM_REGISTER_NODE_TYPE(TensorComputeOpNode);
int TensorComputeOpNode::num_outputs() const {
return static_cast<int>(this->intrin->buffers.size() - this->inputs.size());
}
DataType TensorComputeOpNode::output_dtype(size_t i) const {
return this->intrin->buffers[this->inputs.size() + i]->dtype;
}
Operation TensorComputeOpNode::make(std::string name,
std::string tag,
Array<IterVar> axis,
Array<IterVar> reduce_axis,
int schedulable_ndim,
TensorIntrin intrin,
Array<Tensor> tensors,
Array<Region> regions,
Array<PrimExpr> scalar_inputs) {
auto n = make_object<TensorComputeOpNode>();
n->name = std::move(name);
n->tag = std::move(tag);
n->axis = std::move(axis);
n->reduce_axis = std::move(reduce_axis);
n->schedulable_ndim = std::move(schedulable_ndim);
n->intrin = std::move(intrin);
n->inputs = std::move(tensors);
n->input_regions = std::move(regions);
n->scalar_inputs = std::move(scalar_inputs);
return Operation(n);
}
TVM_REGISTER_GLOBAL("te.TensorComputeOp")
.set_body_typed(TensorComputeOpNode::make);
Array<Tensor> TensorComputeOpNode::InputTensors() const {
return inputs;
}
Operation TensorComputeOpNode::ReplaceInputs(
const Operation& self,
const std::unordered_map<Tensor, Tensor>& rmap) const {
CHECK_EQ(self.operator->(), this);
auto n = make_object<TensorComputeOpNode>(*this);
auto intrin = make_object<TensorIntrinNode>(*(this->intrin.operator->()));
intrin->body = ReplaceTensor(this->intrin->body, rmap);
if (intrin->reduce_init.defined()) {
intrin->reduce_init = ReplaceTensor(this->intrin->reduce_init, rmap);
}
if (intrin->reduce_update.defined()) {
intrin->reduce_update = ReplaceTensor(this->intrin->reduce_update, rmap);
}
for (size_t i = 0; i < n->inputs.size(); ++i) {
Tensor t = n->inputs[i];
if (rmap.count(t)) {
n->inputs.Set(i, rmap.at(t));
}
}
if (intrin->body.same_as(n->intrin->body) &&
intrin->reduce_init.same_as(n->intrin->reduce_init) &&
intrin->reduce_update.same_as(n->intrin->reduce_update) &&
inputs.same_as(n->inputs)) {
return self;
} else {
n->intrin = TensorIntrin(intrin);
return Operation(n);
}
}
void TensorComputeOpNode::PropBoundToInputs(
const Operation& self,
arith::Analyzer* analyzer,
const std::unordered_map<const VarNode*, IntSet>& dom_map,
std::unordered_map<Tensor, TensorDom>* out_dom_map) const {
for (size_t i = 0; i < this->inputs.size(); ++i) {
Tensor t = this->inputs[i];
Region region = input_regions[i];
auto it = out_dom_map->find(t);
if (it == out_dom_map->end()) continue;
TensorDom& dom = it->second;
for (size_t j = 0; j < t.ndim(); ++j) {
dom.data[j].emplace_back(EvalSet(region[j], dom_map));
}
}
}
size_t TensorComputeOpNode::num_schedulable_dims() const {
return schedulable_ndim;
}
Stmt TensorComputeOpNode::BuildProvide(
const Stage& stage,
const std::unordered_map<IterVar, Range>& dom_map,
bool debug_keep_trivial_loop) const {
CHECK_EQ(stage->op.operator->(), this);
// Start bind data.
Stmt nop = EvaluateNode::make(0);
std::vector<Stmt> input_bind_nest, output_bind_nest;
Array<Tensor> inputs = this->InputTensors();
// input binding
size_t num_inputs = inputs.size();
for (size_t i = 0; i < num_inputs; ++i) {
Tensor tensor = inputs[i];
Region region = this->input_regions[i];
Buffer buffer = this->intrin->buffers[i];
Array<ObjectRef> bind_spec{buffer, tensor};
Array<PrimExpr> tuple;
for (size_t i = 0; i < region.size(); ++i) {
tuple.push_back(region[i]->min);
tuple.push_back(region[i]->extent);
}
input_bind_nest.emplace_back(AttrStmtNode::make(
bind_spec, tir::attr::buffer_bind_scope,
CallNode::make(DataType::Handle(),
tir::intrinsic::tvm_tuple,
tuple, CallNode::Intrinsic), nop));
}
// output binding
for (int i = 0; i < this->num_outputs(); ++i) {
Tensor tensor = stage->op.output(i);
Buffer buffer = this->intrin->buffers[num_inputs + i];
Array<ObjectRef> bind_spec{buffer, tensor};
Array<PrimExpr> tuple;
for (size_t i = 0; i < this->axis.size(); ++i) {
auto ivar = this->axis[i];
if (i < static_cast<size_t>(this->schedulable_ndim)) {
tuple.push_back(ivar->var);
tuple.push_back(1);
} else {
Range dom = ivar->dom;
tuple.push_back(dom->min);
tuple.push_back(dom->extent);
}
}
output_bind_nest.emplace_back(AttrStmtNode::make(
bind_spec, tir::attr::buffer_bind_scope,
CallNode::make(DataType::Handle(),
tir::intrinsic::tvm_tuple,
tuple, CallNode::Intrinsic), nop));
}
// Check variable remap
std::unordered_map<const VarNode*, PrimExpr> vmap;
tir::ArgBinder binder(&vmap);
// Map the expressions passed in the call to the TensorIntrin, to the placeholder
// variables
Array<PrimExpr> user_expr = this->scalar_inputs;
Array<Var> scalar_params = this->intrin->scalar_params;
Array<PrimExpr> sp_expr;
for (auto sp : scalar_params) {
PrimExpr esp = sp;
sp_expr.push_back(esp);
}
CHECK_EQ(sp_expr.size(), user_expr.size());
// TODO(jdavies-huawei): what name should be used here?
binder.BindArray(sp_expr, user_expr, this->name);
size_t tloc = stage->leaf_iter_vars.size();
ComputeLoopNest n = ComputeLoopNest::make(this, stage, dom_map, debug_keep_trivial_loop);
if (this->reduce_axis.size() == 0) {
std::vector<std::vector<Stmt> > nest(
n.main_nest.begin(), n.main_nest.begin() + tloc + 1);
nest.emplace_back(MakeIfNest(n.main_predicates));
CHECK_EQ(n.init_predicates.size(), 0U);
CHECK(this->intrin->body.defined())
<< "Normal store op for intrin " << this << " is not defined";
Stmt body = MergeNest(output_bind_nest, this->intrin->body);
body = MergeNest(input_bind_nest, body);
body = tir::Substitute(body, vmap);
body = MergeNest(binder.asserts(), body);
body = te::Substitute(body, n.main_vmap);
Stmt ret = MergeNest(nest, body);
return ret;
} else {
// Need to split reduction
CHECK(this->intrin->reduce_update.defined())
<< "Reduction update op is not defined";
// Need init and update steps
CHECK_NE(this->reduce_axis.size(), 0U);
std::vector<std::vector<Stmt> > common(
n.main_nest.begin(), n.main_nest.begin() + n.num_common_loop + 1);
std::vector<std::vector<Stmt> > update_nest(
n.main_nest.begin() + n.num_common_loop + 1, n.main_nest.begin() + tloc + 1);
update_nest.emplace_back(MakeIfNest(n.main_predicates));
if (this->intrin->reduce_init.defined()) {
// init nest
std::vector<std::vector<Stmt> > init_nest(
n.init_nest.begin(), n.init_nest.begin() + tloc + 1);
init_nest.emplace_back(MakeIfNest(n.init_predicates));
Stmt init = MergeNest(output_bind_nest, this->intrin->reduce_init);
init = te::Substitute(init, n.init_vmap);
init = MergeNest(init_nest, init);
// The update
Stmt update = MergeNest(output_bind_nest, this->intrin->reduce_update);
update = MergeNest(input_bind_nest, update);
update = tir::Substitute(update, vmap);
update = MergeNest(binder.asserts(), update);
update = te::Substitute(update, n.main_vmap);
update = MergeNest(update_nest, update);
return MergeNest(common, SeqStmt::Flatten(init, update));
} else {
// When init op is not available, use body op for reset in the first iter.
CHECK(this->intrin->body.defined())
<< "Normal body op is not defined";
Stmt update = TransformUpdate(stage, dom_map, n,
this->intrin->body,
this->intrin->reduce_update);
update = MergeNest(output_bind_nest, update);
update = MergeNest(input_bind_nest, update);
update = tir::Substitute(update, vmap);
update = MergeNest(binder.asserts(), update);
update = te::Substitute(update, n.main_vmap);
update = MergeNest(update_nest, update);
return MergeNest(common, update);
}
}
}
} // namespace te
} // namespace tvm
|
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Flash Control (FC)
namespace FcSecbit{ ///<FC Security Bit Register
using Addr = Register::Address<0x41fff010,0xfffffffe,0x00000000,unsigned>;
///SECBIT
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> secbit{};
}
namespace FcFlcs{ ///<FC Flash Control Register
using Addr = Register::Address<0x41fff020,0xffc0fffe,0x00000000,unsigned>;
///RDY_BSY
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rdyBsy{};
///BLPRO
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,16),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> blpro{};
}
}
|
/**
* Copyright (c) 2006-2016 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "PNGHandler.h"
// LOVE
#include "common/Exception.h"
#include "common/math.h"
// LodePNG
#include "lodepng/lodepng.h"
// zlib
#include <zlib.h>
// C++
#include <algorithm>
// C
#include <cstdlib>
namespace love
{
namespace image
{
namespace magpie
{
// Custom PNG decompression function for LodePNG, using zlib.
static unsigned zlibDecompress(unsigned char **out, size_t *outsize, const unsigned char *in,
size_t insize, const LodePNGDecompressSettings* /*settings*/)
{
int status = Z_OK;
uLongf outdatasize = insize;
size_t sizemultiplier = 0;
unsigned char *outdata = out != nullptr ? *out : nullptr;
while (true)
{
// Enough size to hold the decompressed data, hopefully.
outdatasize = insize << (++sizemultiplier);
// LodePNG uses malloc, realloc, and free.
// Since version 2014-08-23, LodePNG passes in an existing pointer in
// the 'out' argument that it expects to be realloc'd. Not doing so can
// result in a memory leak.
if (outdata != nullptr)
outdata = (unsigned char *) realloc(outdata, outdatasize);
else
outdata = (unsigned char *) malloc(outdatasize);
if (!outdata)
return 83; // "Memory allocation failed" error code for LodePNG.
// Use zlib to decompress the PNG data.
status = uncompress(outdata, &outdatasize, in, insize);
// If the out buffer was big enough, break out of the loop.
if (status != Z_BUF_ERROR)
break;
// Otherwise delete the out buffer and try again with a larger size...
free(outdata);
outdata = nullptr;
}
if (status != Z_OK)
{
free(outdata);
return 10000; // "Unknown error code" for LodePNG.
}
if (out != nullptr)
*out = outdata;
if (outsize != nullptr)
*outsize = outdatasize;
return 0; // Success.
}
// Custom PNG compression function for LodePNG, using zlib.
static unsigned zlibCompress(unsigned char **out, size_t *outsize, const unsigned char *in,
size_t insize, const LodePNGCompressSettings* /*settings*/)
{
// Get the maximum compressed size of the data.
uLongf outdatasize = compressBound(insize);
// LodePNG uses malloc, realloc, and free.
unsigned char *outdata = (unsigned char *) malloc(outdatasize);
if (!outdata)
return 83; // "Memory allocation failed" error code for LodePNG.
// Use zlib to compress the PNG data.
int status = compress(outdata, &outdatasize, in, insize);
if (status != Z_OK)
{
free(outdata);
return 10000; // "Unknown error code" for LodePNG.
}
if (out != nullptr)
*out = outdata;
if (outsize != nullptr)
*outsize = (size_t) outdatasize;
return 0; // Success.
}
bool PNGHandler::canDecode(love::filesystem::FileData *data)
{
unsigned int width = 0, height = 0;
unsigned char *indata = (unsigned char *) data->getData();
size_t insize = data->getSize();
lodepng::State state;
unsigned status = lodepng_inspect(&width, &height, &state, indata, insize);
return status == 0 && width > 0 && height > 0;
}
bool PNGHandler::canEncode(ImageData::EncodedFormat format)
{
return format == ImageData::ENCODED_PNG;
}
PNGHandler::DecodedImage PNGHandler::decode(love::filesystem::FileData *fdata)
{
unsigned int width = 0, height = 0;
unsigned char *indata = (unsigned char *) fdata->getData();
size_t insize = fdata->getSize();
DecodedImage img;
lodepng::State state;
state.info_raw.colortype = LCT_RGBA;
state.info_raw.bitdepth = 8;
state.decoder.zlibsettings.custom_zlib = zlibDecompress;
unsigned status = lodepng_decode(&img.data, &width, &height,
&state, indata, insize);
if (status != 0)
{
const char *err = lodepng_error_text(status);
throw love::Exception("Could not decode PNG image (%s)", err);
}
img.width = (int) width;
img.height = (int) height;
img.size = width * height * 4;
return img;
}
PNGHandler::EncodedImage PNGHandler::encode(const DecodedImage &img, ImageData::EncodedFormat format)
{
if (format != ImageData::ENCODED_PNG)
throw love::Exception("PNG encoder cannot encode to non-PNG format.");
EncodedImage encimg;
lodepng::State state;
state.info_raw.colortype = LCT_RGBA;
state.info_raw.bitdepth = 8;
// TODO: support plain RGB (24-bit) encoding in the future?
state.info_png.color.colortype = LCT_RGBA;
state.info_png.color.bitdepth = 8;
state.encoder.zlibsettings.custom_zlib = zlibCompress;
unsigned status = lodepng_encode(&encimg.data, &encimg.size,
img.data, img.width, img.height, &state);
if (status != 0)
{
const char *err = lodepng_error_text(status);
throw love::Exception("Could not encode PNG image (%s)", err);
}
return encimg;
}
void PNGHandler::free(unsigned char *mem)
{
// LodePNG uses malloc, realloc, and free.
if (mem)
::free(mem);
}
} // magpie
} // image
} // love
|
// Copyright (c) 2009-2022 The Regents of the University of Michigan.
// Part of HOOMD-blue, released under the BSD 3-Clause License.
// this include is necessary to get MPI included before anything else to support intel MPI
#include "hoomd/ExecutionConfiguration.h"
#include <fstream>
#include <iostream>
#include <functional>
#include <memory>
#include "hoomd/md/PotentialExternal.h"
#ifdef ENABLE_HIP
#include "hoomd/md/PotentialExternalGPU.h"
#endif
#include "hoomd/md/EvaluatorExternalPeriodic.h"
#include "hoomd/Initializers.h"
#include <math.h>
using namespace std;
using namespace std::placeholders;
using namespace hoomd;
using namespace hoomd::md;
typedef PotentialExternal<EvaluatorExternalPeriodic> PotentialExternalPeriodic;
#ifdef ENABLE_HIP
typedef PotentialExternalGPU<EvaluatorExternalPeriodic> PotentialExternalPeriodicGPU;
#endif
/*! \file lj_force_test.cc
\brief Implements unit tests for PotentialPairLJ and PotentialPairLJGPU and descendants
\ingroup unit_tests
*/
#include "hoomd/test/upp11_config.h"
HOOMD_UP_MAIN();
//! Typedef'd LJForceCompute factory
typedef std::function<std::shared_ptr<PotentialExternalPeriodic>(
std::shared_ptr<SystemDefinition> sysdef)>
periodicforce_creator;
//! Test the ability of the lj force compute to actually calculate forces
void periodic_force_particle_test(periodicforce_creator periodic_creator,
std::shared_ptr<ExecutionConfiguration> exec_conf)
{
// this 3-particle test subtly checks several conditions
// the particles are arranged on the x axis, 1 2 3
// types of the particles : 0, 1, 0
// periodic boundary conditions will be handled in another test
std::shared_ptr<SystemDefinition> sysdef_3(
new SystemDefinition(3, BoxDim(5.0), 2, 0, 0, 0, 0, exec_conf));
std::shared_ptr<ParticleData> pdata_3 = sysdef_3->getParticleData();
pdata_3->setPosition(0, make_scalar3(1.7, 0.0, 0.0));
pdata_3->setPosition(1, make_scalar3(2.0, 0.0, 0.0));
pdata_3->setPosition(2, make_scalar3(3.5, 0.0, 0.0));
pdata_3->setType(1, 1);
std::shared_ptr<PotentialExternalPeriodic> fc_3 = periodic_creator(sysdef_3);
// first test: setup a sigma of 1.0 so that all forces will be 0
unsigned int index = 0;
Scalar orderParameter = 0.5;
Scalar interfaceWidth = 0.5;
unsigned int periodicity = 2;
fc_3->setParams(
0,
PotentialExternalPeriodic::param_type(index, orderParameter, interfaceWidth, periodicity));
fc_3->setParams(
1,
PotentialExternalPeriodic::param_type(index, -orderParameter, interfaceWidth, periodicity));
// compute the forces
fc_3->compute(0);
{
const GlobalArray<Scalar4>& force_array_1 = fc_3->getForceArray();
const GlobalArray<Scalar>& virial_array_1 = fc_3->getVirialArray();
size_t pitch = virial_array_1.getPitch();
ArrayHandle<Scalar4> h_force_1(force_array_1, access_location::host, access_mode::read);
ArrayHandle<Scalar> h_virial_1(virial_array_1, access_location::host, access_mode::read);
MY_CHECK_CLOSE(h_force_1.data[0].x, -0.180137, tol);
MY_CHECK_SMALL(h_force_1.data[0].y, tol_small);
MY_CHECK_SMALL(h_force_1.data[0].z, tol_small);
MY_CHECK_CLOSE(h_force_1.data[0].w, -0.0338307, tol);
MY_CHECK_SMALL(h_virial_1.data[0 * pitch + 0] + h_virial_1.data[3 * pitch + 0]
+ h_virial_1.data[5 * pitch + 0],
tol_small);
MY_CHECK_CLOSE(h_force_1.data[1].x, 0.189752, tol);
MY_CHECK_SMALL(h_force_1.data[1].y, tol_small);
MY_CHECK_SMALL(h_force_1.data[1].z, tol_small);
MY_CHECK_CLOSE(h_force_1.data[1].w, -0.024571, tol);
MY_CHECK_SMALL(h_virial_1.data[0 * pitch + 1] + h_virial_1.data[3 * pitch + 1]
+ h_virial_1.data[5 * pitch + 1],
tol_small);
MY_CHECK_CLOSE(h_force_1.data[2].x, 0.115629, tol);
MY_CHECK_SMALL(h_force_1.data[2].y, tol_small);
MY_CHECK_SMALL(h_force_1.data[2].z, tol_small);
MY_CHECK_CLOSE(h_force_1.data[2].w, -0.0640261, tol);
MY_CHECK_SMALL(h_virial_1.data[0 * pitch + 2] + h_virial_1.data[3 * pitch + 2]
+ h_virial_1.data[5 * pitch + 2],
tol_small);
}
}
#if 0
//! Unit test a comparison between 2 PeriodicForceComputes on a "real" system
void periodic_force_comparison_test(periodicforce_creator periodic_creator1, periodicforce_creator periodic_creator2, std::shared_ptr<ExecutionConfiguration> exec_conf)
{
const unsigned int N = 5000;
// create a random particle system to sum forces on
RandomInitializer rand_init(N, Scalar(0.2), Scalar(0.9), "A");
shared_ptr<SystemDefinition> sysdef(new SystemDefinition(rand_init, exec_conf));
shared_ptr<ParticleData> pdata = sysdef->getParticleData();
shared_ptr<PotentialExternalPeriodic> fc1 = periodic_creator1(sysdef);
shared_ptr<PotentialExternalPeriodic> fc2 = periodic_creator2(sysdef);
unsigned int index = 0;
Scalar orderParameter = 0.5;
Scalar interfaceWidth = 0.5;
unsigned int periodicity = 2;
fc1->setParams(make_scalar4(__int_as_scalar(index),orderParameter,interfaceWidth,__int_as_scalar(periodicity)));
fc2->setParams(make_scalar4(__int_as_scalar(index),orderParameter,interfaceWidth,__int_as_scalar(periodicity)));
// compute the forces
fc1->compute(0);
fc2->compute(0);
{
// verify that the forces are identical (within roundoff errors)
GlobalArray<Scalar4>& force_array_5 = fc1->getForceArray();
GlobalArray<Scalar>& virial_array_5 = fc1->getVirialArray();
size_t pitch = virial_array_5.getPitch();
ArrayHandle<Scalar4> h_force_5(force_array_5,access_location::host,access_mode::read);
ArrayHandle<Scalar> h_virial_5(virial_array_5,access_location::host,access_mode::read);
GlobalArray<Scalar4>& force_array_6 = fc2->getForceArray();
GlobalArray<Scalar>& virial_array_6 = fc2->getVirialArray();
ArrayHandle<Scalar4> h_force_6(force_array_6,access_location::host,access_mode::read);
ArrayHandle<Scalar> h_virial_6(virial_array_6,access_location::host,access_mode::read);
// compare average deviation between the two computes
double deltaf2 = 0.0;
double deltape2 = 0.0;
double deltav2[6];
for (unsigned int i = 0; i < 6; i++)
deltav2[i] = 0.0;
for (unsigned int i = 0; i < N; i++)
{
deltaf2 += double(h_force_6.data[i].x - h_force_5.data[i].x) * double(h_force_6.data[i].x - h_force_5.data[i].x);
deltaf2 += double(h_force_6.data[i].y - h_force_5.data[i].y) * double(h_force_6.data[i].y - h_force_5.data[i].y);
deltaf2 += double(h_force_6.data[i].z - h_force_5.data[i].z) * double(h_force_6.data[i].z - h_force_5.data[i].z);
deltape2 += double(h_force_6.data[i].w - h_force_5.data[i].w) * double(h_force_6.data[i].w - h_force_5.data[i].w);
for (unsigned int j = 0; j < 6; j++)
deltav2[j] += double(h_virial_6.data[j*pitch+i] - h_virial_5.data[j*pitch+i]) * double(h_virial_6.data[j*pitch+i] - h_virial_5.data[j*pitch+i]);
// also check that each individual calculation is somewhat close
}
deltaf2 /= double(pdata->getN());
deltape2 /= double(pdata->getN());
for (unsigned int j = 0; j < 6; j++)
deltav2[j] /= double(pdata->getN());
CHECK_SMALL(deltaf2, double(tol_small));
CHECK_SMALL(deltape2, double(tol_small));
CHECK_SMALL(deltav2[0], double(tol_small));
CHECK_SMALL(deltav2[1], double(tol_small));
CHECK_SMALL(deltav2[2], double(tol_small));
CHECK_SMALL(deltav2[3], double(tol_small));
CHECK_SMALL(deltav2[4], double(tol_small));
CHECK_SMALL(deltav2[5], double(tol_small));
}
}
#endif
//! LJForceCompute creator for unit tests
std::shared_ptr<PotentialExternalPeriodic>
base_class_periodic_creator(std::shared_ptr<SystemDefinition> sysdef)
{
return std::shared_ptr<PotentialExternalPeriodic>(new PotentialExternalPeriodic(sysdef));
}
#ifdef ENABLE_HIP
//! LJForceComputeGPU creator for unit tests
std::shared_ptr<PotentialExternalPeriodic>
gpu_periodic_creator(std::shared_ptr<SystemDefinition> sysdef)
{
std::shared_ptr<PotentialExternalPeriodicGPU> periodic(
new PotentialExternalPeriodicGPU(sysdef));
// the default block size kills valgrind :) reduce it
// lj->setBlockSize(64);
return periodic;
}
#endif
//! test case for particle test on CPU
UP_TEST(PotentialExternalPeriodic_particle)
{
periodicforce_creator periodic_creator_base = bind(base_class_periodic_creator, _1);
periodic_force_particle_test(periodic_creator_base,
std::shared_ptr<ExecutionConfiguration>(
new ExecutionConfiguration(ExecutionConfiguration::CPU)));
}
#ifdef ENABLE_HIP
//! test case for particle test on GPU
UP_TEST(PotentialExternalLamellaGPU_particle)
{
periodicforce_creator periodic_creator_gpu = bind(gpu_periodic_creator, _1);
periodic_force_particle_test(periodic_creator_gpu,
std::shared_ptr<ExecutionConfiguration>(
new ExecutionConfiguration(ExecutionConfiguration::GPU)));
}
/*
//! test case for comparing GPU output to base class output
UP_TEST( LJForceGPU_compare )
{
ljforce_creator lj_creator_gpu = bind(gpu_lj_creator, _1, _2);
ljforce_creator lj_creator_base = bind(base_class_lj_creator, _1, _2);
lj_force_comparison_test(lj_creator_base, lj_creator_gpu,
std::shared_ptr<ExecutionConfiguration>(new ExecutionConfiguration(ExecutionConfiguration::GPU)));
}
*/
#endif
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "UiCanvasEditor_precompiled.h"
#include "UiAnimViewAnimNode.h"
#include "UiAnimViewTrack.h"
#include "UiAnimViewSequence.h"
////////////////////////////////////////////////////////////////////////////
void CUiAnimViewKeyConstHandle::GetKey(IKey* pKey) const
{
assert(m_bIsValid);
m_pTrack->GetKey(m_keyIndex, pKey);
}
////////////////////////////////////////////////////////////////////////////
float CUiAnimViewKeyConstHandle::GetTime() const
{
assert(m_bIsValid);
return m_pTrack->GetKeyTime(m_keyIndex);
}
////////////////////////////////////////////////////////////////////////////
void CUiAnimViewKeyHandle::SetKey(IKey* pKey)
{
assert(m_bIsValid);
m_pTrack->SetKey(m_keyIndex, pKey);
}
////////////////////////////////////////////////////////////////////////////
void CUiAnimViewKeyHandle::GetKey(IKey* pKey) const
{
assert(m_bIsValid);
m_pTrack->GetKey(m_keyIndex, pKey);
}
////////////////////////////////////////////////////////////////////////////
void CUiAnimViewKeyHandle::Select(bool bSelect)
{
assert(m_bIsValid);
m_pTrack->SelectKey(m_keyIndex, bSelect);
}
////////////////////////////////////////////////////////////////////////////
bool CUiAnimViewKeyHandle::IsSelected() const
{
assert(m_bIsValid);
return m_pTrack->IsKeySelected(m_keyIndex);
}
////////////////////////////////////////////////////////////////////////////
void CUiAnimViewKeyHandle::SetTime(float time)
{
assert(m_bIsValid);
m_pTrack->SetKeyTime(m_keyIndex, time);
}
////////////////////////////////////////////////////////////////////////////
float CUiAnimViewKeyHandle::GetTime() const
{
assert(m_bIsValid);
return m_pTrack->GetKeyTime(m_keyIndex);
}
////////////////////////////////////////////////////////////////////////////
float CUiAnimViewKeyHandle::GetDuration() const
{
assert(m_bIsValid);
const char* desc = nullptr;
float duration = 0;
m_pTrack->m_pAnimTrack->GetKeyInfo(m_keyIndex, desc, duration);
return duration;
}
////////////////////////////////////////////////////////////////////////////
const char* CUiAnimViewKeyHandle::GetDescription() const
{
assert(m_bIsValid);
const char* desc = "";
float duration = 0;
m_pTrack->m_pAnimTrack->GetKeyInfo(m_keyIndex, desc, duration);
return desc;
}
////////////////////////////////////////////////////////////////////////////
void CUiAnimViewKeyHandle::Offset(float offset)
{
assert(m_bIsValid);
float newTime = m_pTrack->GetKeyTime(m_keyIndex) + offset;
m_pTrack->SetKeyTime(m_keyIndex, newTime);
}
////////////////////////////////////////////////////////////////////////////
void CUiAnimViewKeyHandle::Delete()
{
assert(m_bIsValid);
m_pTrack->RemoveKey(m_keyIndex);
m_bIsValid = false;
}
////////////////////////////////////////////////////////////////////////////
CUiAnimViewKeyHandle CUiAnimViewKeyHandle::Clone()
{
assert(m_bIsValid);
unsigned int newKeyIndex = m_pTrack->CloneKey(m_keyIndex);
return CUiAnimViewKeyHandle(m_pTrack, newKeyIndex);
}
////////////////////////////////////////////////////////////////////////////
CUiAnimViewKeyHandle CUiAnimViewKeyHandle::GetNextKey()
{
return m_pTrack->GetNextKey(GetTime());
}
////////////////////////////////////////////////////////////////////////////
CUiAnimViewKeyHandle CUiAnimViewKeyHandle::GetPrevKey()
{
return m_pTrack->GetPrevKey(GetTime());
}
////////////////////////////////////////////////////////////////////////////
CUiAnimViewKeyHandle CUiAnimViewKeyHandle::GetAboveKey() const
{
// Search for track above that has keys
for (CUiAnimViewNode* pCurrentNode = m_pTrack->GetAboveNode(); pCurrentNode; pCurrentNode = pCurrentNode->GetAboveNode())
{
if (pCurrentNode->GetNodeType() == eUiAVNT_Track)
{
CUiAnimViewTrack* pCurrentTrack = static_cast<CUiAnimViewTrack*>(pCurrentNode);
const unsigned int keyCount = pCurrentTrack->GetKeyCount();
if (keyCount > 0)
{
// Return key with nearest time to this key
return pCurrentTrack->GetNearestKeyByTime(GetTime());
}
}
}
return CUiAnimViewKeyHandle();
}
////////////////////////////////////////////////////////////////////////////
CUiAnimViewKeyHandle CUiAnimViewKeyHandle::GetBelowKey() const
{
// Search for track below that has keys
for (CUiAnimViewNode* pCurrentNode = m_pTrack->GetBelowNode(); pCurrentNode; pCurrentNode = pCurrentNode->GetBelowNode())
{
if (pCurrentNode->GetNodeType() == eUiAVNT_Track)
{
CUiAnimViewTrack* pCurrentTrack = static_cast<CUiAnimViewTrack*>(pCurrentNode);
const unsigned int keyCount = pCurrentTrack->GetKeyCount();
if (keyCount > 0)
{
// Return key with nearest time to this key
return pCurrentTrack->GetNearestKeyByTime(GetTime());
}
}
}
return CUiAnimViewKeyHandle();
}
////////////////////////////////////////////////////////////////////////////
bool CUiAnimViewKeyHandle::operator==(const CUiAnimViewKeyHandle& keyHandle) const
{
return m_pTrack == keyHandle.m_pTrack && m_keyIndex == keyHandle.m_keyIndex;
}
////////////////////////////////////////////////////////////////////////////
bool CUiAnimViewKeyHandle::operator!=(const CUiAnimViewKeyHandle& keyHandle) const
{
return !(*this == keyHandle);
}
////////////////////////////////////////////////////////////////////////////
void CUiAnimViewKeyBundle::AppendKey(const CUiAnimViewKeyHandle& keyHandle)
{
// Check if newly added key has different type than existing ones
if (m_bAllOfSameType && m_keys.size() > 0)
{
const CUiAnimViewKeyHandle& lastKey = m_keys.back();
const CUiAnimViewTrack* pMyTrack = keyHandle.GetTrack();
const CUiAnimViewTrack* pOtherTrack = lastKey.GetTrack();
// Check if keys are from sub tracks, always compare types of parent track
if (pMyTrack->IsSubTrack())
{
pMyTrack = static_cast<const CUiAnimViewTrack*>(pMyTrack->GetParentNode());
}
if (pOtherTrack->IsSubTrack())
{
pOtherTrack = static_cast<const CUiAnimViewTrack*>(pOtherTrack->GetParentNode());
}
// Do comparison
if (pMyTrack->GetParameterType() != pOtherTrack->GetParameterType()
|| pMyTrack->GetCurveType() != pOtherTrack->GetCurveType()
|| pMyTrack->GetValueType() != pOtherTrack->GetValueType())
{
m_bAllOfSameType = false;
}
}
m_keys.push_back(keyHandle);
}
////////////////////////////////////////////////////////////////////////////
void CUiAnimViewKeyBundle::AppendKeyBundle(const CUiAnimViewKeyBundle& bundle)
{
for (auto iter = bundle.m_keys.begin(); iter != bundle.m_keys.end(); ++iter)
{
AppendKey(*iter);
}
}
////////////////////////////////////////////////////////////////////////////
void CUiAnimViewKeyBundle::SelectKeys(const bool bSelected)
{
const unsigned int numKeys = GetKeyCount();
for (unsigned int i = 0; i < numKeys; ++i)
{
GetKey(i).Select(bSelected);
}
}
//////////////////////////////////////////////////////////////////////////
CUiAnimViewKeyHandle CUiAnimViewKeyBundle::GetSingleSelectedKey()
{
const unsigned int keyCount = GetKeyCount();
if (keyCount == 1)
{
return m_keys[0];
}
else if (keyCount > 1 && keyCount <= 4)
{
// All keys must have same time & same parent track
CUiAnimViewNode* pFirstParent = m_keys[0].GetTrack()->GetParentNode();
const float firstTime = m_keys[0].GetTime();
// Parent must be a track
if (pFirstParent->GetNodeType() != eUiAVNT_Track)
{
return CUiAnimViewKeyHandle();
}
// Check other keys for equality
for (unsigned int i = 0; i < keyCount; ++i)
{
if (m_keys[i].GetTrack()->GetParentNode() != pFirstParent || m_keys[i].GetTime() != firstTime)
{
return CUiAnimViewKeyHandle();
}
}
return static_cast<CUiAnimViewTrack*>(pFirstParent)->GetKeyByTime(firstTime);
}
return CUiAnimViewKeyHandle();
}
//////////////////////////////////////////////////////////////////////////
CUiAnimViewNode::CUiAnimViewNode(CUiAnimViewNode* pParent)
: m_pParentNode(pParent)
, m_bSelected(false)
, m_bExpanded(false)
, m_bHidden(false)
{
}
//////////////////////////////////////////////////////////////////////////
bool CUiAnimViewNode::HasObsoleteTrack() const
{
return HasObsoleteTrackRec(this);
}
//////////////////////////////////////////////////////////////////////////
bool CUiAnimViewNode::HasObsoleteTrackRec(const CUiAnimViewNode* pCurrentNode) const
{
if (pCurrentNode->GetNodeType() == eUiAVNT_Track)
{
const CUiAnimViewTrack* pTrack = static_cast<const CUiAnimViewTrack*>(pCurrentNode);
EUiAnimCurveType trackType = pTrack->GetCurveType();
if (trackType == eUiAnimCurveType_TCBFloat || trackType == eUiAnimCurveType_TCBQuat || trackType == eUiAnimCurveType_TCBVector)
{
return true;
}
}
for (unsigned int i = 0; i < pCurrentNode->GetChildCount(); ++i)
{
CUiAnimViewNode* pNode = pCurrentNode->GetChild(i);
if (HasObsoleteTrackRec(pNode))
{
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////
void CUiAnimViewNode::ClearSelection()
{
CUiAnimViewSequenceNotificationContext context(GetSequence());
SetSelected(false);
const unsigned int numChilds = GetChildCount();
for (unsigned int childIndex = 0; childIndex < numChilds; ++childIndex)
{
GetChild(childIndex)->ClearSelection();
}
}
//////////////////////////////////////////////////////////////////////////
CUiAnimViewNode* CUiAnimViewNode::GetAboveNode() const
{
CUiAnimViewNode* pParent = GetParentNode();
if (!pParent)
{
// The root does not have an above node
return nullptr;
}
CUiAnimViewNode* pPrevSibling = GetPrevSibling();
if (!pPrevSibling)
{
// First sibling -> parent is above node
return pParent;
}
// Find last node in sibling tree
CUiAnimViewNode* pCurrentNode = pPrevSibling;
while (pCurrentNode && pCurrentNode->GetChildCount() > 0 && pCurrentNode->IsExpanded())
{
pCurrentNode = pCurrentNode->GetChild(pCurrentNode->GetChildCount() - 1);
}
return pCurrentNode;
}
//////////////////////////////////////////////////////////////////////////
CUiAnimViewNode* CUiAnimViewNode::GetBelowNode() const
{
const unsigned int childCount = GetChildCount();
if (childCount > 0 && IsExpanded())
{
return GetChild(0);
}
CUiAnimViewNode* pParent = GetParentNode();
if (!pParent)
{
// Root without children
return nullptr;
}
// If there is a next sibling return it
CUiAnimViewNode* pNextSibling = GetNextSibling();
if (pNextSibling)
{
return pNextSibling;
}
// Otherwise we need to go up the tree and check
// the parent nodes for next siblings
CUiAnimViewNode* pCurrentNode = pParent;
while (pCurrentNode)
{
CUiAnimViewNode* pNextParentSibling = pCurrentNode->GetNextSibling();
if (pNextParentSibling)
{
return pNextParentSibling;
}
pCurrentNode = pCurrentNode->GetParentNode();
}
return nullptr;
}
//////////////////////////////////////////////////////////////////////////
CUiAnimViewNode* CUiAnimViewNode::GetPrevSibling() const
{
CUiAnimViewNode* pParent = GetParentNode();
if (!pParent)
{
// The root does not have siblings
return nullptr;
}
// Search for prev sibling
unsigned int siblingCount = pParent->GetChildCount();
assert(siblingCount > 0);
for (unsigned int i = 1; i < siblingCount; ++i)
{
CUiAnimViewNode* pSibling = pParent->GetChild(i);
if (pSibling == this)
{
return pParent->GetChild(i - 1);
}
}
return nullptr;
}
//////////////////////////////////////////////////////////////////////////
CUiAnimViewNode* CUiAnimViewNode::GetNextSibling() const
{
CUiAnimViewNode* pParent = GetParentNode();
if (!pParent)
{
// The root does not have siblings
return nullptr;
}
// Search for next sibling
unsigned int siblingCount = pParent->GetChildCount();
assert(siblingCount > 0);
for (unsigned int i = 0; i < siblingCount - 1; ++i)
{
CUiAnimViewNode* pSibling = pParent->GetChild(i);
if (pSibling == this)
{
return pParent->GetChild(i + 1);
}
}
return nullptr;
}
//////////////////////////////////////////////////////////////////////////
void CUiAnimViewNode::SetSelected(bool bSelected)
{
if (bSelected != m_bSelected)
{
m_bSelected = bSelected;
if (m_bSelected)
{
GetSequence()->OnNodeChanged(this, IUiAnimViewSequenceListener::eNodeChangeType_Selected);
}
else
{
GetSequence()->OnNodeChanged(this, IUiAnimViewSequenceListener::eNodeChangeType_Deselected);
}
GetSequence()->OnNodeSelectionChanged();
}
}
//////////////////////////////////////////////////////////////////////////
CUiAnimViewSequence* CUiAnimViewNode::GetSequence()
{
for (CUiAnimViewNode* pCurrentNode = this; pCurrentNode; pCurrentNode = pCurrentNode->GetParentNode())
{
if (pCurrentNode->GetNodeType() == eUiAVNT_Sequence)
{
return static_cast<CUiAnimViewSequence*>(pCurrentNode);
}
}
// Every node belongs to a sequence
assert(false);
return nullptr;
}
//////////////////////////////////////////////////////////////////////////
void CUiAnimViewNode::SetExpanded(bool bExpanded)
{
if (bExpanded != m_bExpanded)
{
m_bExpanded = bExpanded;
if (bExpanded)
{
GetSequence()->OnNodeChanged(this, IUiAnimViewSequenceListener::eNodeChangeType_Expanded);
}
else
{
GetSequence()->OnNodeChanged(this, IUiAnimViewSequenceListener::eNodeChangeType_Collapsed);
}
}
}
//////////////////////////////////////////////////////////////////////////
void CUiAnimViewNode::AddNode(CUiAnimViewNode* pNode)
{
assert (pNode->GetNodeType() != eUiAVNT_Sequence);
m_childNodes.push_back(std::unique_ptr<CUiAnimViewNode>(pNode));
SortNodes();
pNode->m_pParentNode = this;
GetSequence()->OnNodeChanged(pNode, IUiAnimViewSequenceListener::eNodeChangeType_Added);
}
//////////////////////////////////////////////////////////////////////////
void CUiAnimViewNode::SortNodes()
{
// Sort with operator<
std::stable_sort(m_childNodes.begin(), m_childNodes.end(),
[&](const std::unique_ptr<CUiAnimViewNode>& a, const std::unique_ptr<CUiAnimViewNode>& b) -> bool
{
const CUiAnimViewNode* pA = a.get();
const CUiAnimViewNode* pB = b.get();
return *pA < *pB;
}
);
}
namespace
{
static int GetNodeOrder(EUiAnimNodeType nodeType)
{
assert(nodeType < eUiAnimNodeType_Num);
static int nodeOrder[eUiAnimNodeType_Num];
nodeOrder[eUiAnimNodeType_Invalid] = 0;
nodeOrder[eUiAnimNodeType_Director] = 1;
nodeOrder[eUiAnimNodeType_Camera] = 2;
nodeOrder[eUiAnimNodeType_Entity] = 3;
nodeOrder[eUiAnimNodeType_Alembic] = 4;
nodeOrder[eUiAnimNodeType_GeomCache] = 5;
nodeOrder[eUiAnimNodeType_CVar] = 6;
nodeOrder[eUiAnimNodeType_ScriptVar] = 7;
nodeOrder[eUiAnimNodeType_Material] = 8;
nodeOrder[eUiAnimNodeType_Event] = 9;
nodeOrder[eUiAnimNodeType_Layer] = 10;
nodeOrder[eUiAnimNodeType_Comment] = 11;
nodeOrder[eUiAnimNodeType_RadialBlur] = 12;
nodeOrder[eUiAnimNodeType_ColorCorrection] = 13;
nodeOrder[eUiAnimNodeType_DepthOfField] = 14;
nodeOrder[eUiAnimNodeType_ScreenFader] = 15;
nodeOrder[eUiAnimNodeType_Light] = 16;
nodeOrder[eUiAnimNodeType_HDRSetup] = 17;
nodeOrder[eUiAnimNodeType_ShadowSetup] = 18;
nodeOrder[eUiAnimNodeType_Environment] = 19;
nodeOrder[eUiAnimNodeType_ScreenDropsSetup] = 20;
nodeOrder[eUiAnimNodeType_Group] = 21;
return nodeOrder[nodeType];
}
}
bool CUiAnimViewNode::operator<(const CUiAnimViewNode& otherNode) const
{
// Order nodes before tracks
if (GetNodeType() < otherNode.GetNodeType())
{
return true;
}
else if (GetNodeType() > otherNode.GetNodeType())
{
return false;
}
// Same node type
switch (GetNodeType())
{
case eUiAVNT_AnimNode:
{
const CUiAnimViewAnimNode& thisAnimNode = static_cast<const CUiAnimViewAnimNode&>(*this);
const CUiAnimViewAnimNode& otherAnimNode = static_cast<const CUiAnimViewAnimNode&>(otherNode);
const int thisTypeOrder = GetNodeOrder(thisAnimNode.GetType());
const int otherTypeOrder = GetNodeOrder(otherAnimNode.GetType());
if (thisTypeOrder == otherTypeOrder)
{
// Same node type, sort by name
return azstricmp(thisAnimNode.GetName(), otherAnimNode.GetName()) < 0;
}
return thisTypeOrder < otherTypeOrder;
}
case eUiAVNT_Track:
const CUiAnimViewTrack& thisTrack = static_cast<const CUiAnimViewTrack&>(*this);
const CUiAnimViewTrack& otherTrack = static_cast<const CUiAnimViewTrack&>(otherNode);
if (thisTrack.GetParameterType() == otherTrack.GetParameterType())
{
// Same parameter type, sort by name
return azstricmp(thisTrack.GetName(), otherTrack.GetName()) < 0;
}
return thisTrack.GetParameterType() < otherTrack.GetParameterType();
}
return false;
}
//////////////////////////////////////////////////////////////////////////
void CUiAnimViewNode::SetHidden(bool bHidden)
{
bool bWasHidden = m_bHidden;
m_bHidden = bHidden;
if (bHidden && !bWasHidden)
{
GetSequence()->OnNodeChanged(this, IUiAnimViewSequenceListener::eNodeChangeType_Hidden);
}
else if (!bHidden && bWasHidden)
{
GetSequence()->OnNodeChanged(this, IUiAnimViewSequenceListener::eNodeChangeType_Unhidden);
}
}
//////////////////////////////////////////////////////////////////////////
bool CUiAnimViewNode::IsHidden() const
{
return m_bHidden;
}
//////////////////////////////////////////////////////////////////////////
CUiAnimViewNode* CUiAnimViewNode::GetFirstSelectedNode()
{
if (IsSelected())
{
return this;
}
const unsigned int numChilds = GetChildCount();
for (unsigned int childIndex = 0; childIndex < numChilds; ++childIndex)
{
CUiAnimViewNode* pSelectedNode = GetChild(childIndex)->GetFirstSelectedNode();
if (pSelectedNode)
{
return pSelectedNode;
}
}
return nullptr;
}
//////////////////////////////////////////////////////////////////////////
CUiAnimViewAnimNode* CUiAnimViewNode::GetDirector()
{
for (CUiAnimViewNode* pCurrentNode = GetParentNode(); pCurrentNode; pCurrentNode = pCurrentNode->GetParentNode())
{
if (pCurrentNode->GetNodeType() == eUiAVNT_AnimNode)
{
CUiAnimViewAnimNode* pParentAnimNode = static_cast<CUiAnimViewAnimNode*>(pCurrentNode);
if (pParentAnimNode->GetType() == eUiAnimNodeType_Director)
{
return pParentAnimNode;
}
}
else if (pCurrentNode->GetNodeType() == eUiAVNT_Sequence)
{
return static_cast<CUiAnimViewAnimNode*>(pCurrentNode);
}
}
return nullptr;
}
|
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "boundary_conditions.h"
#include "verbose.h"
#include "EPS.h"
#include "project_to_line.h"
#include <vector>
#include <map>
#include <iostream>
IGL_INLINE bool igl::boundary_conditions(
const Eigen::MatrixXd & V ,
const Eigen::MatrixXi & /*Ele*/,
const Eigen::MatrixXd & C ,
const Eigen::VectorXi & P ,
const Eigen::MatrixXi & BE ,
const Eigen::MatrixXi & CE ,
Eigen::VectorXi & b ,
Eigen::MatrixXd & bc )
{
using namespace Eigen;
using namespace std;
if(P.size()+BE.rows() == 0)
{
verbose("^%s: Error: no handles found\n",__FUNCTION__);
return false;
}
vector<int> bci;
vector<int> bcj;
vector<double> bcv;
// loop over points
for(int p = 0;p<P.size();p++)
{
VectorXd pos = C.row(P(p));
// loop over domain vertices
for(int i = 0;i<V.rows();i++)
{
// Find samples just on pos
//Vec3 vi(V(i,0),V(i,1),V(i,2));
// EIGEN GOTCHA:
// double sqrd = (V.row(i)-pos).array().pow(2).sum();
// Must first store in temporary
VectorXd vi = V.row(i);
double sqrd = (vi-pos).squaredNorm();
if(sqrd <= FLOAT_EPS)
{
//cout<<"sum((["<<
// V(i,0)<<" "<<
// V(i,1)<<" "<<
// V(i,2)<<"] - ["<<
// pos(0)<<" "<<
// pos(1)<<" "<<
// pos(2)<<"]).^2) = "<<sqrd<<endl;
bci.push_back(i);
bcj.push_back(p);
bcv.push_back(1.0);
}
}
}
// loop over bone edges
for(int e = 0;e<BE.rows();e++)
{
// loop over domain vertices
for(int i = 0;i<V.rows();i++)
{
// Find samples from tip up to tail
VectorXd tip = C.row(BE(e,0));
VectorXd tail = C.row(BE(e,1));
// Compute parameter along bone and squared distance
double t,sqrd;
project_to_line(
V(i,0),V(i,1),V(i,2),
tip(0),tip(1),tip(2),
tail(0),tail(1),tail(2),
t,sqrd);
if(t>=-FLOAT_EPS && t<=(1.0f+FLOAT_EPS) && sqrd<=FLOAT_EPS)
{
bci.push_back(i);
bcj.push_back(P.size()+e);
bcv.push_back(1.0);
}
}
}
// loop over cage edges
for(int e = 0;e<CE.rows();e++)
{
// loop over domain vertices
for(int i = 0;i<V.rows();i++)
{
// Find samples from tip up to tail
VectorXd tip = C.row(P(CE(e,0)));
VectorXd tail = C.row(P(CE(e,1)));
// Compute parameter along bone and squared distance
double t,sqrd;
project_to_line(
V(i,0),V(i,1),V(i,2),
tip(0),tip(1),tip(2),
tail(0),tail(1),tail(2),
t,sqrd);
if(t>=-FLOAT_EPS && t<=(1.0f+FLOAT_EPS) && sqrd<=FLOAT_EPS)
{
bci.push_back(i);
bcj.push_back(CE(e,0));
bcv.push_back(1.0-t);
bci.push_back(i);
bcj.push_back(CE(e,1));
bcv.push_back(t);
}
}
}
// find unique boundary indices
vector<int> vb = bci;
sort(vb.begin(),vb.end());
vb.erase(unique(vb.begin(), vb.end()), vb.end());
b.resize(vb.size());
bc = MatrixXd::Zero(vb.size(),P.size()+BE.rows());
// Map from boundary index to index in boundary
map<int,int> bim;
int i = 0;
// Also fill in b
for(vector<int>::iterator bit = vb.begin();bit != vb.end();bit++)
{
b(i) = *bit;
bim[*bit] = i;
i++;
}
// Build BC
for(i = 0;i < (int)bci.size();i++)
{
assert(bim.find(bci[i]) != bim.end());
bc(bim[bci[i]],bcj[i]) = bcv[i];
}
// Normalize across rows so that conditions sum to one
for(i = 0;i<bc.rows();i++)
{
double sum = bc.row(i).sum();
assert(sum != 0 && "Some boundary vertex getting all zero BCs");
bc.row(i).array() /= sum;
}
if(bc.size() == 0)
{
verbose("^%s: Error: boundary conditions are empty.\n",__FUNCTION__);
return false;
}
// If there's only a single boundary condition, the following tests
// are overzealous.
if(bc.cols() == 1)
{
// If there is only one weight function,
// then we expect that there is only one handle.
assert(P.rows() + BE.rows() == 1);
return true;
}
// Check that every Weight function has at least one boundary value of 1 and
// one value of 0
for(i = 0;i<bc.cols();i++)
{
double min_abs_c = bc.col(i).array().abs().minCoeff();
double max_c = bc.col(i).maxCoeff();
if(min_abs_c > FLOAT_EPS)
{
verbose("^%s: Error: handle %d does not receive 0 weight\n",__FUNCTION__,i);
return false;
}
if(max_c< (1-FLOAT_EPS))
{
verbose("^%s: Error: handle %d does not receive 1 weight\n",__FUNCTION__,i);
return false;
}
}
return true;
}
|
// Copyright David Abrahams 2002. Permission to copy, use,
// modify, sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.
#ifndef IMPLICIT_DWA2002325_HPP
# define IMPLICIT_DWA2002325_HPP
# include <boost/type.hpp>
# include <boost/python/converter/implicit.hpp>
# include <boost/python/converter/registry.hpp>
# include <boost/python/converter/type_id.hpp>
namespace boost { namespace python {
template <class Source, class Target>
void implicitly_convertible(boost::type<Source>* = 0, boost::type<Target>* = 0)
{
typedef converter::implicit<Source,Target> functions;
converter::registry::push_back(
&functions::convertible
, &functions::construct
, converter::undecorated_type_id<Target>());
}
}} // namespace boost::python
#endif // IMPLICIT_DWA2002325_HPP
|
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#define ri register int
using namespace std;
const int MAXN=605*605;
int n,m,len,ans=0x7fffffff;
inline int getint()
{
int num=0,bj=1;
char c=getchar();
while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar();
while(c>='0'&&c<='9')num=num*10+c-'0',c=getchar();
return num*bj;
}
struct DLX
{
int u[MAXN],d[MAXN],l[MAXN],r[MAXN],col[MAXN],h[MAXN],cnt[MAXN];
void init()
{
for(ri i=0;i<=m;i++)
{
u[i]=d[i]=i;
l[i]=i-1,r[i]=i+1;
}
l[0]=m,r[m]=0;len=m;
}
void link(int x,int y)
{
cnt[y]++,col[++len]=y;
u[len]=u[y],d[len]=y;
u[d[len]]=d[u[len]]=len;
if(!h[x])h[x]=l[len]=r[len]=len;
else l[len]=l[h[x]],r[len]=h[x],l[r[len]]=r[l[len]]=len;
}
void del(int c)//列号
{
l[r[c]]=l[c],r[l[c]]=r[c];
for(ri i=d[c];i!=c;i=d[i])//十字链表向下删
{
for(ri j=r[i];j!=i;j=r[j])//从左往右
{
cnt[col[j]]--;
u[d[j]]=u[j],d[u[j]]=d[j];
}
}
}
void rollback(int c)
{
l[r[c]]=c,r[l[c]]=c;
for(ri i=u[c];i!=c;i=u[i])
{
for(ri j=l[i];j!=i;j=l[j])
{
cnt[col[j]]++;
u[d[j]]=j,d[u[j]]=j;
}
}
}
void dance(int val)
{
if(!r[0]){ans=min(ans,val);return;}//每行删完求最优
int t=r[0];
for(ri i=r[0];i!=0;i=r[i])if(r[i]<r[t])t=i;//找元素最少的行
del(t);
for(ri i=d[t];i!=t;i=d[i])
{
for(ri j=r[i];j!=i;j=r[j])del(col[j]);
dance(val+1);
for(ri j=l[i];j!=i;j=l[j])rollback(col[j]);
}
rollback(t);
}
};
DLX F;
int main()
{
n=getint(),m=getint();
F.init();
for(ri i=1;i<=n;i++)
for(ri j=1;j<=m;j++)
{
int x=getint();
if(x)F.link(i,j);
}
F.dance(0);
printf("%d",ans==0x7fffffff?-1:ans);
return 0;
}
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2020, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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.
***********************************************************************************************************************/
#ifndef MODEL_SETPOINTMANAGERFOLLOWGROUNDTEMPERATURE_IMPL_HPP
#define MODEL_SETPOINTMANAGERFOLLOWGROUNDTEMPERATURE_IMPL_HPP
#include "ModelAPI.hpp"
#include "SetpointManager_Impl.hpp"
namespace openstudio {
namespace model {
class Node;
namespace detail {
/** SetpointManagerFollowGroundTemperature_Impl is a SetpointManager_Impl that is the implementation class for SetpointManagerFollowGroundTemperature.*/
class MODEL_API SetpointManagerFollowGroundTemperature_Impl : public SetpointManager_Impl {
public:
/** @name Constructors and Destructors */
//@{
SetpointManagerFollowGroundTemperature_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle);
SetpointManagerFollowGroundTemperature_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle);
SetpointManagerFollowGroundTemperature_Impl(const SetpointManagerFollowGroundTemperature_Impl& other,
Model_Impl* model,
bool keepHandle);
virtual ~SetpointManagerFollowGroundTemperature_Impl() {}
//@}
/** @name Virtual Methods */
//@{
virtual const std::vector<std::string>& outputVariableNames() const override;
virtual IddObjectType iddObjectType() const override;
// virtual bool addToNode(Node & node) override;
virtual bool isAllowedOnPlantLoop() const override;
//@}
/** @name Getters */
//@{
virtual std::string controlVariable() const override;
std::string referenceGroundTemperatureObjectType() const;
double offsetTemperatureDifference() const;
double maximumSetpointTemperature() const;
double minimumSetpointTemperature() const;
virtual boost::optional<Node> setpointNode() const override;
//@}
/** @name Setters */
//@{
virtual bool setControlVariable(const std::string& controlVariable) override;
bool setReferenceGroundTemperatureObjectType(const std::string& groundTemperatureObjType);
bool setOffsetTemperatureDifference(double offsetTemperatureDifference);
bool setMaximumSetpointTemperature(double maximumSetpointTemperature);
bool setMinimumSetpointTemperature(double minimumSetpointTemperature);
//@}
/** @name Other */
//@{
//@}
protected:
private:
virtual bool setSetpointNode(const Node& node) override;
virtual void resetSetpointNode() override;
REGISTER_LOGGER("openstudio.model.SetpointManagerFollowGroundTemperature");
};
} // detail
} // model
} // openstudio
#endif // MODEL_SETPOINTMANAGERFOLLOWGROUNDTEMPERATURE_IMPL_HPP
|
#ifndef __REGIONDETECTOR_IDXHELPERS_HPP__
#define __REGIONDETECTOR_IDXHELPERS_HPP__
#include <cassert>
#include <cmath>
namespace RegionDetector {
namespace Helpers {
/**
* @returns the x coordinate of the pixel at index idx in an image with the given width
*/
inline int idxToX(const int idx, const int stride) {
assert(stride > 0);
return idx % stride;
}
/**
* @returns the y coordinate of the pixel at index idx in an image with the given width
*/
inline int idxToY(const int idx, const int stride) {
assert(stride > 0);
return idx / stride;
}
/**
* calculates the index of the pixel at position (x, y) in an image with the given width
*/
inline int xyToIdx(const int x, const int y, const int width) {
return y*width + x;
}
}
}
#endif
|
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
#include "random.h"
#include "path_tracer.h"
#include "helpers.h"
#include <fstream>
#include "PathTracerScene.h"
#include "ObjLoader.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace optix;
using namespace std;
using namespace cv;
void PathTracerScene::initContext(){
m_context->setRayTypeCount(3);
m_context->setEntryPointCount(1);
m_context->setStackSize(5000);
m_context["scene_epsilon"]->setFloat(1.e-3f);
m_context["pathtrace_ray_type"]->setUint(0u);
m_context["pathtrace_shadow_ray_type"]->setUint(1u);
m_context["pathtrace_bsdf_shadow_ray_type"]->setUint(2u);
m_context["rr_begin_depth"]->setUint(m_rr_begin_depth);
m_context["sqrt_num_samples"]->setUint(m_sqrt_num_samples);
m_context["eye"]->setFloat(make_float3(0.0f, 0.0f, 0.0f));
m_context["U"]->setFloat(make_float3(0.0f, 0.0f, 0.0f));
m_context["V"]->setFloat(make_float3(0.0f, 0.0f, 0.0f));
m_context["W"]->setFloat(make_float3(0.0f, 0.0f, 0.0f));
m_context["bad_color"]->setFloat(1.0f, 0.0f, 0.0f);
m_context["bg_color"]->setFloat(make_float3(0.0f, 0.0f, 0.0f));
}
void PathTracerScene::initScene(InitialCameraData& camera_data){
this->initContext();
LoadGeometry();
// Setup output buffer
Variable output_buffer = m_context["output_buffer"];
Buffer buffer = createOutputBuffer( RT_FORMAT_FLOAT4, m_width, m_height );
output_buffer->set(buffer);
// Setup random seeds buffer
m_rnd_seeds = m_context->createBuffer(RT_BUFFER_INPUT_OUTPUT | RT_BUFFER_GPU_LOCAL, RT_FORMAT_UNSIGNED_INT, m_width, m_height);
m_context["rnd_seeds"]->setBuffer(m_rnd_seeds);
unsigned int* seeds = static_cast<unsigned int*>(m_rnd_seeds->map());
fillRandBuffer(seeds, m_width * m_height);
m_rnd_seeds->unmap();
// Setup programs
std::string ptx_path = ptxpath( "PathTracer", "path_tracer.cu" );
Program ray_gen_program = m_context->createProgramFromPTXFile(ptx_path, "vertex_camera");
m_context->setRayGenerationProgram( 0, ray_gen_program );
Program exception_program = m_context->createProgramFromPTXFile( ptx_path, "exception" );
m_context->setExceptionProgram( 0, exception_program );
// load env map
const float3 default_color = make_float3(0.0f, 0.0f, 0.0f);
m_context["envmap"]->setTextureSampler(loadTexture(m_context, m_env_path, default_color));
m_context->setMissProgram(0, m_context->createProgramFromPTXFile(ptx_path, "envmap_miss"));
m_context["frame_number"]->setUint(1);
// Index of sampling_stategy (BSDF, light, MIS)
m_sampling_strategy = 0;
m_context["sampling_stategy"]->setInt(m_sampling_strategy);
// Create scene geometry
createGeometry();
/*float max_dim = m_aabb.maxExtent();
float3 eye = m_aabb.center();
eye.z += 2.0f * max_dim;*/
//camera_data = InitialCameraData(eye, // eye
// m_aabb.center(), // lookat
// make_float3(0.0f, 1.0f, 0.0f), // up
// 30.0f);
// Finalize
m_context->validate();
m_context->compile();
}
bool PathTracerScene::keyPressed( unsigned char key, int x, int y )
{
return false;
}
void PathTracerScene::trace( const RayGenCameraData& camera_data )
{
m_context["eye"]->setFloat( camera_data.eye );
m_context["U"]->setFloat( camera_data.U );
m_context["V"]->setFloat( camera_data.V );
m_context["W"]->setFloat( camera_data.W );
Buffer buffer = m_context["output_buffer"]->getBuffer();
RTsize buffer_width, buffer_height;
buffer->getSize(buffer_width, buffer_height );
bool camera_changed = m_camera_changed;
if( m_camera_changed ) {
m_camera_changed = false;
m_frame = 1;
}
m_context["frame_number"]->setUint( m_frame++ );
m_context->launch( 0,
static_cast<unsigned int>(buffer_width),
static_cast<unsigned int>(buffer_height)
);
SaveFrame(this->m_output_path.c_str());
exit(-1);
}
//-----------------------------------------------------------------------------
Buffer PathTracerScene::getOutputBuffer()
{
return m_context["output_buffer"]->getBuffer();
}
void PathTracerScene::LoadGeometry(){
printf("Load geometry...\n");
vector<MyVertex> all_vertices;
//LoadObjFromFile(m_filename.c_str(), all_vertices);
LoadObj(m_filename.c_str(), all_vertices);
int vertex_num = all_vertices.size();
Buffer vertex_buffer = m_context->createBuffer(RT_BUFFER_INPUT_OUTPUT);
vertex_buffer->setFormat(RT_FORMAT_USER);
vertex_buffer->setElementSize(sizeof(MyVertex));
vertex_buffer->setSize(vertex_num);
memcpy(vertex_buffer->map(), &all_vertices[0], vertex_num * sizeof(MyVertex));
vertex_buffer->unmap();
m_context["vertices"]->set(vertex_buffer);
m_width = vertex_num * m_sqrt_num_samples * m_sqrt_num_samples;
m_height = 1;
printf("Load completed... \n");
}
void PathTracerScene::setMaterial( GeometryInstance& gi,
Material material,
const std::string& color_name,
const float3& color){
gi->addMaterial(material);
gi[color_name]->setFloat(color);
}
void PathTracerScene::createGeometry(){
// Set up material
Material diffuse = m_context->createMaterial();
Program diffuse_ch = m_context->createProgramFromPTXFile(ptxpath("PathTracer", "path_tracer.cu"), "one_bounce_diffuse_closest_hit");
Program diffuse_ah = m_context->createProgramFromPTXFile(ptxpath("PathTracer", "path_tracer.cu"), "shadow");
diffuse->setClosestHitProgram(0, diffuse_ch);
diffuse->setAnyHitProgram(1, diffuse_ah);
diffuse["Kd_map"]->setTextureSampler(loadTexture(m_context, "", make_float3(1.f, 1.f, 1.f)));
vector<GeometryInstance> gis;
GeometryGroup geom_group = m_context->createGeometryGroup(gis.begin(), gis.end());
geom_group->setAcceleration(m_context->createAcceleration("Lbvh", "Bvh"));
ObjLoader* loader = new ObjLoader(m_filename.c_str(), m_context, geom_group, diffuse, false);
loader->load(Matrix4x4::scale(make_float3(1.0)));
/*OptiXMesh loader(m_context, geom_group, m_accel_desc);
loader.loadBegin_Geometry(m_filename);
cout << "load finish" << endl;
for (size_t i = 0; i < loader.getMaterialCount(); ++i) {
loader.setOptiXMaterial(static_cast<int>(i), diffuse);
}
loader.loadFinish_Materials();*/
m_context["top_object"]->set(geom_group);
m_context["top_shadower"]->set(geom_group);
//m_aabb = loader->getSceneBBox();
}
void PathTracerScene::SaveFrame(const char* filename){
RTbuffer buffer = m_context["output_buffer"]->getBuffer()->get();
void* imageData;
rtBufferMap(buffer, &imageData);
/*FILE * pFile;
pFile = fopen(filename, "w");
if (pFile == NULL){
printf("cannot open file\n");
exit(-1);
}*/
int sample_num = m_sqrt_num_samples * m_sqrt_num_samples;
int row_num = (m_height * m_width) / (sample_num);
cv::Mat result(row_num, 1, CV_32FC3, Vec3f(0,0,0));
int count = 0;
printf("Save result...\n");
for (int j = m_height - 1; j >= 0; --j) {
float* src_1 = ((float*)imageData) + (4 * m_width*j);
for (int i = 0; i < m_width; i++) {
//fprintf(pFile, "%c ", 'c');
Vec3f pixel_v;
for (int elem = 0; elem < 3; ++elem) {
float c = *src_1;
//fprintf(pFile, "%f ", c);
src_1++;
pixel_v[elem] = c;
}
result.at<Vec3f>(count / sample_num, 0) += pixel_v;
src_1++;
count++;
//fprintf(pFile, "\n");
}
}
result = result / ((float)(sample_num));
imwrite(filename, result);
rtBufferUnmap(buffer);
//fclose(pFile);
exit(-1);
}
|
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/debug.h"
#else
#define db(...)
#endif
#define all(v) v.begin(), v.end()
#define pb push_back
using ll = long long;
const int NAX = 2e5 + 5, MOD = 1000000007;
void solveCase()
{
int m;
cin >> m;
string str;
cin >> str;
int n = str.size();
vector<vector<int>> cnt(n, vector<int>(26));
vector<int> poses[26];
for (size_t i = 0; i < n; i++)
{
// db(i, str[i]);
poses[str[i] - 'a'].pb(i);
if (i > 0)
cnt[i] = cnt[i - 1];
cnt[i][str[i] - 'a']++;
}
for (int c = 0; c < 26; c++)
{
if (poses[c].empty())
continue;
string res;
int now = 0;
int prev = -1;
bool golbOk = true;
while (now < n)
{
int cc = str[now] - 'a';
db(now, prev, c, cc, res);
if (cc < c)
{
db("a");
prev = now;
++now;
}
else if ((now - prev) >= m)
{
db("b");
int j = now;
int cnt = m;
bool ok = false;
while (j >= 0 && cnt > 0)
{
if (str[j] == ('a' + c))
{
res.pb(str[j]);
ok = true;
prev = j;
break;
}
--cnt;
--j;
}
++now;
if (!ok)
{
golbOk = false;
break;
}
}
else
now++;
}
if (golbOk)
{
string res2;
for (int c1 = 0; c1 < c; c1++)
for (size_t i = 0; i < poses[c1].size(); i++)
res2.pb(c1 + 'a');
db(res, res2);
cout << res2 << res << '\n';
return;
}
}
assert(false);
}
int32_t main()
{
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
// cin >> t;
for (int i = 1; i <= t; ++i)
solveCase();
return 0;
}
|
#include "TileWorkgroupRasterizer.h"
#include "CommonWGSL.h"
#include "EncodingContext.h"
#include "utils/WGPUHelpers.h"
#include <string>
#include <iostream>
namespace cassia {
struct ConfigUniforms {
uint32_t width;
uint32_t height;
uint32_t widthInTiles;
uint32_t heightInTiles;
uint32_t segmentCount;
uint32_t tileRangeCount;
uint32_t carrySpillsPerRow;
};
static_assert(sizeof(ConfigUniforms) == 28, "");
struct TileRange {
uint32_t start;
uint32_t end;
};
TileWorkgroupRasterizer::TileWorkgroupRasterizer(wgpu::Device device)
: mDevice(std::move(device)) {
std::string code = std::string(kPSegmentWGSL) + std::string(kStylingWGSL) + R"(
[[block]] struct Config {
width: u32;
height: u32;
widthInTiles: i32;
heightInTiles: i32;
segmentCount: u32;
tileRangeCount: u32;
carrySpillsPerRow: u32;
};
[[group(0), binding(0)]] var<uniform> config : Config;
[[block]] struct PSegments {
data: array<PSegment>;
};
[[group(0), binding(1)]] var<storage> segments : PSegments;
///////////////////////////////////////////////////////////////////
// Tile ranges
///////////////////////////////////////////////////////////////////
struct Range {
start: u32;
end: u32; // Exclusive
};
[[block]] struct TileRanges {
data: array<Range>;
};
[[group(0), binding(2)]] var<storage, read_write> tileRanges : TileRanges;
fn tile_index(tileX: i32, tileY: i32) -> u32 {
return u32(tileX + tileY * (config.widthInTiles + 1));
}
fn tile_in_bounds(tileX: i32, tileY: i32) -> bool {
// Note that tileX is always >= -1
return tileX < config.widthInTiles && tileY >= 0 && tileY < config.heightInTiles;
}
// Large workgroup size to not run into the max dispatch limitation.
[[stage(compute), workgroup_size(256)]]
fn computeTileRanges([[builtin(global_invocation_id)]] GlobalId : vec3<u32>) {
if (GlobalId.x >= config.segmentCount - 1u) {
// This is the last segment of the last referenced tile so we can mark the end of it.
if (GlobalId.x == config.segmentCount - 1u) {
var segment = segments.data[GlobalId.x];
var tileX = psegment_tile_x(segment);
var tileY = psegment_tile_y(segment);
if (!psegment_is_none(segment) && tile_in_bounds(tileX, tileY)) {
var tileIndex = tile_index(tileX, tileY);
tileRanges.data[tileIndex].end = GlobalId.x + 1u;
}
}
return;
}
// TODO we could share segments with the workgroup to avoid redundant load
var segment0 = segments.data[GlobalId.x];
var segment1 = segments.data[GlobalId.x + 1u];
// TODO handle none segments
var tileX0 = psegment_tile_x(segment0);
var tileX1 = psegment_tile_x(segment1);
var tileY0 = psegment_tile_y(segment0);
var tileY1 = psegment_tile_y(segment1);
if (!psegment_is_none(segment0) && (tileX0 != tileX1 || tileY0 != tileY1 || psegment_is_none(segment1))) {
if (tile_in_bounds(tileX0, tileY0)) {
var tileIndex0 = tile_index(tileX0, tileY0);
tileRanges.data[tileIndex0].end = GlobalId.x + 1u;
}
if (!psegment_is_none(segment1) && tile_in_bounds(tileX1, tileY1)) {
var tileIndex1 = tile_index(tileX1, tileY1);
tileRanges.data[tileIndex1].start = GlobalId.x + 1u;
}
}
}
///////////////////////////////////////////////////////////////////
// Misc styling and output
///////////////////////////////////////////////////////////////////
[[block]] struct Stylings {
data: array<Styling>;
};
[[group(0), binding(4)]] var<storage> stylings : Stylings;
[[group(0), binding(5)]] var out : texture_storage_2d<rgba16float, write>;
fn accumulate(accumulator: ptr<function, vec4<f32>,read_write>, layer: u32, cover: i32, area: i32) {
var styling = stylings.data[layer];
var pixelCoverage = area + cover * PIXEL_SIZE;
*accumulator = styling_accumulate_layer(*accumulator, pixelCoverage, styling);
}
///////////////////////////////////////////////////////////////////
// Carry queues
///////////////////////////////////////////////////////////////////
// We need constexprs....
let TILE_WIDTH = 8;
let TILE_WIDTH_PLUS_ONE = 9;
let TILE_HEIGHT = 8u;
let INVALID_LAYER = 0xFFFFu;
let WORKGROUP_SIZE = 32u;
let WORKGROUP_HEIGHT_IN_ROWS = 4; // (TILE_WIDTH * TILE_HEIGHT) / WORKGROUP_SIZE
//let WORKGROUP_SIZE = 64u;
//let WORKGROUP_HEIGHT_IN_ROWS = 8; // (TILE_WIDTH * TILE_HEIGHT) / WORKGROUP_SIZE
type CarryCovers = array<i32, TILE_HEIGHT>;
let WORKGROUP_CARRIES = 10u;
struct LayerCarry {
layer: u32;
rows: CarryCovers;
};
struct LayerCarryQueue {
count: u32;
data: array<LayerCarry, WORKGROUP_CARRIES>;
};
[[block]] struct CarrySpill {
spills: array<LayerCarry>;
};
[[group(0), binding(3)]] var<storage, read_write> carrySpills : CarrySpill;
var<private> storeCarryIndex : u32 = 0u;
var<private> readLayerIndex : u32 = 0u;
var<workgroup> carries : array<LayerCarryQueue, 2>;
fn flip_carry_stores() {
storeCarryIndex = 1u - storeCarryIndex;
carries[storeCarryIndex].count = 0u;
readLayerIndex = 0u;
}
fn compute_carry_spill_index(out: ptr<function, u32, read_write>,
carryFlip: u32, tileY: i32, index: u32) -> bool {
if (index> config.carrySpillsPerRow) {
return false;
}
*out = (index - config.carrySpillsPerRow) +
u32(tileY) * config.carrySpillsPerRow +
carryFlip * config.carrySpillsPerRow * u32(config.heightInTiles);
return true;
}
fn append_output_layer_carry(tileY: i32, layer: u32, covers: CarryCovers) {
// Really??? Can we get rid of var vs. let already?
var localCovers = covers;
var needsStore = false;
for (var i = 0u; i < TILE_HEIGHT; i = i + 1u) {
if (localCovers[i] != 0) {
needsStore = true;
}
}
if (!needsStore) {
return;
}
if (carries[storeCarryIndex].count >= WORKGROUP_CARRIES) {
var spillIndex : u32;
if (!compute_carry_spill_index(&spillIndex,
storeCarryIndex, tileY, carries[storeCarryIndex].count)) {
return;
}
carrySpills.spills[spillIndex].rows = covers;
carrySpills.spills[spillIndex].layer = layer;
carries[storeCarryIndex].count = carries[storeCarryIndex].count + 1u;
return;
}
carries[storeCarryIndex].data[carries[storeCarryIndex].count].rows = covers;
carries[storeCarryIndex].data[carries[storeCarryIndex].count].layer = layer;
carries[storeCarryIndex].count = carries[storeCarryIndex].count + 1u;
}
fn consume_input_layer_carry(tileY: i32, thredIdx: u32) -> i32 {
var readIndex = 1u - storeCarryIndex;
var localLayerIndex = readLayerIndex;
readLayerIndex = readLayerIndex + 1u;
if (thredIdx >= TILE_HEIGHT) {
return 0;
}
if (localLayerIndex >= WORKGROUP_CARRIES) {
var spillIndex : u32;
if (!compute_carry_spill_index(&spillIndex, readIndex, tileY, localLayerIndex)) {
// Should never happen.
return 0;
}
return carrySpills.spills[spillIndex].rows[thredIdx];
}
return carries[readIndex].data[localLayerIndex].rows[thredIdx];
}
fn peek_layer_for_next_input_layer_carry(tileY: i32) -> u32 {
var readIndex = 1u - storeCarryIndex;
if (readLayerIndex < carries[readIndex].count) {
if (readLayerIndex >= WORKGROUP_CARRIES) {
var spillIndex : u32;
if (!compute_carry_spill_index(&spillIndex, readIndex, tileY, readLayerIndex)) {
// Should never happen.
return 0u;
}
return carrySpills.spills[spillIndex].layer;
}
return carries[readIndex].data[readLayerIndex].layer;
}
return INVALID_LAYER;
}
var<workgroup> subgroupAnyBool : bool;
fn fakeSubgroupAny(b: bool) -> bool {
var targetBool = !subgroupAnyBool;
if (b) {
subgroupAnyBool = targetBool;
}
workgroupBarrier();
return (subgroupAnyBool == targetBool);
}
var<workgroup> foo : atomic<i32>;
fn append_output_layer_carry2(tileY: i32, layer: u32, threadIdx: u32, cover: i32) {
if (!fakeSubgroupAny(cover != 0 && threadIdx < TILE_HEIGHT)) {
return;
}
if (threadIdx < TILE_HEIGHT) {
var prevCarryCount = carries[storeCarryIndex].count;
if (prevCarryCount >= WORKGROUP_CARRIES) {
var spillIndex : u32;
if (!compute_carry_spill_index(&spillIndex,
storeCarryIndex, tileY, prevCarryCount)) {
return;
}
carrySpills.spills[spillIndex].rows[threadIdx] = cover;
carrySpills.spills[spillIndex].layer = layer;
carries[storeCarryIndex].count = prevCarryCount + 1u;
return;
}
carries[storeCarryIndex].data[prevCarryCount].rows[threadIdx] = cover;
carries[storeCarryIndex].data[prevCarryCount].layer = layer;
carries[storeCarryIndex].count = prevCarryCount + 1u;
}
}
///////////////////////////////////////////////////////////////////
// Main tile rasterization
///////////////////////////////////////////////////////////////////
var<workgroup> areas : array<array<atomic<i32>, TILE_HEIGHT>, TILE_WIDTH_PLUS_ONE>;
var<workgroup> covers : array<array<atomic<i32>, TILE_HEIGHT>, TILE_WIDTH_PLUS_ONE>;
var<workgroup> accumulators : array<array<vec4<f32>, TILE_HEIGHT>, TILE_WIDTH_PLUS_ONE>;
var<workgroup> psegmentsProcessed : atomic<u32>;
var<workgroup> nextPsegmentIndex : u32;
fn accumulate_layer_and_save_carry(tileY: i32, layer: u32, threadIdx: u32) {
workgroupBarrier();
var cover = 0;
if (threadIdx < TILE_HEIGHT) {
for (var x = 0; x < TILE_WIDTH; x = x + 1) {
cover = cover + atomicLoad(&covers[x][threadIdx]);
atomicStore(&covers[x][threadIdx], cover);
}
cover = cover + atomicExchange(&covers[TILE_WIDTH][threadIdx], 0);
}
append_output_layer_carry2(tileY, layer, threadIdx, cover);
workgroupBarrier();
for (var y = 0; y < i32(TILE_HEIGHT); y = y + WORKGROUP_HEIGHT_IN_ROWS) {
var tx = i32(threadIdx & 7u);
var ty = i32(threadIdx >> TILE_WIDTH_SHIFT) + y;
var tarea = atomicExchange(&areas[tx][ty], 0);
var tcover = atomicExchange(&covers[tx][ty], 0);
var localAccumulator = accumulators[tx][ty];
accumulate(&localAccumulator, layer, tcover, tarea);
accumulators[tx][ty] = localAccumulator;
}
workgroupBarrier();
}
fn rasterizeTile(tileId: vec2<i32>, threadIdx: u32) {
var tileRange = tileRanges.data[tile_index(tileId.x, tileId.y)];
var currentLayer : u32 = INVALID_LAYER;
if (threadIdx == 0u) {
nextPsegmentIndex = tileRange.start;
atomicStore(&psegmentsProcessed, 0u);
}
loop {
workgroupBarrier();
var carryLayer = peek_layer_for_next_input_layer_carry(tileId.y);
var segmentLayer = INVALID_LAYER;
if (nextPsegmentIndex < tileRange.end) {
segmentLayer = psegment_layer(segments.data[nextPsegmentIndex]);
}
if (segmentLayer == INVALID_LAYER && carryLayer == INVALID_LAYER) {
break;
}
var minLayer = min(carryLayer, segmentLayer);
if (minLayer != currentLayer) {
if (currentLayer != INVALID_LAYER) {
accumulate_layer_and_save_carry(tileId.y, currentLayer, threadIdx);
}
currentLayer = minLayer;
}
if (carryLayer == minLayer){
var carry = consume_input_layer_carry(tileId.y, threadIdx);
if (threadIdx < TILE_HEIGHT) {
atomicStore(&covers[0][threadIdx], carry);
}
}
if (segmentLayer == minLayer) {
var segmentLocalIndex = nextPsegmentIndex + threadIdx;
if (segmentLocalIndex < tileRange.end) {
var segment = segments.data[segmentLocalIndex];
if (psegment_layer(segment) == segmentLayer) {
ignore(atomicAdd(&psegmentsProcessed, 1u));
var segmentLocalX = psegment_local_x(segment);
var segmentLocalY = psegment_local_y(segment);
var segmentCover = psegment_cover(segment);
var segmentArea = psegment_area(segment);
ignore(atomicAdd(&covers[segmentLocalX + 1u][segmentLocalY], segmentCover));
ignore(atomicAdd(&areas[segmentLocalX][segmentLocalY], segmentArea));
}
}
workgroupBarrier();
if (threadIdx == 0u) {
nextPsegmentIndex = nextPsegmentIndex + atomicExchange(&psegmentsProcessed, 0u);
}
continue;
}
}
if (currentLayer != INVALID_LAYER) {
accumulate_layer_and_save_carry(tileId.y, currentLayer, threadIdx);
}
var tx = i32(threadIdx & 7u);
var ty = i32(threadIdx >> TILE_WIDTH_SHIFT);
for (var y = 0; y < i32(TILE_HEIGHT); y = y + WORKGROUP_HEIGHT_IN_ROWS) {
textureStore(out, tileId * 8 + vec2<i32>(tx, y + ty), accumulators[tx][y + ty]);
accumulators[tx][y + ty] = vec4<f32>(0.0);
}
}
[[stage(compute), workgroup_size(WORKGROUP_SIZE)]]
fn rasterizeTileRow([[builtin(workgroup_id)]] WorkgroupId : vec3<u32>,
[[builtin(local_invocation_id)]] LocalId : vec3<u32>) {
flip_carry_stores();
var tileY = i32(WorkgroupId.x) % config.heightInTiles;
var threadIdx = LocalId.x;
// TODO make parallel over whole subgroup
if (threadIdx == 0u) {
var tileRange = tileRanges.data[tile_index(-1, tileY)];
var currentCovers : CarryCovers;
var currentLayer = INVALID_LAYER;
for (var i = tileRange.start; i < tileRange.end; i = i + 1u) {
var segment = segments.data[i];
var segmentLayer = psegment_layer(segment);
if (currentLayer != segmentLayer) {
append_output_layer_carry(tileY, currentLayer, currentCovers);
currentCovers = CarryCovers();
currentLayer = segmentLayer;
}
var segmentLocalY = psegment_local_y(segment);
var cover = psegment_cover(segment);
currentCovers[segmentLocalY] = currentCovers[segmentLocalY] + cover;
}
append_output_layer_carry(tileY, currentLayer, currentCovers);
}
workgroupBarrier();
flip_carry_stores();
var tileId = vec2<i32>(0, tileY);
for (; tileId.x < i32(config.widthInTiles); tileId.x = tileId.x + 1) {
rasterizeTile(tileId, threadIdx);
workgroupBarrier(); // TODO not needed? or put in the flipping of carry stores?
flip_carry_stores();
}
}
)";
wgpu::ShaderModule module = utils::CreateShaderModule(mDevice, code.c_str());
wgpu::ComputePipelineDescriptor pDesc;
pDesc.label = "TileWorkgroupRasterizer::mTileRangePipeline";
pDesc.compute.module = module;
pDesc.compute.entryPoint = "computeTileRanges";
mTileRangePipeline = mDevice.CreateComputePipeline(&pDesc);
pDesc.label = "TileWorkgroupRasterizer::mRasterPipeline";
pDesc.compute.entryPoint = "rasterizeTileRow";
mRasterPipeline = mDevice.CreateComputePipeline(&pDesc);
}
wgpu::Texture TileWorkgroupRasterizer::Rasterize(EncodingContext* context,
wgpu::Buffer sortedPsegments, wgpu::Buffer stylingsBuffer,
const Config& config) {
uint32_t widthInTiles = (config.width + TILE_WIDTH_SHIFT - 1) >> TILE_WIDTH_SHIFT;
uint32_t heightInTiles = (config.height + TILE_HEIGHT_SHIFT - 1) >> TILE_HEIGHT_SHIFT;
uint32_t tileRangeCount = (widthInTiles + 1) * heightInTiles;
constexpr uint64_t kCarrySpillsPerRow = 100;
ConfigUniforms uniformData = {
config.width,
config.height,
widthInTiles,
heightInTiles,
config.segmentCount,
tileRangeCount,
kCarrySpillsPerRow,
};
wgpu::Buffer uniforms = utils::CreateBufferFromData(
mDevice, &uniformData, sizeof(uniformData), wgpu::BufferUsage::Uniform);
wgpu::BufferDescriptor tileRangeDesc;
tileRangeDesc.size = tileRangeCount * sizeof(TileRange);
tileRangeDesc.usage = wgpu::BufferUsage::Storage;
wgpu::Buffer tileRangeBuffer = mDevice.CreateBuffer(&tileRangeDesc);
constexpr uint64_t kSizeofCarry = sizeof(uint32_t) + 8 * sizeof(int32_t);
wgpu::BufferDescriptor tileCarrySpillDesc;
tileCarrySpillDesc.size = 2 * kSizeofCarry * kCarrySpillsPerRow * heightInTiles;
tileCarrySpillDesc.usage = wgpu::BufferUsage::Storage;
wgpu::Buffer tileCarrySpillBuffer = mDevice.CreateBuffer(&tileCarrySpillDesc);
{
wgpu::BindGroup bg = utils::MakeBindGroup(mDevice, mTileRangePipeline.GetBindGroupLayout(0), {
{0, uniforms},
{1, sortedPsegments},
{2, tileRangeBuffer},
});
// TODO reuse tile range buffer instead?
{
ScopedComputePass pass(context, "TileWorkgroupRasterizer::FakePassToFactorOutLazyClearCost");
pass->SetBindGroup(0, bg);
pass->SetPipeline(mTileRangePipeline);
pass->Dispatch(0);
}
ScopedComputePass pass(context, "TileWorkgroupRasterizer::TileRangeComputation");
pass->SetBindGroup(0, bg);
pass->SetPipeline(mTileRangePipeline);
pass->Dispatch((config.segmentCount + 255) / 256);
}
wgpu::TextureDescriptor texDesc;
texDesc.label = "rasterized paths";
texDesc.size = {config.width, config.height};
texDesc.usage = wgpu::TextureUsage::StorageBinding | wgpu::TextureUsage::TextureBinding;
texDesc.format = wgpu::TextureFormat::RGBA16Float;
wgpu::Texture outTexture = mDevice.CreateTexture(&texDesc);
{
wgpu::BindGroup bg = utils::MakeBindGroup(mDevice, mRasterPipeline.GetBindGroupLayout(0), {
{0, uniforms},
{1, sortedPsegments},
{2, tileRangeBuffer},
{3, tileCarrySpillBuffer},
{4, stylingsBuffer},
{5, outTexture.CreateView()}
});
{
ScopedComputePass pass(context, "TileWorkgroupRasterizer::FakePassToFactorOutLazyClearCost");
pass->SetBindGroup(0, bg);
pass->SetPipeline(mRasterPipeline);
pass->Dispatch(0);
}
ScopedComputePass pass(context, "TileWorkgroupRasterizer::Raster");
pass->SetBindGroup(0, bg);
pass->SetPipeline(mRasterPipeline);
pass->Dispatch(heightInTiles);
}
return outTexture;
}
} // namespace cassia
|
//==============================================================================================
// Originally written in 2016 by Peter Shirley <ptrshrl@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related and
// neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy (see file COPYING.txt) of the CC0 Public Domain Dedication
// along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//==============================================================================================
#include "rtweekend.h"
#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
int main() {
int inside_circle = 0;
int inside_circle_stratified = 0;
int sqrt_N = 10000;
for (int i = 0; i < sqrt_N; i++) {
for (int j = 0; j < sqrt_N; j++) {
auto x = random_double(-1,1);
auto y = random_double(-1,1);
if (x*x + y*y < 1)
inside_circle++;
x = 2*((i + random_double()) / sqrt_N) - 1;
y = 2*((j + random_double()) / sqrt_N) - 1;
if (x*x + y*y < 1)
inside_circle_stratified++;
}
}
auto N = static_cast<double>(sqrt_N) * sqrt_N;
std::cout << std::fixed << std::setprecision(12);
std::cout << "Regular Estimate of Pi = "
<< 4 * double(inside_circle) / (sqrt_N*sqrt_N) << '\n';
std::cout << "Stratified Estimate of Pi = "
<< 4 * double(inside_circle_stratified) / (sqrt_N*sqrt_N) << '\n';
}
|
// Copyright Carl Philipp Reh 2009 - 2021.
// 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 FCPPT_CONTAINER_DETAIL_HAS_INSERT_RANGE_HPP_INCLUDED
#define FCPPT_CONTAINER_DETAIL_HAS_INSERT_RANGE_HPP_INCLUDED
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt::container::detail
{
template <typename Type, typename Test = void>
struct has_insert_range : std::false_type
{
};
template <typename Type>
struct has_insert_range<
Type,
decltype(std::declval<Type>().insert(
std::declval<typename Type::iterator>(), std::declval<typename Type::iterator>()))>
: std::true_type
{
};
}
#endif
|
/*
* @Author: gpinchon
* @Date: 2021-03-14 23:55:31
* @Last Modified by: gpinchon
* @Last Modified time: 2021-05-18 18:19:52
*/
#include <Assets/Asset.hpp>
#include <Light/HDRLight.hpp>
#include <Texture/TextureCubemap.hpp>
#include <Texture/TextureSampler.hpp>
#if RENDERINGAPI == OpenGL
#include <Driver/OpenGL/Renderer/Light/HDRLightRenderer.hpp>
#endif
HDRLight::HDRLight(std::shared_ptr<Asset> hdrTexture)
: Light()
{
_renderer.reset(new Renderer::HDRLightRenderer(*this));
SetHDRTexture(hdrTexture);
}
glm::vec3 HDRLight::GetHalfSize() const
{
return GetScale() / 2.f;
}
void HDRLight::SetHalfSize(const glm::vec3& halfSize)
{
SetScale(halfSize * 2.f);
}
glm::vec3 HDRLight::GetMin() const
{
return WorldPosition() - GetHalfSize();
}
glm::vec3 HDRLight::GetMax() const
{
return WorldPosition() + GetHalfSize();
}
void HDRLight::SetHDRTexture(std::shared_ptr<Asset> hdrTexture)
{
if (hdrTexture != GetHDRTexture())
GetRenderer().FlagDirty();
SetComponent(hdrTexture);
_SetReflection(Component::Create<TextureCubemap>(hdrTexture));
GetReflection()->SetAutoMipMap(true);
GetReflection()->GetTextureSampler()->SetMinFilter(TextureSampler::Filter::LinearMipmapLinear);
}
std::shared_ptr<Asset> HDRLight::GetHDRTexture()
{
return GetComponent<Asset>();
}
glm::vec2 ToImageCoords(double phi, double theta, int width, int height)
{
// Allow theta to repeat and map to 0 to pi. However, to account for cases
// where y goes beyond the normal 0 to pi range, phi may need to be adjusted.
theta = glm::clamp(glm::mod(theta, 2.0 * M_PI), 0.0, 2.0 * M_PI);
if (theta > M_PI) {
// theta is out of bounds. Effectively, theta has rotated past the pole
// so after adjusting theta to be in range, rotating phi by pi forms an
// equivalent direction.
theta = 2.0 * M_PI - theta; // now theta is between 0 and pi
phi += M_PI;
}
// Allow phi to repeat and map to the normal 0 to 2pi range.
// Clamp and map after adjusting theta in case theta was forced to update phi.
phi = glm::clamp(glm::mod(phi, 2.0 * M_PI), 0.0, 2.0 * M_PI);
// Now phi is in [0, 2pi] and theta is in [0, pi] so it's simple to inverse
// the linear equations in ImageCoordsToSphericalCoords, although there's no
// -0.5 because we're returning floating point coordinates and so don't need
// to center the pixel.
return glm::vec2(width * phi / (2.0 * M_PI), height * theta / M_PI);
}
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#include "grfmt_bmp.hpp"
namespace cv
{
static const char* fmtSignBmp = "BM";
/************************ BMP decoder *****************************/
BmpDecoder::BmpDecoder()
{
m_signature = fmtSignBmp;
m_offset = -1;
m_buf_supported = true;
}
BmpDecoder::~BmpDecoder()
{
}
void BmpDecoder::close()
{
m_strm.close();
}
ImageDecoder BmpDecoder::newDecoder() const
{
return makePtr<BmpDecoder>();
}
bool BmpDecoder::readHeader()
{
bool result = false;
bool iscolor = false;
if( !m_buf.empty() )
{
if( !m_strm.open( m_buf ) )
return false;
}
else if( !m_strm.open( m_filename ))
return false;
try
{
m_strm.skip( 10 );
m_offset = m_strm.getDWord();
int size = m_strm.getDWord();
if( size >= 36 )
{
m_width = m_strm.getDWord();
m_height = m_strm.getDWord();
m_bpp = m_strm.getDWord() >> 16;
m_rle_code = (BmpCompression)m_strm.getDWord();
m_strm.skip(12);
int clrused = m_strm.getDWord();
m_strm.skip( size - 36 );
if( m_width > 0 && m_height != 0 &&
(((m_bpp == 1 || m_bpp == 4 || m_bpp == 8 ||
m_bpp == 24 || m_bpp == 32 ) && m_rle_code == BMP_RGB) ||
(m_bpp == 16 && (m_rle_code == BMP_RGB || m_rle_code == BMP_BITFIELDS)) ||
(m_bpp == 4 && m_rle_code == BMP_RLE4) ||
(m_bpp == 8 && m_rle_code == BMP_RLE8)))
{
iscolor = true;
result = true;
if( m_bpp <= 8 )
{
memset( m_palette, 0, sizeof(m_palette));
m_strm.getBytes( m_palette, (clrused == 0? 1<<m_bpp : clrused)*4 );
iscolor = IsColorPalette( m_palette, m_bpp );
}
else if( m_bpp == 16 && m_rle_code == BMP_BITFIELDS )
{
int redmask = m_strm.getDWord();
int greenmask = m_strm.getDWord();
int bluemask = m_strm.getDWord();
if( bluemask == 0x1f && greenmask == 0x3e0 && redmask == 0x7c00 )
m_bpp = 15;
else if( bluemask == 0x1f && greenmask == 0x7e0 && redmask == 0xf800 )
;
else
result = false;
}
else if( m_bpp == 16 && m_rle_code == BMP_RGB )
m_bpp = 15;
}
}
else if( size == 12 )
{
m_width = m_strm.getWord();
m_height = m_strm.getWord();
m_bpp = m_strm.getDWord() >> 16;
m_rle_code = BMP_RGB;
if( m_width > 0 && m_height != 0 &&
(m_bpp == 1 || m_bpp == 4 || m_bpp == 8 ||
m_bpp == 24 || m_bpp == 32 ))
{
if( m_bpp <= 8 )
{
uchar buffer[256*3];
int j, clrused = 1 << m_bpp;
m_strm.getBytes( buffer, clrused*3 );
for( j = 0; j < clrused; j++ )
{
m_palette[j].b = buffer[3*j+0];
m_palette[j].g = buffer[3*j+1];
m_palette[j].r = buffer[3*j+2];
}
}
result = true;
}
}
}
catch(...)
{
}
m_type = iscolor ? CV_8UC3 : CV_8UC1;
m_origin = m_height > 0 ? IPL_ORIGIN_BL : IPL_ORIGIN_TL;
m_height = std::abs(m_height);
if( !result )
{
m_offset = -1;
m_width = m_height = -1;
m_strm.close();
}
return result;
}
bool BmpDecoder::readData( Mat& img )
{
uchar* data = img.data;
int step = (int)img.step;
bool color = img.channels() > 1;
uchar gray_palette[256];
bool result = false;
int src_pitch = ((m_width*(m_bpp != 15 ? m_bpp : 16) + 7)/8 + 3) & -4;
int nch = color ? 3 : 1;
int y, width3 = m_width*nch;
if( m_offset < 0 || !m_strm.isOpened())
return false;
if( m_origin == IPL_ORIGIN_BL )
{
data += (m_height - 1)*step;
step = -step;
}
AutoBuffer<uchar> _src, _bgr;
_src.allocate(src_pitch + 32);
if( !color )
{
if( m_bpp <= 8 )
{
CvtPaletteToGray( m_palette, gray_palette, 1 << m_bpp );
}
_bgr.allocate(m_width*3 + 32);
}
uchar *src = _src, *bgr = _bgr;
try
{
m_strm.setPos( m_offset );
switch( m_bpp )
{
/************************* 1 BPP ************************/
case 1:
for( y = 0; y < m_height; y++, data += step )
{
m_strm.getBytes( src, src_pitch );
FillColorRow1( color ? data : bgr, src, m_width, m_palette );
if( !color )
icvCvt_BGR2Gray_8u_C3C1R( bgr, 0, data, 0, cvSize(m_width,1) );
}
result = true;
break;
/************************* 4 BPP ************************/
case 4:
if( m_rle_code == BMP_RGB )
{
for( y = 0; y < m_height; y++, data += step )
{
m_strm.getBytes( src, src_pitch );
if( color )
FillColorRow4( data, src, m_width, m_palette );
else
FillGrayRow4( data, src, m_width, gray_palette );
}
result = true;
}
else if( m_rle_code == BMP_RLE4 ) // rle4 compression
{
uchar* line_end = data + width3;
y = 0;
for(;;)
{
int code = m_strm.getWord();
int len = code & 255;
code >>= 8;
if( len != 0 ) // encoded mode
{
PaletteEntry clr[2];
uchar gray_clr[2];
int t = 0;
clr[0] = m_palette[code >> 4];
clr[1] = m_palette[code & 15];
gray_clr[0] = gray_palette[code >> 4];
gray_clr[1] = gray_palette[code & 15];
uchar* end = data + len*nch;
if( end > line_end ) goto decode_rle4_bad;
do
{
if( color )
WRITE_PIX( data, clr[t] );
else
*data = gray_clr[t];
t ^= 1;
}
while( (data += nch) < end );
}
else if( code > 2 ) // absolute mode
{
if( data + code*nch > line_end ) goto decode_rle4_bad;
m_strm.getBytes( src, (((code + 1)>>1) + 1) & -2 );
if( color )
data = FillColorRow4( data, src, code, m_palette );
else
data = FillGrayRow4( data, src, code, gray_palette );
}
else
{
int x_shift3 = (int)(line_end - data);
int y_shift = m_height - y;
if( code == 2 )
{
x_shift3 = m_strm.getByte()*nch;
y_shift = m_strm.getByte();
}
len = x_shift3 + ((y_shift * width3) & ((code == 0) - 1));
if( color )
data = FillUniColor( data, line_end, step, width3,
y, m_height, x_shift3,
m_palette[0] );
else
data = FillUniGray( data, line_end, step, width3,
y, m_height, x_shift3,
gray_palette[0] );
if( y >= m_height )
break;
}
}
result = true;
decode_rle4_bad: ;
}
break;
/************************* 8 BPP ************************/
case 8:
if( m_rle_code == BMP_RGB )
{
for( y = 0; y < m_height; y++, data += step )
{
m_strm.getBytes( src, src_pitch );
if( color )
FillColorRow8( data, src, m_width, m_palette );
else
FillGrayRow8( data, src, m_width, gray_palette );
}
result = true;
}
else if( m_rle_code == BMP_RLE8 ) // rle8 compression
{
uchar* line_end = data + width3;
int line_end_flag = 0;
y = 0;
for(;;)
{
int code = m_strm.getWord();
int len = code & 255;
code >>= 8;
if( len != 0 ) // encoded mode
{
int prev_y = y;
len *= nch;
if( data + len > line_end )
goto decode_rle8_bad;
if( color )
data = FillUniColor( data, line_end, step, width3,
y, m_height, len,
m_palette[code] );
else
data = FillUniGray( data, line_end, step, width3,
y, m_height, len,
gray_palette[code] );
line_end_flag = y - prev_y;
}
else if( code > 2 ) // absolute mode
{
int prev_y = y;
int code3 = code*nch;
if( data + code3 > line_end )
goto decode_rle8_bad;
m_strm.getBytes( src, (code + 1) & -2 );
if( color )
data = FillColorRow8( data, src, code, m_palette );
else
data = FillGrayRow8( data, src, code, gray_palette );
line_end_flag = y - prev_y;
}
else
{
int x_shift3 = (int)(line_end - data);
int y_shift = m_height - y;
if( code || !line_end_flag || x_shift3 < width3 )
{
if( code == 2 )
{
x_shift3 = m_strm.getByte()*nch;
y_shift = m_strm.getByte();
}
x_shift3 += (y_shift * width3) & ((code == 0) - 1);
if( y >= m_height )
break;
if( color )
data = FillUniColor( data, line_end, step, width3,
y, m_height, x_shift3,
m_palette[0] );
else
data = FillUniGray( data, line_end, step, width3,
y, m_height, x_shift3,
gray_palette[0] );
if( y >= m_height )
break;
}
line_end_flag = 0;
if( y >= m_height )
break;
}
}
result = true;
decode_rle8_bad: ;
}
break;
/************************* 15 BPP ************************/
case 15:
for( y = 0; y < m_height; y++, data += step )
{
m_strm.getBytes( src, src_pitch );
if( !color )
icvCvt_BGR5552Gray_8u_C2C1R( src, 0, data, 0, cvSize(m_width,1) );
else
icvCvt_BGR5552BGR_8u_C2C3R( src, 0, data, 0, cvSize(m_width,1) );
}
result = true;
break;
/************************* 16 BPP ************************/
case 16:
for( y = 0; y < m_height; y++, data += step )
{
m_strm.getBytes( src, src_pitch );
if( !color )
icvCvt_BGR5652Gray_8u_C2C1R( src, 0, data, 0, cvSize(m_width,1) );
else
icvCvt_BGR5652BGR_8u_C2C3R( src, 0, data, 0, cvSize(m_width,1) );
}
result = true;
break;
/************************* 24 BPP ************************/
case 24:
for( y = 0; y < m_height; y++, data += step )
{
m_strm.getBytes( src, src_pitch );
if(!color)
icvCvt_BGR2Gray_8u_C3C1R( src, 0, data, 0, cvSize(m_width,1) );
else
memcpy( data, src, m_width*3 );
}
result = true;
break;
/************************* 32 BPP ************************/
case 32:
for( y = 0; y < m_height; y++, data += step )
{
m_strm.getBytes( src, src_pitch );
if( !color )
icvCvt_BGRA2Gray_8u_C4C1R( src, 0, data, 0, cvSize(m_width,1) );
else
icvCvt_BGRA2BGR_8u_C4C3R( src, 0, data, 0, cvSize(m_width,1) );
}
result = true;
break;
default:
assert(0);
}
}
catch(...)
{
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////
BmpEncoder::BmpEncoder()
{
m_description = "Windows bitmap (*.bmp;*.dib)";
m_buf_supported = true;
}
BmpEncoder::~BmpEncoder()
{
}
ImageEncoder BmpEncoder::newEncoder() const
{
return makePtr<BmpEncoder>();
}
bool BmpEncoder::write( const Mat& img, const std::vector<int>& )
{
int width = img.cols, height = img.rows, channels = img.channels();
int fileStep = (width*channels + 3) & -4;
uchar zeropad[] = "\0\0\0\0";
WLByteStream strm;
if( m_buf )
{
if( !strm.open( *m_buf ) )
return false;
}
else if( !strm.open( m_filename ))
return false;
int bitmapHeaderSize = 40;
int paletteSize = channels > 1 ? 0 : 1024;
int headerSize = 14 /* fileheader */ + bitmapHeaderSize + paletteSize;
int fileSize = fileStep*height + headerSize;
PaletteEntry palette[256];
if( m_buf )
m_buf->reserve( alignSize(fileSize + 16, 256) );
// write signature 'BM'
strm.putBytes( fmtSignBmp, (int)strlen(fmtSignBmp) );
// write file header
strm.putDWord( fileSize ); // file size
strm.putDWord( 0 );
strm.putDWord( headerSize );
// write bitmap header
strm.putDWord( bitmapHeaderSize );
strm.putDWord( width );
strm.putDWord( height );
strm.putWord( 1 );
strm.putWord( channels << 3 );
strm.putDWord( BMP_RGB );
strm.putDWord( 0 );
strm.putDWord( 0 );
strm.putDWord( 0 );
strm.putDWord( 0 );
strm.putDWord( 0 );
if( channels == 1 )
{
FillGrayPalette( palette, 8 );
strm.putBytes( palette, sizeof(palette));
}
width *= channels;
for( int y = height - 1; y >= 0; y-- )
{
strm.putBytes( img.data + img.step*y, width );
if( fileStep > width )
strm.putBytes( zeropad, fileStep - width );
}
strm.close();
return true;
}
}
|
/**
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* 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.
*
* @brief RpcFactory
* @file RpcFactory.h
* @author: octopus
* @date 2021-07-15
*/
#include "bcos-framework/interfaces/gateway/GatewayTypeDef.h"
#include <bcos-boostssl/context/ContextBuilder.h>
#include <bcos-boostssl/websocket/WsError.h>
#include <bcos-boostssl/websocket/WsInitializer.h>
#include <bcos-boostssl/websocket/WsMessage.h>
#include <bcos-boostssl/websocket/WsService.h>
#include <bcos-protocol/amop/AMOPRequest.h>
#include <bcos-rpc/RpcFactory.h>
#include <bcos-rpc/event/EventSubMatcher.h>
#include <bcos-rpc/jsonrpc/JsonRpcImpl_2_0.h>
#include <bcos-rpc/ws/ProtocolVersion.h>
#include <bcos-utilities/Exceptions.h>
#include <bcos-utilities/FileUtility.h>
#include <bcos-utilities/Log.h>
#include <bcos-utilities/ThreadPool.h>
#include <boost/core/ignore_unused.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <memory>
#include <string>
#include <utility>
using namespace bcos;
using namespace bcos::rpc;
using namespace bcos::protocol;
using namespace bcos::crypto;
using namespace bcos::gateway;
using namespace bcos::group;
using namespace bcos::boostssl::ws;
using namespace bcos::protocol;
RpcFactory::RpcFactory(std::string const& _chainID, GatewayInterface::Ptr _gatewayInterface,
KeyFactory::Ptr _keyFactory)
: m_chainID(_chainID), m_gateway(_gatewayInterface), m_keyFactory(_keyFactory)
{}
std::shared_ptr<bcos::boostssl::ws::WsConfig> RpcFactory::initConfig(
bcos::tool::NodeConfig::Ptr _nodeConfig)
{
auto wsConfig = std::make_shared<boostssl::ws::WsConfig>();
wsConfig->setModel(bcos::boostssl::ws::WsModel::Server);
wsConfig->setListenIP(_nodeConfig->rpcListenIP());
wsConfig->setListenPort(_nodeConfig->rpcListenPort());
wsConfig->setThreadPoolSize(_nodeConfig->rpcThreadPoolSize());
wsConfig->setDisableSsl(_nodeConfig->rpcDisableSsl());
if (_nodeConfig->rpcDisableSsl())
{
BCOS_LOG(INFO) << LOG_BADGE("[RPC][FACTORY][initConfig]")
<< LOG_DESC("rpc work in disable ssl model")
<< LOG_KV("listenIP", wsConfig->listenIP())
<< LOG_KV("listenPort", wsConfig->listenPort())
<< LOG_KV("threadCount", wsConfig->threadPoolSize())
<< LOG_KV("asServer", wsConfig->asServer());
return wsConfig;
}
auto contextConfig = std::make_shared<boostssl::context::ContextConfig>();
if (!_nodeConfig->rpcSmSsl())
{ // ssl
boostssl::context::ContextConfig::CertConfig certConfig;
certConfig.caCert = _nodeConfig->caCert();
certConfig.nodeCert = _nodeConfig->nodeCert();
certConfig.nodeKey = _nodeConfig->nodeKey();
contextConfig->setCertConfig(certConfig);
contextConfig->setSslType("ssl");
BCOS_LOG(INFO) << LOG_DESC("[RPC][FACTORY][initConfig]")
<< LOG_DESC("rpc work in ssl model")
<< LOG_KV("listenIP", wsConfig->listenIP())
<< LOG_KV("listenPort", wsConfig->listenPort())
<< LOG_KV("threadCount", wsConfig->threadPoolSize())
<< LOG_KV("asServer", wsConfig->asServer())
<< LOG_KV("caCert", _nodeConfig->caCert())
<< LOG_KV("nodeCert", _nodeConfig->nodeCert())
<< LOG_KV("nodeKey", _nodeConfig->nodeKey());
}
else
{ // sm ssl
boostssl::context::ContextConfig::SMCertConfig certConfig;
certConfig.caCert = _nodeConfig->smCaCert();
certConfig.nodeCert = _nodeConfig->smNodeCert();
certConfig.nodeKey = _nodeConfig->smNodeKey();
certConfig.enNodeCert = _nodeConfig->enSmNodeCert();
certConfig.enNodeKey = _nodeConfig->enSmNodeKey();
contextConfig->setSmCertConfig(certConfig);
contextConfig->setSslType("sm_ssl");
BCOS_LOG(INFO) << LOG_DESC("[RPC][FACTORY][initConfig]")
<< LOG_DESC("rpc work in sm ssl model")
<< LOG_KV("listenIP", wsConfig->listenIP())
<< LOG_KV("listenPort", wsConfig->listenPort())
<< LOG_KV("threadCount", wsConfig->threadPoolSize())
<< LOG_KV("asServer", wsConfig->asServer())
<< LOG_KV("caCert", _nodeConfig->smCaCert())
<< LOG_KV("nodeCert", _nodeConfig->smNodeCert())
<< LOG_KV("nodeKey", _nodeConfig->smNodeKey())
<< LOG_KV("enNodeCert", _nodeConfig->enSmNodeCert())
<< LOG_KV("enNodeKey", _nodeConfig->enSmNodeKey());
}
wsConfig->setContextConfig(contextConfig);
return wsConfig;
}
bcos::boostssl::ws::WsService::Ptr RpcFactory::buildWsService(
bcos::boostssl::ws::WsConfig::Ptr _config)
{
auto wsService = std::make_shared<bcos::boostssl::ws::WsService>();
auto initializer = std::make_shared<bcos::boostssl::ws::WsInitializer>();
initializer->setConfig(_config);
initializer->initWsService(wsService);
return wsService;
}
void RpcFactory::registerHandlers(std::shared_ptr<boostssl::ws::WsService> _wsService,
bcos::rpc::JsonRpcImpl_2_0::Ptr _jsonRpcInterface)
{
_wsService->registerMsgHandler(bcos::rpc::MessageType::HANDESHAKE,
[_jsonRpcInterface](std::shared_ptr<boostssl::ws::WsMessage> _msg,
std::shared_ptr<boostssl::ws::WsSession> _session) {
auto seq = std::string(_msg->data()->begin(), _msg->data()->end());
// Note: Clean up request data to prevent taking up too much memory
bytes emptyBuffer;
_msg->data()->swap(emptyBuffer);
_jsonRpcInterface->getGroupInfoList(
[_msg, _session, seq, _jsonRpcInterface](
bcos::Error::Ptr _error, Json::Value& _jGroupInfoList) {
if (_error && _error->errorCode() != bcos::protocol::CommonError::SUCCESS)
{
BCOS_LOG(ERROR)
<< LOG_BADGE("HANDSHAKE") << LOG_DESC("get group info list error")
<< LOG_KV("seq", seq)
<< LOG_KV("endpoint", _session ? _session->endPoint() : std::string(""))
<< LOG_KV("errorCode", _error->errorCode())
<< LOG_KV("errorMessage", _error->errorMessage());
return;
}
_jsonRpcInterface->getGroupBlockNumber([_jGroupInfoList, _session, _msg, seq](
bcos::Error::Ptr,
Json::Value& _jBlockNumberInfo) {
auto version = ws::EnumPV::CurrentVersion;
_session->setVersion(ws::EnumPV::CurrentVersion);
auto pv = std::make_shared<ws::ProtocolVersion>();
pv->setProtocolVersion(version);
auto jResult = pv->toJson();
jResult["groupInfoList"] = _jGroupInfoList;
jResult["groupBlockNumber"] = _jBlockNumberInfo;
Json::FastWriter writer;
std::string result = writer.write(jResult);
_msg->setData(std::make_shared<bcos::bytes>(result.begin(), result.end()));
_session->asyncSendMessage(_msg);
BCOS_LOG(INFO)
<< LOG_BADGE("HANDSHAKE") << LOG_DESC("handshake response")
<< LOG_KV("version", version) << LOG_KV("seq", seq)
<< LOG_KV("endpoint", _session ? _session->endPoint() : std::string(""))
<< LOG_KV("result", result);
});
});
});
_wsService->registerMsgHandler(bcos::rpc::MessageType::RPC_REQUEST,
[_jsonRpcInterface](std::shared_ptr<boostssl::ws::WsMessage> _msg,
std::shared_ptr<boostssl::ws::WsSession> _session) {
if (!_jsonRpcInterface)
{
return;
}
std::string req = std::string(_msg->data()->begin(), _msg->data()->end());
// Note: Clean up request data to prevent taking up too much memory
bytes emptyBuffer;
_msg->data()->swap(emptyBuffer);
_jsonRpcInterface->onRPCRequest(req, [req, _msg, _session](const std::string& _resp) {
if (_session && _session->isConnected())
{
auto buffer = std::make_shared<bcos::bytes>(_resp.begin(), _resp.end());
_msg->setData(buffer);
_session->asyncSendMessage(_msg);
}
else
{
auto seq = std::string(_msg->seq()->begin(), _msg->seq()->end());
// remove the callback
_session->getAndRemoveRespCallback(seq);
BCOS_LOG(WARNING)
<< LOG_DESC("[RPC][FACTORY][buildJsonRpc]")
<< LOG_DESC("unable to send response for session has been inactive")
<< LOG_KV("req", req) << LOG_KV("resp", _resp) << LOG_KV("seq", seq)
<< LOG_KV("endpoint", _session ? _session->endPoint() : std::string(""));
}
});
});
}
bcos::rpc::JsonRpcImpl_2_0::Ptr RpcFactory::buildJsonRpc(
std::shared_ptr<boostssl::ws::WsService> _wsService, GroupManager::Ptr _groupManager)
{
// JsonRpcImpl_2_0
auto jsonRpcInterface = std::make_shared<bcos::rpc::JsonRpcImpl_2_0>(_groupManager, m_gateway);
auto httpServer = _wsService->httpServer();
if (httpServer)
{
httpServer->setHttpReqHandler(std::bind(&bcos::rpc::JsonRpcInterface::onRPCRequest,
jsonRpcInterface, std::placeholders::_1, std::placeholders::_2));
}
registerHandlers(_wsService, jsonRpcInterface);
return jsonRpcInterface;
}
bcos::event::EventSub::Ptr RpcFactory::buildEventSub(
std::shared_ptr<boostssl::ws::WsService> _wsService, GroupManager::Ptr _groupManager)
{
auto eventSubFactory = std::make_shared<event::EventSubFactory>();
auto eventSub = eventSubFactory->buildEventSub();
auto matcher = std::make_shared<event::EventSubMatcher>();
eventSub->setIoc(_wsService->ioc());
eventSub->setGroupManager(_groupManager);
eventSub->setMessageFactory(_wsService->messageFactory());
eventSub->setMatcher(matcher);
auto eventSubWeakPtr = std::weak_ptr<bcos::event::EventSub>(eventSub);
// register event subscribe message
_wsService->registerMsgHandler(bcos::event::MessageType::EVENT_SUBSCRIBE,
[eventSubWeakPtr](std::shared_ptr<WsMessage> _msg, std::shared_ptr<WsSession> _session) {
auto eventSub = eventSubWeakPtr.lock();
if (eventSub)
{
eventSub->onRecvSubscribeEvent(_msg, _session);
}
});
// register event subscribe message
_wsService->registerMsgHandler(bcos::event::MessageType::EVENT_UNSUBSCRIBE,
[eventSubWeakPtr](std::shared_ptr<WsMessage> _msg, std::shared_ptr<WsSession> _session) {
auto eventSub = eventSubWeakPtr.lock();
if (eventSub)
{
eventSub->onRecvUnsubscribeEvent(_msg, _session);
}
});
BCOS_LOG(INFO) << LOG_DESC("[RPC][FACTORY][buildEventSub]") << LOG_DESC("create event sub obj");
return eventSub;
}
Rpc::Ptr RpcFactory::buildRpc(std::string const& _gatewayServiceName)
{
auto config = initConfig(m_nodeConfig);
auto wsService = buildWsService(config);
auto groupManager = buildGroupManager();
auto amopClient = buildAMOPClient(wsService, _gatewayServiceName);
BCOS_LOG(INFO) << LOG_DESC("[RPC][FACTORY][buildRpc]") << LOG_KV("listenIP", config->listenIP())
<< LOG_KV("listenPort", config->listenPort())
<< LOG_KV("threadCount", config->threadPoolSize())
<< LOG_KV("gatewayServiceName", _gatewayServiceName);
auto rpc = buildRpc(wsService, groupManager, amopClient);
return rpc;
}
Rpc::Ptr RpcFactory::buildLocalRpc(
bcos::group::GroupInfo::Ptr _groupInfo, NodeService::Ptr _nodeService)
{
auto config = initConfig(m_nodeConfig);
auto wsService = buildWsService(config);
auto groupManager = buildAirGroupManager(_groupInfo, _nodeService);
auto amopClient = buildAirAMOPClient(wsService);
auto rpc = buildRpc(wsService, groupManager, amopClient);
// Note: init groupManager after create rpc and register the handlers
groupManager->init();
return rpc;
}
/**
* @brief: Rpc
* @param _config: WsConfig
* @param _nodeInfo: node info
* @return Rpc::Ptr:
*/
Rpc::Ptr RpcFactory::buildRpc(std::shared_ptr<boostssl::ws::WsService> _wsService,
GroupManager::Ptr _groupManager, AMOPClient::Ptr _amopClient)
{
// JsonRpc
auto jsonRpc = buildJsonRpc(_wsService, _groupManager);
// EventSub
auto es = buildEventSub(_wsService, _groupManager);
return std::make_shared<Rpc>(_wsService, jsonRpc, es, _amopClient);
}
GroupManager::Ptr RpcFactory::buildGroupManager()
{
auto nodeServiceFactory = std::make_shared<NodeServiceFactory>();
return std::make_shared<GroupManager>(m_chainID, nodeServiceFactory);
}
AirGroupManager::Ptr RpcFactory::buildAirGroupManager(
GroupInfo::Ptr _groupInfo, NodeService::Ptr _nodeService)
{
return std::make_shared<AirGroupManager>(m_chainID, _groupInfo, _nodeService);
}
AMOPClient::Ptr RpcFactory::buildAMOPClient(
std::shared_ptr<boostssl::ws::WsService> _wsService, std::string const& _gatewayServiceName)
{
auto wsFactory = std::make_shared<WsMessageFactory>();
auto requestFactory = std::make_shared<AMOPRequestFactory>();
return std::make_shared<AMOPClient>(
_wsService, wsFactory, requestFactory, m_gateway, _gatewayServiceName);
}
AMOPClient::Ptr RpcFactory::buildAirAMOPClient(std::shared_ptr<boostssl::ws::WsService> _wsService)
{
auto wsFactory = std::make_shared<WsMessageFactory>();
auto requestFactory = std::make_shared<AMOPRequestFactory>();
return std::make_shared<AirAMOPClient>(_wsService, wsFactory, requestFactory, m_gateway);
}
|
/////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001- Twelve Tone Systems, Inc. All rights reserved.
//
// MotorMixSubclasses.cpp
/////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MotorMixSubclasses.h"
#include "StateDefs.h"
/////////////////////////////////////////////////////////////////////////
// CMMChoiceLedUpdater:
/////////////////////////////////////////////////////////////////////////
CMMChoiceLedUpdater::CMMChoiceLedUpdater( CControlSurface *pSurface ) :
CMultiStateListener( pSurface ),
m_msgUpperLeftLed( pSurface ),
m_msgUpperRightLed( pSurface ),
m_msgLowerLeftLed( pSurface ),
m_msg7Segment( pSurface ),
m_msgScribble( pSurface )
{
m_msgUpperLeftLed.SetMessageType( CMidiMsg::mtCCSel );
m_msgUpperLeftLed.SetCCSelNum( 0x0C );
m_msgUpperLeftLed.SetCCSelVal( 0x0A);
m_msgUpperLeftLed.SetCCNum( 0x2C );
m_msgUpperRightLed.SetMessageType( CMidiMsg::mtCCSel );
m_msgUpperRightLed.SetCCSelNum( 0x0C );
m_msgUpperRightLed.SetCCSelVal( 0x0B);
m_msgUpperRightLed.SetCCNum( 0x2C );
m_msgLowerLeftLed.SetMessageType( CMidiMsg::mtCCSel );
m_msgLowerLeftLed.SetCCSelNum( 0x0C );
m_msgLowerLeftLed.SetCCSelVal( 0x08);
m_msgLowerLeftLed.SetCCNum( 0x2C );
// 7 segment display setup
m_msg7Segment.SetMessageType( CMidiMsg::mtSysXString );
BYTE pczPreString[] = {0xF0, 0x00, 0x01, 0x0F, 0x00, 0x11, 0x00, 0x12 };
BYTE pczPostString[] = {0xF7};
m_msg7Segment.SetSysXPreString( (const unsigned char *)( pczPreString ), sizeof(pczPreString) );
m_msg7Segment.SetSysXPostString( (const unsigned char *)( pczPostString ), sizeof(pczPostString) );
m_msg7Segment.SetSysXTextLen( 4 );
// notice that subscriptions are always done at the end of construction code,
// because one possible side effect of construction is
// that the OnStateChange method may get called.
SubscribeToState( stBankShiftMode );
SubscribeToState( stBurnButtonsChoice );
SubscribeToState( stMultiButtonsChoice );
SubscribeToState( stTrackRotaryMapping );
SubscribeToState( stBusRotaryMapping );
SubscribeToState( stSendPanOrLevel );
SubscribeToState( stContainerClass );
SubscribeToState( stShiftKey );
SubscribeToState( stInsertEditMode );
SubscribeToState( stFineTweakMode );
SubscribeToState( stQueryState );
}
/////////////////////////////////////////////////////////////////////////
HRESULT CMMChoiceLedUpdater::OnStateChange( DWORD dwStateID, int nNewState)
{
switch (dwStateID)
{
case stBankShiftMode:
switch (nNewState)
{
case smOneByOne:
m_msgUpperLeftLed.Send( (DWORD)0x00 );
break;
case smByBanks:
m_msgUpperLeftLed.Send( (DWORD)0x40 );
break;
default:
_ASSERT( 0 ); // unknown bank shift mode
}
break;
case stBurnButtonsChoice:
switch (nNewState)
{
case bbRecRdy:
m_msgUpperLeftLed.Send( (DWORD)0x42 );
m_msgUpperLeftLed.Send( (DWORD)0x04 );
m_msgUpperLeftLed.Send( (DWORD)0x06 );
break;
case bbWrite:
m_msgUpperLeftLed.Send( (DWORD)0x02 );
m_msgUpperLeftLed.Send( (DWORD)0x44 );
m_msgUpperLeftLed.Send( (DWORD)0x06 );
break;
case bbOther:
m_msgUpperLeftLed.Send( (DWORD)0x02 );
m_msgUpperLeftLed.Send( (DWORD)0x04 );
m_msgUpperLeftLed.Send( (DWORD)0x46 );
break;
default:
_ASSERT( 0 ); // unknown burn buttons choice
}
break;
case stMultiButtonsChoice:
switch (nNewState)
{
case mbFxBypassE1:
m_msgUpperRightLed.Send( (DWORD)0x40 );
m_msgUpperRightLed.Send( (DWORD)0x02 );
m_msgUpperRightLed.Send( (DWORD)0x04 );
m_msgUpperRightLed.Send( (DWORD)0x06 );
break;
case mbSMuteE2:
m_msgUpperRightLed.Send( (DWORD)0x00 );
m_msgUpperRightLed.Send( (DWORD)0x42 );
m_msgUpperRightLed.Send( (DWORD)0x04 );
m_msgUpperRightLed.Send( (DWORD)0x06 );
break;
case mbPrePostE3:
m_msgUpperRightLed.Send( (DWORD)0x00 );
m_msgUpperRightLed.Send( (DWORD)0x02 );
m_msgUpperRightLed.Send( (DWORD)0x44 );
m_msgUpperRightLed.Send( (DWORD)0x06 );
break;
case mbSelectE4:
m_msgUpperRightLed.Send( (DWORD)0x00 );
m_msgUpperRightLed.Send( (DWORD)0x02 );
m_msgUpperRightLed.Send( (DWORD)0x04 );
m_msgUpperRightLed.Send( (DWORD)0x46 );
break;
default:
_ASSERT( 0 ); // unknown multi buttons choice
}
break;
case stTrackRotaryMapping:
case stBusRotaryMapping:
case stSendPanOrLevel:
case stContainerClass:
{
updateRotaryMappingLED();
}
break;
case stShiftKey:
{
switch (nNewState)
{
case skShiftIn:
m_msgLowerLeftLed.Send( (DWORD)0x40 );
break;
case skShiftOut:
m_msgLowerLeftLed.Send( (DWORD)0x00 );
break;
default:
_ASSERT( 0 ); // unknown state for shift key
}
break;
}
case stInsertEditMode:
updateRotaryMappingLED();
// break left out on purpose
case stQueryState:
updatePlugInBtnLED(); // this LED depends on both the stQueryState and the
// stInsertEditMode.
break;
case stFineTweakMode:
{
switch (nNewState)
{
case ftEngaged:
m_msgLowerLeftLed.Send( (DWORD)0x43 );
break;
case ftEngagedTimed:
case ftDisengaged:
m_msgLowerLeftLed.Send( (DWORD)0x03 );
break;
default:
_ASSERT( 0 ); // unknown fine tweak mode
}
break;
}
}
return S_OK;
}
/////////////////////////////////////////////////////////////////////////
void CMMChoiceLedUpdater::updatePlugInBtnLED()
{
switch (GetStateForID( stInsertEditMode ))
{
case ieEngaged:
m_msgLowerLeftLed.Send( (DWORD)0x45 );
break;
case ieDisengaged:
if (GetStateForID( stQueryState ) == qsChooseInsert )
m_msgLowerLeftLed.Send( (DWORD)0x45 );
else
m_msgLowerLeftLed.Send( (DWORD)0x05 );
break;
default:
_ASSERT( 0 ); // unknown insert edit mode
}
}
/////////////////////////////////////////////////////////////////////////
void CMMChoiceLedUpdater::updateRotaryMappingLED()
{
// construct the 7 segment display message from the current aux number
char pbyMsg[4];
char strDigits[3];
const SONAR_MIXER_STRIP strip = m_pSurface->GetCurrentStripKind();
const int nRotState = (strip == MIX_STRIP_TRACK) ? GetStateForID( stTrackRotaryMapping ) : GetStateForID( stBusRotaryMapping );
if (GetStateForID( stInsertEditMode ) == ieDisengaged)
{
if ( strip == MIX_STRIP_MASTER )
{
::strcpy( strDigits, " " );
}
else
{
const int nSendState = GetStateForID( stSendPanOrLevel );
if ( nRotState == trPan || nRotState == buPan )
{
::strcpy( strDigits, "PN" );
}
else
{
const int nSendIx = min( 8, nRotState - trSendBase );
if ( sendLevel == nSendState )
::sprintf( strDigits, "L%d", nSendIx + 1 );
else
::sprintf( strDigits, "P%d", nSendIx + 1 );
}
}
}
else
{
::sprintf( strDigits, "EF" );
}
if (strlen( strDigits ) > 1)
{
pbyMsg[0] = strDigits[0] >> 4;
pbyMsg[1] = strDigits[0] & 0x0f;
pbyMsg[2] = strDigits[1] >> 4;
pbyMsg[3] = strDigits[1] & 0x0f;
}
else // length is one
{
_ASSERT( 0 );
}
if ( (strip == MIX_STRIP_TRACK || strip == MIX_STRIP_BUS ) && nRotState == sendPan)
{
// put a DOT in the display
pbyMsg[0] |= 0x40;
}
m_msg7Segment.SendText( 4, pbyMsg );
}
/////////////////////////////////////////////////////////////////////////
// CMMEncoderStateShifter:
/////////////////////////////////////////////////////////////////////////
CMMEncoderStateShifter::CMMEncoderStateShifter(
CControlSurface *pSurface,
CMidiMsg *pMsg,
DWORD dwStateID,
DWORD dwInitialState /* =0 */
) :
CStateShifter( pSurface, dwStateID, dwInitialState ),
m_pSurface( pSurface ),
m_pMsgRotary( pMsg )
{
if (m_pMsgRotary)
m_pMsgRotary->AddListener( this );
SubscribeToState( stInsertEditMode );
SubscribeToState( stContainerClass );
}
/////////////////////////////////////////////////////////////////////////
HRESULT CMMEncoderStateShifter::setValue( CMidiMsg *pMsg, DWORD dwVal )
{
if (m_pMsgRotary != pMsg) // ignore it
return S_FALSE;
// determine where to shift to
int nNewState = 0;
int nInc = dwVal & 0x3f; // value
DWORD dwSign = dwVal & 0x40; // top bit, or sign
if (dwSign == 0)
nInc = 0 - nInc;
if ((GetStateID() == stTrackRotaryMapping &&
(m_pSurface->GetCurrentStripKind() == MIX_STRIP_TRACK)) ||
(GetStateID() == stBusRotaryMapping &&
(m_pSurface->GetCurrentStripKind() == MIX_STRIP_BUS) ))
{
if (GetStateForID( stInsertEditMode ) == ieEngaged)
{
int nBaseFxParam = m_pSurface->GetStateMgr()->GetShifterFromID( stBaseEffectParam )->GetCurrentState();
m_pSurface->GetStateMgr()->PostStateChange( stBaseEffectParam, nBaseFxParam + nInc );
return S_OK;
}
else if (m_pSurface->GetCurrentStripKind() != MIX_STRIP_MAIN)
{
// shift my own state
nNewState = GetCurrentState() + nInc;
return SetNewState( nNewState );
}
else
return S_FALSE;
}
else
return S_FALSE;
}
/////////////////////////////////////////////////////////////////////////
int CMMEncoderStateShifter::GetMaxState()
{
DWORD nMax = 0;
if (GetStateID() == stTrackRotaryMapping || GetStateID() == stBusRotaryMapping)
{
return 10;
}
else
{
_ASSERT( 0 ); // unknown rotary mapping ID
return 0;
}
}
/////////////////////////////////////////////////////////////////////////
HRESULT CMMEncoderStateShifter::SetNewState( int nNewState )
{
// When loading, sonar may not have yet defined its containers,
// and a validation of them may fail.
// Instead, simply set the state variable without validating it
// and wait until the next call to OnHostNotify to validate
if (m_pSurface->GetStateMgr()->IsLoading())
{
m_nCurrentState = nNewState;
return S_FALSE;
}
else
return CStateShifter::SetNewState( nNewState );
}
/////////////////////////////////////////////////////////////////////////
CMMEncoderStateShifter::~CMMEncoderStateShifter()
{
if (m_pMsgRotary)
m_pMsgRotary->RemoveListener( this );
}
/////////////////////////////////////////////////////////////////////////
// CMMRotaryParam:
/////////////////////////////////////////////////////////////////////////
CMMRotaryParam::CMMRotaryParam(
CControlSurface *pSurface,
DWORD dwHWStripNum,
CMidiMsg *pMsgInput,
CMidiMsg *pMsgOutput /*= NULL */,
CMidiMsg *pMsgCapture /* = NULL */, DWORD dwCaptureVal /* = VAL_ANY */,
CMidiMsg *pMsgRelease /* = NULL */, DWORD dwReleaseVal /* = VAL_ANY */
):
CMixParamFloat(
pSurface,
pMsgInput,
pMsgOutput,
pMsgCapture,
dwCaptureVal,
pMsgRelease,
dwReleaseVal
),
m_dwHWStripNum( dwHWStripNum ),
m_msgPointerGraph( pSurface )
{
// scribble bargraph message setup
m_msgPointerGraph.SetMessageType( CMidiMsg::mtSysX7bit );
SetPointerType( 0x03 );
BYTE pczPostString[] = {0xF7};
m_msgPointerGraph.SetSysXPostString( (const unsigned char *)( pczPostString ), sizeof(pczPostString) );
}
/////////////////////////////////////////////////////////////////////////
void CMMRotaryParam::SetPointerType( DWORD dwPointerType )
{
// **** pointer type is index 8
BYTE pczPreString[] = {0xF0, 0x00, 0x01, 0x0F, 0x00, 0x11, 0x00, 0x11, 0x00, 0x00 }; // last byte is replaced with the "address" for the scribble strip.
pczPreString[9] = BYTE(m_dwHWStripNum);
pczPreString[8] = BYTE(dwPointerType);
m_msgPointerGraph.SetSysXPreString( (const unsigned char *)( pczPreString ), sizeof(pczPreString) );
}
/////////////////////////////////////////////////////////////////////////
HRESULT CMMRotaryParam::SetIsEnabled( BOOL bIsEnabled )
{
if (bIsEnabled == FALSE)
m_msgPointerGraph.Send( (DWORD)0 );
return CMixParamFloat::SetIsEnabled( bIsEnabled );
}
/////////////////////////////////////////////////////////////////////////
void CMMRotaryParam::refreshParam( float *pfValue /*= NULL*/ )
{
if (m_bIsEnabled == FALSE)
return;
if (IsParamValid( m_mixerStrip, m_dwStripNum, m_mixerParam, m_dwParamNum ) == S_OK)
{
float fValue = 0;
if (pfValue == NULL)
{
CComPtr<ISonarMixer> pSonarMixer;
HRESULT hr = m_pSurface->GetSonarMixer( &pSonarMixer );
if (FAILED( hr ))
{
fValue = 0; // nothing else we can do
}
else
{
pSonarMixer->GetMixParam( m_mixerStrip, m_dwStripNum, m_mixerParam, m_dwParamNum, &fValue );
// for metering, clamp the value to 1.0f
if ( MIX_PARAM_AUDIO_METER == m_mixerParam )
fValue = min( 1.0f, fValue );
}
}
else
fValue = *pfValue;
m_msgPointerGraph.Send( fValue );
CMixParamFloat::refreshParam( pfValue );
}
else
m_msgPointerGraph.Send( (DWORD)0 );
}
/////////////////////////////////////////////////////////////////////////
// CMMContainerPicker:
/////////////////////////////////////////////////////////////////////////
#define OUT_OF_SCOPE_LED (8)
#define INVALID_LED (-1)
CMMContainerPicker::CMMContainerPicker( CControlSurface *pSurface ) :
CMultiStateListener( pSurface ),
m_nLastLedIndex( INVALID_LED ), // we do our own thinning
m_msgSelectBtns( pSurface ),
m_msgSelectLED( pSurface )
{
// setup the select buttons
m_msgSelectBtns.SetMessageType( CMidiMsg::mtCCHiLo );
m_msgSelectBtns.SetCCNum( 0x0f );
m_msgSelectBtns.SetCC2Num( 0x2f );
// setup the select buttons LED message
m_msgSelectLED.SetMessageType( CMidiMsg::mtCCHiLo );
m_msgSelectLED.SetCCNum( 0x0c );
m_msgSelectLED.SetCC2Num( 0x2c );
// we do our own thinning since this message gets used
// for all 8 LEDs
m_msgSelectLED.SetIsOutputThin( FALSE );
m_msgSelectBtns.AddListener( this );
SubscribeToState( stContainerClass );
SubscribeToState( stShiftKey );
SubscribeToState( stBaseTrack );
SubscribeToState( stBaseBus );
SubscribeToState( stBaseMain );
SubscribeToState( stQueryState );
}
/////////////////////////////////////////////////////////////////////////
CMMContainerPicker::~CMMContainerPicker()
{
m_msgSelectBtns.RemoveListener( this );
}
/////////////////////////////////////////////////////////////////////////
HRESULT CMMContainerPicker::OnStateChange( DWORD dwStateID, int nNewState )
{
switch (dwStateID)
{
case stQueryState:
case stShiftKey:
m_nLastLedIndex = INVALID_LED;
}
return refreshButtonLEDs();
}
/////////////////////////////////////////////////////////////////////////
HRESULT CMMContainerPicker::refreshButtonLEDs()
{
if (GetStateForID( stQueryState ) != qsIdle)
return S_FALSE;
int nLedIndex = 0; // this index may be less than 0 or more than 7 if the
// current container is out of the bank's scope. This is not a problem.
switch (GetStateForID( stContainerClass ))
{
case ccTracks:
nLedIndex = GetStateForID( stCurrentTrack ) - GetStateForID( stBaseTrack );
break;
case ccBus:
nLedIndex = GetStateForID( stCurrentBus ) - GetStateForID( stBaseBus );
break;
case ccMains:
nLedIndex = GetStateForID( stCurrentMain ) - GetStateForID( stBaseMain );
break;
default:
_ASSERT( 0 ); // unknown container class
}
if (nLedIndex > 7 || nLedIndex < 0)
nLedIndex = OUT_OF_SCOPE_LED;
// Because we reuse the same m_msgSelectLED for all the LEDs
// thinning does not work (since we send a different message for each LED)
// A way this could have been solved would have been by having
// 8 m_msgSelects one for each LED. However, I preffer
// do my own thinning locally.
if (nLedIndex == m_nLastLedIndex) // if unchanged, dont resend
return S_FALSE;
// flash the select button leds
for (int ix = 0; ix < 8; ix++)
{
if (nLedIndex == ix)
m_msgSelectLED.Send( (DWORD)( ( ix << 7 ) + 0x41) );
else
m_msgSelectLED.Send( (DWORD)( ( ix << 7 ) + 0x01) );
}
m_nLastLedIndex = nLedIndex;
return S_OK;
}
/////////////////////////////////////////////////////////////////////////
HRESULT CMMContainerPicker::setValue( CMidiMsg *pMsg, DWORD dwVal )
{
if (pMsg == &m_msgSelectBtns)
{
// allow picking a container only when the shift key is out.
if ( ( GetStateForID( stShiftKey ) == skShiftOut ) &&
( GetStateForID( stQueryState ) == qsIdle ) )
{
DWORD dwButtonIx = dwVal >> 7;
DWORD dwButtonState = dwVal & 0x7f;
if (dwButtonIx > 7)
return S_FALSE;
if (dwButtonState == 0x41) // button was pressed
{
switch (GetStateForID( stContainerClass ))
{
case ccTracks:
{
DWORD dwNewTrack = dwButtonIx + GetStateForID( stBaseTrack );
m_pSurface->GetStateMgr()->PostStateChange( stCurrentTrack, dwNewTrack );
}
break;
case ccBus:
{
DWORD dwNewBus = dwButtonIx + GetStateForID( stBaseBus );
m_pSurface->GetStateMgr()->PostStateChange( stCurrentBus, dwNewBus );
}
break;
case ccMains:
{
DWORD dwNewMain = dwButtonIx + GetStateForID( stBaseMain );
m_pSurface->GetStateMgr()->PostStateChange( stCurrentMain, dwNewMain );
}
break;
default:
_ASSERT( 0 ); // unknown container class
}
}
}
HRESULT hr = refreshButtonLEDs();
_ASSERT( SUCCEEDED( hr ) );
}
return S_OK;
}
/////////////////////////////////////////////////////////////////////////
CMMFineTweakMode::CMMFineTweakMode( CControlSurface *pSurface ) :
m_pSurface( pSurface ),
CHostNotifyListener( 0, pSurface ),
CMultiStateListener( pSurface ),
CLastParamChangeListener( pSurface ),
m_msgScribbleContainer( pSurface ),
m_msgScribbleSubCont( pSurface ),
m_msgScribbleParam( pSurface ),
m_msgScribbleValue( pSurface ),
m_nRefreshCount( 0 )
{
// setup scribble message
BYTE pczPreString[] = {0xF0, 0x00, 0x01, 0x0F, 0x00, 0x11, 0x00, 0x10, 0x00 };
BYTE pczPostString[] = {0xF7};
pczPreString[8] = BYTE(0);
m_msgScribbleContainer.SetMessageType( CMidiMsg::mtSysXString );
m_msgScribbleContainer.SetSysXPreString( (const unsigned char *)( pczPreString ), sizeof(pczPreString) );
m_msgScribbleContainer.SetSysXPostString( (const unsigned char *)( pczPostString ), sizeof(pczPostString) );
m_msgScribbleContainer.SetSysXTextLen( 10 ); // print 10 characters out each time
m_msgScribbleContainer.SetSysXPadLen( 1 ); // force last one to be padding
m_msgScribbleContainer.SetSysXTextFillChar( ' ' ); // padding is space bar
pczPreString[8] = BYTE(10);
m_msgScribbleSubCont.SetMessageType( CMidiMsg::mtSysXString );
m_msgScribbleSubCont.SetSysXPreString( (const unsigned char *)( pczPreString ), sizeof(pczPreString) );
m_msgScribbleSubCont.SetSysXPostString( (const unsigned char *)( pczPostString ), sizeof(pczPostString) );
m_msgScribbleSubCont.SetSysXTextLen( 10 ); // print 10 characters out each time
m_msgScribbleSubCont.SetSysXPadLen( 1 ); // force last one to be padding
m_msgScribbleSubCont.SetSysXTextFillChar( ' ' ); // padding is space bar
pczPreString[8] = BYTE(20);
m_msgScribbleParam.SetMessageType( CMidiMsg::mtSysXString );
m_msgScribbleParam.SetSysXPreString( (const unsigned char *)( pczPreString ), sizeof(pczPreString) );
m_msgScribbleParam.SetSysXPostString( (const unsigned char *)( pczPostString ), sizeof(pczPostString) );
m_msgScribbleParam.SetSysXTextLen( 10 ); // print 10 characters out each time
m_msgScribbleParam.SetSysXPadLen( 1 ); // force last one to be padding
m_msgScribbleParam.SetSysXTextFillChar( ' ' ); // padding is space bar
pczPreString[8] = BYTE(30);
m_msgScribbleValue.SetMessageType( CMidiMsg::mtSysXString );
m_msgScribbleValue.SetSysXPreString( (const unsigned char *)( pczPreString ), sizeof(pczPreString) );
m_msgScribbleValue.SetSysXPostString( (const unsigned char *)( pczPostString ), sizeof(pczPostString) );
m_msgScribbleValue.SetSysXTextLen( 10 ); // print 10 characters out each time
m_msgScribbleValue.SetSysXTextFillChar( ' ' ); // padding is space bar
SubscribeToState( stFineTweakMode );
}
/////////////////////////////////////////////////////////////////////////
CMMFineTweakMode::~CMMFineTweakMode()
{
}
/////////////////////////////////////////////////////////////////////////
HRESULT CMMFineTweakMode::OnStateChange( DWORD dwStateID, int nNewState )
{
if (m_pSurface->GetLastParamChange()->IsDefined() && ( GetStateForID( stFineTweakMode ) != ftDisengaged ) )
{
// show it on the screen
m_msgScribbleContainer.Invalidate();
m_msgScribbleSubCont.Invalidate();
m_msgScribbleValue.Invalidate();
m_msgScribbleParam.Invalidate();
RequestRefresh();
}
return S_OK;
}
/////////////////////////////////////////////////////////////////////////
void CMMFineTweakMode::OnParamChange()
{
if (GetStateForID(stFineTweakMode) == ftDisengaged)
{
m_pSurface->GetStateMgr()->PostStateChange( stFineTweakMode, ftEngagedTimed );
}
else
{
RequestRefresh();
}
if (GetStateForID(stFineTweakMode) != ftEngaged)
// only bypass scheduled disengagement if it is "engaged"
m_pSurface->GetStateMgr()->ScheduleStateChange( stFineTweakMode, ftDisengaged, 2000, TRUE );
}
/////////////////////////////////////////////////////////////////////////
void CMMFineTweakMode::OnHostNotify( DWORD fdwRefresh, DWORD dwCookie )
{
if (GetStateForID(stFineTweakMode) == ftDisengaged)
return;
if ( m_nRefreshCount++ % 2 != 0 )
return;
// get the fine text for the last parameter change:
SONAR_MIXER_STRIP mixerStrip = MIX_STRIP_TRACK;
DWORD dwStripNum = 0;
SONAR_MIXER_PARAM mixerParam = MIX_PARAM_VOL;
DWORD dwParamNum = 0;
m_pSurface->GetLastParamChange()->GetLastParamID( &mixerStrip, &dwStripNum, &mixerParam, &dwParamNum );
CComPtr<ISonarMixer> pSonarMixer;
if (FAILED( m_pSurface->GetSonarMixer( &pSonarMixer ) ))
return;
char szParamText[64];
DWORD dwLength = 64;
pSonarMixer->GetMixStripName( mixerStrip, dwStripNum, szParamText, &dwLength );
m_msgScribbleContainer.SendText( (DWORD)strlen( szParamText ), szParamText );
if (mixerParam == MIX_PARAM_FX_PARAM)
{
dwLength = 64;
pSonarMixer->GetMixParamLabel( mixerStrip, dwStripNum, MIX_PARAM_FX, LOWORD( dwParamNum ), szParamText, &dwLength );
m_msgScribbleSubCont.SendText( (DWORD)strlen( szParamText ), szParamText );
}
else
m_msgScribbleSubCont.SendText( 10, " " );
dwLength = 64;
pSonarMixer->GetMixParamLabel( mixerStrip, dwStripNum, mixerParam, dwParamNum, szParamText, &dwLength );
m_msgScribbleParam.SendText( (DWORD)strlen( szParamText ), szParamText );
float fFoo = 0;
pSonarMixer->GetMixParam( mixerStrip, dwStripNum, mixerParam, dwParamNum, &fFoo );
dwLength = 64;
pSonarMixer->GetMixParamValueText( mixerStrip, dwStripNum, mixerParam, dwParamNum, fFoo, szParamText, &dwLength );
m_msgScribbleValue.SendText( (DWORD)strlen( szParamText ), szParamText );
}
//----------------------------------------------------------------------
CMMCommand::CMMCommand( CControlSurface *pSurface ) :
CMultiStateListener( pSurface ),
m_msgUndoSave( pSurface ),
m_nCurShift( 1 )
{
m_msgUndoSave.SetMessageType( CMidiMsg::mtCCSel );
m_msgUndoSave.SetCCSelNum( 0x0f );
m_msgUndoSave.SetCCSelVal( 0x08 );
m_msgUndoSave.SetCCNum( 0x2F );
m_msgUndoSave.AddListener( this );
SubscribeToState( stShiftKey );
}
CMMCommand::~CMMCommand()
{
m_msgUndoSave.RemoveListener( this );
}
// CMultiStateListener override
HRESULT CMMCommand::OnStateChange( DWORD dwStateID, int nNewState )
{
switch( dwStateID )
{
case stShiftKey:
m_nCurShift = nNewState;
break;
}
return S_OK;
}
// CMidiMsgListener override
HRESULT CMMCommand::setValue( CMidiMsg *pMsg, DWORD dwVal )
{
CComPtr<ISonarCommands> pISonarCommands;
MM_CHECKHR( m_pSurface->GetSonarCommands( &pISonarCommands ) );
if ( 0x41 == dwVal ) // Undo/Save button
{
if ( 0 == m_nCurShift )
MM_CHECKHR( pISonarCommands->DoCommand( CMD_FILE_SAVE ) );
else
MM_CHECKHR( pISonarCommands->DoCommand( CMD_EDIT_UNDO ) );
}
else if ( 0x42 == dwVal ) // "Default" button as REDO
{
MM_CHECKHR( pISonarCommands->DoCommand( CMD_EDIT_REDO ) );
}
return S_OK;
}
|
// Copyright (C) 2019-2020 Zilliz. 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 "db/Utils.h"
#include <fiu-local.h>
#include <boost/filesystem.hpp>
#include <chrono>
#include <mutex>
#include <regex>
#include <vector>
#include "config/Config.h"
#include "storage/s3/S3ClientWrapper.h"
#include "utils/CommonUtil.h"
#include "utils/Log.h"
namespace milvus {
namespace engine {
namespace utils {
namespace {
const char* TABLES_FOLDER = "/tables/";
uint64_t index_file_counter = 0;
std::mutex index_file_counter_mutex;
static std::string
ConstructParentFolder(const std::string& db_path, const meta::SegmentSchema& table_file) {
std::string table_path = db_path + TABLES_FOLDER + table_file.collection_id_;
std::string partition_path = table_path + "/" + table_file.segment_id_;
return partition_path;
}
static std::string
GetTableFileParentFolder(const DBMetaOptions& options, const meta::SegmentSchema& table_file) {
uint64_t path_count = options.slave_paths_.size() + 1;
std::string target_path = options.path_;
uint64_t index = 0;
if (meta::SegmentSchema::NEW_INDEX == table_file.file_type_) {
// index file is large file and to be persisted permanently
// we need to distribute index files to each db_path averagely
// round robin according to a file counter
std::lock_guard<std::mutex> lock(index_file_counter_mutex);
index = index_file_counter % path_count;
++index_file_counter;
} else {
// for other type files, they could be merged or deleted
// so we round robin according to their file id
index = table_file.id_ % path_count;
}
if (index > 0) {
target_path = options.slave_paths_[index - 1];
}
return ConstructParentFolder(target_path, table_file);
}
} // namespace
int64_t
GetMicroSecTimeStamp() {
auto now = std::chrono::system_clock::now();
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count();
return micros;
}
Status
CreateTablePath(const DBMetaOptions& options, const std::string& collection_id) {
std::string db_path = options.path_;
std::string table_path = db_path + TABLES_FOLDER + collection_id;
auto status = server::CommonUtil::CreateDirectory(table_path);
if (!status.ok()) {
ENGINE_LOG_ERROR << status.message();
return status;
}
for (auto& path : options.slave_paths_) {
table_path = path + TABLES_FOLDER + collection_id;
status = server::CommonUtil::CreateDirectory(table_path);
fiu_do_on("CreateTablePath.creat_slave_path", status = Status(DB_INVALID_PATH, ""));
if (!status.ok()) {
ENGINE_LOG_ERROR << status.message();
return status;
}
}
return Status::OK();
}
Status
DeleteTablePath(const DBMetaOptions& options, const std::string& collection_id, bool force) {
std::vector<std::string> paths = options.slave_paths_;
paths.push_back(options.path_);
for (auto& path : paths) {
std::string table_path = path + TABLES_FOLDER + collection_id;
if (force) {
boost::filesystem::remove_all(table_path);
ENGINE_LOG_DEBUG << "Remove collection folder: " << table_path;
} else if (boost::filesystem::exists(table_path) && boost::filesystem::is_empty(table_path)) {
boost::filesystem::remove_all(table_path);
ENGINE_LOG_DEBUG << "Remove collection folder: " << table_path;
}
}
bool s3_enable = false;
server::Config& config = server::Config::GetInstance();
config.GetStorageConfigS3Enable(s3_enable);
if (s3_enable) {
std::string table_path = options.path_ + TABLES_FOLDER + collection_id;
auto& storage_inst = milvus::storage::S3ClientWrapper::GetInstance();
Status stat = storage_inst.DeleteObjects(table_path);
if (!stat.ok()) {
return stat;
}
}
return Status::OK();
}
Status
CreateTableFilePath(const DBMetaOptions& options, meta::SegmentSchema& table_file) {
std::string parent_path = GetTableFileParentFolder(options, table_file);
auto status = server::CommonUtil::CreateDirectory(parent_path);
fiu_do_on("CreateTableFilePath.fail_create", status = Status(DB_INVALID_PATH, ""));
if (!status.ok()) {
ENGINE_LOG_ERROR << status.message();
return status;
}
table_file.location_ = parent_path + "/" + table_file.file_id_;
return Status::OK();
}
Status
GetTableFilePath(const DBMetaOptions& options, meta::SegmentSchema& table_file) {
std::string parent_path = ConstructParentFolder(options.path_, table_file);
std::string file_path = parent_path + "/" + table_file.file_id_;
bool s3_enable = false;
server::Config& config = server::Config::GetInstance();
config.GetStorageConfigS3Enable(s3_enable);
fiu_do_on("GetTableFilePath.enable_s3", s3_enable = true);
if (s3_enable) {
/* need not check file existence */
table_file.location_ = file_path;
return Status::OK();
}
if (boost::filesystem::exists(parent_path)) {
table_file.location_ = file_path;
return Status::OK();
}
for (auto& path : options.slave_paths_) {
parent_path = ConstructParentFolder(path, table_file);
file_path = parent_path + "/" + table_file.file_id_;
if (boost::filesystem::exists(parent_path)) {
table_file.location_ = file_path;
return Status::OK();
}
}
std::string msg = "Collection file doesn't exist: " + file_path;
if (table_file.file_size_ > 0) { // no need to pop error for empty file
ENGINE_LOG_ERROR << msg << " in path: " << options.path_ << " for collection: " << table_file.collection_id_;
}
return Status(DB_ERROR, msg);
}
Status
DeleteTableFilePath(const DBMetaOptions& options, meta::SegmentSchema& table_file) {
utils::GetTableFilePath(options, table_file);
boost::filesystem::remove(table_file.location_);
return Status::OK();
}
Status
DeleteSegment(const DBMetaOptions& options, meta::SegmentSchema& table_file) {
utils::GetTableFilePath(options, table_file);
std::string segment_dir;
GetParentPath(table_file.location_, segment_dir);
boost::filesystem::remove_all(segment_dir);
return Status::OK();
}
Status
GetParentPath(const std::string& path, std::string& parent_path) {
boost::filesystem::path p(path);
parent_path = p.parent_path().string();
return Status::OK();
}
bool
IsSameIndex(const TableIndex& index1, const TableIndex& index2) {
return index1.engine_type_ == index2.engine_type_ && index1.extra_params_ == index2.extra_params_ &&
index1.metric_type_ == index2.metric_type_;
}
bool
IsRawIndexType(int32_t type) {
return (type == (int32_t)EngineType::FAISS_IDMAP) || (type == (int32_t)EngineType::FAISS_BIN_IDMAP);
}
bool
IsBinaryIndexType(int32_t index_type) {
return (index_type == (int32_t)engine::EngineType::FAISS_BIN_IDMAP) ||
(index_type == (int32_t)engine::EngineType::FAISS_BIN_IVFFLAT);
}
bool
IsBinaryMetricType(int32_t metric_type) {
return (metric_type == (int32_t)engine::MetricType::HAMMING) ||
(metric_type == (int32_t)engine::MetricType::JACCARD) ||
(metric_type == (int32_t)engine::MetricType::SUBSTRUCTURE) ||
(metric_type == (int32_t)engine::MetricType::SUPERSTRUCTURE) ||
(metric_type == (int32_t)engine::MetricType::TANIMOTO);
}
meta::DateT
GetDate(const std::time_t& t, int day_delta) {
struct tm ltm;
localtime_r(&t, <m);
if (day_delta > 0) {
do {
++ltm.tm_mday;
--day_delta;
} while (day_delta > 0);
mktime(<m);
} else if (day_delta < 0) {
do {
--ltm.tm_mday;
++day_delta;
} while (day_delta < 0);
mktime(<m);
} else {
ltm.tm_mday;
}
return ltm.tm_year * 10000 + ltm.tm_mon * 100 + ltm.tm_mday;
}
meta::DateT
GetDateWithDelta(int day_delta) {
return GetDate(std::time(nullptr), day_delta);
}
meta::DateT
GetDate() {
return GetDate(std::time(nullptr), 0);
}
// URI format: dialect://username:password@host:port/database
Status
ParseMetaUri(const std::string& uri, MetaUriInfo& info) {
std::string dialect_regex = "(.*)";
std::string username_tegex = "(.*)";
std::string password_regex = "(.*)";
std::string host_regex = "(.*)";
std::string port_regex = "(.*)";
std::string db_name_regex = "(.*)";
std::string uri_regex_str = dialect_regex + "\\:\\/\\/" + username_tegex + "\\:" + password_regex + "\\@" +
host_regex + "\\:" + port_regex + "\\/" + db_name_regex;
std::regex uri_regex(uri_regex_str);
std::smatch pieces_match;
if (std::regex_match(uri, pieces_match, uri_regex)) {
info.dialect_ = pieces_match[1].str();
info.username_ = pieces_match[2].str();
info.password_ = pieces_match[3].str();
info.host_ = pieces_match[4].str();
info.port_ = pieces_match[5].str();
info.db_name_ = pieces_match[6].str();
// TODO(myh): verify host, port...
} else {
return Status(DB_INVALID_META_URI, "Invalid meta uri: " + uri);
}
return Status::OK();
}
} // namespace utils
} // namespace engine
} // namespace milvus
|
/*
* 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/ccc/v20200210/model/DescribeIMCdrsResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ccc::V20200210::Model;
using namespace std;
DescribeIMCdrsResponse::DescribeIMCdrsResponse() :
m_totalCountHasBeenSet(false),
m_iMCdrsHasBeenSet(false)
{
}
CoreInternalOutcome DescribeIMCdrsResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("TotalCount") && !rsp["TotalCount"].IsNull())
{
if (!rsp["TotalCount"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `TotalCount` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_totalCount = rsp["TotalCount"].GetInt64();
m_totalCountHasBeenSet = true;
}
if (rsp.HasMember("IMCdrs") && !rsp["IMCdrs"].IsNull())
{
if (!rsp["IMCdrs"].IsArray())
return CoreInternalOutcome(Core::Error("response `IMCdrs` is not array type"));
const rapidjson::Value &tmpValue = rsp["IMCdrs"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
IMCdrInfo item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_iMCdrs.push_back(item);
}
m_iMCdrsHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string DescribeIMCdrsResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_totalCountHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TotalCount";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_totalCount, allocator);
}
if (m_iMCdrsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "IMCdrs";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_iMCdrs.begin(); itr != m_iMCdrs.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
int64_t DescribeIMCdrsResponse::GetTotalCount() const
{
return m_totalCount;
}
bool DescribeIMCdrsResponse::TotalCountHasBeenSet() const
{
return m_totalCountHasBeenSet;
}
vector<IMCdrInfo> DescribeIMCdrsResponse::GetIMCdrs() const
{
return m_iMCdrs;
}
bool DescribeIMCdrsResponse::IMCdrsHasBeenSet() const
{
return m_iMCdrsHasBeenSet;
}
|
#include "state.h"
#include "main.h"
State state;
void statusLed_changeState(State s);
void wiggle_set_detector_timeout();
void mqtt_send_log(const char* s);
void mqtt_send_status(const char* status);
void state_change(State s)
{
#ifdef DEBUG
Serial.print("State changing from: ");
Serial.println(s);
#endif
statusLed_changeState(s);
switch(s)
{
case State::NotifyingManual:
mqtt_send_status("MANUAL ALERT");
break;
case State::NotifyingTimeout:
// get here when enough time has passed without wiggle threshold being exceeded
mqtt_send_status("DONE");
break;
case State::Detected:
// revert right back again, we don't want to restart detecting process
s = State::Detecting;
break;
case State::Detecting:
mqtt_send_log("Detection mode begins");
wiggle_set_detector_timeout();
break;
}
// global state is changed FIRST so that callbacks/context-specific code
// (such as statusLed_blink_event)
// has access to up-to-date state
state = s;
Serial.print("State changed: ");
Serial.println(s);
}
void state_setup()
{
state_change(State::Idle);
}
void state_loop()
{
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.