db-d2/primevul-codebert-embeddings huggingface dataset:
Commit message: Disabled external entities loading
CVE: CVE-2013-1643
CWE: CWE-200
Vulnerability description: The SOAP parser in PHP before 5.3.23 and 5.4.x before 5.4.13 allows remote attackers to read arbitrary files via a SOAP WSDL file containing an XML external entity declaration in conjunction with an entity reference, related to an XML External Entity (XXE) issue in the soap_xmlParseFile and soap_xmlParseMemory functions.  NOTE: this vulnerability exists because of an incorrect fix for CVE-2013-1824.

Project: php-src
File: php_xml.c

xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
{
	xmlParserCtxtPtr ctxt = NULL;
	xmlDocPtr ret;

/*
	xmlInitParser();
*/
	ctxt = xmlCreateMemoryParserCtxt(buf, buf_size);
	if (ctxt) {
		ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
		ctxt->sax->comment = soap_Comment;
		ctxt->sax->warning = NULL;
		ctxt->sax->error = NULL;
		/*ctxt->sax->fatalError = NULL;*/
#if LIBXML_VERSION >= 20703
		ctxt->options |= XML_PARSE_HUGE;
#endif
		xmlParseDocument(ctxt);
		if (ctxt->wellFormed) {
			ret = ctxt->myDoc;
			if (ret->URL == NULL && ctxt->directory != NULL) {
				ret->URL = xmlCharStrdup(ctxt->directory);
			}
		} else {
			ret = NULL;
			xmlFreeDoc(ctxt->myDoc);
			ctxt->myDoc = NULL;
		}
		xmlFreeParserCtxt(ctxt);
	} else {
		ret = NULL;
	}

/*
	xmlCleanupParser();
*/

/*
	if (ret) {
		cleanup_xml_node((xmlNodePtr)ret);
	}
*/
	return ret;
}

Project: php-src
File: php_xml.c

xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
	xmlParserCtxtPtr ctxt = NULL;
	xmlDocPtr ret;
	zend_bool old_allow_url_fopen;

/*
	xmlInitParser();
*/

	old_allow_url_fopen = PG(allow_url_fopen);
	PG(allow_url_fopen) = 1;
	ctxt = xmlCreateFileParserCtxt(filename);
	PG(allow_url_fopen) = old_allow_url_fopen;
	if (ctxt) {
		ctxt->keepBlanks = 0;
		ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
		ctxt->sax->comment = soap_Comment;
		ctxt->sax->warning = NULL;
		ctxt->sax->error = NULL;
		/*ctxt->sax->fatalError = NULL;*/
		xmlParseDocument(ctxt);
		if (ctxt->wellFormed) {
			ret = ctxt->myDoc;
			if (ret->URL == NULL && ctxt->directory != NULL) {
				ret->URL = xmlCharStrdup(ctxt->directory);
			}
		} else {
			ret = NULL;
			xmlFreeDoc(ctxt->myDoc);
			ctxt->myDoc = NULL;
		}
		xmlFreeParserCtxt(ctxt);
	} else {
		ret = NULL;
	}

/*
	xmlCleanupParser();
*/

	if (ret) {
		cleanup_xml_node((xmlNodePtr)ret);
	}
	return ret;
}
Commit message: ICU-20246 Fixing another integer overflow in number parsing.
CVE: CVE-2018-18928
CWE: CWE-190
Vulnerability description: International Components for Unicode (ICU) for C/C++ 63.1 has an integer overflow in number::impl::DecimalQuantity::toScientificString() in i18n/number_decimalquantity.cpp.

Project: icu
File: number_decimalquantity.cpp

UnicodeString DecimalQuantity::toScientificString() const {
    U_ASSERT(!isApproximate);
    UnicodeString result;
    if (isNegative()) {
        result.append(u'-');
    }
    if (precision == 0) {
        result.append(u"0E+0", -1);
        return result;
    }
    // NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from
    // rOptPos (aka -maxFrac) due to overflow.
    int32_t upperPos = std::min(precision + scale, lOptPos) - scale - 1;
    int32_t lowerPos = std::max(scale, rOptPos) - scale;
    int32_t p = upperPos;
    result.append(u'0' + getDigitPos(p));
    if ((--p) >= lowerPos) {
        result.append(u'.');
        for (; p >= lowerPos; p--) {
            result.append(u'0' + getDigitPos(p));
        }
    }
    result.append(u'E');
    int32_t _scale = upperPos + scale;
    if (_scale < 0) {
        _scale *= -1;
        result.append(u'-');
    } else {
        result.append(u'+');
    }
    if (_scale == 0) {
        result.append(u'0');
    }
    int32_t insertIndex = result.length();
    while (_scale > 0) {
        std::div_t res = std::div(_scale, 10);
        result.insert(insertIndex, u'0' + res.rem);
        _scale = res.quot;
    }
    return result;
}
Commit message: nwfilter: fix crash when counting number of network filters

The virNWFilterObjListNumOfNWFilters method iterates over the
driver->nwfilters, accessing virNWFilterObj instances. As such
it needs to be protected against concurrent modification of
the driver->nwfilters object.

This API allows unprivileged users to connect, so users with
read-only access to libvirt can cause a denial of service
crash if they are able to race with a call of virNWFilterUndefine.
Since network filters are usually statically defined, this is
considered a low severity problem.

This is assigned CVE-2022-0897.

Reviewed-by: Eric Blake <eblake@redhat.com>
Signed-off-by: Daniel P. Berrangé <berrange@redhat.com>
CVE: CVE-2022-0897
CWE: CWE-667
Vulnerability description: A flaw was found in the libvirt nwfilter driver. The virNWFilterObjListNumOfNWFilters method failed to acquire the driver->nwfilters mutex before iterating over virNWFilterObj instances. There was no protection to stop another thread from concurrently modifying the driver->nwfilters object. This flaw allows a malicious, unprivileged user to exploit this issue via libvirt's API virConnectNumOfNWFilters to crash the network filter management daemon (libvirtd/virtnwfilterd).

Project: libvirt
File: nwfilter_driver.c

nwfilterConnectNumOfNWFilters(virConnectPtr conn)
{
    if (virConnectNumOfNWFiltersEnsureACL(conn) < 0)
        return -1;

    return virNWFilterObjListNumOfNWFilters(driver->nwfilters, conn,
                                        virConnectNumOfNWFiltersCheckACL);
}
Commit message: check zlib space to be within buffer #39
CVE: CVE-2018-7725
CWE: CWE-119
Vulnerability description: An issue was discovered in ZZIPlib 0.13.68. An invalid memory address dereference was discovered in zzip_disk_fread in mmapped.c. The vulnerability causes an application crash, which leads to denial of service.

Project: zziplib
File: mmapped.c

zzip_disk_entry_fopen(ZZIP_DISK * disk, ZZIP_DISK_ENTRY * entry)
{
    /* keep this in sync with zzip_mem_entry_fopen */
    struct zzip_file_header *header =
        zzip_disk_entry_to_file_header(disk, entry);
    if (! header)
        return 0; /* EBADMSG */
    ___ ZZIP_DISK_FILE *file = malloc(sizeof(ZZIP_DISK_FILE));
    if (! file)
        return 0; /* ENOMEM */
    file->buffer = disk->buffer;
    file->endbuf = disk->endbuf;
    file->avail = zzip_file_header_usize(header);

    if (! file->avail || zzip_file_header_data_stored(header))
    { 
         file->stored = zzip_file_header_to_data (header);
         DBG2("stored size %i", (int) file->avail);
         if (file->stored + file->avail >= disk->endbuf)
             goto error;
         return file; 
    }

    file->stored = 0;
    file->zlib.opaque = 0;
    file->zlib.zalloc = Z_NULL;
    file->zlib.zfree = Z_NULL;
    file->zlib.avail_in = zzip_file_header_csize(header);
    file->zlib.next_in = zzip_file_header_to_data(header);

    DBG2("compressed size %i", (int) file->zlib.avail_in);
    if (file->zlib.next_in + file->zlib.avail_in >= disk->endbuf)
         goto error;

    if (! zzip_file_header_data_deflated(header))
        goto error;
    if (inflateInit2(&file->zlib, -MAX_WBITS) != Z_OK)
        goto error;

    return file;
error:
    free (file);
    errno = EBADMSG;
    return 0; 
    ____;
}
Commit message: http_done: close Negotiate connections when done

When doing HTTP requests Negotiate authenticated, the entire connnection
may become authenticated and not just the specific HTTP request which is
otherwise how HTTP works, as Negotiate can basically use NTLM under the
hood. curl was not adhering to this fact but would assume that such
requests would also be authenticated per request.

CVE-2015-3148

Bug: http://curl.haxx.se/docs/adv_20150422B.html
Reported-by: Isaac Boukris
CVE: CVE-2015-3148
CWE: CWE-284
Vulnerability description: cURL and libcurl 7.10.6 through 7.41.0 do not properly re-use authenticated Negotiate connections, which allows remote attackers to connect as other users via a request.

Project: curl
File: http.c

CURLcode Curl_http_done(struct connectdata *conn,
                        CURLcode status, bool premature)
{
  struct SessionHandle *data = conn->data;
  struct HTTP *http =data->req.protop;

  Curl_unencode_cleanup(conn);

#ifdef USE_SPNEGO
  if(data->state.proxyneg.state == GSS_AUTHSENT ||
      data->state.negotiate.state == GSS_AUTHSENT)
    Curl_cleanup_negotiate(data);
#endif

  /* set the proper values (possibly modified on POST) */
  conn->fread_func = data->set.fread_func; /* restore */
  conn->fread_in = data->set.in; /* restore */
  conn->seek_func = data->set.seek_func; /* restore */
  conn->seek_client = data->set.seek_client; /* restore */

  if(http == NULL)
    return CURLE_OK;

  if(http->send_buffer) {
    Curl_send_buffer *buff = http->send_buffer;

    free(buff->buffer);
    free(buff);
    http->send_buffer = NULL; /* clear the pointer */
  }

  if(HTTPREQ_POST_FORM == data->set.httpreq) {
    data->req.bytecount = http->readbytecount + http->writebytecount;

    Curl_formclean(&http->sendit); /* Now free that whole lot */
    if(http->form.fp) {
      /* a file being uploaded was left opened, close it! */
      fclose(http->form.fp);
      http->form.fp = NULL;
    }
  }
  else if(HTTPREQ_PUT == data->set.httpreq)
    data->req.bytecount = http->readbytecount + http->writebytecount;

  if(status)
    return status;

  if(!premature && /* this check is pointless when DONE is called before the
                      entire operation is complete */
     !conn->bits.retry &&
     !data->set.connect_only &&
     ((http->readbytecount +
       data->req.headerbytecount -
       data->req.deductheadercount)) <= 0) {
    /* If this connection isn't simply closed to be retried, AND nothing was
       read from the HTTP server (that counts), this can't be right so we
       return an error here */
    failf(data, "Empty reply from server");
    return CURLE_GOT_NOTHING;
  }

  return CURLE_OK;
}
Commit message: rpmsg: char: release allocated memory

In rpmsg_eptdev_write_iter, if copy_from_iter_full fails the allocated
buffer needs to be released.

Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com>
Signed-off-by: Bjorn Andersson <bjorn.andersson@linaro.org>
CVE: CVE-2019-19053
CWE: CWE-401
Vulnerability description: A memory leak in the rpmsg_eptdev_write_iter() function in drivers/rpmsg/rpmsg_char.c in the Linux kernel through 5.3.11 allows attackers to cause a denial of service (memory consumption) by triggering copy_from_iter_full() failures, aka CID-bbe692e349e2.

Project: linux
File: rpmsg_char.c

static ssize_t rpmsg_eptdev_write_iter(struct kiocb *iocb,
				       struct iov_iter *from)
{
	struct file *filp = iocb->ki_filp;
	struct rpmsg_eptdev *eptdev = filp->private_data;
	size_t len = iov_iter_count(from);
	void *kbuf;
	int ret;

	kbuf = kzalloc(len, GFP_KERNEL);
	if (!kbuf)
		return -ENOMEM;

	if (!copy_from_iter_full(kbuf, len, from))
		return -EFAULT;

	if (mutex_lock_interruptible(&eptdev->ept_lock)) {
		ret = -ERESTARTSYS;
		goto free_kbuf;
	}

	if (!eptdev->ept) {
		ret = -EPIPE;
		goto unlock_eptdev;
	}

	if (filp->f_flags & O_NONBLOCK)
		ret = rpmsg_trysend(eptdev->ept, kbuf, len);
	else
		ret = rpmsg_send(eptdev->ept, kbuf, len);

unlock_eptdev:
	mutex_unlock(&eptdev->ept_lock);

free_kbuf:
	kfree(kbuf);
	return ret < 0 ? ret : len;
}
Commit message: fix parsing double % in query parameters
CVE: CVE-2013-7298
CWE: CWE-399
Vulnerability description: query_params.cpp in cxxtools before 2.2.1 allows remote attackers to cause a denial of service (infinite recursion and crash) via an HTTP query that contains %% (double percent) characters.

Project: cxxtools
File: query_params.cpp

  void UrlParser::parse(char ch)
  {
    switch(_state)
    {
      case state_0:
        if (ch == '=')
          _state = state_value;
        else if (ch == '&')
          ;
        else if (ch == '%')
          _state = state_keyesc;
        else
        {
          _key = ch;
          _state = state_key;
        }
        break;

      case state_key:
        if (ch == '=')
          _state = state_value;
        else if (ch == '&')
        {
          _q.add(_key);
          _key.clear();
          _state = state_0;
        }
        else if (ch == '%')
          _state = state_keyesc;
        else
          _key += ch;
        break;

      case state_value:
        if (ch == '%')
          _state = state_valueesc;
        else if (ch == '&')
        {
          _q.add(_key, _value);
          _key.clear();
          _value.clear();
          _state = state_0;
        }
        else if (ch == '+')
          _value += ' ';
        else
          _value += ch;
        break;

      case state_keyesc:
      case state_valueesc:
        if (ch >= '0' && ch <= '9')
        {
          ++_cnt;
          _v = (_v << 4) + (ch - '0');
        }
        else if (ch >= 'a' && ch <= 'f')
        {
          ++_cnt;
          _v = (_v << 4) + (ch - 'a' + 10);
        }
        else if (ch >= 'A' && ch <= 'F')
        {
          ++_cnt;
          _v = (_v << 4) + (ch - 'A' + 10);
        }
        else
        {
          if (_cnt == 0)
          {
            if (_state == state_keyesc)
              _state = state_key;
            else
              _state = state_value;
            parse('%');
          }
          else
          {
            if (_state == state_keyesc)
            {
              _key += static_cast<char>(_v);
              _state = state_key;
            }
            else
            {
              _value += static_cast<char>(_v);
              _state = state_value;
            }

            _cnt = 0;
            _v = 0;
          }

          parse(ch);
          break;
        }

        if (_cnt >= 2)
        {
          if (_state == state_keyesc)
          {
            _key += static_cast<char>(_v);
            _state = state_key;
          }
          else
          {
            _value += static_cast<char>(_v);
            _state = state_value;
          }
          _cnt = 0;
          _v = 0;
        }

        break;

    }

  }
Commit message: Use ciphertext blinding for Elgamal decryption.

* cipher/elgamal.c (USE_BLINDING): New.
(decrypt): Rewrite to use ciphertext blinding.
--

CVE-id: CVE-2014-3591

As a countermeasure to a new side-channel attacks on sliding windows
exponentiation we blind the ciphertext for Elgamal decryption.  This
is similar to what we are doing with RSA.

Unfortunately, the performance impact of Elgamal blinding is quite
noticeable: For a 3072 bit Elgamal key the decryption used to take
13ms; with the blinding it takes 24ms.  This has been measured using
time(1), calling gpg with a 100 byte message, and having gpg modified
to run the pubkey_decrypt function 100 times and finally scale the
result (using an i5-2410M CPU @ 2.30GHz TP 220).
CVE: CVE-2014-3591
CWE: CWE-200
Vulnerability description: Libgcrypt before 1.6.3 and GnuPG before 1.4.19 does not implement ciphertext blinding for Elgamal decryption, which allows physically proximate attackers to obtain the server's private key by determining factors using crafted ciphertext and the fluctuations in the electromagnetic field during multiplication.

Project: gnupg

decrypt(MPI output, MPI a, MPI b, ELG_secret_key *skey )
{
    MPI t1 = mpi_alloc_secure( mpi_get_nlimbs( skey->p ) );

    mpi_normalize (a);
    mpi_normalize (b);

    /* output = b/(a^x) mod p */
    mpi_powm( t1, a, skey->x, skey->p );
    mpi_invm( t1, t1, skey->p );
    mpi_mulm( output, b, t1, skey->p );
#if 0
    if( DBG_CIPHER ) {
	log_mpidump("elg decrypted x= ", skey->x);
	log_mpidump("elg decrypted p= ", skey->p);
	log_mpidump("elg decrypted a= ", a);
	log_mpidump("elg decrypted b= ", b);
	log_mpidump("elg decrypted M= ", output);
    }
#endif
    mpi_free(t1);
}
Commit message: rfbserver: don't leak stack memory to the remote

Thanks go to Pavel Cheremushkin of Kaspersky for reporting.
CVE: CVE-2019-15681
CWE: CWE-772
Vulnerability description: LibVNC commit before d01e1bb4246323ba6fcee3b82ef1faa9b1dac82a contains a memory leak (CWE-655) in VNC server code, which allow an attacker to read stack memory and can be abused for information disclosure. Combined with another vulnerability, it can be used to leak stack memory and bypass ASLR. This attack appear to be exploitable via network connectivity. These vulnerabilities have been fixed in commit d01e1bb4246323ba6fcee3b82ef1faa9b1dac82a.

Project: libvncserver
File: rfbserver.c

rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len)
{
    rfbClientPtr cl;
    rfbServerCutTextMsg sct;
    rfbClientIteratorPtr iterator;

    iterator = rfbGetClientIterator(rfbScreen);
    while ((cl = rfbClientIteratorNext(iterator)) != NULL) {
        sct.type = rfbServerCutText;
        sct.length = Swap32IfLE(len);
        LOCK(cl->sendMutex);
        if (rfbWriteExact(cl, (char *)&sct,
                       sz_rfbServerCutTextMsg) < 0) {
            rfbLogPerror("rfbSendServerCutText: write");
            rfbCloseClient(cl);
            UNLOCK(cl->sendMutex);
            continue;
        }
        if (rfbWriteExact(cl, str, len) < 0) {
            rfbLogPerror("rfbSendServerCutText: write");
            rfbCloseClient(cl);
        }
        UNLOCK(cl->sendMutex);
        rfbStatRecordMessageSent(cl, rfbServerCutText, sz_rfbServerCutTextMsg+len, sz_rfbServerCutTextMsg+len);
    }
    rfbReleaseClientIterator(iterator);
}
Commit message: Fix security issue when reading username and password

This patch fixes two integer underflows at:
  * grub-core/lib/crypto.c
  * grub-core/normal/auth.c

CVE-2015-8370

Signed-off-by: Hector Marco-Gisbert <hecmargi@upv.es>
Signed-off-by: Ismael Ripoll-Ripoll <iripoll@disca.upv.es>
Also-By: Andrey Borzenkov <arvidjaar@gmail.com>
CVE: CVE-2015-8370
CWE: CWE-264
Vulnerability description: Multiple integer underflows in Grub2 1.98 through 2.02 allow physically proximate attackers to bypass authentication, obtain sensitive information, or cause a denial of service (disk corruption) via backspace characters in the (1) grub_username_get function in grub-core/normal/auth.c or the (2) grub_password_get function in lib/crypto.c, which trigger an "Off-by-two" or "Out of bounds overwrite" memory error.

Project: grub
File: crypto.c

grub_password_get (char buf[], unsigned buf_size)
{
  unsigned cur_len = 0;
  int key;

  while (1)
    {
      key = grub_getkey (); 
      if (key == '\n' || key == '\r')
	break;

      if (key == '\e')
	{
	  cur_len = 0;
	  break;
	}

      if (key == '\b')
	{
	  cur_len--;
	  continue;
	}

      if (!grub_isprint (key))
	continue;

      if (cur_len + 2 < buf_size)
	buf[cur_len++] = key;
    }

  grub_memset (buf + cur_len, 0, buf_size - cur_len);

  grub_xputs ("\n");
  grub_refresh ();

  return (key != '\e');
}

Project: grub
File: auth.c

grub_username_get (char buf[], unsigned buf_size)
{
  unsigned cur_len = 0;
  int key;

  while (1)
    {
      key = grub_getkey (); 
      if (key == '\n' || key == '\r')
	break;

      if (key == '\e')
	{
	  cur_len = 0;
	  break;
	}

      if (key == '\b')
	{
	  cur_len--;
	  grub_printf ("\b");
	  continue;
	}

      if (!grub_isprint (key))
	continue;

      if (cur_len + 2 < buf_size)
	{
	  buf[cur_len++] = key;
	  grub_printf ("%c", key);
	}
    }

  grub_memset (buf + cur_len, 0, buf_size - cur_len);

  grub_xputs ("\n");
  grub_refresh ();

  return (key != '\e');
}
Commit message: ExecHelperMain: fix privilege lowering code
CVE: CVE-2018-12615
CWE: CWE-284
Vulnerability description: An issue was discovered in switchGroup() in agent/ExecHelper/ExecHelperMain.cpp in Phusion Passenger before 5.3.2. The set of groups (gidset) is not set correctly, leaving it up to randomness (i.e., uninitialized memory) which supplementary groups are actually being set while lowering privileges.

Project: passenger
File: ExecHelperMain.cpp

switchGroup(uid_t uid, const struct passwd *userInfo, gid_t gid) {
	if (userInfo != NULL) {
		bool setgroupsCalled = false;

		#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
			#ifdef __APPLE__
				int groups[1024];
				int ngroups = sizeof(groups) / sizeof(int);
			#else
				gid_t groups[1024];
				int ngroups = sizeof(groups) / sizeof(gid_t);
			#endif
			boost::scoped_array<gid_t> gidset;

			int ret = getgrouplist(userInfo->pw_name, gid,
				groups, &ngroups);
			if (ret == -1) {
				int e = errno;
				fprintf(stderr, "ERROR: getgrouplist(%s, %d) failed: %s (errno=%d)\n",
					userInfo->pw_name, (int) gid, strerror(e), e);
				exit(1);
			}

			if (ngroups <= NGROUPS_MAX) {
				setgroupsCalled = true;
				gidset.reset(new gid_t[ngroups]);
				if (setgroups(ngroups, gidset.get()) == -1) {
					int e = errno;
					fprintf(stderr, "ERROR: setgroups(%d, ...) failed: %s (errno=%d)\n",
						ngroups, strerror(e), e);
					exit(1);
				}
			}
		#endif

		if (!setgroupsCalled && initgroups(userInfo->pw_name, gid) == -1) {
			int e = errno;
			fprintf(stderr, "ERROR: initgroups(%s, %d) failed: %s (errno=%d)\n",
				userInfo->pw_name, (int) gid, strerror(e), e);
			exit(1);
		}
	}

	if (setgid(gid) == -1) {
		int e = errno;
		fprintf(stderr, "ERROR: setgid(%d) failed: %s (errno=%d)\n",
			(int) gid, strerror(e), e);
		exit(1);
	}
}
Commit message: Handle invalid instantiation of generic methods.

	* verify.c: Add new function to internal verifier API to check
	method instantiations.

	* reflection.c (mono_reflection_bind_generic_method_parameters):
	Check the instantiation before returning it.

	Fixes #655847
CVE: CVE-2010-4254
CWE: CWE-20
Vulnerability description: Mono, when Moonlight before 2.3.0.1 or 2.99.x before 2.99.0.10 is used, does not properly validate arguments to generic methods, which allows remote attackers to bypass generic constraints, and possibly execute arbitrary code, via a crafted method call.

Project: mono

MonoReflectionMethod*
mono_reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoArray *types)
{
	MonoClass *klass;
	MonoMethod *method, *inflated;
	MonoMethodInflated *imethod;
	MonoGenericContext tmp_context;
	MonoGenericInst *ginst;
	MonoType **type_argv;
	int count, i;

	MONO_ARCH_SAVE_REGS;

	if (!strcmp (rmethod->object.vtable->klass->name, "MethodBuilder")) {
#ifndef DISABLE_REFLECTION_EMIT
		MonoReflectionMethodBuilder *mb = NULL;
		MonoReflectionTypeBuilder *tb;
		MonoClass *klass;

		mb = (MonoReflectionMethodBuilder *) rmethod;
		tb = (MonoReflectionTypeBuilder *) mb->type;
		klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));

		method = methodbuilder_to_mono_method (klass, mb);
#else
		g_assert_not_reached ();
		method = NULL;
#endif
	} else {
		method = rmethod->method;
	}

	klass = method->klass;

	if (method->is_inflated)
		method = ((MonoMethodInflated *) method)->declaring;

	count = mono_method_signature (method)->generic_param_count;
	if (count != mono_array_length (types))
		return NULL;

	type_argv = g_new0 (MonoType *, count);
	for (i = 0; i < count; i++) {
		MonoReflectionType *garg = mono_array_get (types, gpointer, i);
		type_argv [i] = mono_reflection_type_get_handle (garg);
	}
	ginst = mono_metadata_get_generic_inst (count, type_argv);
	g_free (type_argv);

	tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
	tmp_context.method_inst = ginst;

	inflated = mono_class_inflate_generic_method (method, &tmp_context);
	imethod = (MonoMethodInflated *) inflated;

	if (method->klass->image->dynamic) {
		MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
		/*
		 * This table maps metadata structures representing inflated methods/fields
		 * to the reflection objects representing their generic definitions.
		 */
		mono_loader_lock ();
		mono_g_hash_table_insert (image->generic_def_objects, imethod, rmethod);
		mono_loader_unlock ();
	}
	
	return mono_method_get_object (mono_object_domain (rmethod), inflated, NULL);