How to get the information of DeclRefExpr from the basic block in Clang:CFG? - clang

How to get the information of DeclRefExpr from the basic block in Clang:CFG?
This is code i have coded
class CFGPrinter : public MatchFinder::MatchCallback {
public:
virtual void run(const MatchFinder::MatchResult &Result) {
if (const FunctionDecl *funcDecl =
Result.Nodes.getNodeAs<clang::FunctionDecl>("mainFunction")) {
ASTContext *context = Result.Context;
Stmt *funcBody = funcDecl->getBody();
static std::unique_ptr<CFG> sourceCFG = CFG::buildCFG(funcDecl, funcBody, context, clang::CFG::BuildOptions());
for(CFG::const_iterator it = sourceCFG->begin(), ei = sourceCFG->end(); it != ei; ++it){
const CFGBlock* block = *it;
for(CFGBlock::const_iterator bi = block->begin(), be = block->end(); bi != be; ++bi){
const CFGElement &elem = *bi;
const Stmt *stmt_tmp = elem.castAs<CFGStmt>().getStmt();
/*I want to get DeclRefExpr from next*/
}
}
}
}
}
};

Related

Trilib: Select files from iOS, nothing happens

I have some issue while using Trilib on iOS with LoadModelFromFilePickerAsync, although it runs well on Android, Unity Editor, and Mac.
Here code:
var assetLoaderOptions = AssetLoader.CreateDefaultLoaderOptions();
var filePickerAssetLoader = AssetLoaderFilePicker.Create();
filePickerAssetLoader.LoadModelFromFilePickerAsync("Load model",
onLoad,
onMaterialsLoad,
onProgress,
onBeginLoad,
onError,
null,
assetLoaderOptions);
private void onBeginLoad(bool x)
{
btnUploadModel3D.interactable = true;
if (x == true)
{
uiCoat.SetActive(true);
uiBFill.SetActive(true);
// txtPercent.text="0%";
}
else
{
// txtPercent.text="";
ReStore();
}
}
private void onError(IContextualizedError obj)
{
btnUploadModel3D.interactable = true;
ReStore();
warningFileFormat.enabled = true;
warningFileSize.enabled = false;
}
private void onProgress(AssetLoaderContext assetLoaderContext, float progress)
{
}
private void onMaterialsLoad(AssetLoaderContext x)
{
}
private void onLoad(AssetLoaderContext x)
{
string path = ModelManager.modelFilepath;
var fileInfo = new System.IO.FileInfo(path);
var lengthFile = fileInfo.Length / 1000000;
var modelName = getModelName(path);
string formatFile = ModelManager.modelExtension.ToUpper();
if (Array.IndexOf(arrFormatFile, formatFile) < 0)
{
ReStore();
warningFileSize.enabled = false;
warningFileFormat.enabled = true;
}
else
{
if (lengthFile > 100)
{
ReStore();
warningFileSize.enabled = true;
warningFileFormat.enabled = false;
}
else
{
x.RootGameObject.tag = "ModelClone";
x.RootGameObject.name = modelName;
warningFileFormat.enabled = false;
warningFileSize.enabled = false;
UploadModelToServer(File.ReadAllBytes(path), path);
DontDestroyOnLoad(x.RootGameObject);
}
}
}
I used the above code to select file with extension: .fbx, .zip, .obj, .glb from my iPhone. I selected a file with extension in that list, nothing happens though. There are no errors reported.
How can I fix it ? Thanks.

How to get function definition/signature as a string in Clang?

How can I get a function's signature (or at least the entire definition?) as a string using Clang/Libclang, assuming I have its CXCursor or so?
I think that the definition may be somehow obtainable by using the cursor's extents, but I don't really know how (what function to use).
You can use this simple code to get prototype of a function ( name, return type, count of arguments and arguments[name,data type]).
string Convert(const CXString& s)
{
string result = clang_getCString(s);
clang_disposeString(s);
return result;
}
void print_function_prototype(CXCursor cursor)
{
// TODO : Print data!
auto type = clang_getCursorType(cursor);
auto function_name = Convert(clang_getCursorSpelling(cursor));
auto return_type = Convert(clang_getTypeSpelling(clang_getResultType(type)));
int num_args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < num_args; ++i)
{
auto arg_cursor = clang_Cursor_getArgument(cursor, i);
auto arg_name = Convert(clang_getCursorSpelling(arg_cursor));
if (arg_name.empty())
{
arg_name = "no name!";
}
auto arg_data_type = Convert(clang_getTypeSpelling(clang_getArgType(type, i)));
}
}
CXChildVisitResult functionVisitor(CXCursor cursor, CXCursor /* parent */, CXClientData /* clientData */)
{
if (clang_Location_isFromMainFile(clang_getCursorLocation(cursor)) == 0)
return CXChildVisit_Continue;
CXCursorKind kind = clang_getCursorKind(cursor);
if ((kind == CXCursorKind::CXCursor_FunctionDecl || kind == CXCursorKind::CXCursor_CXXMethod || kind == CXCursorKind::CXCursor_FunctionTemplate || \
kind == CXCursorKind::CXCursor_Constructor))
{
print_function_prototype(cursor);
}
return CXChildVisit_Continue;
}
You could try using clang_Cursor_getMangling() and demangle the result in order to get the complete definition.
I'm using the following for a project I am working on and it works great for the definition. TL&DR clang_getCursorPrettyPrinted with the policy TerseOutput set to true.
std::string getStdString(const CXString &s)
{
std::string rv = clang_getCString(s);
clang_disposeString(s);
return rv;
}
bool isFunctionImplementation(CXCursor &cursor,std::string &decl,std::string &filename,unsigned &lineno)
{
std::string cs = getStdString(clang_getCursorPrettyPrinted(cursor,nullptr));
if (cs.find('{') == std::string::npos) // Just a declaration, not the "meat" of the function, so we dont care
return false;
clang::LangOptions lo;
struct clang::PrintingPolicy pol(lo);
pol.adjustForCPlusPlus();
pol.TerseOutput = true;
pol.FullyQualifiedName = true;
decl = getStdString(clang_getCursorPrettyPrinted(cursor,&pol));
CXSourceLocation location = clang_getCursorLocation( cursor );
CXFile f;
lineno = 0;
filename = "(None)";
clang_getSpellingLocation(location,&f,&lineno,nullptr,nullptr);
if (lineno)
{
filename = getStdString(clang_File_tryGetRealPathName(f));
}
return isAllowedDirectory(filename);
}
This one checks if the function call is "meat" or just a definition. Obviously you can adjust as needed, including writing your own isAllowedDirectory function. Just pass the cursor, two strings and an unsigned into this as you walk your AST when you hit a declaration type.
I use the following, shorter way with clang 10 (though its using a matcher, not a cursor):
The 2 helper functions are general helpers to get the code snippet as a string.
// helper function 1: find position of end of token
SourceLocation
end_of_the_end(SourceLocation const & start_of_end, SourceManager & sm)
{
using namespace clang;
LangOptions lopt;
return Lexer::getLocForEndOfToken(start_of_end, 0, sm, lopt);
}
// helper function 2:
std::string getSymbolString(clang::SourceManager & sm,
const clang::SourceRange & range)
{
return std::string(sm.getCharacterData(range.getBegin()),
sm.getCharacterData(end_of_the_end(range.getEnd(), sm)));
}
The actual code snippet to get the function declaration string is:
// ... in run() of a matcher:
virtual void run(corct::result_t const & result) override
{
using namespace clang;
FunctionDecl * f_decl = const_cast<FunctionDecl *>(
result.Nodes.getNodeAs<FunctionDecl>(fd_bd_name_));
if(f_decl) {
SourceManager & sm(result.Context->getSourceManager());
FunctionDecl * f_decl = const_cast<FunctionDecl *>(
result.Nodes.getNodeAs<FunctionDecl>(fd_bd_name_));
auto full_decl_string =
getSymbolString(sm, f_decl->DeclaratorDecl::getSourceRange());
}
}
This will output inline bool test2(std::string const & str, std::vector<std::string> & sss) for the following function:
inline bool test2(std::string const & str, std::vector<std::string> & sss)
{
return true;
}

What will be the time complexity of reversing the linked list in a different way using below code?

Given a linked List $link1, with elements (a->b->c->d->e->f->g->h->i->j), we need to reverse the linked list provided that the reversing will be done in a manner like -
Reverse 1st element (a)
Reverse next 2 elements (a->c->b)
Reverse next 3 elements (a->c->b->f->e->d)
Reverse next 4 elements (a->c->b->f->e->d->j->i->h->g)
....
....
I have created below code in PHP to solve this problem
Things I need -
I need to calculate the time complexity of reverseLinkedList function below.
Need to know if we can optimize reverseLinkedList function to reduce time complexity.
-
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function read_node()
{
return $this->data;
}
}
class LinkList
{
private $first_node;
private $last_node;
private $count;
function __construct()
{
$this->first_node = NULL;
$this->last_node = NULL;
$this->count = 0;
}
function size()
{
return $this->count;
}
public function read_list()
{
$listData = array();
$current = $this->first_node;
while($current != NULL)
{
echo $current->read_node().' ';
$current = $current->next;
}
}
public function reverse_list()
{
if(($this->first_node != NULL)&&($this->first_node->next != NULL))
{
$current = $this->first_node;
$new = NULL;
while ($current != NULL)
{
$temp = $current->next;
$current->next = $new;
$new = $current;
$current = $temp;
}
$this->first_node = $new;
}
}
public function read_node($position)
{
if($position <= $this->count)
{
$current = $this->first_node;
$pos = 1;
while($pos != $position)
{
if($current->next == NULL)
return null;
else
$current = $current->next;
$pos++;
}
return $current->data;
}
else
return NULL;
}
public function insert($data)
{
$new_node = new ListNode($data);
if($this->first_node != NULL)
{
$this->last_node->next = $new_node;
$new_node->next = NULL;
$this->last_node = &$new_node;
$this->count++;
}
else
{
$new_node->next = $this->first_node;
$this->first_node = &$new_node;
if($this->last_node == NULL)
$this->last_node = &$new_node;
$this->count++;
}
}
}
//Create linked list
$link1 = new LinkList();
//Insert elements
$link1->insert('a');
$link1->insert('b');
$link1->insert('c');
$link1->insert('d');
$link1->insert('e');
$link1->insert('f');
$link1->insert('g');
$link1->insert('h');
$link1->insert('i');
$link1->insert('j');
echo "<b>Input :</b><br>";
$link1->read_list();
//function to reverse linked list in specified manner
function reverseLinkedList(&$link1)
{
$size= $link1->size();
if($size>2)
{
$link2=new LinkList();
$link2->insert($link1->read_node(1));
$elements_covered=1;
//reverse
$rev_size=2;
while($elements_covered<$size)
{
$start=$elements_covered+1;
$temp_link = new LinkList();
$temp_link->insert($link1->read_node($start));
for($i=1;$i<$rev_size;$i++)
{
$temp_link->insert($link1->read_node(++$start));
}
$temp_link->reverse_list();
$temp_size=$temp_link->size();
$link2_size=$link2->size();
for($i=1;$i<=$temp_size;$i++)
{
$link2->insert($temp_link->read_node($i));
++$elements_covered;
++$link2_size;
}
++$rev_size;
}
///reverse
//Flip the linkedlist
$link1=$link2;
}
}
///function to reverse linked list in specified manner
//Reverse current linked list $link1
reverseLinkedList($link1);
echo "<br><br><b>Output :</b><br>";
$link1->read_list();
It's O(n)...just one traversal.
And secondly, here tagging it in language is not necessary.
I have provided a Pseudocode here for your reference:
current => head_ref
prev => NULL;
current => head_ref;
next => null;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;

How to perform Image comparison in Appium?

I need one help.
I am using Appium and I have a scenerio wherein I need to capture an image from the app under test, preserve that image as a baseline image and then capture another image from that app under test and then perform an image comparison between these two images.
Can anyone guide me how to do this please.
This is how you do it:
#Test(dataProvider = "search")
public void eventsSearch(String data) throws InterruptedException, IOException {
Thread.sleep(2000);
boolean status = false;
//WebElement img = driver.findElementByClassName("android.widget.ImageView");
//take screen shot
File screen = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
// for (String event : events) {
driver.findElementById("your id")
.sendKeys(data);
driver.hideKeyboard();
List<WebElement> list = driver
.findElementsByXPath("//*[#class='android.widget.TextView' and #index='1']");
System.out.println(list.size());
int i = 0;
for (WebElement el : list) {
String eventList = el.getText();
System.out.println("events" + " " + eventList);
if (eventList.equals("gg")) {
status = true;
break;
}
i++;
}
//capture image of searched contact icon
List<WebElement > imageList = driver.findElementsByXPath("//*[#class='android.widget.ImageView' and #index='0']");
System.out.println(imageList.size());
System.out.println(i);
WebElement image = imageList.get(1);
Point point = image.getLocation();
//get element dimension
int width = image.getSize().getWidth();
int height = image.getSize().getHeight();
BufferedImage img = ImageIO.read(screen);
BufferedImage dest = img.getSubimage(point.getX(), point.getY(), width,
height);
ImageIO.write(dest, "png", screen);
File file = new File("Menu.png");
FileUtils.copyFile(screen, file);
//verify images
verifyImage("Menu.png", "Menu.png" );
//Assert.assertTrue(status, "FAIL Event doesn't match" + data);
}
#DataProvider(name = "search")
public Object[][] searchData() {
return new Object[][] { { "gg" } };
}
public void verifyImage(String image1, String image2) throws IOException{
File fileInput = new File(image1);
File fileOutPut = new File(image2);
BufferedImage bufileInput = ImageIO.read(fileInput);
DataBuffer dafileInput = bufileInput.getData().getDataBuffer();
int sizefileInput = dafileInput.getSize();
BufferedImage bufileOutPut = ImageIO.read(fileOutPut);
DataBuffer dafileOutPut = bufileOutPut.getData().getDataBuffer();
int sizefileOutPut = dafileOutPut.getSize();
Boolean matchFlag = true;
if(sizefileInput == sizefileOutPut) {
for(int j=0; j<sizefileInput; j++) {
if(dafileInput.getElem(j) != dafileOutPut.getElem(j)) {
matchFlag = false;
break;
}
}
}
else
matchFlag = false;
Assert.assertTrue(matchFlag, "Images are not same");
}

SharpDX / XAudio2 : Sending a SourceVoice through a SubmixVoice

I can't figure this out, how do I route a SourceVoice through a Submixvoice? The C++ examples on the net suggest I can use effect chains, but there's no EffectChain constructor or functions that accept voices. Here're the basics:
private XAudio2 xa = null;
private MasteringVoice mv = null;
private SourceVoice sv = null;
private SubmixVoice sm = null;
private SoundStream ss = null;
private AudioBuffer ab = null;
private WaveFormat wf = null;
private FilterParameters fp;
private bool sv_playing = false;
private void button1_Click(object sender, EventArgs e)
{
if (null == xa)
{
xa = new XAudio2();
mv = new MasteringVoice(xa);
var nativefilestream = new NativeFileStream(
#"c:\dev\beat_loop.wav",
NativeFileMode.Open,
NativeFileAccess.Read,
NativeFileShare.Read);
ss = new SoundStream(nativefilestream);
wf = ss.Format;
ab = new AudioBuffer
{
Stream = ss.ToDataStream(),
AudioBytes = (int)ss.Length,
Flags = BufferFlags.EndOfStream
};
fp.Frequency = 1.0f;
fp.OneOverQ = 1.0f;
fp.Type = FilterType.LowPassFilter;
}
if (sv_playing)
{
if (null != sv)
{
sv.Stop();
sv.Dispose();
sv = null;
}
}
if (null == sv)
{
sv = new SourceVoice(xa, wf,VoiceFlags.None,1.0f, true);
sv.SubmitSourceBuffer(ab, ss.DecodedPacketsInfo);
sv.BufferEnd += new Action<IntPtr>(sv_BufferEnd);
sm = new SubmixVoice(xa, ss.Format.Channels, ss.Format.SampleRate, VoiceSendFlags.UseFilter,10);
sm.SetFilterParameters(fp);
// HOW DO I TELL sv TO ROUTE THROUGH sm??
sv.Start();
sv_playing = true;
}
}
You can use the VoiceSendDescriptor class to route source voices to submix voices
VoiceSendDescriptor vs = new VoiceSendDescriptor(VoiceSendFlags.None, sm);
sv.SetOutputVoices(vs);

Resources