CHROMIUM: initctl: Avoid negative indexing on length==0

In racy conditions (especially in unit tests, where we poll `initctl
list-sessions` while starting Upstart), we might find an empty session
file. If length==0, we might perform undefined behavior and read off the
front of a buffer via (a few lines down):

  if (contents[len-1] == '\n')
    ...

A 0-length file is invalid anyway, so we should skip this condition.

This should resolve reports seen like:

 * ASAN error detected:
 * initctl.c:2189:7: runtime error: addition of unsigned offset to 0x64c8e95fc700 overflowed to 0x64c8e95fc6ff
 *     #0 [...] in list_sessions_action [...]/util/initctl.c:0:0
 *     #1 [...] in nih_command_join ??:?
 *     #2 [...] in nih_command_parser ??:0:0
 *     #3 [...] in main [...]/util/initctl.c:3389:8
 *     #4 [...] in __libc_start_call_main ??:0:0
 *     #5 [...] in __libc_start_main@GLIBC_2.2.5 ??:0:0
 *     #6 [...] in _start ??:0:0
 *
 * SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior initctl.c:2189:7 in

This ASAN report is also reproduced with the new "with 1 instance and an
empty session file" test case.

BUG=b:232122437
TEST=cros_run_unit_tests with UBSAN enabled

Change-Id: I5e498cee74d2fb80d8d6937e095d534c04ebdb55
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/upstart/+/5435497
Reviewed-by: Gwendal Grignou <gwendal@chromium.org>
Tested-by: Brian Norris <briannorris@chromium.org>
Commit-Queue: Brian Norris <briannorris@chromium.org>
2 files changed