zmq.cpp 20.6 KB
Newer Older
Martin Sustrik's avatar
Martin Sustrik committed
1
/*
2
    Copyright (c) 2007-2010 iMatix Corporation
Martin Sustrik's avatar
Martin Sustrik committed
3 4 5 6

    This file is part of 0MQ.

    0MQ is free software; you can redistribute it and/or modify it under
7
    the terms of the GNU Lesser General Public License as published by
Martin Sustrik's avatar
Martin Sustrik committed
8 9 10 11 12 13
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    0MQ is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
    GNU Lesser General Public License for more details.
Martin Sustrik's avatar
Martin Sustrik committed
15

16
    You should have received a copy of the GNU Lesser General Public License
Martin Sustrik's avatar
Martin Sustrik committed
17 18 19
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include "platform.hpp"

//  On AIX, poll.h has to be included before zmq.h to get consistent
//  definition of pollfd structure (AIX uses 'reqevents' and 'retnevents'
//  instead of 'events' and 'revents' and defines macros to map from POSIX-y
//  names to AIX-specific names).
#if defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
    defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_SOLARIS ||\
    defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_QNXNTO ||\
    defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_AIX ||\
    defined ZMQ_HAVE_NETBSD
#include <poll.h>
#endif

34
#include "../include/zmq.h"
Martin Sustrik's avatar
Martin Sustrik committed
35
#include "../include/zmq_utils.h"
Martin Sustrik's avatar
Martin Sustrik committed
36

37
#include <string.h>
Martin Sustrik's avatar
Martin Sustrik committed
38 39 40 41
#include <errno.h>
#include <stdlib.h>
#include <new>

42
#include "device.hpp"
43
#include "socket_base.hpp"
44
#include "msg_content.hpp"
45
#include "stdint.hpp"
46
#include "config.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
47
#include "clock.hpp"
48
#include "ctx.hpp"
49
#include "err.hpp"
50
#include "fd.hpp"
51

52 53 54
#if !defined ZMQ_HAVE_WINDOWS
#include <unistd.h>
#endif
Martin Sustrik's avatar
Martin Sustrik committed
55

56
#if defined ZMQ_HAVE_OPENPGM
57
#define __PGM_WININT_H__
58 59 60
#include <pgm/pgm.h>
#endif

61 62 63 64
#if defined __GNUC__ && __GNUC__ >= 4 && !defined ZMQ_HAVE_WINDOWS
#pragma GCC visibility push(default)
#endif

65 66
void zmq_version (int *major_, int *minor_, int *patch_)
{
Martin Sustrik's avatar
Martin Sustrik committed
67 68 69
    *major_ = ZMQ_VERSION_MAJOR;
    *minor_ = ZMQ_VERSION_MINOR;
    *patch_ = ZMQ_VERSION_PATCH;
70 71
}

72 73
const char *zmq_strerror (int errnum_)
{
74
    return zmq::errno_to_string (errnum_);
75 76
}

77
int zmq_msg_init (zmq_msg_t *msg_)
Martin Sustrik's avatar
Martin Sustrik committed
78
{
79
    msg_->content = (zmq::msg_content_t*) ZMQ_VSM;
80
    msg_->flags = 0;
Martin Sustrik's avatar
Martin Sustrik committed
81 82 83 84
    msg_->vsm_size = 0;
    return 0;
}

85
int zmq_msg_init_size (zmq_msg_t *msg_, size_t size_)
Martin Sustrik's avatar
Martin Sustrik committed
86
{
Martin Sustrik's avatar
Martin Sustrik committed
87
    if (size_ <= ZMQ_MAX_VSM_SIZE) {
88
        msg_->content = (zmq::msg_content_t*) ZMQ_VSM;
89
        msg_->flags = 0;
90
        msg_->vsm_size = (uint8_t) size_;
Martin Sustrik's avatar
Martin Sustrik committed
91 92
    }
    else {
93 94
        msg_->content =
            (zmq::msg_content_t*) malloc (sizeof (zmq::msg_content_t) + size_);
Martin Sustrik's avatar
Martin Sustrik committed
95 96 97 98
        if (!msg_->content) {
            errno = ENOMEM;
            return -1;
        }
99 100
        msg_->flags = 0;
        
101 102 103 104
        zmq::msg_content_t *content = (zmq::msg_content_t*) msg_->content;
        content->data = (void*) (content + 1);
        content->size = size_;
        content->ffn = NULL;
105
        content->hint = NULL;
106
        new (&content->refcnt) zmq::atomic_counter_t ();
Martin Sustrik's avatar
Martin Sustrik committed
107 108 109 110
    }
    return 0;
}

111
int zmq_msg_init_data (zmq_msg_t *msg_, void *data_, size_t size_,
112
    zmq_free_fn *ffn_, void *hint_)
Martin Sustrik's avatar
Martin Sustrik committed
113
{
114
    msg_->content = (zmq::msg_content_t*) malloc (sizeof (zmq::msg_content_t));
Martin Sustrik's avatar
Martin Sustrik committed
115
    zmq_assert (msg_->content);
116
    msg_->flags = 0;
117 118 119 120
    zmq::msg_content_t *content = (zmq::msg_content_t*) msg_->content;
    content->data = data_;
    content->size = size_;
    content->ffn = ffn_;
121
    content->hint = hint_;
122
    new (&content->refcnt) zmq::atomic_counter_t ();
Martin Sustrik's avatar
Martin Sustrik committed
123 124 125
    return 0;
}

126
int zmq_msg_close (zmq_msg_t *msg_)
Martin Sustrik's avatar
Martin Sustrik committed
127
{
128
    //  For VSMs and delimiters there are no resources to free.
129 130
    if (msg_->content != (zmq::msg_content_t*) ZMQ_DELIMITER &&
          msg_->content != (zmq::msg_content_t*) ZMQ_VSM) {
Martin Sustrik's avatar
Martin Sustrik committed
131

132 133 134 135
        //  If the content is not shared, or if it is shared and the reference.
        //  count has dropped to zero, deallocate it.
        zmq::msg_content_t *content = (zmq::msg_content_t*) msg_->content;
        if (!(msg_->flags & ZMQ_MSG_SHARED) || !content->refcnt.sub (1)) {
Martin Sustrik's avatar
Martin Sustrik committed
136

137 138 139
            //  We used "placement new" operator to initialize the reference.
            //  counter so we call its destructor now.
            content->refcnt.~atomic_counter_t ();
Martin Sustrik's avatar
Martin Sustrik committed
140

141 142 143 144
            if (content->ffn)
                content->ffn (content->data, content->hint);
            free (content);
        }
Martin Sustrik's avatar
Martin Sustrik committed
145 146
    }

147 148 149 150 151 152
    //  As a safety measure, let's make the deallocated message look like
    //  an empty message.
    msg_->content = (zmq::msg_content_t*) ZMQ_VSM;
    msg_->flags = 0;
    msg_->vsm_size = 0;

Martin Sustrik's avatar
Martin Sustrik committed
153 154 155
    return 0;
}

156
int zmq_msg_move (zmq_msg_t *dest_, zmq_msg_t *src_)
Martin Sustrik's avatar
Martin Sustrik committed
157
{
Martin Sustrik's avatar
Martin Sustrik committed
158
    zmq_msg_close (dest_);
Martin Sustrik's avatar
Martin Sustrik committed
159
    *dest_ = *src_;
Martin Sustrik's avatar
Martin Sustrik committed
160
    zmq_msg_init (src_);
Martin Sustrik's avatar
Martin Sustrik committed
161 162 163
    return 0;
}

164
int zmq_msg_copy (zmq_msg_t *dest_, zmq_msg_t *src_)
Martin Sustrik's avatar
Martin Sustrik committed
165
{
Martin Sustrik's avatar
Martin Sustrik committed
166
    zmq_msg_close (dest_);
Martin Sustrik's avatar
Martin Sustrik committed
167 168

    //  VSMs and delimiters require no special handling.
169 170
    if (src_->content != (zmq::msg_content_t*) ZMQ_DELIMITER &&
          src_->content != (zmq::msg_content_t*) ZMQ_VSM) {
Martin Sustrik's avatar
Martin Sustrik committed
171 172 173

        //  One reference is added to shared messages. Non-shared messages
        //  are turned into shared messages and reference count is set to 2.
174
        zmq::msg_content_t *content = (zmq::msg_content_t*) src_->content;
175
        if (src_->flags & ZMQ_MSG_SHARED)
176
            content->refcnt.add (1);
Martin Sustrik's avatar
Martin Sustrik committed
177
        else {
178
            src_->flags |= ZMQ_MSG_SHARED;
179
            content->refcnt.set (2);
Martin Sustrik's avatar
Martin Sustrik committed
180 181 182 183 184 185 186
        }
    }

    *dest_ = *src_;
    return 0;
}

187
void *zmq_msg_data (zmq_msg_t *msg_)
Martin Sustrik's avatar
Martin Sustrik committed
188
{
189
    if (msg_->content == (zmq::msg_content_t*) ZMQ_VSM)
Martin Sustrik's avatar
Martin Sustrik committed
190
        return msg_->vsm_data;
191
    if (msg_->content == (zmq::msg_content_t*) ZMQ_DELIMITER)
Martin Sustrik's avatar
Martin Sustrik committed
192
        return NULL;
193 194

    return ((zmq::msg_content_t*) msg_->content)->data;
Martin Sustrik's avatar
Martin Sustrik committed
195 196
}

197
size_t zmq_msg_size (zmq_msg_t *msg_)
Martin Sustrik's avatar
Martin Sustrik committed
198
{
199
    if (msg_->content == (zmq::msg_content_t*) ZMQ_VSM)
Martin Sustrik's avatar
Martin Sustrik committed
200
        return msg_->vsm_size;
201
    if (msg_->content == (zmq::msg_content_t*) ZMQ_DELIMITER)
Martin Sustrik's avatar
Martin Sustrik committed
202
        return 0;
203 204

    return ((zmq::msg_content_t*) msg_->content)->size;
Martin Sustrik's avatar
Martin Sustrik committed
205 206
}

207
void *zmq_init (int io_threads_)
Martin Sustrik's avatar
Martin Sustrik committed
208
{
209 210 211 212
    if (io_threads_ < 0) {
        errno = EINVAL;
        return NULL;
    }
Martin Sustrik's avatar
Martin Sustrik committed
213

214 215 216 217 218 219
#if defined ZMQ_HAVE_OPENPGM

    //  Init PGM transport. Ensure threading and timer are enabled. Find PGM
    //  protocol ID. Note that if you want to use gettimeofday and sleep for
    //  openPGM timing, set environment variables PGM_TIMER to "GTOD" and
    //  PGM_SLEEP to "USLEEP".
Steven McCoy's avatar
Steven McCoy committed
220
    pgm_error_t *pgm_error = NULL;
221
    const bool rc = pgm_init (&pgm_error);
222
    if (rc != TRUE) {
223 224 225 226 227 228 229

        //  Invalid parameters don't set pgm_error_t
        zmq_assert (pgm_error != NULL);
        if (pgm_error->domain == PGM_ERROR_DOMAIN_TIME && (
              pgm_error->code == PGM_ERROR_FAILED)) {

            //  Failed to access RTC or HPET device.
Steven McCoy's avatar
Steven McCoy committed
230
            pgm_error_free (pgm_error);
231 232 233
            errno = EINVAL;
            return NULL;
        }
234 235

        //  PGM_ERROR_DOMAIN_ENGINE: WSAStartup errors or missing WSARecvMsg.
236 237 238 239 240
        zmq_assert (false);
    }
#endif

    //  Create 0MQ context.
241 242 243
    zmq::ctx_t *ctx = new (std::nothrow) zmq::ctx_t ((uint32_t) io_threads_);
    zmq_assert (ctx);
    return (void*) ctx;
Martin Sustrik's avatar
Martin Sustrik committed
244 245
}

246
int zmq_term (void *ctx_)
Martin Sustrik's avatar
Martin Sustrik committed
247
{
248 249 250 251
    if (!ctx_) {
        errno = EFAULT;
        return -1;
    }
252 253 254 255

    int rc = ((zmq::ctx_t*) ctx_)->terminate ();
    int en = errno;

256 257 258 259 260 261 262 263
#if defined ZMQ_HAVE_OPENPGM
    //  Shut down the OpenPGM library.
    if (pgm_shutdown () != TRUE)
        zmq_assert (false);
#endif

    errno = en;
    return rc;
Martin Sustrik's avatar
Martin Sustrik committed
264 265
}

266
void *zmq_socket (void *ctx_, int type_)
Martin Sustrik's avatar
Martin Sustrik committed
267
{
268 269 270 271
    if (!ctx_) {
        errno = EFAULT;
        return NULL;
    }
272
    return (void*) (((zmq::ctx_t*) ctx_)->create_socket (type_));
Martin Sustrik's avatar
Martin Sustrik committed
273 274
}

Martin Sustrik's avatar
Martin Sustrik committed
275
int zmq_close (void *s_)
Martin Sustrik's avatar
Martin Sustrik committed
276
{
277 278 279 280
    if (!s_) {
        errno = EFAULT;
        return -1;
    }
281
    ((zmq::socket_base_t*) s_)->close ();
Martin Sustrik's avatar
Martin Sustrik committed
282 283 284
    return 0;
}

285 286
int zmq_setsockopt (void *s_, int option_, const void *optval_,
    size_t optvallen_)
Martin Sustrik's avatar
Martin Sustrik committed
287
{
288 289 290 291
    if (!s_) {
        errno = EFAULT;
        return -1;
    }
292 293
    return (((zmq::socket_base_t*) s_)->setsockopt (option_, optval_,
        optvallen_));
Martin Sustrik's avatar
Martin Sustrik committed
294 295
}

296 297
int zmq_getsockopt (void *s_, int option_, void *optval_, size_t *optvallen_)
{
298 299 300 301
    if (!s_) {
        errno = EFAULT;
        return -1;
    }
302 303 304 305
    return (((zmq::socket_base_t*) s_)->getsockopt (option_, optval_,
        optvallen_));
}

306
int zmq_bind (void *s_, const char *addr_)
Martin Sustrik's avatar
Martin Sustrik committed
307
{
308 309 310 311
    if (!s_) {
        errno = EFAULT;
        return -1;
    }
312
    return (((zmq::socket_base_t*) s_)->bind (addr_));
313 314 315 316
}

int zmq_connect (void *s_, const char *addr_)
{
317 318 319 320
    if (!s_) {
        errno = EFAULT;
        return -1;
    }
321
    return (((zmq::socket_base_t*) s_)->connect (addr_));
Martin Sustrik's avatar
Martin Sustrik committed
322 323
}

324
int zmq_send (void *s_, zmq_msg_t *msg_, int flags_)
Martin Sustrik's avatar
Martin Sustrik committed
325
{
326 327 328 329
    if (!s_) {
        errno = EFAULT;
        return -1;
    }
330
    return (((zmq::socket_base_t*) s_)->send (msg_, flags_));
Martin Sustrik's avatar
Martin Sustrik committed
331 332
}

333
int zmq_recv (void *s_, zmq_msg_t *msg_, int flags_)
Martin Sustrik's avatar
Martin Sustrik committed
334
{
335 336 337 338
    if (!s_) {
        errno = EFAULT;
        return -1;
    }
339
    return (((zmq::socket_base_t*) s_)->recv (msg_, flags_));
Martin Sustrik's avatar
Martin Sustrik committed
340
}
341

342 343 344 345 346
#if defined ZMQ_FORCE_SELECT
#define ZMQ_POLL_BASED_ON_SELECT
#elif defined ZMQ_FORCE_POLL
#define ZMQ_POLL_BASED_ON_POLL
#elif defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
347 348
    defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_SOLARIS ||\
    defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_QNXNTO ||\
Martin Lucina's avatar
Martin Lucina committed
349 350
    defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_AIX ||\
    defined ZMQ_HAVE_NETBSD
351 352 353 354 355 356 357 358
#define ZMQ_POLL_BASED_ON_POLL
#elif defined ZMQ_HAVE_WINDOWS || defined ZMQ_HAVE_OPENVMS
#define ZMQ_POLL_BASED_ON_SELECT
#endif

int zmq_poll (zmq_pollitem_t *items_, int nitems_, long timeout_)
{
#if defined ZMQ_POLL_BASED_ON_POLL
359

360 361 362 363
    if (!items_) {
        errno = EFAULT;
        return -1;
    }
364

365 366 367 368
    zmq::clock_t clock;
    uint64_t now = 0;
    uint64_t end = 0;

369 370 371
    pollfd *pollfds = (pollfd*) malloc (nitems_ * sizeof (pollfd));
    zmq_assert (pollfds);

372
    //  Build pollset for poll () system call.
373 374
    for (int i = 0; i != nitems_; i++) {

375 376
        //  If the poll item is a 0MQ socket, we poll on the file descriptor
        //  retrieved by the ZMQ_FD socket option.
377
        if (items_ [i].socket) {
378
            size_t zmq_fd_size = sizeof (zmq::fd_t);
379 380 381 382
            if (zmq_getsockopt (items_ [i].socket, ZMQ_FD, &pollfds [i].fd,
                &zmq_fd_size) == -1) {
                free (pollfds);
                return -1;
383
            }
384
            pollfds [i].events = items_ [i].events ? POLLIN : 0;
385
        }
386 387
        //  Else, the poll item is a raw file descriptor. Just convert the
        //  events to normal POLLIN/POLLOUT for poll ().
Martin Lucina's avatar
Martin Lucina committed
388
        else {
389 390 391 392
            pollfds [i].fd = items_ [i].fd;
            pollfds [i].events =
                (items_ [i].events & ZMQ_POLLIN ? POLLIN : 0) |
                (items_ [i].events & ZMQ_POLLOUT ? POLLOUT : 0);
Martin Lucina's avatar
Martin Lucina committed
393
        }
394 395
    }

396
    bool first_pass = true;
397
    int nevents = 0;
398

399
    while (true) {
400

401 402 403 404 405 406 407 408 409
         //  Compute the timeout for the subsequent poll.
         int timeout;
         if (first_pass)
             timeout = 0;
         else if (timeout_ < 0)
             timeout = -1;
         else
             timeout = end - now;

410
        //  Wait for events.
411
        while (true) {
412
            int rc = poll (pollfds, nitems_, timeout);
413
            if (rc == -1 && errno == EINTR) {
414 415
                free (pollfds);
                return -1;
416
            }
417 418
            errno_assert (rc >= 0);
            break;
419
        }
420

421 422
        //  Check for the events.
        for (int i = 0; i != nitems_; i++) {
423

424
            items_ [i].revents = 0;
425

426 427
            //  The poll item is a 0MQ socket. Retrieve pending events
            //  using the ZMQ_EVENTS socket option.
428
            if (items_ [i].socket) {
429 430 431 432 433 434 435 436 437 438 439 440 441
                size_t zmq_events_size = sizeof (uint32_t);
                uint32_t zmq_events;
                if (zmq_getsockopt (items_ [i].socket, ZMQ_EVENTS, &zmq_events,
                    &zmq_events_size) == -1) {
                    free (pollfds);
                    return -1;
                }
                if ((items_ [i].events & ZMQ_POLLOUT) &&
                      (zmq_events & ZMQ_POLLOUT))
                    items_ [i].revents |= ZMQ_POLLOUT;
                if ((items_ [i].events & ZMQ_POLLIN) &&
                      (zmq_events & ZMQ_POLLIN))
                    items_ [i].revents |= ZMQ_POLLIN;
442
            }
443 444 445 446 447 448 449 450 451 452 453 454 455
            //  Else, the poll item is a raw file descriptor, simply convert
            //  the events to zmq_pollitem_t-style format.
            else {
                if (pollfds [i].revents & POLLIN)
                    items_ [i].revents |= ZMQ_POLLIN;
                if (pollfds [i].revents & POLLOUT)
                    items_ [i].revents |= ZMQ_POLLOUT;
                if (pollfds [i].revents & ~(POLLIN | POLLOUT))
                    items_ [i].revents |= ZMQ_POLLERR;
            }

            if (items_ [i].revents)
                nevents++;
456
        }
457

458 459 460
        //  If timout is zero, exit immediately whether there are events or not.
        if (timeout_ == 0)
            break;
461

462 463 464 465 466 467
        //  If there are events to return, we can exit immediately.
        if (nevents)
            break;

        //  At this point we are meant to wait for events but there are none.
        //  If timeout is infinite we can just loop until we get some events.
468 469 470
        if (timeout_ < 0) {
            if (first_pass)
                first_pass = false;
471
            continue;
472
        }
473

474 475 476 477 478 479 480
        //  The timeout is finite and there are no events. In the first pass
        //  we get a timestamp of when the polling have begun. (We assume that
        //  first pass have taken negligible time). We also compute the time
        //  when the polling should time out.
        if (first_pass) {
            now = clock.now_ms ();
            end = now + (timeout_ / 1000);
481 482 483
            if (now == end)
                break;
            first_pass = false;
484 485
            continue;
        }
486

487 488 489 490
        //  Find out whether timeout have expired.
        now = clock.now_ms ();
        if (now >= end)
            break;
491 492 493 494 495
    }

    free (pollfds);
    return nevents;

496
#elif defined ZMQ_POLL_BASED_ON_SELECT
497

498 499 500 501 502 503 504 505 506 507 508 509 510
    if (!items_) {
        errno = EFAULT;
        return -1;
    }

    zmq::clock_t clock;
    uint64_t now = 0;
    uint64_t end = 0;

    //  Ensure we do not attempt to select () on more than FD_SETSIZE
    //  file descriptors.
    zmq_assert (nitems_ <= FD_SETSIZE);

511 512 513 514 515 516 517
    fd_set pollset_in;
    FD_ZERO (&pollset_in);
    fd_set pollset_out;
    FD_ZERO (&pollset_out);
    fd_set pollset_err;
    FD_ZERO (&pollset_err);

518
    zmq::fd_t maxfd = 0;
519

520
    //  Build the fd_sets for passing to select ().
521 522
    for (int i = 0; i != nitems_; i++) {

523 524
        //  If the poll item is a 0MQ socket we are interested in input on the
        //  notification file descriptor retrieved by the ZMQ_FD socket option.
525
        if (items_ [i].socket) {
526 527 528 529 530
            size_t zmq_fd_size = sizeof (zmq::fd_t);
            zmq::fd_t notify_fd;
            if (zmq_getsockopt (items_ [i].socket, ZMQ_FD, &notify_fd,
                &zmq_fd_size) == -1)
                return -1;
531 532 533 534 535
            if (items_ [i].events) {
                FD_SET (notify_fd, &pollset_in);
                if (maxfd < notify_fd)
                    maxfd = notify_fd;
            }
536
        }
537 538 539 540 541 542 543 544 545 546 547
        //  Else, the poll item is a raw file descriptor. Convert the poll item
        //  events to the appropriate fd_sets.
        else {
            if (items_ [i].events & ZMQ_POLLIN)
                FD_SET (items_ [i].fd, &pollset_in);
            if (items_ [i].events & ZMQ_POLLOUT)
                FD_SET (items_ [i].fd, &pollset_out);
            if (items_ [i].events & ZMQ_POLLERR)
                FD_SET (items_ [i].fd, &pollset_err);
            if (maxfd < items_ [i].fd)
                maxfd = items_ [i].fd;
548 549 550
        }
    }

551
    bool first_pass = true;
552
    int nevents = 0;
553
    fd_set inset, outset, errset;
554 555

    while (true) {
556

557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
        //  Compute the timeout for the subsequent poll.
        timeval timeout;
        timeval *ptimeout;
        if (first_pass) {
            timeout.tv_sec = 0;
            timeout.tv_usec = 0;
            ptimeout = &timeout;
        }
        else if (timeout_ < 0)
            ptimeout = NULL;
        else {
            timeout.tv_sec = (long) ((end - now) / 1000);
            timeout.tv_usec = (long) ((end - now) % 1000 * 1000);
            ptimeout = &timeout;
        }

573 574 575 576 577
        //  Wait for events. Ignore interrupts if there's infinite timeout.
        while (true) {
            memcpy (&inset, &pollset_in, sizeof (fd_set));
            memcpy (&outset, &pollset_out, sizeof (fd_set));
            memcpy (&errset, &pollset_err, sizeof (fd_set));
578
            int rc = select (maxfd + 1, &inset, &outset, &errset, ptimeout);
579
#if defined ZMQ_HAVE_WINDOWS
580
            wsa_assert (rc != SOCKET_ERROR);
581
#else
582 583
            if (rc == -1 && errno == EINTR)
                return -1;
584
            errno_assert (rc >= 0);
585
#endif
586 587
            break;
        }
588

589 590
        //  Check for the events.
        for (int i = 0; i != nitems_; i++) {
591

592
            items_ [i].revents = 0;
593

594 595 596
            //  The poll item is a 0MQ socket. Retrieve pending events
            //  using the ZMQ_EVENTS socket option.
            if (items_ [i].socket) {
597 598 599 600
                size_t zmq_events_size = sizeof (uint32_t);
                uint32_t zmq_events;
                if (zmq_getsockopt (items_ [i].socket, ZMQ_EVENTS, &zmq_events,
                      &zmq_events_size) == -1)
601
                    return -1;
602 603 604 605 606 607
                if ((items_ [i].events & ZMQ_POLLOUT) &&
                      (zmq_events & ZMQ_POLLOUT))
                    items_ [i].revents |= ZMQ_POLLOUT;
                if ((items_ [i].events & ZMQ_POLLIN) &&
                      (zmq_events & ZMQ_POLLIN))
                    items_ [i].revents |= ZMQ_POLLIN;
608 609 610 611 612
            }
            //  Else, the poll item is a raw file descriptor, simply convert
            //  the events to zmq_pollitem_t-style format.
            else {
                if (FD_ISSET (items_ [i].fd, &inset))
613
                    items_ [i].revents |= ZMQ_POLLIN;
614 615 616 617
                if (FD_ISSET (items_ [i].fd, &outset))
                    items_ [i].revents |= ZMQ_POLLOUT;
                if (FD_ISSET (items_ [i].fd, &errset))
                    items_ [i].revents |= ZMQ_POLLERR;
618
            }
619 620 621

            if (items_ [i].revents)
                nevents++;
622
        }
623

624 625 626
        //  If timout is zero, exit immediately whether there are events or not.
        if (timeout_ == 0)
            break;
627

628 629 630 631 632 633
        //  If there are events to return, we can exit immediately.
        if (nevents)
            break;

        //  At this point we are meant to wait for events but there are none.
        //  If timeout is infinite we can just loop until we get some events.
634 635 636
        if (timeout_ < 0) {
            if (first_pass)
                first_pass = false;
637
            continue;
638
        }
639

640 641 642 643 644 645 646
        //  The timeout is finite and there are no events. In the first pass
        //  we get a timestamp of when the polling have begun. (We assume that
        //  first pass have taken negligible time). We also compute the time
        //  when the polling should time out.
        if (first_pass) {
            now = clock.now_ms ();
            end = now + (timeout_ / 1000);
647 648 649
            if (now == end)
                break;
            first_pass = false;
650 651
            continue;
        }
652

653 654 655 656
        //  Find out whether timeout have expired.
        now = clock.now_ms ();
        if (now >= end)
            break;
657 658 659 660 661
    }

    return nevents;

#else
662
    //  Exotic platforms that support neither poll() nor select().
663 664
    errno = ENOTSUP;
    return -1;
665 666 667
#endif
}

668 669 670 671 672 673 674
#if defined ZMQ_POLL_BASED_ON_SELECT
#undef ZMQ_POLL_BASED_ON_SELECT
#endif
#if defined ZMQ_POLL_BASED_ON_POLL
#undef ZMQ_POLL_BASED_ON_POLL
#endif

675 676 677 678 679
int zmq_errno ()
{
    return errno;
}

680 681
int zmq_device (int device_, void *insocket_, void *outsocket_)
{
682 683 684 685
    if (!insocket_ || !outsocket_) {
        errno = EFAULT;
        return -1;
    }
686 687 688 689 690

    if (device_ != ZMQ_FORWARDER && device_ != ZMQ_QUEUE &&
          device_ != ZMQ_STREAMER) {
       errno = EINVAL;
       return -1;
691
    }
692 693 694

    return zmq::device ((zmq::socket_base_t*) insocket_,
        (zmq::socket_base_t*) outsocket_);
695
}
696 697 698 699 700 701 702

////////////////////////////////////////////////////////////////////////////////
//  0MQ utils - to be used by perf tests
////////////////////////////////////////////////////////////////////////////////

void zmq_sleep (int seconds_)
{
Martin Sustrik's avatar
Martin Sustrik committed
703
#if defined ZMQ_HAVE_WINDOWS
704 705 706 707
    Sleep (seconds_ * 1000);
#else
    sleep (seconds_);
#endif
Martin Sustrik's avatar
Martin Sustrik committed
708
}
709 710 711 712 713

void *zmq_stopwatch_start ()
{
    uint64_t *watch = (uint64_t*) malloc (sizeof (uint64_t));
    assert (watch);
Martin Sustrik's avatar
Martin Sustrik committed
714
    *watch = zmq::clock_t::now_us ();
715 716 717 718 719
    return (void*) watch;
}

unsigned long zmq_stopwatch_stop (void *watch_)
{
Martin Sustrik's avatar
Martin Sustrik committed
720
    uint64_t end = zmq::clock_t::now_us ();
721 722 723 724 725
    uint64_t start = *(uint64_t*) watch_;
    free (watch_);
    return (unsigned long) (end - start);
}

726 727 728 729
#if defined __GNUC__ && __GNUC__ >= 4 && !defined ZMQ_HAVE_WINDOWS
#pragma GCC visibility pop
#endif