Home | History | Annotate | Download | only in autofill
      1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "chrome/browser/autofill/form_structure.h"
      6 
      7 #include "base/basictypes.h"
      8 #include "base/logging.h"
      9 #include "base/sha1.h"
     10 #include "base/string_number_conversions.h"
     11 #include "base/utf_string_conversions.h"
     12 #include "chrome/browser/autofill/autofill_metrics.h"
     13 #include "chrome/browser/autofill/autofill_xml_parser.h"
     14 #include "chrome/browser/autofill/field_types.h"
     15 #include "chrome/browser/autofill/form_field.h"
     16 #include "third_party/libjingle/source/talk/xmllite/xmlelement.h"
     17 #include "webkit/glue/form_field.h"
     18 
     19 using webkit_glue::FormData;
     20 
     21 namespace {
     22 
     23 const char kFormMethodPost[] = "post";
     24 
     25 // XML elements and attributes.
     26 const char kAttributeAcceptedFeatures[] = "accepts";
     27 const char kAttributeAutofillUsed[] = "autofillused";
     28 const char kAttributeAutofillType[] = "autofilltype";
     29 const char kAttributeClientVersion[] = "clientversion";
     30 const char kAttributeDataPresent[] = "datapresent";
     31 const char kAttributeFormSignature[] = "formsignature";
     32 const char kAttributeSignature[] = "signature";
     33 const char kAcceptedFeatures[] = "e"; // e=experiments
     34 const char kClientVersion[] = "6.1.1715.1442/en (GGLL)";
     35 const char kXMLDeclaration[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
     36 const char kXMLElementAutofillQuery[] = "autofillquery";
     37 const char kXMLElementAutofillUpload[] = "autofillupload";
     38 const char kXMLElementForm[] = "form";
     39 const char kXMLElementField[] = "field";
     40 
     41 // The number of fillable fields necessary for a form to be fillable.
     42 #ifdef ANDROID
     43 // Try and autofill more forms on Android, as filling out forms is
     44 // more frustrating on a mobile device.
     45 const size_t kRequiredFillableFields = 2;
     46 #else
     47 const size_t kRequiredFillableFields = 3;
     48 #endif
     49 
     50 }  // namespace
     51 
     52 FormStructure::FormStructure(const FormData& form)
     53     : form_name_(form.name),
     54       source_url_(form.origin),
     55       target_url_(form.action),
     56       has_credit_card_field_(false),
     57       has_autofillable_field_(false),
     58       has_password_fields_(false),
     59       autofill_count_(0) {
     60   // Copy the form fields.
     61   std::vector<webkit_glue::FormField>::const_iterator field;
     62   for (field = form.fields.begin();
     63        field != form.fields.end(); field++) {
     64     // Add all supported form fields (including with empty names) to the
     65     // signature.  This is a requirement for Autofill servers.
     66     form_signature_field_names_.append("&");
     67     form_signature_field_names_.append(UTF16ToUTF8(field->name));
     68 
     69     // Generate a unique name for this field by appending a counter to the name.
     70     string16 unique_name = field->name +
     71         base::IntToString16(fields_.size() + 1);
     72     fields_.push_back(new AutofillField(*field, unique_name));
     73   }
     74 
     75   // Terminate the vector with a NULL item.
     76   fields_.push_back(NULL);
     77 
     78   std::string method = UTF16ToUTF8(form.method);
     79   if (StringToLowerASCII(method) == kFormMethodPost) {
     80     method_ = POST;
     81   } else {
     82     // Either the method is 'get', or we don't know.  In this case we default
     83     // to GET.
     84     method_ = GET;
     85   }
     86 }
     87 
     88 FormStructure::~FormStructure() {}
     89 
     90 void FormStructure::DetermineHeuristicTypes() {
     91   has_credit_card_field_ = false;
     92   has_autofillable_field_ = false;
     93   autofill_count_ = 0;
     94 
     95   FieldTypeMap field_type_map;
     96   GetHeuristicFieldInfo(&field_type_map);
     97 
     98   for (size_t index = 0; index < field_count(); index++) {
     99     AutofillField* field = fields_[index];
    100     DCHECK(field);
    101     FieldTypeMap::iterator iter = field_type_map.find(field->unique_name());
    102 
    103     AutofillFieldType heuristic_autofill_type;
    104     if (iter == field_type_map.end()) {
    105       heuristic_autofill_type = UNKNOWN_TYPE;
    106     } else {
    107       heuristic_autofill_type = iter->second;
    108       ++autofill_count_;
    109     }
    110 
    111     field->set_heuristic_type(heuristic_autofill_type);
    112 
    113     AutofillType autofill_type(field->type());
    114     if (autofill_type.group() == AutofillType::CREDIT_CARD)
    115       has_credit_card_field_ = true;
    116     if (autofill_type.field_type() != UNKNOWN_TYPE)
    117       has_autofillable_field_ = true;
    118   }
    119 }
    120 
    121 bool FormStructure::EncodeUploadRequest(bool autofill_used,
    122                                         std::string* encoded_xml) const {
    123   DCHECK(encoded_xml);
    124   encoded_xml->clear();
    125   bool autofillable = ShouldBeParsed(true);
    126   DCHECK(autofillable);  // Caller should've checked for search pages.
    127   if (!autofillable)
    128     return false;
    129 
    130   // Set up the <autofillupload> element and its attributes.
    131   buzz::XmlElement autofill_request_xml(
    132       (buzz::QName(kXMLElementAutofillUpload)));
    133   autofill_request_xml.SetAttr(buzz::QName(kAttributeClientVersion),
    134                                kClientVersion);
    135   autofill_request_xml.SetAttr(buzz::QName(kAttributeFormSignature),
    136                                FormSignature());
    137   autofill_request_xml.SetAttr(buzz::QName(kAttributeAutofillUsed),
    138                                autofill_used ? "true" : "false");
    139   autofill_request_xml.SetAttr(buzz::QName(kAttributeDataPresent),
    140                                ConvertPresenceBitsToString().c_str());
    141 
    142   if (!EncodeFormRequest(FormStructure::UPLOAD, &autofill_request_xml))
    143     return false;  // Malformed form, skip it.
    144 
    145   // Obtain the XML structure as a string.
    146   *encoded_xml = kXMLDeclaration;
    147   *encoded_xml += autofill_request_xml.Str().c_str();
    148 
    149   return true;
    150 }
    151 
    152 // static
    153 bool FormStructure::EncodeQueryRequest(const ScopedVector<FormStructure>& forms,
    154     std::vector<std::string>* encoded_signatures,
    155     std::string* encoded_xml) {
    156   DCHECK(encoded_signatures);
    157   DCHECK(encoded_xml);
    158   encoded_xml->clear();
    159   encoded_signatures->clear();
    160   encoded_signatures->reserve(forms.size());
    161 
    162   // Set up the <autofillquery> element and attributes.
    163   buzz::XmlElement autofill_request_xml(
    164       (buzz::QName(kXMLElementAutofillQuery)));
    165   autofill_request_xml.SetAttr(buzz::QName(kAttributeClientVersion),
    166                                kClientVersion);
    167   autofill_request_xml.SetAttr(buzz::QName(kAttributeAcceptedFeatures),
    168                                kAcceptedFeatures);
    169 
    170   // Some badly formatted web sites repeat forms - detect that and encode only
    171   // one form as returned data would be the same for all the repeated forms.
    172   std::set<std::string> processed_forms;
    173   for (ScopedVector<FormStructure>::const_iterator it = forms.begin();
    174        it != forms.end();
    175        ++it) {
    176     std::string signature((*it)->FormSignature());
    177     if (processed_forms.find(signature) != processed_forms.end())
    178       continue;
    179     processed_forms.insert(signature);
    180     scoped_ptr<buzz::XmlElement> encompassing_xml_element(
    181         new buzz::XmlElement(buzz::QName(kXMLElementForm)));
    182     encompassing_xml_element->SetAttr(buzz::QName(kAttributeSignature),
    183                                       signature);
    184 
    185     if (!(*it)->EncodeFormRequest(FormStructure::QUERY,
    186                                   encompassing_xml_element.get()))
    187       continue;  // Malformed form, skip it.
    188 
    189     autofill_request_xml.AddElement(encompassing_xml_element.release());
    190     encoded_signatures->push_back(signature);
    191   }
    192 
    193   if (!encoded_signatures->size())
    194     return false;
    195 
    196   // Obtain the XML structure as a string.
    197   *encoded_xml = kXMLDeclaration;
    198   *encoded_xml += autofill_request_xml.Str().c_str();
    199 
    200   return true;
    201 }
    202 
    203 // static
    204 void FormStructure::ParseQueryResponse(const std::string& response_xml,
    205                                        const std::vector<FormStructure*>& forms,
    206                                        UploadRequired* upload_required,
    207                                        const AutofillMetrics& metric_logger) {
    208   metric_logger.Log(AutofillMetrics::QUERY_RESPONSE_RECEIVED);
    209 
    210   // Parse the field types from the server response to the query.
    211   std::vector<AutofillFieldType> field_types;
    212   std::string experiment_id;
    213   AutofillQueryXmlParser parse_handler(&field_types, upload_required,
    214                                        &experiment_id);
    215   buzz::XmlParser parser(&parse_handler);
    216   parser.Parse(response_xml.c_str(), response_xml.length(), true);
    217   if (!parse_handler.succeeded())
    218     return;
    219 
    220   metric_logger.Log(AutofillMetrics::QUERY_RESPONSE_PARSED);
    221 
    222   bool heuristics_detected_fillable_field = false;
    223   bool query_response_overrode_heuristics = false;
    224 
    225   // Copy the field types into the actual form.
    226   std::vector<AutofillFieldType>::iterator current_type = field_types.begin();
    227   for (std::vector<FormStructure*>::const_iterator iter = forms.begin();
    228        iter != forms.end(); ++iter) {
    229     FormStructure* form = *iter;
    230     form->server_experiment_id_ = experiment_id;
    231 
    232     if (form->has_autofillable_field_)
    233       heuristics_detected_fillable_field = true;
    234 
    235     form->has_credit_card_field_ = false;
    236     form->has_autofillable_field_ = false;
    237 
    238     for (std::vector<AutofillField*>::iterator field = form->fields_.begin();
    239          field != form->fields_.end(); ++field, ++current_type) {
    240       // The field list is terminated by a NULL AutofillField.
    241       if (!*field)
    242         break;
    243 
    244       // In some cases *successful* response does not return all the fields.
    245       // Quit the update of the types then.
    246       if (current_type == field_types.end())
    247         break;
    248 
    249       // UNKNOWN_TYPE is reserved for use by the client.
    250       DCHECK_NE(*current_type, UNKNOWN_TYPE);
    251 
    252       AutofillFieldType heuristic_type = (*field)->type();
    253       (*field)->set_server_type(*current_type);
    254       if (heuristic_type != (*field)->type())
    255         query_response_overrode_heuristics = true;
    256 
    257       AutofillType autofill_type((*field)->type());
    258       if (autofill_type.group() == AutofillType::CREDIT_CARD)
    259         form->has_credit_card_field_ = true;
    260       if (autofill_type.field_type() != UNKNOWN_TYPE)
    261         form->has_autofillable_field_ = true;
    262     }
    263 
    264     form->UpdateAutofillCount();
    265   }
    266 
    267   AutofillMetrics::ServerQueryMetric metric;
    268   if (query_response_overrode_heuristics) {
    269     if (heuristics_detected_fillable_field) {
    270       metric = AutofillMetrics::QUERY_RESPONSE_OVERRODE_LOCAL_HEURISTICS;
    271     } else {
    272       metric = AutofillMetrics::QUERY_RESPONSE_WITH_NO_LOCAL_HEURISTICS;
    273     }
    274   } else {
    275     metric = AutofillMetrics::QUERY_RESPONSE_MATCHED_LOCAL_HEURISTICS;
    276   }
    277   metric_logger.Log(metric);
    278 }
    279 
    280 std::string FormStructure::FormSignature() const {
    281   std::string scheme(target_url_.scheme());
    282   std::string host(target_url_.host());
    283 
    284   // If target host or scheme is empty, set scheme and host of source url.
    285   // This is done to match the Toolbar's behavior.
    286   if (scheme.empty() || host.empty()) {
    287     scheme = source_url_.scheme();
    288     host = source_url_.host();
    289   }
    290 
    291   std::string form_string = scheme + "://" + host + "&" +
    292                             UTF16ToUTF8(form_name_) +
    293                             form_signature_field_names_;
    294 
    295   return Hash64Bit(form_string);
    296 }
    297 
    298 bool FormStructure::IsAutofillable(bool require_method_post) const {
    299   if (autofill_count() < kRequiredFillableFields)
    300     return false;
    301 
    302   return ShouldBeParsed(require_method_post);
    303 }
    304 
    305 void FormStructure::UpdateAutofillCount() {
    306   autofill_count_ = 0;
    307   for (std::vector<AutofillField*>::const_iterator iter = begin();
    308        iter != end(); ++iter) {
    309     AutofillField* field = *iter;
    310     if (field && field->IsFieldFillable())
    311       ++autofill_count_;
    312   }
    313 }
    314 
    315 bool FormStructure::ShouldBeParsed(bool require_method_post) const {
    316   if (field_count() < kRequiredFillableFields)
    317     return false;
    318 
    319   // Rule out http(s)://*/search?...
    320   //  e.g. http://www.google.com/search?q=...
    321   //       http://search.yahoo.com/search?p=...
    322   if (target_url_.path() == "/search")
    323     return false;
    324 
    325   return !require_method_post || (method_ == POST);
    326 }
    327 
    328 void FormStructure::UpdateFromCache(const FormStructure& cached_form) {
    329   // Map from field signatures to cached fields.
    330   std::map<std::string, const AutofillField*> cached_fields;
    331   for (size_t i = 0; i < cached_form.field_count(); ++i) {
    332     const AutofillField* field = cached_form.field(i);
    333     cached_fields[field->FieldSignature()] = field;
    334   }
    335 
    336   for (std::vector<AutofillField*>::const_iterator iter = begin();
    337        iter != end(); ++iter) {
    338     AutofillField* field = *iter;
    339     if (!field)
    340       continue;
    341 
    342     std::map<std::string, const AutofillField*>::const_iterator
    343         cached_field = cached_fields.find(field->FieldSignature());
    344     if (cached_field != cached_fields.end()) {
    345       field->set_heuristic_type(cached_field->second->heuristic_type());
    346       field->set_server_type(cached_field->second->server_type());
    347     }
    348   }
    349 
    350   UpdateAutofillCount();
    351 
    352   server_experiment_id_ = cached_form.server_experiment_id();
    353 }
    354 
    355 void FormStructure::LogQualityMetrics(
    356     const AutofillMetrics& metric_logger) const {
    357   std::string experiment_id = server_experiment_id();
    358   for (size_t i = 0; i < field_count(); ++i) {
    359     const AutofillField* field = this->field(i);
    360     metric_logger.Log(AutofillMetrics::FIELD_SUBMITTED, experiment_id);
    361 
    362     // No further logging for empty fields nor for fields where the entered data
    363     // does not appear to already exist in the user's stored Autofill data.
    364     const FieldTypeSet& field_types = field->possible_types();
    365     DCHECK(!field_types.empty());
    366     if (field_types.count(EMPTY_TYPE) || field_types.count(UNKNOWN_TYPE))
    367       continue;
    368 
    369     // Collapse field types that Chrome treats as identical, e.g. home and
    370     // billing address fields.
    371     FieldTypeSet collapsed_field_types;
    372     for (FieldTypeSet::const_iterator it = field_types.begin();
    373          it != field_types.end();
    374          ++it) {
    375       // Since we currently only support US phone numbers, the (city code + main
    376       // digits) number is almost always identical to the whole phone number.
    377       // TODO(isherman): Improve this logic once we add support for
    378       // international numbers.
    379       if (*it == PHONE_HOME_CITY_AND_NUMBER)
    380         collapsed_field_types.insert(PHONE_HOME_WHOLE_NUMBER);
    381       else if (*it == PHONE_FAX_CITY_AND_NUMBER)
    382         collapsed_field_types.insert(PHONE_FAX_WHOLE_NUMBER);
    383       else
    384         collapsed_field_types.insert(AutofillType::GetEquivalentFieldType(*it));
    385     }
    386 
    387     // Capture the field's type, if it is unambiguous.
    388     AutofillFieldType field_type = UNKNOWN_TYPE;
    389     if (collapsed_field_types.size() == 1)
    390       field_type = *collapsed_field_types.begin();
    391 
    392     AutofillFieldType heuristic_type = field->heuristic_type();
    393     AutofillFieldType server_type = field->server_type();
    394     AutofillFieldType predicted_type = field->type();
    395 
    396     // Log heuristic, server, and overall type quality metrics, independently of
    397     // whether the field was autofilled.
    398     if (heuristic_type == UNKNOWN_TYPE) {
    399       metric_logger.Log(AutofillMetrics::HEURISTIC_TYPE_UNKNOWN,
    400                         field_type, experiment_id);
    401     } else if (field_types.count(heuristic_type)) {
    402       metric_logger.Log(AutofillMetrics::HEURISTIC_TYPE_MATCH,
    403                         field_type, experiment_id);
    404     } else {
    405       metric_logger.Log(AutofillMetrics::HEURISTIC_TYPE_MISMATCH,
    406                         field_type, experiment_id);
    407     }
    408 
    409     if (server_type == NO_SERVER_DATA) {
    410       metric_logger.Log(AutofillMetrics::SERVER_TYPE_UNKNOWN,
    411                         field_type, experiment_id);
    412     } else if (field_types.count(server_type)) {
    413       metric_logger.Log(AutofillMetrics::SERVER_TYPE_MATCH,
    414                         field_type, experiment_id);
    415     } else {
    416       metric_logger.Log(AutofillMetrics::SERVER_TYPE_MISMATCH,
    417                         field_type, experiment_id);
    418     }
    419 
    420     if (predicted_type == UNKNOWN_TYPE) {
    421       metric_logger.Log(AutofillMetrics::PREDICTED_TYPE_UNKNOWN,
    422                         field_type, experiment_id);
    423     } else if (field_types.count(predicted_type)) {
    424       metric_logger.Log(AutofillMetrics::PREDICTED_TYPE_MATCH,
    425                         field_type, experiment_id);
    426     } else {
    427       metric_logger.Log(AutofillMetrics::PREDICTED_TYPE_MISMATCH,
    428                         field_type, experiment_id);
    429     }
    430 
    431     // TODO(isherman): <select> fields don't support |is_autofilled()|, so we
    432     // have to skip them for the remaining metrics.
    433     if (field->form_control_type == ASCIIToUTF16("select-one"))
    434       continue;
    435 
    436     if (field->is_autofilled) {
    437       metric_logger.Log(AutofillMetrics::FIELD_AUTOFILLED, experiment_id);
    438     } else {
    439       metric_logger.Log(AutofillMetrics::FIELD_NOT_AUTOFILLED,
    440                         experiment_id);
    441 
    442       if (heuristic_type == UNKNOWN_TYPE) {
    443         metric_logger.Log(
    444             AutofillMetrics::NOT_AUTOFILLED_HEURISTIC_TYPE_UNKNOWN,
    445             experiment_id);
    446       } else if (field_types.count(heuristic_type)) {
    447         metric_logger.Log(AutofillMetrics::NOT_AUTOFILLED_HEURISTIC_TYPE_MATCH,
    448                           experiment_id);
    449       } else {
    450         metric_logger.Log(
    451             AutofillMetrics::NOT_AUTOFILLED_HEURISTIC_TYPE_MISMATCH,
    452             experiment_id);
    453       }
    454 
    455       if (server_type == NO_SERVER_DATA) {
    456         metric_logger.Log(AutofillMetrics::NOT_AUTOFILLED_SERVER_TYPE_UNKNOWN,
    457                           experiment_id);
    458       } else if (field_types.count(server_type)) {
    459         metric_logger.Log(AutofillMetrics::NOT_AUTOFILLED_SERVER_TYPE_MATCH,
    460                           experiment_id);
    461       } else {
    462         metric_logger.Log(AutofillMetrics::NOT_AUTOFILLED_SERVER_TYPE_MISMATCH,
    463                           experiment_id);
    464       }
    465     }
    466   }
    467 }
    468 
    469 void FormStructure::set_possible_types(int index, const FieldTypeSet& types) {
    470   int num_fields = static_cast<int>(field_count());
    471   DCHECK(index >= 0 && index < num_fields);
    472   if (index >= 0 && index < num_fields)
    473     fields_[index]->set_possible_types(types);
    474 }
    475 
    476 const AutofillField* FormStructure::field(int index) const {
    477   return fields_[index];
    478 }
    479 
    480 size_t FormStructure::field_count() const {
    481   // Don't count the NULL terminator.
    482   size_t field_size = fields_.size();
    483   return (field_size == 0) ? 0 : field_size - 1;
    484 }
    485 
    486 std::string FormStructure::server_experiment_id() const {
    487   return server_experiment_id_;
    488 }
    489 
    490 bool FormStructure::operator==(const FormData& form) const {
    491   // TODO(jhawkins): Is this enough to differentiate a form?
    492   if (form_name_ == form.name &&
    493       source_url_ == form.origin &&
    494       target_url_ == form.action) {
    495     return true;
    496   }
    497 
    498   // TODO(jhawkins): Compare field names, IDs and labels once we have labels
    499   // set up.
    500 
    501   return false;
    502 }
    503 
    504 bool FormStructure::operator!=(const FormData& form) const {
    505   return !operator==(form);
    506 }
    507 
    508 std::string FormStructure::Hash64Bit(const std::string& str) {
    509   std::string hash_bin = base::SHA1HashString(str);
    510   DCHECK_EQ(20U, hash_bin.length());
    511 
    512   uint64 hash64 = (((static_cast<uint64>(hash_bin[0])) & 0xFF) << 56) |
    513                   (((static_cast<uint64>(hash_bin[1])) & 0xFF) << 48) |
    514                   (((static_cast<uint64>(hash_bin[2])) & 0xFF) << 40) |
    515                   (((static_cast<uint64>(hash_bin[3])) & 0xFF) << 32) |
    516                   (((static_cast<uint64>(hash_bin[4])) & 0xFF) << 24) |
    517                   (((static_cast<uint64>(hash_bin[5])) & 0xFF) << 16) |
    518                   (((static_cast<uint64>(hash_bin[6])) & 0xFF) << 8) |
    519                    ((static_cast<uint64>(hash_bin[7])) & 0xFF);
    520 
    521   return base::Uint64ToString(hash64);
    522 }
    523 
    524 void FormStructure::GetHeuristicFieldInfo(FieldTypeMap* field_type_map) {
    525   FormFieldSet fields(this);
    526 
    527   FormFieldSet::const_iterator field;
    528   for (field = fields.begin(); field != fields.end(); field++) {
    529     bool ok = (*field)->GetFieldInfo(field_type_map);
    530     DCHECK(ok);
    531   }
    532 }
    533 
    534 bool FormStructure::EncodeFormRequest(
    535     FormStructure::EncodeRequestType request_type,
    536     buzz::XmlElement* encompassing_xml_element) const {
    537   if (!field_count())  // Nothing to add.
    538     return false;
    539 
    540   // Some badly formatted web sites repeat fields - limit number of fields to
    541   // 48, which is far larger than any valid form and XML still fits into 2K.
    542   // Do not send requests for forms with more than this many fields, as they are
    543   // near certainly not valid/auto-fillable.
    544   const size_t kMaxFieldsOnTheForm = 48;
    545   if (field_count() > kMaxFieldsOnTheForm)
    546     return false;
    547 
    548   // Add the child nodes for the form fields.
    549   for (size_t index = 0; index < field_count(); ++index) {
    550     const AutofillField* field = fields_[index];
    551     if (request_type == FormStructure::UPLOAD) {
    552       FieldTypeSet types = field->possible_types();
    553       // |types| could be empty in unit-tests only.
    554       for (FieldTypeSet::iterator field_type = types.begin();
    555            field_type != types.end(); ++field_type) {
    556         buzz::XmlElement *field_element = new buzz::XmlElement(
    557             buzz::QName(kXMLElementField));
    558 
    559         field_element->SetAttr(buzz::QName(kAttributeSignature),
    560                                field->FieldSignature());
    561         field_element->SetAttr(buzz::QName(kAttributeAutofillType),
    562                                base::IntToString(*field_type));
    563         encompassing_xml_element->AddElement(field_element);
    564       }
    565     } else {
    566       buzz::XmlElement *field_element = new buzz::XmlElement(
    567           buzz::QName(kXMLElementField));
    568       field_element->SetAttr(buzz::QName(kAttributeSignature),
    569                              field->FieldSignature());
    570       encompassing_xml_element->AddElement(field_element);
    571     }
    572   }
    573   return true;
    574 }
    575 
    576 std::string FormStructure::ConvertPresenceBitsToString() const {
    577   std::vector<uint8> presence_bitfield;
    578   // Determine all of the field types that were autofilled. Pack bits into
    579   // |presence_bitfield|. The necessary size for |presence_bitfield| is
    580   // ceil((MAX_VALID_FIELD_TYPE + 7) / 8) bytes (uint8).
    581   presence_bitfield.resize((MAX_VALID_FIELD_TYPE + 0x7) / 8);
    582   for (size_t i = 0; i < presence_bitfield.size(); ++i)
    583     presence_bitfield[i] = 0;
    584 
    585   for (size_t i = 0; i < field_count(); ++i) {
    586     const AutofillField* field = fields_[i];
    587     FieldTypeSet types = field->possible_types();
    588     // |types| could be empty in unit-tests only.
    589     for (FieldTypeSet::iterator field_type = types.begin();
    590          field_type != types.end(); ++field_type) {
    591       DCHECK(presence_bitfield.size() > (static_cast<size_t>(*field_type) / 8));
    592       // Set bit in the bitfield: byte |field_type| / 8, bit in byte
    593       // |field_type| % 8 from the left.
    594       presence_bitfield[*field_type / 8] |= (0x80 >> (*field_type % 8));
    595     }
    596   }
    597 
    598   std::string data_presence;
    599   data_presence.reserve(presence_bitfield.size() * 2 + 1);
    600 
    601   // Skip trailing zeroes. If all mask is 0 - return empty string.
    602   size_t data_end = presence_bitfield.size();
    603   for (; data_end > 0 && !presence_bitfield[data_end - 1]; --data_end) {
    604   }
    605 
    606   // Print all meaningfull bytes into the string.
    607   for (size_t i = 0; i < data_end; ++i) {
    608     base::StringAppendF(&data_presence, "%02x", presence_bitfield[i]);
    609   }
    610 
    611   return data_presence;
    612 }
    613 
    614