Uploaded image for project: 'C Driver'
  1. C Driver
  2. CDRIVER-4820

Check return values of `bson_snprintf`

    XMLWordPrintableJSON

Details

    • Icon: Improvement Improvement
    • Resolution: Unresolved
    • Icon: Unknown Unknown
    • None
    • None
    • None
    • C Drivers

    Description

      Scope

      Check return values of bson_snprintf.

      Background & Motivation

      Calls to bson_snprintf may truncate if the destination does not have enough capacity:

      char dest[3];
      int req = bson_snprintf (dest, sizeof dest, "%s", "foobar");
      ASSERT_CMPSTR (dest, "fo"); // "foobar" is truncated.
      ASSERT_CMPINT (req, ==, 6); // Return value indicates required capacity (excluding NULL)
      

      If the destination does not have enough capacity, bson_snprintf returns the number of bytes required (excluding the trailing NULL byte).
      Many calls to bson_snprintf do not check the return value. This contributed to the bug reported in CDRIVER-4816.

      Possible Solution

      If the destination is expected to always have enough capacity (and is otherwise a bug), assert the return value is less than the capacity. Example:

      int req = bson_snprintf (dest, sizeof dest, format, input);
      BSON_ASSERT (bson_in_range_size_t_signed (req));
      // Check `dest` had enough capacity.
      BSON_ASSERT ((size_t) req < sizeof dest);
      

      If the destination is not always expected to have enough capacity (and truncating is OK), check the return value is > 0 (no error occurred).

      int req = bson_snprintf (dest, sizeof dest, format, input);
      // Check no error occurred. `dest` may expectedly not have enough capacity.
      BSON_ASSERT (req > 0);
      

      Attachments

        Activity

          People

            Unassigned Unassigned
            kevin.albertson@mongodb.com Kevin Albertson
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated: