Clair does not parse header files correctly for pointers in arguments - abstract-syntax-tree

I am parsing a header file using Rascal ClaiR:
iFile = toLocation("file://D:/test.h");
ast = parseCpp(iFile);
iprint(ast);
The header file test.h looks as follows:
#ifndef TEST_H
#define TEST_H
/* Generic function */
result_t API get_data(query_h query, char **string, result_t *res);
result_t API set_data(node_h node, const char *string);
result_t API update_data(node_h node, char ***names, uint32_t *count);
#endif
As an outcome I get multiple errors like this:
decl=|cpp+parameter:///update_data(org.eclipse.cdt.internal.core.dom.parser.ProblemType#53e470da,char...,%3F.)/count|),
Is this a bug in ClaiR?

Related

Qt logical error during getting user's input from terminal via getline function and writing it into a file

Using console, I want to write the desired user's input into a file via getline function inside the wFile function and then read it. I face with logical error during Runtime; whatever I as user write doesn't type into the output terminal and it doesn't succeed more steps. Apparently fwrite function with this feature in the libraries exists, but I want to write my own code differently this way. I think I must have neglected a point. Here's the code:
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <String>
#include <cstdlib>
using namespace std;
void wFile(QString Filename)
{
QFile mFile(Filename);
QTextStream str(&mFile);
qDebug() << "what do you want to write in the desired file: ";
istream& getline (istream& is, string& str);
if (!mFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "could not open the file";
return;
}
mFile.flush();
mFile.close();
}
void read (QString Filename){
QFile nFile(Filename);
if(!nFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "could not open file for reading";
return;
}
QTextStream in(&nFile);
QString nText = in.readAll();
qDebug() << nText;
nFile.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString nFilename ="P:/DocumentArminV.txt";
wFile(nFilename);
read(nFilename);
return a.exec();
}
Spoiler alarm: At the very end of this answer, there is a very simple recommendation for a fix.
What OP did
Concerning istream& getline (istream& is, string& str); in wFile(QString Filename):
This declares function getline() in function wFile().
This is a valid declaration concerning C++.
Concerning the sample code, I missed the respective headers. IMHO,
#include <istream> and
#include <string>
are required to make this compiling.
However, it is possible that the existing #includes include them indirectly. So, OP's code may even compile without them.
Declaring functions, which are not used as well as re-declaring functions which are already declared is somehow useless but not wrong.
To demonstrate this, I made a small sample:
#include <cstdio>
#include <istream>
#include <string>
void func()
{
puts("in func()\n");
std::istream& getline(std::istream&, std::string&);
// Even duplicated prototyping is accepted without complaints:
std::istream& getline(std::istream&, std::string&);
}
int main ()
{
func();
return 0;
}
compiles and runs perfectly.
Output:
in func()
Live Demo on coliru
What OP (probably) wanted
Using console, I want to write the desired user's input into a file via getline function inside the wFile function and then read it.
This sounds a bit confusing to me. std::getline(std::cin, ) can be used to read user input from console. May be, it's a bit bad wording only.
Assuming, the OP wanted to read input from console, obviously, declaring a function is not sufficient – it must be called to become effective:
#include <iostream>
void func()
{
std::cout << "Enter file name: ";
std::string fileName; std::getline(std::cin, fileName);
std::cout << "Got file name '" << fileName << "'\n");
}
int main ()
{
func();
return 0;
}
Output:
Enter file name: test.txt↵
Got file name 'test.txt'
Live Demo on coliru
C++ std vs. Qt
Qt is undoubtly built on top of the C++ std library. However, though it's possible it is not recommended to mix both APIs when it can be prevented (or there aren't specific reasons to do so).
Both, Qt and C++ std, are a possibility to write portable software.
Qt covers a lot of things which are provided in the std library as well but a lot of other things additionally which are not or not yet part of std. In some cases, the Qt is a bit less generic but more convenient though this is my personal opinion. IMHO, the following explains how I came to this:
std::string vs. QString
std::string stores a sequence of chars. The meaning of chars when exposed as glyph (e.g. printing on console or displaying in a window) depends on the encoding which is used in this exposing. There are lot of encodings which interprete the numbers in the chars in distinct ways.
Example:
std::string text = "\xc3\xbc";
Decoded/displayed with
Windows-1252: ü
UTF-8: ü
Based on character type of std::string, it is not possible to determine the encoding. Hence, an additional hint must be provided to decode this properly.
(AFAIK, it is similar for std::wstring and wchar_t.)
QString stores a sequence of Unicode characters. So, one universal encoding was chosen by design to mitigate the "encoding hell".
As long as the program operates on QString, no encoding issues should be expected. The same is true when combining QString with other functions of Qt. However, it becomes a bit more complicated when "leaving the Qt universe" – e.g. storing contents of a std::string to QString.
This is the point where the programmer has to provide the additional hint for the encoding of the contents in std::string. QString provides a lot of from...() and to...() methods which can be used to re-encode contents but the application programmer is still responsible to chose the right one.
Assuming that the intended contents of text should have been the ü (i.e. UTF-8 encoding), this can be converted to QString (and back) by:
// std::string (UTF-8) -> QString
std::string text = "\xc3\xbc";
QString qText = QString::fromUtf8(text.c_str());
// QString -> std::string (UTF-8)
std::string text2 = qText.toUtf8();
This has to be considered when input from std::cin shall be passed to QString:
std::cout << "Enter file name: ";
std::string input; std::getline(std::cin, input);
QString qFileName = QString::fromLocal8Bit(input);
And even now, the code contains a little flaw – the locale of std::cin might have changed with std::ios::imbue(). I must admit that I cannot say much more about this. (In daily work, I try to prevent this topic at all e.g. by not relying on Console input which I consider especially critical on Windows – the OS on which we usually deploy to customers.)
Instead, a last note about OP's code:
How to fix it
Remembering my above recommendation (not to mix std and Qt if not necessary), this can be done in Qt exclusively:
QTextStream qtin(stdin);
qtin.readline();
I must admit that I never did it by myself but found this in the Qt forum: Re: stdin reading.

Qt QFile / QTemporaryFile cannot read or write

I have no idea why, but i can´t get the simplest example of QTemporaryFile to run... My real intent is to write data from QAudioInput into a temporary file before it is processed later.
After trying several times I realized that neither .read(), .readLine(), .readAll() or .write() would have any effect... The error string is always "Unknown Error" and it neither works for QFile or QTemporaryFile.
#include <QCoreApplication>
#include <QTemporaryFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTemporaryFile tf;
tf.open();
tf.write("Test");
QTextStream in(&tf);
qDebug() << "Testprogramm";
qDebug() << tf.isOpen();
qDebug() << tf.errorString();
qDebug() << in.readLine();
qDebug() << tf.readAll();
tf.close();
return a.exec();
}
The debug posts:
Testprogramm
true
"Unknown error"
""
""
Thank you in advance!
You need to move the file pointer back to the beginning of the file. This has to be done on the file itself when there's no stream on the file, or using the stream when one exists. Also - QFile is a proper C++ class that manages the file resource. There's no need to manually close the file. QFile::~QFile does that job.
The following works just fine:
#include <QtCore>
int main() {
auto line = QLatin1String("Test");
QTemporaryFile tf;
tf.open();
Q_ASSERT(tf.isOpen());
tf.write(line.data());
tf.reset(); // or tf.seek(0)
QTextStream in(&tf);
Q_ASSERT(in.readLine() == line);
in.seek(0); // not in.reset() nor tf.reset()!
Q_ASSERT(in.readLine() == line);
}
The above also demonstrates the following techniques applicable to sscce-style code:
Inclusion of entire Qt module(s). Remember that modules include their dependencies, i.e. #include <QtWidgets> is sufficient by itself.
Absence of main() arguments where unnecessary.
Absence of QCoreApplication instance where unnecessary. You will get clear runtime errors if you need the application instance but don't have one.
Use of asserts to indicate conditions that are expected to be true - that way you don't need to look at the output to verify that it is correct.
Use of QLatin1String over QStringLiteral where ASCII strings need to be compared to both C strings and QStrings. Implicit ASCII casts can be a source of bugs and are discouraged.
QLatin1String is a constant (read-only) wrapper, designed to wrap C string literals - thus there's no need to make line additionally const, although in real projects you'd want to follow the project's style guide here.

qUncompress: Z_DATA_ERROR: Input data is corrupted

I am using the qUncompress of Qt and head to a problem I cant find more information to solve it.
Here is my code:
#include <QCoreApplication>
#include <QByteArray>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile f("/user/XXXXX/home/AgeRegression"); // hided
if (f.exists())
qDebug() << "File exists";
else
qDebug() << "Missing file";
f.open(QIODevice::ReadOnly);
QByteArray qb = f.readAll();
qb = qUncompress(qb);
qDebug()<<"Successfully";
const char *qt_version = qVersion();
qDebug()<< QString(qt_version);
return a.exec();
}
Here is the output:
File exists
qUncompress: Z_DATA_ERROR: Input data is corrupted
Successfully
"5.3.2"
From the documentation of Qt(you can find here):
Note: If you want to use this function to uncompress external data that was compressed using zlib, you first need to prepend a four byte header to the byte array containing the data. The header must contain the expected length (in bytes) of the uncompressed data, expressed as an unsigned, big-endian, 32-bit integer.
So what exactly should I do here? Do I have to find the length of uncompressed data (is there a way? I just have compressed data.)? An example would be appreciated.
qUncompress is not a general-purpose decompression function. It should only be used with data compressed with qCompress.
If your data was compressed using something other than qCompress, you must decompress it in the same way - using zlib directly, using an external utility, etc.
By using qUncompress like you do, you're relying on an implementation detail that may change at any moment. Don't do that. Simply assume that qCompress is a black box and uses an alien compressor implementation that nobody else does.

atmel studio ifndef compilation error

Hi imy project recognises double definitions of variables that do not exist 2 times. I suppose that some how by changing my code and recompiling it stucks.
LedMatrix7219.cpp.o:(.data.Alphaletter+0x0): multiple definition of `Alphaletter' LedController.cpp.o:(.data.Alphaletter+0x0): first
defined here
LedMatrix7219.cpp.o:In function `loop'
LedController.cpp.o:(.bss.arr+0x0): first defined here
LedMatrix7219.cpp.o:In function `loop'
LedController.cpp.o:(.data.Alphaletter2+0x0): first defined here
collect2.exe*:error: ld returned 1 exit status
I have a class LedController and a header LettersDefinition.h
All the headers start like this:
I am including a struct and an enum from the LetterDefinition.h to the LedController so at the header i need to include the LetterDefinition.h in order to make a certain struck.
#ifndef __LEDCONTROLLER_H__
#define __LEDCONTROLLER_H__
#include <Arduino.h>
#include "LettersDefinition.h"
LetterStruct finalText;
String theText="Test";
void test();
//it does some extra staff
#endif //__LEDCONTROLLER_H__
And the header of the letter definition.
#ifndef LETTERSDEFINITION_H_
#define LETTERSDEFINITION_H_
#include "arduino.h"
#include <avr/pgmspace.h>
struct LetterStruct{
lettersEnum name;
uint8_t size;
uint8_t columnSize[5];
uint8_t data[18];
}Alphaletter;
#endif /* LETTERSDEFINITION_H_ */
And from my main .ide file i call the test function of the Ledcontroller i a get the error you see above. The test fuction just checks the LetterStruct.name variable nothing more.
My .ide is something like:
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Max72xxPanel.h>
#include "LedController.h"
LedController controller;
void setup()
{
//irrelevant inits
}
void loop()
{
controller.test();
delay(2000);
}
If i delete the #include "LettersDefinition.h" from the LedController.h this error gives its place to an error that the LetterStruct is not defined in the LedController.h which is normal since i have to add the LettersDefinition.h in order to be defined.
Your problem originates that you "define" variables in header files. This in general will lead to the multiple definition problem and is not standard design.
The model you need to follow is to define once in a source file:
//some.cpp
// this is define
int variableX = 5;
And declare in the header file:
//some.h
// this is declare
extern int variableX;
Every other source file that includes the header just processes the "extern" line, which says roughly "there is an int variableX that will exist in the final program". The compiler runs over every .cpp .c file and creates a module. For the some.cpp that defines the variable, it will create the variableX. All the other .cpp files will just have the extern reference which is a placeholder. The linker will resolve those placeholders when it combines all the modules together.
In your specific case, this means changing:
// .h file should only be externs:
extern LetterStruct finalText;
extern String theText;
// .cpp file contains definitions
LetterStruct finalText;
String theText="Test";

C++: OpenSSL, aes cfb encryption [duplicate]

I tried to implement a "very" simple encryption/decryption example. I need it for a project where I would like to encrypt some user information. I can't encrypt the whole database but only some fields in a table.
The database and most of the rest of the project works, except the encryption:
Here is a simplified version of it:
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
/* ckey and ivec are the two 128-bits keys necessary to
en- and recrypt your data. Note that ckey can be
192 or 256 bits as well
*/
unsigned char ckey[] = "helloworldkey";
unsigned char ivec[] = "goodbyworldkey";
int bytes_read;
unsigned char indata[AES_BLOCK_SIZE];
unsigned char outdata[AES_BLOCK_SIZE];
unsigned char decryptdata[AES_BLOCK_SIZE];
/* data structure that contains the key itself */
AES_KEY keyEn;
/* set the encryption key */
AES_set_encrypt_key(ckey, 128, &keyEn);
/* set where on the 128 bit encrypted block to begin encryption*/
int num = 0;
strcpy( (char*)indata , "Hello World" );
bytes_read = sizeof(indata);
AES_cfb128_encrypt(indata, outdata, bytes_read, &keyEn, ivec, &num, AES_ENCRYPT);
cout << "original data:\t" << indata << endl;
cout << "encrypted data:\t" << outdata << endl;
AES_cfb128_encrypt(outdata, decryptdata, bytes_read, &keyEn, ivec, &num, AES_DECRYPT);
cout << "input data was:\t" << decryptdata << endl;
return 0;
}
But the output of "decrypted" data are some random characters, but they are the same after every execution of the code. outdata changes with every execution...
I tried to debug and search for a solution, but I couldn't find any solution for my problem.
Now my question, what is going wrong here? Or do I completely misunderstand the provided functions?
The problem is that AES_cfb128_encrypt modifies the ivec (it has to in order to allow for chaining). Your solution is to create a copy of the ivec and initialize it before each call to AES_cfb128_encrypt as follows:
const char ivecstr[AES_BLOCK_SIZE] = "goodbyworldkey\0";
unsigned char ivec[AES_BLOCK_SIZE];
memcpy( ivec , ivecstr, AES_BLOCK_SIZE);
Then repeat the memcpy before your second call to AES_cfb128_encrypt.
Note 1: Your initial vector was a byte too short, so I put an explicit additional \0 at the end of it. You should make sure all of your strings are of the correct length when copying or passing them.
Note 2: Any code which uses encryption should REALLY avoid using strcpy or any other copy of unchecked length. It's a hazard.

Resources