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

Check return values of `bson_snprintf`

    • Type: Icon: Improvement Improvement
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 1.28.0
    • Affects Version/s: None
    • Component/s: None
    • C Drivers
    • Completed
    • Hide

      1. What would you like to communicate to the user about this feature?
      2. Would you like the user to see examples of the syntax and/or executable code and its output?
      3. Which versions of the driver/connector does this apply to?

      Show
      1. What would you like to communicate to the user about this feature? 2. Would you like the user to see examples of the syntax and/or executable code and its output? 3. Which versions of the driver/connector does this apply to?

      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);
      

            Assignee:
            laurel.xiang@mongodb.com Laurel Xiang
            Reporter:
            kevin.albertson@mongodb.com Kevin Albertson
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: