Fix possible file descriptor leaking

Original code returns w/o closing the file descriptor
Close the descriptors and free the direct object before
return to avoid leaking

original id of the change I09204a8e989d041a12d6a6a00d1138b958f68a8f

picked from:
https://android-review.googlesource.com/#/c/23191/

Change-Id: I429c7cd0384b993c7f575306bd22be1b9c92fb35