Running compiled code on another machine crash (mingw-w64 32 and 64 bit toolchain ) cryptopp - crypto++

I have one problem that I can't understand.
First I am making program that is using Crypto++ for RSA. I have separated toolchain for 32bit and 64bit mingw-w64. So I downloaded cryptopp source and build it for 2 times for 32 bit and 64bit and copied lib and include files. I used default make...
So I have compile my code and with static libraries and when I run it on machine that is compiled,32bit and 64bit works ok. But When I copy it to another machine XP 64bit or Win7 32bit it crash on runtime. On Win7 I use only 32bit and on XP I use 32 and 64.
I was searching for a while and found that it crash on this code:
StringSource ss1(message, true,
new SignerFilter(rng, signer,
new StringSink(signature)
)
);
But running only this it doesn't crash.
new SignerFilter(rng, signer,
new StringSink(signature)
)
Does anyone have a clue what can it be?
This is my test code
AutoSeededRandomPool rng;
string privKey, privKey_Base64 =
"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMm4ybhUat8MwkHwWxwEFQ/7\
0wsJIT+Y3sIUFhwF8BslsJrhkTYYbhMYM9gHi/T5Y0m75h4jXesZNgfv0SUie1/6aWe61eZG\
bCMUgWh/6+onNtQOiJV88VgxBJG45OOinlG3l7NJpZZukiEXNqlv4dj2mWLgt6cIC8Gz2QQh\
cb9zAgERAoGANWWezukrWSkGPqGBh2p+C8KozjcfY6h3M1+rf+N0Q2vb7MM9Bso7QUor101K\
scmLOSo1YlSn62iOTWUgxhCoL4WbZK2UDxrMhdtEV+i4jtkopceJF6x5XBOBYdKPjEbJxd2m\
FPMBxA8NaI4D+WdSGCrzCSmAAp/A1qHFJZErdXkCQQD7P7htvv3slqYQMJZB+BLVMnE7TNOY\
YLCxbAVRTM70pvE/sn9DwXQEJQcOTavv6hr1AU0OC70KtYxQDo5eN7ppAkEAzYlPaAQEn0Kf\
x/lNQI/0j2rUGlJMA6m9bsw3TCR0hhmRa3HIb912o1bkYi9PTvp/JnO6UlaKvkTRq1N2EJXX\
ewJBAN2wsco/HEk5oZXQhJSPmCWG3GGABf7r5zMjE8A0tpuiXGVhQx2qsalN2Qye4wDdn1Cm\
y4TdLlS+TqD9yOm4s4kCQQC1WwnUP8fX0V/OkK2TUdfJ1rsmSJ1spNRStDDKtsErB4BPvr/q\
O+EmthTPGq9jzfe4hDr9W2tclxNa70oOolS3AkEA7qZDM0BHALxK/2Q6lU2zpjfh1gUxLAlg\
OGyIGTafq1o0y2b5HGrmwVYQAGaUPlBLVRLRBxhL+kXnSzXhTR1xRA==\
";
CryptoPP::StringSource tasdst(privKey_Base64, true, new CryptoPP::Base64Decoder(new CryptoPP::StringSink(privKey)));
string pubKey, pubKey_Base64 =
"MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDJuMm4VGrfDMJB8FscBBUP+9MLCSE/mN7C\
FBYcBfAbJbCa4ZE2GG4TGDPYB4v0+WNJu+YeI13rGTYH79ElIntf+mlnutXmRmwjFIFof+vq\
JzbUDoiVfPFYMQSRuOTjop5Rt5ezSaWWbpIhFzapb+HY9pli4LenCAvBs9kEIXG/cwIBEQ==\
";
CryptoPP::StringSource tasdst2(pubKey_Base64, true, new CryptoPP::Base64Decoder(new CryptoPP::StringSink(pubKey)));
RSA::PrivateKey privateKey;
char const *a = privKey.c_str();
size_t dataLen = privKey.size();
privateKey.Load(CryptoPP::StringStore((const byte*)a,(size_t)dataLen).Ref());
RSA::PublicKey publicKey;
char const *b = pubKey.c_str();
dataLen = pubKey.size();
publicKey.Load(CryptoPP::StringStore((const byte*)b,(size_t)dataLen).Ref());
string message = "RSA Signature", signature;
std::cout << message << std::endl;
RSASSA_PKCS1v15_SHA_Signer signer(privateKey);
StringSource ss1(message, true,
new SignerFilter(rng, signer,
new StringSink(signature)
)
);
string encoded, decoded;
CryptoPP::StringSource(signature, true, new CryptoPP::Base64Encoder(new CryptoPP::StringSink(encoded)));
CryptoPP::StringSource tasdst3(encoded, true, new CryptoPP::Base64Decoder(new CryptoPP::StringSink(decoded)));
RSASSA_PKCS1v15_SHA_Verifier verifier(publicKey);
StringSource ss2(message+decoded, true,
new SignatureVerificationFilter(
verifier, NULL,
SignatureVerificationFilter::THROW_EXCEPTION
)
);

After just a little looking around. I found out that there is problem with building libcryptopp and just a few lines of code fixed symptoms that was before.
Here is what to change in GNUmakefile:
https://sites.google.com/site/ievgensychov/cryptopp
Yes, problem is solved.

Related

nvwgf2umx.dll CComPtr Crash Sometimes

I am receiving a very strange bug right now. I'm currently writing a small project in DirectX 11 and making use of ATL CComPtr's for the COM components. In one instance, I'm wrapping an ID3D11Buffer in a CComPtr. In most of my application, this has been fine and seen no crashes, however, for some reason in this very particular instance, I'm crashing occasionally.
ZeroMemory(&bd, sizeof(bd));
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bd.ByteWidth = sizeof(MiscCBuffer);
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;
hr = device->CreateBuffer(&bd, nullptr, &_gcVoxelBuffer);
if (FAILED(hr)) {
throw std::exception("[E] Creating constant buffer in TerrainComponent onAwake.");
}
This is the code I'm using to create the constant buffer. The CPU buffer's values are set like this
float dimX = _instanceDimensions.x;
float dimY = _instanceDimensions.y;
float dimZ = _instanceDimensions.z;
_cVoxelBuffer.misc.x = dimX;
_cVoxelBuffer.misc.y = dimY;
_cVoxelBuffer.misc.z = dimZ;
_cVoxelBuffer.misc.w = 0;
The MiscCBuffer struct only holds a XMFLOAT4. Finally, to update the constant buffer on the GPU with the CPU data, I use this code.
updateD11Buffer(_gcVoxelBuffer, _cVoxelBuffer, context);
template <class T>
updateD11Buffer(const CComPtr<ID3D11Buffer>& gcBuffer, const T& cbuffer, const CComPtr<ID3D11DeviceContext>& ctx){
D3D11_MAPPED_SUBRESOURCE mappedResource;
ZeroMemory(&mappedResource, sizeof(D3D11_MAPPED_SUBRESOURCE));
ctx->Map(gcBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
memcpy(mappedResource.pData, &cbuffer, sizeof(cbuffer));
ctx->Unmap(gcBuffer, 0);
}
As for the error itself, it sometimes happens when the program first launches. It could successfully launch 10 times in a row, and then fail the next 3 times.
Exception thrown at 0x00007FFB003B273B (nvwgf2umx.dll) in ECS_Simulation.exe: 0xC0000005: Access violation reading location 0x000001BE69F9F000.
I have tried reading online but a lot of posts regarding nvwgf2umx.dll crashing with an access violation come from shipped game titles, other posts regarding access violations are usually caused by NULL pointers. In my case, I have checked the _gcVoxelBuffer and _gcVoxelBuffer.p, both of which are valid pointers.
In addition, the D3D Context object is pointing to a valid location, and the CPU side buffer object is also valid to the best of my knowledge.
I'm not sure if this is really the problem, but it's a problem.
Instead try:
template <class T>
updateD11Buffer(const CComPtr<ID3D11Buffer>& gcBuffer, const T& cbuffer, const CComPtr<ID3D11DeviceContext>& ctx)
{
D3D11_MAPPED_SUBRESOURCE mappedResource = {};
if (SUCCEEDED(ctx->Map(gcBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource))
{
memcpy(mappedResource.pData, &cbuffer, sizeof(cbuffer));
ctx->Unmap(gcBuffer, 0);
}
}
ZeroMemory is ancient Win32 pattern. With C++11 or later compilers, uniform initialization is much easier to use.
Note that a more flexible design would be:
template <class T>
updateD11Buffer(ID3D11Buffer* gcBuffer, const T& cbuffer, ID3D11DeviceContext* ctx)
{
...
}
// call using updateD11Buffer(_gcVoxelBuffer.Get(), _cVoxelBuffer, context.Get());
This version doesn't force the use of a particular smart-pointer, and is less of a "thick syntax forest".
PS: ATL's CComPtr is a bit dated and has a few quirks to it. For example, &_gcVoxelBuffer assumes that _gcVoxelBuffer is always null so you can easily get resource leaks.
You should take a look at WRL's ComPtr which is "ATL 2.0". See this article.

IBM HP5Si Print Stream to XPS print driver

I am hoping someone can have suggestions about this issue.
We have a custom driver taken from https://learn.microsoft.com/en-us/samples/microsoft/windows-driver-samples/xpsdrv-driver-and-filter-sample/
The print driver works well and outputs XPS when the documents are opened in MS word or PDF. But when a document is printed from HP5Si series printer, the driver returns 0 bytes. The job is sent from HP5Si printer to the XPS driver. Why is the driver rejecting this input when the source is a HP series printer. What can I do to fix it?
The printer on the AS400 is setup with an IBM HP5Si driver and sends the job to a windows service on a server. This windows service routes the job to XPS driver as if it were an HP series printer. The XPS driver processes this job and returns XPS to the windows service. The windows service then converts to a tiff file.
For some reason if printing is done using this workflow XPS driver returns 0.
If the same document is opened in word or notepad or any not AS400+ HP, it works and XPS is returned.
To prove my theory, I sent a PCL file in C# code to the driver and it returned 0 bytes.
public static void SendBytesToPrinterPCL(string printerName, string szFileName) {
IntPtr lhPrinter;
OpenPrinter(printerName, out lhPrinter, new IntPtr(0));
if (lhPrinter.ToInt32() == 0) return; //Printer not found!!
var rawPrinter = new DOCINFOA() {
pDocName = "My Document",
pDataType = "RAW"
};
StartDocPrinter(lhPrinter, 1, rawPrinter);
using(var b = new BinaryReader(File.Open(szFileName, FileMode.Open))) {
var length = (int) b.BaseStream.Length;
const int bufferSize = 8192;
var numLoops = length / bufferSize;
var leftOver = length % bufferSize;
for (int i = 0; i < numLoops; i++) {
var buffer = new byte[bufferSize];
int dwWritten;
b.Read(buffer, 0, bufferSize);
IntPtr unmanagedPointer = Marshal.AllocHGlobal(buffer.Length);
Marshal.Copy(buffer, 0, unmanagedPointer, buffer.Length);
WritePrinter(lhPrinter, unmanagedPointer, bufferSize, out dwWritten);
Marshal.FreeHGlobal(unmanagedPointer);
}
if (leftOver > 0) {
var buffer = new byte[leftOver];
int dwWritten;
b.Read(buffer, 0, leftOver);
IntPtr unmanagedPointer = Marshal.AllocHGlobal(buffer.Length);
Marshal.Copy(buffer, 0, unmanagedPointer, buffer.Length);
WritePrinter(lhPrinter, unmanagedPointer, leftOver, out dwWritten);
Marshal.FreeHGlobal(unmanagedPointer);
}
}
EndDocPrinter(lhPrinter);
ClosePrinter(lhPrinter);
}
string filePath = #"C:\Users\tom\Desktop\form.PCL";
string szPrinterName = #"\\server\xpsdrv";
Print.SendBytesToPrinterPCL(szPrinterName, filePath);
Then I sent a regular text file to the driver and it successfully converted to XPS.
public static void SendToPrinterNonPCL(string filePath)
{
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.FileName = filePath;
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = new Process();
p.StartInfo = info;
p.Start();
p.WaitForInputIdle();
System.Threading.Thread.Sleep(3000);
if (false == p.CloseMainWindow())
p.Kill();
}
string filePath = #"C:\Users\tom\Desktop\form.txt";
string szPrinterName = #"\\server\xpsdrv";
Print.SendToPrinterNonPCL(filePath);
Why doesn't the driver in Microsoft samples accept PCL? What should I do. I am not a driver developer. This project was given to me.
EDIT:
Initally I didn't know of this printing from AS400. Our legacy driver was built 15 years back. The developer wrote a custom print driver to PCL and a Custom converter to Tiff. But the driver only supported monochrome. I am not a driver expert or a PCL expert or a converter expert. In order to support color and less pixelated feel for the final Tiff, I decided to change it to a XPS driver. Also it is less custom code and could use Microsoft's XPS conversion in WPF. It is not a very big learning curve for a non-driver development person compared to learning PCL and then changing the converter to accomodate color Tiff. But I guess it is falling apart since the users also print from AS400 which sends PCL.
Do you know any good products which we could purchase a license to? We need a PCL driver and a converter to Tiff
Thank you

Cannot open file on Ubuntu

I'm using Ubuntu 14 and trying to create a script to write files, but I'm getting the 5004 error, every time I try to open a file.
datetime currtime;
bool newcandle;
string terminal_data_path = TerminalInfoString( TERMINAL_DATA_PATH );
string filename = terminal_data_path + "\\MQL4\\Files\\" + "data.csv";
int filehandle;
filehandle = FileOpen( filename, FILE_WRITE | FILE_CSV );
if ( filehandle < 0 ){
Print( "Failed to open the file by the absolute path " );
Print( "Error code ", GetLastError() );
}
else {
Print( "file opened with sucess" );
}
How can I solve this problem on Ubuntu?
UPDATE
I tried to change my file to the following:
string terminal_data_path = TerminalInfoString( TERMINAL_DATA_PATH );
string filename = terminal_data_path + "\\tester\\files\\data.csv";
and just for this
string filename = "\\tester\\files\\data.csv";
and for this
string filename = "\\files\\data.csv";
But I'm still getting error, but this time is 5002 not 5004.
MQL4 Permissions By Design Do Not Allow / Restrict FileIO
There are three directories (with subdirectories) where working files can be placed:
/HISTORY/<current broker> - especially for the FileOpenHistory() function;
/EXPERTS/FILES - common case;
/TESTER/FILES - especially for testing ( ref. during Strategy Tester operations ).
Working with files from other directories is prohibited.
Solution
Adapt your MQL4-code so as to meet this fact and respect pre-Build 762 and post-Build 762 differences ( a "new"-MQL4 file-localisations ).
Update
As posted, your MQL4-code ( whether you share it's updated state or not ) shall better handle exceptions. Have met several suprising artefacts with filenames. Some platform specific, causing no harm in wXP, but failing to operate (the same code) on VPS-hosted wServer2008 VM or a LinuxVM-encapsulated Wine/MT4 instance.
Carefully read MQL4-help documentation and create a few post-mortem tools to step further.
5002
ERR_FILE_WRONG_FILENAME
Wrong file name -------> pre-test + "fuse" the corner cases
5003
ERR_FILE_TOO_LONG_FILENAME
Too long file name
5004 <------ a good sign, we are on the safer side here
ERR_FILE_CANNOT_OPEN
Cannot open file
//-------------------------------------------------------------
// MT4_GUI_postMortem
//-------------------------------------------------------------
void MT4_GUI_postMortem( string aFileNAME = "caller forgot to pass aFileNAME"
){
// SYNTAX
// if ( aFileHANDLE == INVALID_HANDLE ) MT4_GUI_postMortem( filename );
//
int aLastErrorNUM = GetLastError();
Comment( "POST-MORTEM >>> [", aFileNAME, "] Threw error ", aLastErrorNUM );
Print( "POST-MORTEM >>> [", aFileNAME, "] Threw error ", aLastErrorNUM );
return;
}

System.OutOfMemoryException while writing to excel

Public Function GenerateReportAsExcel()
Dim workbook = WorkbookFactory.Create(template)
template.Close()
Dim worksheet = workbook.GetSheetAt(0)
// Writing record to worksheet
Dim workbookStream = New MemoryStream()
workbookStream.Flush()
workbookStream.Position = 0
workbook.Write(workbookStream) //throws error if the rocord is more then 500000...runs fine for 400000
Return New MemoryStream(workbookStream.ToArray())
End Function
WorkbookFactory is using NPOI.SS.UserModel ....
Is there a way to increase the memory stream capacity? I am getting System.OutOfMemoryException while writing 500000 record to the excel but upto 400000 record works fine.
I found couple of similar issue but not getting any solid solution to this problem...
Someone one suggested to use
workbookStream.Flush()
workbookStream.Position = 0
but not of any help....
Thanks for the concern..
What environment you are running in?
If it's 32 bit you get OutOfMemoryException at aprox. 500meg memory stream.
static void Main(string[] args)
{
var buffer = new byte[1024 * 1024];
Console.WriteLine(IntPtr.Size);
using (var memoryStream = new MemoryStream())
{
for (var i = 0; i < 100000000; i++)
{
try
{
memoryStream.Write(buffer, 0, 1024);
}
catch (OutOfMemoryException e)
{
Console.WriteLine("Out of memory at {0} meg", i);
break;
}
}
}
Console.ReadKey();
}
If you run on a 64bit os, make sure you build with 'Prefer 32 bit' switch off.
Turn off the switch in project properties:
I would recommend using a FileStream instead of MemoryStream here.
The following code adds nothing, so you can let it go:
workbookStream.Flush() ' Does nothing
workbookStream.Position = 0 ' Does nothing
But the rest is a matter of memory. You need more working memory (RAM) in order to do what you are trying to do. So if you add RAM memory to the machine you should be good to go... Unless you have a 32-bit-machine and run into the 3GB practical RAM limit. In that case you would need to upgrade to a 64-bit-machine where this memory limit is not an issue.
But if you are generating Excel files, you may want to look at ClosedXML instead of using the Excel object model. This is a library that doesn't require Excel on your machine. Have a look at http://www.campusmvp.net/blog/generating-excel-files-like-a-pro-with-closedxml.

Can we compress a large file as a chunk data for GZIP in blackberry?

I saw the sample APIas below
public static byte[] compress( byte[] data )
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipStream = new GZIPOutputStream( baos, 6, GZIPOutputStream.MAX_LOG2_WINDOW_LENGTH );
gzipStream.write( data );
gzipStream.close();
}
catch(IOException ioe)
{
return null;
}
return baos.toByteArray();
}
But when I tried to compress with a large file with Curve 8900 OS 4.6, I got a "OutOfMemoryError" so I would like to know that how to compress as a chunk small data?
I already tried with this code as below but it doesn't work, compressed file cannot decompress...
file = (FileConnection)Connector.open(_fileOutputPath, Connector.READ_WRITE);
if (!file.exists()) {
file.create();
}
os = file.openOutputStream();
is = FileUtil.getInputStream(_fileInputPath, 0);
int tmpSize = 1024;
byte[] tmp = new byte[tmpSize];
int len = -1;
gzipStream = new GZIPOutputStream( os, 6, GZIPOutputStream.MAX_LOG2_WINDOW_LENGTH );
while((len = is.read(tmp, 0, tmpSize)) != -1) {
gzipStream.write(tmp, 0, len);
}
GZIPOutputStream does not produce a file suitable for use with the gzip command line tool. This is because it doesn't produce the necessary file headers. How did you test decompressing it? You should write a similar Java program that makes use of GZIPInputStream to test, as 'gunzip' is not going to recognize the input.
The problem of the first code sample is that the ByteArrayOutputStream is getting too big for the limited memory of a mobile device.
An option could be to first write to a file (for instance) on SD card.
The second code sample seems fine, but see Michael's answer.

Resources