Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break gmtime_r C++

This may be an odd question, but I am trying to find a way to break the gmtime_r function. I am writing a test for this block of code, but I cannot find a case to reach the else statement that does not include setting ptr or dates to NULL.

int main() {
    time_t ptr; // Actual storage for time_t
    struct tm dates; // Actual storage for struct tm
    time(&ptr); // Pointer to a time_t
    if(gmtime_r(&ptr, &dates)) { // Pointer to a time_t, pointer to a
        size_t a = 10;
    }
    else
    {
        size_t a = 20; //<-- trying to reach this else statement
    }
return 0;
}

Are there any valid and non-NULL values to set ptr or dates to that would bypass the if-statement and go into the else?

like image 233
bmb Avatar asked Oct 30 '25 11:10

bmb


1 Answers

To provide an exact answer your question, we would need to know the implementation you're using to build your project.

Usually, standard headers like have public source, so you can search by yourself for the failure possibilities.

For glibc, I went down the rabbithole to give an example. (See source here)

In time/gmtime.c, we can see that gmtime_r is a weak alias for __gmtime_r, which returns __tz_convert directly.

In time/txset.c we see that __tz_convert can only return NULL if the __offtime function fails (returning 0).

Finally, in time/offtime.c, we see that:

  tp->tm_year = y - 1900;
  if (tp->tm_year != y - 1900)
    {
      /* The year cannot be represented due to overflow.  */
      __set_errno (EOVERFLOW);
      return 0;
    }

Which indicates a good clue about how we can make it fail. You can verify your idea with a short program.

e.g. Sample program to test out how to make gmtime_r fail

In my case, simply providing a large positive time does the trick, as the code uses integers for years, but time_t being a 64 bit value (on my system), I can have much more years than what int (on my system) can represent.

Of course, you could do the sample test program imediatly, without looking at the source.. but isn't it much more interesting that way? :P

like image 69
Alceste_ Avatar answered Nov 01 '25 01:11

Alceste_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!