Skip to content

Polymorphic instance of xml archive can produce a corrupted format  #189

Description

@correaa

This code generates an xml file that cannot be read by deserialization:

#include<fstream>
#include <boost/serialization/nvp.hpp>
#include<boost/archive/polymorphic_xml_oarchive.hpp>

int main(){
	int i = 5;
	{
		std::ofstream ofs{"file.xml"};
		boost::archive::polymorphic_oarchive* poa = new boost::archive::polymorphic_xml_oarchive(ofs);
		(*poa) << i;
		delete poa;
	}
}

file.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="16">
5</boost_serialization>

Of course the problem is that I "forgot" to add the named value pair. For non-polymorphic archives this would produce a compilation error, but fails silently in the polymorphic case. I think a more correct behavior would be either 1) to make a runtime-time check that the passed object is a named-value pair when passing to an actual XML archive, or 2) force polymorphic archives to only accept named-value pairs.

In this case is obvious but in the case were many runtime cases are considered (including other archives format that do not require named-value-pair), this is difficult to spot. The error only happens when trying to load the file.

For reference, the workaround is to do this:

		(*poa) << boost::serialization::make_nvp("i", i);

with the output:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="16">
<i>5</i>
</boost_serialization>

Any how I think this points out to another possibility that could make the XML archive more powerful, and that is that if no named-value pair is passed to it, the archive should generate unique names, (possibly based partially on the type information + some uuid or fixed string, e.g. "unnamed").

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions