  void Compute(OpKernelContext* context) override {
    // Only create one, if one does not exist already. Report status for all
    // other exceptions. If one already exists, it unrefs the new one.
    // An epsilon value of zero could cause performance issues and is therefore,
    // disallowed.
    const Tensor* epsilon_t;
    OP_REQUIRES_OK(context, context->input(kEpsilonName, &epsilon_t));
    float epsilon = epsilon_t->scalar<float>()();
    OP_REQUIRES(
        context, epsilon > 0,
        errors::InvalidArgument("An epsilon value of zero is not allowed."));

    const Tensor* num_streams_t;
    OP_REQUIRES_OK(context, context->input(kNumStreamsName, &num_streams_t));
    int64_t num_streams = num_streams_t->scalar<int64>()();

    auto result =
        new QuantileStreamResource(epsilon, max_elements_, num_streams);
    auto status = CreateResource(context, HandleFromInput(context, 0), result);
    if (!status.ok() && status.code() != tensorflow::error::ALREADY_EXISTS) {
      OP_REQUIRES(context, false, status);
    }
  }

Ensure num_streams >= 0 in tf.raw_ops.BoostedTreesCreateQuantileStreamResource

PiperOrigin-RevId: 387452765
Change-Id: I9990c760e177fabca6a3b9b4612ceeaeeba51495


CURLcode Curl_build_unencoding_stack(struct Curl_easy *data,
                                     const char *enclist, int maybechunked)
{
  struct SingleRequest *k = &data->req;

  do {
    const char *name;
    size_t namelen;

    /* Parse a single encoding name. */
    while(ISSPACE(*enclist) || *enclist == ',')
      enclist++;

    name = enclist;

    for(namelen = 0; *enclist && *enclist != ','; enclist++)
      if(!ISSPACE(*enclist))
        namelen = enclist - name + 1;

    /* Special case: chunked encoding is handled at the reader level. */
    if(maybechunked && namelen == 7 && strncasecompare(name, "chunked", 7)) {
      k->chunk = TRUE;             /* chunks coming our way. */
      Curl_httpchunk_init(data);   /* init our chunky engine. */
    }
    else if(namelen) {
      const struct content_encoding *encoding = find_encoding(name, namelen);
      struct contenc_writer *writer;

      if(!k->writer_stack) {
        k->writer_stack = new_unencoding_writer(data, &client_encoding, NULL);

        if(!k->writer_stack)
          return CURLE_OUT_OF_MEMORY;
      }

      if(!encoding)
        encoding = &error_encoding;  /* Defer error at stack use. */

      /* Stack the unencoding stage. */
      writer = new_unencoding_writer(data, encoding, k->writer_stack);
      if(!writer)
        return CURLE_OUT_OF_MEMORY;
      k->writer_stack = writer;
    }
  } while(*enclist);

  return CURLE_OK;
}

content_encoding: return error on too many compression steps

The max allowed steps is arbitrarily set to 5.

Bug: https://curl.se/docs/CVE-2022-32206.html
CVE-2022-32206
Reported-by: Harry Sintonen
Closes #9049


void fmtutil_macbitmap_read_pixmap_only_fields(deark *c, dbuf *f, struct fmtutil_macbitmap_info *bi,
	i64 pos)
{
	i64 pixmap_version;
	i64 pack_size;
	i64 plane_bytes;
	i64 n;

	de_dbg(c, "additional PixMap header fields, at %d", (int)pos);
	de_dbg_indent(c, 1);

	pixmap_version = dbuf_getu16be(f, pos+0);
	de_dbg(c, "pixmap version: %d", (int)pixmap_version);

	bi->packing_type = dbuf_getu16be(f, pos+2);
	de_dbg(c, "packing type: %d", (int)bi->packing_type);

	pack_size = dbuf_getu32be(f, pos+4);
	de_dbg(c, "pixel data length: %d", (int)pack_size);

	bi->hdpi = pict_read_fixed(f, pos+8);
	bi->vdpi = pict_read_fixed(f, pos+12);
	de_dbg(c, "dpi: %.2f"DE_CHAR_TIMES"%.2f", bi->hdpi, bi->vdpi);

	bi->pixeltype = dbuf_getu16be(f, pos+16);
	bi->pixelsize = dbuf_getu16be(f, pos+18);
	bi->cmpcount = dbuf_getu16be(f, pos+20);
	bi->cmpsize = dbuf_getu16be(f, pos+22);
	de_dbg(c, "pixel type=%d, bits/pixel=%d, components/pixel=%d, bits/comp=%d",
		(int)bi->pixeltype, (int)bi->pixelsize, (int)bi->cmpcount, (int)bi->cmpsize);

	bi->pdwidth = (bi->rowbytes*8)/bi->pixelsize;
	if(bi->pdwidth < bi->npwidth) {
		bi->pdwidth = bi->npwidth;
	}

	plane_bytes = dbuf_getu32be(f, pos+24);
	de_dbg(c, "plane bytes: %d", (int)plane_bytes);

	bi->pmTable = (u32)dbuf_getu32be(f, pos+28);
	de_dbg(c, "pmTable: 0x%08x", (unsigned int)bi->pmTable);

	n = dbuf_getu32be(f, pos+32);
	de_dbg(c, "pmReserved: 0x%08x", (unsigned int)n);

	de_dbg_indent(c, -1);
}

pict,macrsrc: Fixed a bug that could cause division by 0

Found by F. Çelik.


 */
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
	st_entry 			*ent1, *ent2;
	wddx_stack 			*stack = (wddx_stack *)user_data;
	HashTable 			*target_hash;
	zend_class_entry 	*pce;
	zval				obj;

/* OBJECTS_FIXME */
	if (stack->top == 0) {
		return;
	}

	if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) ||
		!strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) ||
	  	!strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) ||
		!strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) ||
		!strcmp((char *)name, EL_DATETIME)) {
		wddx_stack_top(stack, (void**)&ent1);

		if (Z_TYPE(ent1->data) == IS_UNDEF) {
			if (stack->top > 1) {
				stack->top--;
			} else {
				stack->done = 1;
			}
			efree(ent1);
			return;
		}

		if (!strcmp((char *)name, EL_BINARY)) {
			zend_string *new_str = php_base64_decode(
				(unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
			zval_ptr_dtor(&ent1->data);
			ZVAL_STR(&ent1->data, new_str);
		}

		/* Call __wakeup() method on the object. */
		if (Z_TYPE(ent1->data) == IS_OBJECT) {
			zval fname, retval;

			ZVAL_STRING(&fname, "__wakeup");

			call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL);

			zval_ptr_dtor(&fname);
			zval_ptr_dtor(&retval);
		}

		if (stack->top > 1) {
			stack->top--;
			wddx_stack_top(stack, (void**)&ent2);

			/* if non-existent field */
			if (ent2->type == ST_FIELD && Z_ISUNDEF(ent2->data)) {
				zval_ptr_dtor(&ent1->data);
				efree(ent1);
				return;
			}

			if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) {
				target_hash = HASH_OF(&ent2->data);

				if (ent1->varname) {
					if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
						Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) &&
						ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) {
						zend_bool incomplete_class = 0;

						zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
						zend_string_forget_hash_val(Z_STR(ent1->data));
						if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) {
							incomplete_class = 1;
							pce = PHP_IC_ENTRY;
						}

						/* Initialize target object */
						object_init_ex(&obj, pce);

						/* Merge current hashtable with object's default properties */
						zend_hash_merge(Z_OBJPROP(obj),
										Z_ARRVAL(ent2->data),
										zval_add_ref, 0);

						if (incomplete_class) {
							php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data));
						}

						/* Clean up old array entry */
						zval_ptr_dtor(&ent2->data);

						/* Set stack entry to point to the newly created object */
						ZVAL_COPY_VALUE(&ent2->data, &obj);

						/* Clean up class name var entry */
						zval_ptr_dtor(&ent1->data);
					} else if (Z_TYPE(ent2->data) == IS_OBJECT) {
						zend_class_entry *old_scope = EG(scope);

						EG(scope) = Z_OBJCE(ent2->data);
						add_property_zval(&ent2->data, ent1->varname, &ent1->data);
						if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data);
						EG(scope) = old_scope;
					} else {
						zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data);
					}
					efree(ent1->varname);
				} else	{
					zend_hash_next_index_insert(target_hash, &ent1->data);
				}
			}
			efree(ent1);
		} else {
			stack->done = 1;
		}
	} else if (!strcmp((char *)name, EL_VAR) && stack->varname) {
		efree(stack->varname);
		stack->varname = NULL;
	} else if (!strcmp((char *)name, EL_FIELD)) {
		st_entry *ent;
		wddx_stack_top(stack, (void **)&ent);
		efree(ent);
		stack->top--;
	}

Fix for bug #72790 and bug #72799

(cherry picked from commit a14fdb9746262549bbbb96abb87338bacd147e1b)

Conflicts:
	ext/wddx/wddx.c


DocumentSource::GetNextResult DocumentSourceUnionWith::doGetNext() {
    if (!_pipeline) {
        // We must have already been disposed, so we're finished.
        return GetNextResult::makeEOF();
    }

    if (_executionState == ExecutionProgress::kIteratingSource) {
        auto nextInput = pSource->getNext();
        if (!nextInput.isEOF()) {
            return nextInput;
        }
        _executionState = ExecutionProgress::kStartingSubPipeline;
        // All documents from the base collection have been returned, switch to iterating the sub-
        // pipeline by falling through below.
    }

    if (_executionState == ExecutionProgress::kStartingSubPipeline) {
        auto serializedPipe = _pipeline->serializeToBson();
        LOGV2_DEBUG(23869,
                    1,
                    "$unionWith attaching cursor to pipeline {pipeline}",
                    "pipeline"_attr = serializedPipe);
        // $$SEARCH_META can be set during runtime earlier in the pipeline, and therefore must be
        // copied to the subpipeline manually.
        if (pExpCtx->variables.hasConstantValue(Variables::kSearchMetaId)) {
            _pipeline->getContext()->variables.setReservedValue(
                Variables::kSearchMetaId,
                pExpCtx->variables.getValue(Variables::kSearchMetaId, Document()),
                true);
        }
        try {
            _pipeline =
                pExpCtx->mongoProcessInterface->attachCursorSourceToPipeline(_pipeline.release());
            _executionState = ExecutionProgress::kIteratingSubPipeline;
        } catch (const ExceptionFor<ErrorCodes::CommandOnShardedViewNotSupportedOnMongod>& e) {
            _pipeline = buildPipelineFromViewDefinition(
                pExpCtx,
                ExpressionContext::ResolvedNamespace{e->getNamespace(), e->getPipeline()},
                serializedPipe);
            LOGV2_DEBUG(4556300,
                        3,
                        "$unionWith found view definition. ns: {ns}, pipeline: {pipeline}. New "
                        "$unionWith sub-pipeline: {new_pipe}",
                        "ns"_attr = e->getNamespace(),
                        "pipeline"_attr = Value(e->getPipeline()),
                        "new_pipe"_attr = _pipeline->serializeToBson());
            return doGetNext();
        }
    }

    auto res = _pipeline->getNext();
    if (res)
        return std::move(*res);

    // Record the plan summary stats after $unionWith operation is done.
    recordPlanSummaryStats(*_pipeline);

    _executionState = ExecutionProgress::kFinished;
    return GetNextResult::makeEOF();
}

SERVER-58203 factor out logging statements into helper functions


display_debug_names (struct dwarf_section *section, void *file)
{
  unsigned char *hdrptr = section->start;
  dwarf_vma unit_length;
  unsigned char *unit_start;
  const unsigned char *const section_end = section->start + section->size;
  unsigned char *unit_end;

  introduce (section, false);

  load_debug_section_with_follow (str, file);

  for (; hdrptr < section_end; hdrptr = unit_end)
    {
      unsigned int offset_size;
      uint16_t dwarf_version, padding;
      uint32_t comp_unit_count, local_type_unit_count, foreign_type_unit_count;
      uint64_t bucket_count, name_count, abbrev_table_size;
      uint32_t augmentation_string_size;
      unsigned int i;
      bool augmentation_printable;
      const char *augmentation_string;
      size_t total;

      unit_start = hdrptr;

      /* Get and check the length of the block.  */
      SAFE_BYTE_GET_AND_INC (unit_length, hdrptr, 4, section_end);

      if (unit_length == 0xffffffff)
	{
	  /* This section is 64-bit DWARF.  */
	  SAFE_BYTE_GET_AND_INC (unit_length, hdrptr, 8, section_end);
	  offset_size = 8;
	}
      else
	offset_size = 4;

      if (unit_length > (size_t) (section_end - hdrptr)
	  || unit_length < 2 + 2 + 4 * 7)
	{
	too_short:
	  warn (_("Debug info is corrupted, %s header at %#lx has length %s\n"),
		section->name,
		(unsigned long) (unit_start - section->start),
		dwarf_vmatoa ("x", unit_length));
	  return 0;
	}
      unit_end = hdrptr + unit_length;

      /* Get and check the version number.  */
      SAFE_BYTE_GET_AND_INC (dwarf_version, hdrptr, 2, unit_end);
      printf (_("Version %ld\n"), (long) dwarf_version);

      /* Prior versions did not exist, and future versions may not be
	 backwards compatible.  */
      if (dwarf_version != 5)
	{
	  warn (_("Only DWARF version 5 .debug_names "
		  "is currently supported.\n"));
	  return 0;
	}

      SAFE_BYTE_GET_AND_INC (padding, hdrptr, 2, unit_end);
      if (padding != 0)
	warn (_("Padding field of .debug_names must be 0 (found 0x%x)\n"),
	      padding);

      SAFE_BYTE_GET_AND_INC (comp_unit_count, hdrptr, 4, unit_end);
      if (comp_unit_count == 0)
	warn (_("Compilation unit count must be >= 1 in .debug_names\n"));

      SAFE_BYTE_GET_AND_INC (local_type_unit_count, hdrptr, 4, unit_end);
      SAFE_BYTE_GET_AND_INC (foreign_type_unit_count, hdrptr, 4, unit_end);
      SAFE_BYTE_GET_AND_INC (bucket_count, hdrptr, 4, unit_end);
      SAFE_BYTE_GET_AND_INC (name_count, hdrptr, 4, unit_end);
      SAFE_BYTE_GET_AND_INC (abbrev_table_size, hdrptr, 4, unit_end);

      SAFE_BYTE_GET_AND_INC (augmentation_string_size, hdrptr, 4, unit_end);
      if (augmentation_string_size % 4 != 0)
	{
	  warn (_("Augmentation string length %u must be rounded up "
		  "to a multiple of 4 in .debug_names.\n"),
		augmentation_string_size);
	  augmentation_string_size += (-augmentation_string_size) & 3;
	}
      if (augmentation_string_size > (size_t) (unit_end - hdrptr))
	goto too_short;

      printf (_("Augmentation string:"));

      augmentation_printable = true;
      augmentation_string = (const char *) hdrptr;

      for (i = 0; i < augmentation_string_size; i++)
	{
	  unsigned char uc;

	  SAFE_BYTE_GET_AND_INC (uc, hdrptr, 1, unit_end);
	  printf (" %02x", uc);

	  if (uc != 0 && !ISPRINT (uc))
	    augmentation_printable = false;
	}

      if (augmentation_printable)
	{
	  printf ("  (\"");
	  for (i = 0;
	       i < augmentation_string_size && augmentation_string[i];
	       ++i)
	    putchar (augmentation_string[i]);
	  printf ("\")");
	}
      putchar ('\n');

      printf (_("CU table:\n"));
      if (_mul_overflow (comp_unit_count, offset_size, &total)
	  || total > (size_t) (unit_end - hdrptr))
	goto too_short;
      for (i = 0; i < comp_unit_count; i++)
	{
	  uint64_t cu_offset;

	  SAFE_BYTE_GET_AND_INC (cu_offset, hdrptr, offset_size, unit_end);
	  printf (_("[%3u] 0x%lx\n"), i, (unsigned long) cu_offset);
	}
      putchar ('\n');

      printf (_("TU table:\n"));
      if (_mul_overflow (local_type_unit_count, offset_size, &total)
	  || total > (size_t) (unit_end - hdrptr))
	goto too_short;
      for (i = 0; i < local_type_unit_count; i++)
	{
	  uint64_t tu_offset;

	  SAFE_BYTE_GET_AND_INC (tu_offset, hdrptr, offset_size, unit_end);
	  printf (_("[%3u] 0x%lx\n"), i, (unsigned long) tu_offset);
	}
      putchar ('\n');

      printf (_("Foreign TU table:\n"));
      if (_mul_overflow (foreign_type_unit_count, 8, &total)
	  || total > (size_t) (unit_end - hdrptr))
	goto too_short;
      for (i = 0; i < foreign_type_unit_count; i++)
	{
	  uint64_t signature;

	  SAFE_BYTE_GET_AND_INC (signature, hdrptr, 8, unit_end);
	  printf (_("[%3u] "), i);
	  print_dwarf_vma (signature, 8);
	  putchar ('\n');
	}
      putchar ('\n');

      uint64_t xtra = (bucket_count * sizeof (uint32_t)
		       + name_count * (sizeof (uint32_t) + 2 * offset_size)
		       + abbrev_table_size);
      if (xtra > (size_t) (unit_end - hdrptr))
	{
	  warn (_("Entry pool offset (0x%lx) exceeds unit size 0x%lx "
		  "for unit 0x%lx in the debug_names\n"),
		(long) xtra,
		(long) (unit_end - unit_start),
		(long) (unit_start - section->start));
	  return 0;
	}
      const uint32_t *const hash_table_buckets = (uint32_t *) hdrptr;
      hdrptr += bucket_count * sizeof (uint32_t);
      const uint32_t *const hash_table_hashes = (uint32_t *) hdrptr;
      hdrptr += name_count * sizeof (uint32_t);
      unsigned char *const name_table_string_offsets = hdrptr;
      hdrptr += name_count * offset_size;
      unsigned char *const name_table_entry_offsets = hdrptr;
      hdrptr += name_count * offset_size;
      unsigned char *const abbrev_table = hdrptr;
      hdrptr += abbrev_table_size;
      const unsigned char *const abbrev_table_end = hdrptr;
      unsigned char *const entry_pool = hdrptr;

      size_t buckets_filled = 0;
      size_t bucketi;
      for (bucketi = 0; bucketi < bucket_count; bucketi++)
	{
	  const uint32_t bucket = hash_table_buckets[bucketi];

	  if (bucket != 0)
	    ++buckets_filled;
	}
      printf (ngettext ("Used %zu of %lu bucket.\n",
			"Used %zu of %lu buckets.\n",
			bucket_count),
	      buckets_filled, (unsigned long) bucket_count);

      if (bucket_count != 0)
	{
	  uint32_t hash_prev = 0;
	  size_t hash_clash_count = 0;
	  size_t longest_clash = 0;
	  size_t this_length = 0;
	  size_t hashi;
	  for (hashi = 0; hashi < name_count; hashi++)
	    {
	      const uint32_t hash_this = hash_table_hashes[hashi];

	      if (hashi > 0)
		{
		  if (hash_prev % bucket_count == hash_this % bucket_count)
		    {
		      ++hash_clash_count;
		      ++this_length;
		      longest_clash = MAX (longest_clash, this_length);
		    }
		  else
		    this_length = 0;
		}
	      hash_prev = hash_this;
	    }
	  printf (_("Out of %lu items there are %zu bucket clashes"
		    " (longest of %zu entries).\n"),
		  (unsigned long) name_count, hash_clash_count, longest_clash);
	  assert (name_count == buckets_filled + hash_clash_count);
	}

      struct abbrev_lookup_entry
      {
	dwarf_vma abbrev_tag;
	unsigned char *abbrev_lookup_ptr;
      };
      struct abbrev_lookup_entry *abbrev_lookup = NULL;
      size_t abbrev_lookup_used = 0;
      size_t abbrev_lookup_allocated = 0;

      unsigned char *abbrevptr = abbrev_table;
      for (;;)
	{
	  dwarf_vma abbrev_tag;

	  READ_ULEB (abbrev_tag, abbrevptr, abbrev_table_end);
	  if (abbrev_tag == 0)
	    break;
	  if (abbrev_lookup_used == abbrev_lookup_allocated)
	    {
	      abbrev_lookup_allocated = MAX (0x100,
					     abbrev_lookup_allocated * 2);
	      abbrev_lookup = xrealloc (abbrev_lookup,
					(abbrev_lookup_allocated
					 * sizeof (*abbrev_lookup)));
	    }
	  assert (abbrev_lookup_used < abbrev_lookup_allocated);
	  struct abbrev_lookup_entry *entry;
	  for (entry = abbrev_lookup;
	       entry < abbrev_lookup + abbrev_lookup_used;
	       entry++)
	    if (entry->abbrev_tag == abbrev_tag)
	      {
		warn (_("Duplicate abbreviation tag %lu "
			"in unit 0x%lx in the debug_names\n"),
		      (long) abbrev_tag, (long) (unit_start - section->start));
		break;
	      }
	  entry = &abbrev_lookup[abbrev_lookup_used++];
	  entry->abbrev_tag = abbrev_tag;
	  entry->abbrev_lookup_ptr = abbrevptr;

	  /* Skip DWARF tag.  */
	  SKIP_ULEB (abbrevptr, abbrev_table_end);
	  for (;;)
	    {
	      dwarf_vma xindex, form;

	      READ_ULEB (xindex, abbrevptr, abbrev_table_end);
	      READ_ULEB (form, abbrevptr, abbrev_table_end);
	      if (xindex == 0 && form == 0)
		break;
	    }
	}

      printf (_("\nSymbol table:\n"));
      uint32_t namei;
      for (namei = 0; namei < name_count; ++namei)
	{
	  uint64_t string_offset, entry_offset;
	  unsigned char *p;

	  p = name_table_string_offsets + namei * offset_size;
	  SAFE_BYTE_GET (string_offset, p, offset_size, unit_end);
	  p = name_table_entry_offsets + namei * offset_size;
	  SAFE_BYTE_GET (entry_offset, p, offset_size, unit_end);

	  printf ("[%3u] #%08x %s:", namei, hash_table_hashes[namei],
		  fetch_indirect_string (string_offset));

	  unsigned char *entryptr = entry_pool + entry_offset;

	  /* We need to scan first whether there is a single or multiple
	     entries.  TAGNO is -2 for the first entry, it is -1 for the
	     initial tag read of the second entry, then it becomes 0 for the
	     first entry for real printing etc.  */
	  int tagno = -2;
	  /* Initialize it due to a false compiler warning.  */
	  dwarf_vma second_abbrev_tag = -1;
	  for (;;)
	    {
	      dwarf_vma abbrev_tag;
	      dwarf_vma dwarf_tag;
	      const struct abbrev_lookup_entry *entry;

	      READ_ULEB (abbrev_tag, entryptr, unit_end);
	      if (tagno == -1)
		{
		  second_abbrev_tag = abbrev_tag;
		  tagno = 0;
		  entryptr = entry_pool + entry_offset;
		  continue;
		}
	      if (abbrev_tag == 0)
		break;
	      if (tagno >= 0)
		printf ("%s<%lu>",
		        (tagno == 0 && second_abbrev_tag == 0 ? " " : "\n\t"),
			(unsigned long) abbrev_tag);

	      for (entry = abbrev_lookup;
		   entry < abbrev_lookup + abbrev_lookup_used;
		   entry++)
		if (entry->abbrev_tag == abbrev_tag)
		  break;
	      if (entry >= abbrev_lookup + abbrev_lookup_used)
		{
		  warn (_("Undefined abbreviation tag %lu "
			  "in unit 0x%lx in the debug_names\n"),
			(long) abbrev_tag,
			(long) (unit_start - section->start));
		  break;
		}
	      abbrevptr = entry->abbrev_lookup_ptr;
	      READ_ULEB (dwarf_tag, abbrevptr, abbrev_table_end);
	      if (tagno >= 0)
		printf (" %s", get_TAG_name (dwarf_tag));
	      for (;;)
		{
		  dwarf_vma xindex, form;

		  READ_ULEB (xindex, abbrevptr, abbrev_table_end);
		  READ_ULEB (form, abbrevptr, abbrev_table_end);
		  if (xindex == 0 && form == 0)
		    break;

		  if (tagno >= 0)
		    printf (" %s", get_IDX_name (xindex));
		  entryptr = read_and_display_attr_value (0, form, 0,
							  unit_start, entryptr, unit_end,
							  0, 0, offset_size,
							  dwarf_version, NULL,
							  (tagno < 0), section,
							  NULL, '=', -1);
		}
	      ++tagno;
	    }
	  if (tagno <= 0)
	    printf (_(" <no entries>"));
	  putchar ('\n');
	}

      free (abbrev_lookup);
    }

  return 1;
}

Replace a run-time assertion failure with a warning message when parsing corrupt DWARF data.

	PR 29289
	* dwarf.c (display_debug_names): Replace assert with a warning
	message.


int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
		    u64 devid)
{
	struct btrfs_device *device;
	struct btrfs_fs_devices *cur_devices;
	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
	u64 num_devices;
	int ret = 0;

	mutex_lock(&uuid_mutex);

	num_devices = btrfs_num_devices(fs_info);

	ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
	if (ret)
		goto out;

	device = btrfs_find_device_by_devspec(fs_info, devid, device_path);

	if (IS_ERR(device)) {
		if (PTR_ERR(device) == -ENOENT &&
		    strcmp(device_path, "missing") == 0)
			ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
		else
			ret = PTR_ERR(device);
		goto out;
	}

	if (btrfs_pinned_by_swapfile(fs_info, device)) {
		btrfs_warn_in_rcu(fs_info,
		  "cannot remove device %s (devid %llu) due to active swapfile",
				  rcu_str_deref(device->name), device->devid);
		ret = -ETXTBSY;
		goto out;
	}

	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
		ret = BTRFS_ERROR_DEV_TGT_REPLACE;
		goto out;
	}

	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
	    fs_info->fs_devices->rw_devices == 1) {
		ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
		goto out;
	}

	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
		mutex_lock(&fs_info->chunk_mutex);
		list_del_init(&device->dev_alloc_list);
		device->fs_devices->rw_devices--;
		mutex_unlock(&fs_info->chunk_mutex);
	}

	mutex_unlock(&uuid_mutex);
	ret = btrfs_shrink_device(device, 0);
	if (!ret)
		btrfs_reada_remove_dev(device);
	mutex_lock(&uuid_mutex);
	if (ret)
		goto error_undo;

	/*
	 * TODO: the superblock still includes this device in its num_devices
	 * counter although write_all_supers() is not locked out. This
	 * could give a filesystem state which requires a degraded mount.
	 */
	ret = btrfs_rm_dev_item(device);
	if (ret)
		goto error_undo;

	clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
	btrfs_scrub_cancel_dev(device);

	/*
	 * the device list mutex makes sure that we don't change
	 * the device list while someone else is writing out all
	 * the device supers. Whoever is writing all supers, should
	 * lock the device list mutex before getting the number of
	 * devices in the super block (super_copy). Conversely,
	 * whoever updates the number of devices in the super block
	 * (super_copy) should hold the device list mutex.
	 */

	/*
	 * In normal cases the cur_devices == fs_devices. But in case
	 * of deleting a seed device, the cur_devices should point to
	 * its own fs_devices listed under the fs_devices->seed.
	 */
	cur_devices = device->fs_devices;
	mutex_lock(&fs_devices->device_list_mutex);
	list_del_rcu(&device->dev_list);

	cur_devices->num_devices--;
	cur_devices->total_devices--;
	/* Update total_devices of the parent fs_devices if it's seed */
	if (cur_devices != fs_devices)
		fs_devices->total_devices--;

	if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
		cur_devices->missing_devices--;

	btrfs_assign_next_active_device(device, NULL);

	if (device->bdev) {
		cur_devices->open_devices--;
		/* remove sysfs entry */
		btrfs_sysfs_remove_device(device);
	}

	num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
	btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
	mutex_unlock(&fs_devices->device_list_mutex);

	/*
	 * at this point, the device is zero sized and detached from
	 * the devices list.  All that's left is to zero out the old
	 * supers and free the device.
	 */
	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
		btrfs_scratch_superblocks(fs_info, device->bdev,
					  device->name->str);

	btrfs_close_bdev(device);
	synchronize_rcu();
	btrfs_free_device(device);

	if (cur_devices->open_devices == 0) {
		list_del_init(&cur_devices->seed_list);
		close_fs_devices(cur_devices);
		free_fs_devices(cur_devices);
	}

out:
	mutex_unlock(&uuid_mutex);
	return ret;

error_undo:
	btrfs_reada_undo_remove_dev(device);
	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
		mutex_lock(&fs_info->chunk_mutex);
		list_add(&device->dev_alloc_list,
			 &fs_devices->alloc_list);
		device->fs_devices->rw_devices++;
		mutex_unlock(&fs_info->chunk_mutex);
	}
	goto out;
}

btrfs: fix NULL pointer dereference when deleting device by invalid id

[BUG]
It's easy to trigger NULL pointer dereference, just by removing a
non-existing device id:

 # mkfs.btrfs -f -m single -d single /dev/test/scratch1 \
				     /dev/test/scratch2
 # mount /dev/test/scratch1 /mnt/btrfs
 # btrfs device remove 3 /mnt/btrfs

Then we have the following kernel NULL pointer dereference:

 BUG: kernel NULL pointer dereference, address: 0000000000000000
 #PF: supervisor read access in kernel mode
 #PF: error_code(0x0000) - not-present page
 PGD 0 P4D 0
 Oops: 0000 [#1] PREEMPT SMP NOPTI
 CPU: 9 PID: 649 Comm: btrfs Not tainted 5.14.0-rc3-custom+ #35
 Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 0.0.0 02/06/2015
 RIP: 0010:btrfs_rm_device+0x4de/0x6b0 [btrfs]
  btrfs_ioctl+0x18bb/0x3190 [btrfs]
  ? lock_is_held_type+0xa5/0x120
  ? find_held_lock.constprop.0+0x2b/0x80
  ? do_user_addr_fault+0x201/0x6a0
  ? lock_release+0xd2/0x2d0
  ? __x64_sys_ioctl+0x83/0xb0
  __x64_sys_ioctl+0x83/0xb0
  do_syscall_64+0x3b/0x90
  entry_SYSCALL_64_after_hwframe+0x44/0xae

[CAUSE]
Commit a27a94c2b0c7 ("btrfs: Make btrfs_find_device_by_devspec return
btrfs_device directly") moves the "missing" device path check into
btrfs_rm_device().

But btrfs_rm_device() itself can have case where it only receives
@devid, with NULL as @device_path.

In that case, calling strcmp() on NULL will trigger the NULL pointer
dereference.

Before that commit, we handle the "missing" case inside
btrfs_find_device_by_devspec(), which will not check @device_path at all
if @devid is provided, thus no way to trigger the bug.

[FIX]
Before calling strcmp(), also make sure @device_path is not NULL.

Fixes: a27a94c2b0c7 ("btrfs: Make btrfs_find_device_by_devspec return btrfs_device directly")
CC: stable@vger.kernel.org # 5.4+
Reported-by: butt3rflyh4ck <butterflyhuangxx@gmail.com>
Reviewed-by: Anand Jain <anand.jain@oracle.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>