PVS studio fails to find an incorrect usage of use after free - pvs-studio

I was facing a bug in my little app that is using sqlpp11 to access the database. ASAN aborted the program with a use after free because I was using incorrectly the API. While trying to find out the issues I gave PVS a try without success. I therefore share the code snippet as an opportunity to add an additional check in your software.
The incorrect code was:
Record result; // this is the native struct
demo_dao::Record records; // this is the generated struct
auto const & record =
store.db (select (all_of (records)).from (records).where (record.id == static_cast<long> (id))).front ();
// free has happened now
...
// use after free happens now
result.conditions = Conditions {record.Conditions.value ()};
The correct usage is:
auto result = store.db (select (all_of (records)).from (records).where (record.id == static_cast<long> id)));
auto const & record = result.front();

Thanks for the tip, Serge! We already have a similar case in our TODO for C++ diagnostics, and will implement it some time in the future, although I cannot give you any estimations.

Related

sccm Query - Trying to create a query for all devices with a certain folder

I'm trying to use SCCM to update all devices with zoom to the latest version. It runs locally under the user, so a typical { SMS_G_System_ADD_REMOVE_PROGRAMS.DisplayName like "%Zoom%" } doesn't work. The best workaround we've come up with is to search for the Zoom folder under C:\Users\ %UserProfile%\AppData\Roaming\Zoom. So far we've tried various ways of doing this without any success. Does anyone have any suggestions?
SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_SoftwareFile on SMS_G_System_SoftwareFile.ResourceID = SMS_R_System.ResourceId where SMS_G_System_SoftwareFile.FileName = "Zoom.exe" and SMS_G_System_SoftwareFile.FilePath = "C:\Users\ %UserProfile%\AppData\Roaming\Zoom"
I was expecting a report where all workstations with said folder & file would appear.
It gives the error:
ConfigMgr Error Object:
instance of __ExtendedStatus
{
Operation = "ExecQuery";
ParameterInfo = "SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_SoftwareFile on SMS_G_System_SoftwareFile.ResourceID = SMS_R_System.ResourceId where SMS_G_System_SoftwareFile.FileName = \"Zoom.exe\" and SMS_G_System_SoftwareFile.FilePath = \"C:\\Users\\%UserProfile%\\AppData\\Roaming\\Zoom\"";
ProviderName = "WinMgmt";
};
Error Code:
InvalidQuery
-------------------------------
Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlQueryException
The SMS Provider reported an error.
Stack Trace:
at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlQueryResultsObject.<GetEnumerator>d__75.MoveNext()
at Microsoft.ConfigurationManagement.ManagementProvider.QueryProcessorBase.ProcessQuery(Object sender, DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
-------------------------------
System.Management.ManagementException
Invalid query
Stack Trace:
at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlQueryResultsObject.<GetEnumerator>d__75.MoveNext()
at Microsoft.ConfigurationManagement.ManagementProvider.QueryProcessorBase.ProcessQuery(Object sender, DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
-------------------------------
What you are looking for is "Configuration Item" and "Configuration Baseline", which are created as a pair (a CI/CB) and produces a resultant membership, which can be marshalled into a collection. I will warn you that the way CM organizes this is a bit byzantine. It will take some testing and tweaking to get the concept understood properly and then set up to your satisfaction.
Googling gave me this page, which has a fair enough description to get you started:
https://www.anoopcnair.com/how-create-sccm-configuration-items-baselines/
My best shoot-from-the-hip braindump:
Create the CI, which defines criteria (such as existence of a folder or file among many other possibilities, including writing your own script to use as the test)
Create the CB, which uses a CI against a Collection to evaluate, which then dumps the results behind the scenes into some internal table
Create the Collection (which can be done with assistance by right-clicking the CB and selecting the right context menu item) which scoops up this data into what you want (a collection of devices) based upon state data. The collection query is difficult to easily see what it's doing, because it uses referenced guids for the CI/CB as well as a state code (for compliant or non-compliant) that isn't really human-readable.
At this point you'll have what you want. But as warned before: the vagaries of setting up the CI/CB and collection are finicky. Expect to do a fair bit of googling and fiddling with the parameters before you get it right.

Metaplex Auction House Error "Error processing Instruction 0: insufficient account keys for instruction"

I have been trying to run the execute_sale ix from the mpl-auction-house package but I get this error in the logs I have got the sellInstruction and buyInstruction working
This is my Code
const executeSellInstructionAccounts:ExecuteSaleInstructionAccounts = {
buyer:buyerwallet.publicKey,
seller:Sellerwallet.publicKey,
tokenAccount:tokenAccountKey,
tokenMint:mint,
metadata:await getMetadata(mint),
treasuryMint:new anchor.web3.PublicKey(AuctionHouse.mint),
auctionHouse:new anchor.web3.PublicKey(AuctionHouse.address),
auctionHouseFeeAccount:new anchor.web3.PublicKey(AuctionHouse.feeAccount),
authority:new anchor.web3.PublicKey(AuctionHouse.authority),
programAsSigner:programAsSigner,
auctionHouseTreasury:new anchor.web3.PublicKey(AuctionHouse.treasuryAccount),
buyerReceiptTokenAccount:buyerATA.address,
sellerPaymentReceiptAccount:Sellerwallet.publicKey,
buyerTradeState:BuyertradeState,
escrowPaymentAccount:escrowPaymentAccount,
freeTradeState:freeTradeState,
sellerTradeState:SellertradeState,
}
const executeSellInstructionArgs:ExecuteSaleInstructionArgs = {
escrowPaymentBump:escrowBump,
freeTradeStateBump:freeTradeBump,
programAsSignerBump:programAsSignerBump,
buyerPrice:buyPriceAdjusted,
tokenSize:tokenSizeAdjusted,
}
const execute_sale_ix = createExecuteSaleInstruction(
executeSellInstructionAccounts,executeSellInstructionArgs
)
const execute_sale_tx = new anchor.web3.Transaction(
{
recentBlockhash: blockhash,
feePayer: Sellerwallet.publicKey,
}
)
execute_sale_tx.add(execute_sale_ix);
const execute_sale_res = await sprovider.sendAndConfirm(execute_sale_tx);
There is currently a discrepancy between the published AuctionHouse SDK and the underlying Rust program.
The console reference implementation is here: https://github.com/metaplex-foundation/metaplex/blob/master/js/packages/cli/src/auction-house-cli.ts
The console reference implementation works because it loads the idl directly from the chain and is therefore up to date. It bypasses the AuctionHouse SDK completely.
However, if you're doing this in the browser, you probably don't want to load the IDL from the chain. You'd need things like a decompression library and that would blow up your package size quite a bit.
To work around this, I've forked metaplex repo here: https://github.com/neftworld/metaplex
The fork above has the following changes:
Including the IDL definition as a typescript src file (correct as at 30 May 2022)
Fetching auctionHouse program from local IDL definition instead getting it from the chain
Hence, you can use this as a base for your web implementation. To make this work on the web, you will need to remove references to keypair - console uses a key pair file - and use the browser wallet to sign the transaction before sending.

boost interprocess file_lock understanding/usage

I have been having issues using an anonymous mutex (boost::interprocess::interprocess_mutex) in a boost::interprocess::managed_shared_memory instance. Namely, issues arise if the software crashes; the mutex may remain locked (depending on its state at time of crash). It can make debugging interesting too :).
My understanding is that I can substitute the interprocess_mutex with boost::interprocess::file_lock (FL). #DaveF posted some questions that I would like to build upon. I'd like to have a good understanding what I'm getting myself into before I put FL into use.
Can I use an anonymous boost::interprocess::condition_variable (CV) with FL? Having looked through the code, it appears that it will work.
In using a CV, am I opening myself up to the same problems I have experienced when using mutex (ie. if the application unexpectedly ends without proper cleanup/finalisation)?
What is the best way to create a FL. I've thought about something similar to the following...
Note code may not compile:
namespace bi = boost::interprocess;
namespace bf = boost::filesystem;
const std::string strSharedMemName = std::string("cp_shdmem_") + std::to_string(nIdx);
const std::string strNamedMutexName = strSharedMemName + "_mtx";
// I'm working on Linux, but would like to Boost to create a temporary file path.
const bf::path pathTmpFile =
bf::temp_directory_path() / (strNamedMutexName + ".txt");
{
// 1. So can I just create the file? What happens if it exists? Boost docs say this
// about the file_lock constructor:
// "Throws interprocess_exception if the file does not exist
// or there are no operating system resources."
// 2. What happens if file already exists?
bf::ofstream f(pathTmpFile);
}
// Create.
bi::file_lock lockFile(pathTmpFile.string().c_str());
// Lock.
bi::scoped_lock<bi::file_lock> lockNamed(lockFile);
Platform specifics:
Ubuntu 17.10
Boost 1.63
GCC 7.2

Coded UI error: The following element is not longer availabe

I recorded some test cases with CUIT in VS2010. Everything worked fine the day before. So, today I run again, all the test failed, with the warning: The following element is no longer available ... and I got the exception : Can't perform "Click" on the hidden control, which is not true because all the controls are not hidden. I tried on the other machine, and they failed as well.
Does anyone know why it happens? Is it because of the web application for something else? Please help, thanks.
PS: So I tried to record a new test with the same controls that said "hidden controls", and the new test worked!? I don't understand why.
EDIT
The warning "The following element blah blah ..." appears when I tried to capture an element or a control while recording. The source code of the button is said 'hidden'
public HtmlImage UIAbmeldenImage
{
get
{
if ((this.mUIAbmeldenImage == null))
{
this.mUIAbmeldenImage = new HtmlImage(this);
#region Search Criteria
this.mUIAbmeldenImage.SearchProperties[HtmlImage.PropertyNames.Id] = null;
this.mUIAbmeldenImage.SearchProperties[HtmlImage.PropertyNames.Name] = null;
this.mUIAbmeldenImage.SearchProperties[HtmlImage.PropertyNames.Alt] = "abmelden";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.AbsolutePath] = "/webakte-vnext/content/apps/Ordner/images/logOut.png";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.Src] = "http://localhost/webakte-vnext/content/apps/Ordner/images/logOut.png";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.LinkAbsolutePath] = "/webakte-vnext/e.consult.9999/webakte/logout/index";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.Href] = "http://localhost/webakte-vnext/e.consult.9999/webakte/logout/index";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.Class] = null;
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.ControlDefinition] = "alt=\"abmelden\" src=\"http://localhost/web";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.TagInstance] = "1";
this.mUIAbmeldenImage.WindowTitles.Add("Akte - Test Akte Coded UI VS2010");
#endregion
}
return this.mUIAbmeldenImage;
}
}
Although I am running Visual Studio 2012, I find it odd that we started experiencing the same problem on the same day, I can not see any difference in the DOM for the Coded UI Tests I have for my web page, but for some reason VS is saying the control is hidden and specifies the correct ID of the element it is looking for (I verified that the ID is still the same one). I even tried to re-record the action, because I assumed that something must have changed, but I get the same error.
Since this sounds like the same problem, occurring at the same time I am thinking this might be related to some automatic update? That's my best guess at the moment, I am going to look into it, I will update my post if I figure anything out.
EDIT
I removed update KB2870699, which removes some voulnerability in IE, this fixed the problems I was having with my tests. This update was added on the 12. september, so it fits. Hope this helps you. :)
https://connect.microsoft.com/VisualStudio/feedback/details/800953/security-update-kb2870699-for-ie-breaks-existing-coded-ui-tests#tabs
Official link to get around the problem :
http://blogs.msdn.com/b/visualstudioalm/archive/2013/09/17/coded-ui-mtm-issues-on-internet-explorer-with-kb2870699.aspx
The problem is more serious than that! In my case I can't even record new Coded UI Tests. After I click in any Hyper Link of any web page of my application the coded UI test builder cannot record that click "The following element is no longer available....".
Apparently removing the updates, as said by AdrianHHH do the trick!
Shut down VS2010, launch it again "Run as administrator".
There may be a field in the SearchProperties (or possible the FilterProperties) that has a value set by the web site, or that represents some kind of window ID on your desktop. Another possibility is that the web page title changes from day to day or visit to visit. Different executions of the browser or different visits to the web page(s) create different values. Removing these values from the SearchProperties (or FilterProperties) or changing the check for the title from an equals to a contains for a constant part of the title should fix the problem. Coded UI often searches for more values than the minimum set needed.
Compare the search properties etc for the same control in the two recorded tests.
Update based extra detail given in the comments:
I solved a similar problem as follows. I copied property code similar to that shown in your question into a method that called FindMatchingControls. I checked how many controls were returned, in my case up to 3. I examined various properties of the controls found, by writing lots of text to a debug file. In my case I found that the Left and Top properties were negative for the unwanted, ie hidden, controls.
For your code rather than just using the UIAbmeldenImage property, you might call the method below. Change an expression such as
HtmlImage im = UIMap.abc.def.UIAbmeldenImage;
to be
HtmlImage im = FindHtmlHyperLink(UIMap.abc.def);
Where the method is:
public HtmlImage FindHtmlHyperLink(HtmlDocument doc)
{
HtmlImage myImage = new HtmlImage(doc);
myImage.SearchProperties[HtmlImage.PropertyNames.Id] = null;
myImage.SearchProperties[HtmlImage.PropertyNames.Name] = null;
myImage.SearchProperties[HtmlImage.PropertyNames.Alt] = "abmelden";
myImage.FilterProperties[HtmlImage.PropertyNames.AbsolutePath] = "/webakte-vnext/content/apps/Ordner/images/logOut.png";
myImage.FilterProperties[HtmlImage.PropertyNames.Src] = "http://localhost/webakte-vnext/content/apps/Ordner/images/logOut.png";
myImage.FilterProperties[HtmlImage.PropertyNames.LinkAbsolutePath] = "/webakte-vnext/e.consult.9999/webakte/logout/index";
myImage.FilterProperties[HtmlImage.PropertyNames.Href] = "http://localhost/webakte-vnext/e.consult.9999/webakte/logout/index";
myImage.FilterProperties[HtmlImage.PropertyNames.Class] = null;
myImage.FilterProperties[HtmlImage.PropertyNames.ControlDefinition] = "alt=\"abmelden\" src=\"http://localhost/web";
myImage.FilterProperties[HtmlImage.PropertyNames.TagInstance] = "1";
myImage.WindowTitles.Add("Akte - Test Akte Coded UI VS2010");
UITestControlCollection controls = myImage.FindMatchingControls();
if (controls.Count > 1)
{
foreach (UITestControl con in controls)
{
if ( con.Left < 0 || con.Top < 0 )
{
// Not on display, ignore it.
}
else
{
// Select this one and break out of the loop.
myImage = con as HtmlImage;
break;
}
}
}
return myImage;
}
Note that the above code has not been compiled or tested, it should be taken as ideas not as the final code.
I had the same problem on VS 2012. As a workaround, you can remove that step, and re-record it again. That usually works.
One of the biggest problem while analyzing the Coded UI test failures is that the error stack trace indicates the line of code which might be completely unrelated to the actual cause of failure.
I would suggest you to enable HTML logging in your tests - this will display step by step details of how Coded UI tried to execute the tests - with screenshots of your application. It will also highlight the control in red which Coded UI is trying to search/operate upon.This is very beneficial in troubleshooting the actual cause of test failures.
To enable tracing you can just add the below code to your app.config file --

Address Book is returning old values

I am having a problem with the AddressBook framework.
It all seems to be stemming from ABCopyRecordForUniqueId returning a record with old data.
Example:
I run up the program below in one terminal window - it shows the current data.
I make a change through the address book UI - my program continues to show old data.
I run up another instance of the same program in a new terminal window - it shows the updated data.
I have tried posting on the omnigroup site with no luck :( so any guidance is really appreciated
PS: If you would like to try the code, to get an address book ID you can export a contact as a vCard and open it with a text editor
int main (int argc, const char * argv[])
{
ABAddressBookRef addressBook = ABGetSharedAddressBook();
while(1)
{
ABRecordRef addressBookRecord = NULL;
addressBookRecord = ABCopyRecordForUniqueId(addressBook, CFSTR("4064D587-0378-4DCF-A6B9-D3702F01C94C:ABPerson"));
CFShow(addressBookRecord);
CFRelease(addressBookRecord);
sleep(1);
}
return 0;
}
I tried your example myself and am seeing the same problem. Out of curiosity, I tried asking for the shared address book inside the loop (in case there was some weirdness going on with the address book singleton) but this made no difference. I checked out the documentation (ABAddressBook C Reference) as well as the higher-level address book framework reference and guide. As far as I can tell, you're doing the right thing.
I'd file this as a bug against the framework.
thanks for the suggestion. I did file a report but it turns out this is expected
Annoying that it wasn't in the docs..
"Engineering has determined that this issue behaves as intended based on the following information:
The address book requires the run loop to be run in order to receive updates from other applications. Instead of sleep(1), use CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0, false)."
Thanks,
M

Resources