From b6232b96ddda96f3d72dd787fae0b0087ddbcab9 Mon Sep 17 00:00:00 2001 From: Josh Gao Date: Wed, 17 Feb 2016 16:45:39 -0800 Subject: [PATCH] adb: move win32 fd base to 2048, fix fd allocation. Windows has a maximum fd limit of 2048, so we can avoid collision with real file descriptors by starting from there. Also, fds would be previously be allocated by a linear walk from the last allocated FD, instead of the lowest available FD, as required by POSIX. Keep track of the lowest available file descriptor to make things feel more familiar. Change-Id: Id6ac1c54f4f7964a6cdfa8d3f4f96262e4881964 --- adb/sysdeps_win32.cpp | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/adb/sysdeps_win32.cpp b/adb/sysdeps_win32.cpp index 0dbfb9847..c36d77991 100644 --- a/adb/sysdeps_win32.cpp +++ b/adb/sysdeps_win32.cpp @@ -190,8 +190,7 @@ typedef struct FHRec_ #define fh_handle u.handle #define fh_socket u.socket -#define WIN32_FH_BASE 100 - +#define WIN32_FH_BASE 2048 #define WIN32_MAX_FHS 128 static adb_mutex_t _win32_lock; @@ -241,17 +240,10 @@ _fh_alloc( FHClass clazz ) adb_mutex_lock( &_win32_lock ); - // Search entire array, starting from _win32_fh_next. - for (int nn = 0; nn < WIN32_MAX_FHS; nn++) { - // Keep incrementing _win32_fh_next to avoid giving out an index that - // was recently closed, to try to avoid use-after-free. - const int index = _win32_fh_next++; - // Handle wrap-around of _win32_fh_next. - if (_win32_fh_next == WIN32_MAX_FHS) { - _win32_fh_next = 0; - } - if (_win32_fhs[index].clazz == NULL) { - f = &_win32_fhs[index]; + for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) { + if (_win32_fhs[i].clazz == NULL) { + f = &_win32_fhs[i]; + _win32_fh_next = i + 1; goto Exit; } } @@ -276,6 +268,12 @@ _fh_close( FH f ) // Use lock so that closing only happens once and so that _fh_alloc can't // allocate a FH that we're in the middle of closing. adb_mutex_lock(&_win32_lock); + + int offset = f - _win32_fhs; + if (_win32_fh_next > offset) { + _win32_fh_next = offset; + } + if (f->used) { f->clazz->_fh_close( f ); f->name[0] = '\0';