freeing pwfx after waveOutOpen throws - winapi

According to Microsoft documentation:
"You can free this [pwfx] structure immediately after passing it to waveOutOpen."
But this code dosen't seem to agree:
pwfx=new WAVEFORMATEX;
pwfx->wFormatTag=WAVE_FORMAT_PCM;
pwfx->nChannels=2;
pwfx->nSamplesPerSec=SPS;
pwfx->nAvgBytesPerSec=SPS*2;
pwfx->nBlockAlign=2;
pwfx->wBitsPerSample=8;
mmres=waveOutOpen(&ghwo,uDeviceID,pwfx,dwCallback,dwCallbackInstance,fdwOpen);
delete pwfx;

The only problem I can see in the code you provided is that you did not fully initialise the struct. You did not initialise cbSize which in this instance must be set to 0.
Given that you are not allocating any extra data at the end of this struct, there's no need to allocate it in the heap.
It's entirely plausible that the problem lies in the other parameters that you pass to the function. We can't see any details of them, and therefore can't comment.

You don't need to new or delete anything. You can just do:
WAVEFORMATEX wfx = { };
wfx.wFormatTag=WAVE_FORMAT_PCM;
...
mmres=waveOutOpen(&ghwo,uDeviceID,&wfx,dwCallback,dwCallbackInstance,fdwOpen);
Does that help at all?

Related

How to serialize a SecTrustRef object?

I have a SecTrustRef object from the system that I'd like to evaluate myself. Just calling SecTrustEvaluateAsync will be sufficient for this job. The problem is, I must evaluate it in a different process as only this other process has access to the keychains where the CA certificates are stored that may cause evaluation to succeed.
The two processes have an IPC link that allows me to exchange arbitrary byte data between them but I don't see any way to easily serialize a SecTrustRef into byte data and deserialize that data back to an object at the other process. There doesn't seem to be a persistent storage mechanism for SecTrustRef.
So am I overlooking something important here, or do I really have to get all the certs (SecTrustGetCertificateAtIndex) and all the policies (SecTrustCopyPolicies) and serialize these myself?
And if so, how would I serialize a policy?
For the certificate (SecCertificateRef) it's rather easy, I just call SecCertificateCopyData and later on SecCertificateCreateWithData.
But for policies I can only call SecPolicyCopyProperties on one side and later on SecPolicyCreateWithProperties, however the later one requires a 2nd parameter, a policyIdentifier and I see no way to get that value from an existing policy. What am I missing?
Reading through the source of the Security framework, I finally figured it out how to copy a SecPolicyRef:
SecPolicyCreateWithProperties wants what it calls a "policyIdentifier". It's a constant like kSecPolicyAppleIPsec.
This does not get stored directly by the function, it's comparing the value and calling dedicated internal "initializers" (like SecPolicyCreateIPsec).
These in turn call SecPolicyCreate (which is private). They end up passing the same identifier value that you passed to SecPolicyCreateWithProperties.
And this value then gets stored as-is in the _oid field!
The identifier is actually the OID. You can get it either via SecPolicyCopyProperties(policy) (stored in the dictionary with key kSecPolicyOid) or via SecPolicyGetOID (but that returns it as an inconvenient CSSM_OID). Some of those specialized initializers also use values from the properties dictionary passed to SecPolicyCreateWithProperties, those should be present in the copied properties dictionary already.
So this gives us:
Serialization:
CFDictionaryRef createSerializedPolicy(SecPolicyRef policy) {
// Already contains all the information needed.
return SecPolicyCopyProperties(policy);
}
Deserialization:
SecPolicyRef createDeserializedPolicy (CFDictionaryRef serialized) {
CFStringRef oid = CFDictionaryGetValue(serialized, kSecPolicyOid);
if (oid == NULL || CFGetTypeID(oid) != CFStringGetTypeID()) {
return NULL;
}
return SecPolicyCreateWithProperties(oid, serialized);
}
To reproduce the original SecTrustRef as closely as possible, the anchors need to be copied as well. There is an internal variable _anchorsOnly which is set to true once you set anchors. Unfortunately, there is no way to query this value and I've seen it being false in trusts passed by NSURLSession, for example. No idea yet on how to get this value in a public way.
Another problematic bit are the exceptions: if _exceptions is NULL but you query them via SecTrustCopyExceptions(trust), you do get data! And if you assign that to the deserialized trust via SecTrustSetExceptions(trust, exceptions) you suddenly end up with exceptions that were not there before and can change the evaluation result! (I've seen those suddenly appearing exceptions lead to an evaluation result of "proceed" instead of "recoverable trust failure").

parse.com - cloud code - what do i do with a pointer?

Someone doesn't understand what i want. I want to know what i can do with a pointer.
I have js cloud code.
I have a pointer.
What can i do with it?
Example:
var query = new Parse.Query("Messages"); //POINTER QUERY
console.log(userMessages[0].get("messageId"));
console.log("end2");
query.equalTo("objectId",userMessages[position].get("messageId"));
In the example, userMessages is the result of a prior cloud query.
This line
console.log(userMessages[0].get("messageId"));
helpfully outputs
{"__type":"Pointer","className":"Messages","objectId":"5J4eOletgz"}
This is less useful than you might imagine. I cannot seem to call the objectId from it, and the query
query.equalTo("objectId",userMessages[position].get("messageId"));
query.find ({ ... });
returns nothing. Note that the query should find the pointer-object the pointer-points-to, but instead it helpfully throws the error
Error: 102 bad special key: __type
Which is just about useless.
What can i do with a pointer?
Why don't the people at parse.com bother to write this stuff up anywhere?
That second question is more like a buddhist koan for them to meditate over, no need to respond!
you can use:
userMessagesQuery.include("messageId")
before you execute your query that returns userMessages and you will get the entire object in "messageId" instead of just a pointer.
Also you use
userMessages[0].get("messageId").fetch({success:function(){}})
to get the full object if you don't want to use "include"
Suggestion: I'd rename "messageId" to "message" to make it clear that it's an object pointer and not an ID field.
A pointer is a Parse object with just the minimal data used for linking. If you want to get the rest of the data for a pointer (fully populate it), use the fetch() method.
If you just want the objectId from a pointer, you retrieve it just like you would any other Parse object, by using the myPointer.objectId property.
In your case the following would work, but isn't the most optimal solution:
// I would suggest renaming messageId if you're actually storing pointers
var messagePointer = userMessages[position].get("messageId");
query.equalTo("objectId", messagePointer.objectId);
Instead, as stated by #RipRyness, you could just change your previous query to include() the full object, avoiding many extra queries.
userMessagesQuery.include("messageId");
// ... later in success handler ...
// now a fully populated Message object
var message = userMessages[position].get("messageId");
console.log(message);
Okay so a pointer is does not only point to a certain object, but it can BE that object.
In the query that returns the userMessages result, you can use the line .include("messageId") - this makes your query not only return a pointer to that object, it actually includes that object in place of the pointer.
After using the include statement, userMessages[0].get("messageId") will return the Message object linked that that userMessage object. You no longer need to query the Message collection to get the object.

Pointer object Creates a windows error in Visual C++ 6.0

I will paste a code snippet and explain the problem I am facing,
void materialPropertiesDlg::OnNext() {
contiBeam *continousBeamPtr;
contiBeam contiBeamObj;
UpdateData(TRUE);
switch (m_steel_grade) {
// Do Something
}
continousBeamPtr->setMaterial(m_conc_grade, m_steel_grade);
OnOK();
}
As you see, in line 2 a pointer object is created and in the next line an object is created. So, then I call the member function setMaterials() of the class contiBeam. I can easily do that with the object contiBeamObj, but when I call the function using contiBeamPointer, the windows throws an error which reads
Application Has Stopped working.
I am able to do the needful, I just want to know what could be the possible reason for this?
You are using your pointer contiBeam *continousBeamPtr; without having allocated it.
That is Undefined Behaviour and will make your application crash.
You should allocate (reserve memory for) your pointer by using new, like so:
contiBeam *continousBeamPtr = new contiBeam;
However, the ultimate question is, why are you using a pointer in the first place? Do you need one? Doesn't look like it from the code you posted.

Find who's calling the method

I'd like to somehow find out which CFC is calling my method.
I have a logging CFC which is called by many different CFC's. On this logging CFC there's a need to store which CFC called for the log.
Whilst I could simply pass the CFC name as an argument to my log.cfc, I find this to be a repetitive task, that might not be necessary, if I somehow could find out "who's" calling the method on log.cfc
Is there any programmatic way of achieving this?
Thanks in advance
Update: As Richard Tingle's answer points out, since CF10 you can use CallStackGet(), which is better than throwing a dummy exception.
Original answer: The easiest way is to throw a dummy exception and immediately catch it. But this has the downside of making a dummy exception show up in your debug output. For me, this was a deal-breaker, so I wrote the following code (based off of this code on cflib). I wanted to create an object that is similar to a cfcatch object, so that I could use it in places that expected a cfcatch object.
Note: You may have to adjust this code a bit to make it work in CF8 or earlier. I don't think the {...} syntax for creating object was supported prior to CF9.
StackTrace = {
Type= 'StackTrace',
Detail= '',
Message= 'This is not a real exception. It is only used to generate debugging information.',
TagContext= ArrayNew(1)
};
j = CreateObject("java","java.lang.Thread").currentThread().getStackTrace();
for (i=1; i LTE ArrayLen(j); i++)
{
if(REFindNoCase("\.cf[cm]$", j[i].getFileName())) {
ArrayAppend(StackTrace.TagContext, {
Line= j[i].getLineNumber(),
Column= 0,
Template= j[i].getFileName()
});
}
}
From ColdFusion 10 there is now a function to do this callStackGet()
For example the following code will dump the stack trace to D:/web/cfdump.txt
<cfdump var="#callStackGet()#" output="D:/web/cfdump.txt">
One kludgey way is to throw/catch a custom error and parse the stack trace. Here are some examples
http://www.bennadel.com/blog/406-Determining-Which-Function-Called-This-Function-Using-ColdFusion-.htm
http://coldfusion.dzone.com/news/what-function-called-my-functi
I don't know of a method to do directly what you are asking, maybe someone else does.
However, I believe you could get the stack trace and create a function to parse the last method call.
This function on cflib will get you the stack trace.

when to release object in npapi plugin

I am confused about the ref count in npapi. Mostly, I don't know which method will increase ref count. Can anyone explain in detail about this? For the convenience, I listed most common used NPN_* functions here and my own understanding:
NPN_CreateObject: set ref count to 0
NPN_RetainObject: inc ref count
NPN_ReleaseObject: dec ref count
NPN_Evaluate: ?? (in case return an NPObject*)
NPN_GetValue: ?? (in case return an NPObject*)
NPN_SetValue: ?? (in case set to an NPObject*)
NPN_GetProperty: ?? (in case return an NPObject*)
NPN_SetProperty: ?? (in case set to an NPObject*)
NPN_RemoveProperty: ??
NPN_Enumerate: ??
NPN_Construct: ??
another thing: is npapi do nested release? (In case NPObject* with a property of NPObject*, release parent will decrease the ref count of child).
Thanks.
There isn't room in comments to answer your question in the comment well, so I'll put it in another answer.
Any time your code gets an NPObject from a NPObject function (one of those you mentioned above), you should Release that NPObject when you're done with it. (that could be immediately, or you could save it for awhile and release it when your object gets destroyed). The same holds true with a NPVariant. It does not hold true with the arguments passed into your Invoke function, but the return value you set will get released by the browser when it's done.
When you call NPN_GetValue and get an NPObject from there, that also has to be released. This means that when the browser calls NPP_GetValue, it will release your NPObject when it's done. If you want to create a new NPObject every time the browser calls NPP_GetValue to get your NPObject, then you don't have to call NPN_RetainObject on it; the assumption in the NPAPI example is that you are saving a copy of your NPObject so that it doesn't get deleted until your plugin object gets deleted.
Since the browser will call Release for every time that it calls NPP_GetValue to get your NPObject, you need to make sure that the refcount is incremented before you return it. The reason you don't have to call it twice in the case that you're going to keep it is that NPN_CreateObject does an implicit Retain before it returns your object.
I have written up a more detailed explanation here:
http://colonelpanic.net/2009/12/memory-management-in-npapi
First, to correct a misconception: NPN_CreateObject sets the refCount to 1, not to 0. Then, when you call NPN_RetainObject it increments the refcount, and NPN_ReleaseObject will decrement it. If ReleaseObject decrements the refcount to 0, it will also free it by calling the deallocate function from your NPClass (which should delete the NPObject after doing any needed cleanup)
see: https://developer.mozilla.org/En/NPClass
beyond that, a good general rule of thumb for any of the other NPClass functions is that any time you put an NPObject in a NPVariant, you need to call NPN_RetainObject. To remember this, simply remember that when you're done with an NPVariant (one that you have used and are done with, not one that was passed as a return value), you call NPN_ReleaseVariantValue, which will release the NPString data if it's a string or the NPObject if it's an object.
So from any of the other methods, if you are returning an NPObject, you need to call NPN_RetainObject before you stuff it into the NPVariant. Also, if you save a copy of the NPObject, you should call NPN_RetainObject on it and NPN_ReleaseObject when you're done saving it. It also bears mentioning that you should never call any NPN_ method from a thread other than the main thread.
Does that help?

Resources